本文基于C语言代码,编写的一个小游戏,代码运行后,小鸟将会自动坠落,只有摁下空格的时候小鸟才会上升。在飞行过程中小鸟也会遇到各种障碍。度过障碍则会加分。
1初始化数据
2死循环
3绘制图画
4用户无关的数据更新
5用户有关得数据更新
重新进入步骤3
本文引用头文件
- #include<stdio.h>
- #include<stdlib.h>
- #include<conio.h>
- #include<windows.h>
-
相关头文件函数分析请查阅作者相关博客.
封装函数故,在设置全局变量,以便在相应得函数能够更改变量值
- //全局变量
- int high, width; //游戏的画面大小
- int bird_x, bird_y; //小鸟的坐标
- int barl_y, barl_xDown, barl_xTop; //障碍物
- int score; //得分
-
system(“cls”)由于会导致图像闪烁所以我们使用了重绘画这一方法
- // 光标移到(X, Y)位置
- void gotoxy(int x, int y)
- {
- HANDLE handle = GetStdHandle(STD_OUTPUT_HANDLE);
- COORD pos;
- pos.X = x;
- pos.Y = y;
- SetConsoleCursorPosition(handle, pos);
- }
-
- //隐藏光标
- void HideCursor()
- {
- CONSOLE_CURSOR_INFO cursor_info = { 1,0 }; //第二个值为0,表示隐藏光标
- SetConsoleCursorInfo(GetStdHandle(STD_OUTPUT_HANDLE), &cursor_info);
- }
-
-
相应的数据可根据自己选择更改
- //数据的初始化
- void startup()
- {
- high = 15;
- width = 20;
- bird_x = 0;
- bird_y = width / 3;
- barl_y = width ;
- barl_xDown = high / 3;
- barl_xTop = width / 3;
- score = 0;
- }
-
-
- //显示画面
- void show()
- {
- gotoxy(0, 0);
- int i, j;
-
- for (i = 0; i <= high; i++)
- {
- for (j = 0; j <= width; j++)
- {
- if (i == bird_x && j == bird_y)
- printf("@"); //输出小鸟
- else if (i == high)
- printf("-");
- else if (j == width)
- printf("|");
- else if (j == barl_y && (i<barl_xDown || i>barl_xTop))
- printf("*"); //输出障碍物
- else
- printf(" "); //输出空格
- }
- printf("\n");
- }
- printf("得分:%d\n", score);
- }
-
比如图象中的障碍左移动,小鸟下坠,分数判断以及游戏是否能够继续
-
- //与用户无关的输出
- void updateWithoutInput()
- {
- bird_x++;
- barl_y--;
- if (bird_y == barl_y)
- {
- if (bird_x >= barl_xDown && bird_x <= barl_xTop)
- score++;
- else
- {
- printf("游戏失败\n");
- system("pause");
- exit(0);
- }
- }
- if (bird_x == high)
- {
- printf("游戏失败\n");
- system("pause");
- exit(0);
- }
- if (barl_y <= 0)
- {
- barl_y = width;
- int temp = rand() % (int)(high * 0.8);
- barl_xDown = temp - high / 10;
- barl_xTop = temp + high / 10;
- }
- Sleep(150);
- }
-
很明显在游戏中与用户有关的则是用户按下空格键,小鸟上升
- ///与用户输入有关的更行
- void updateWithInput()
- {
- char input;
- if (_kbhit())
- {
- input = _getch();
- if (bird_x > 1 && input == ' ')
- bird_x = bird_x - 2;
- }
- }
-
- int main()
- {
- HideCursor();//隐藏光标
- startup();
- while (1)
- {
- show();
- updateWithoutInput();
- updateWithInput();
- }
- return 0;
- }
-