这个比之前发的两个还要简单,只是为了记录自己的学习内容
感兴趣的可以看看,编译器用的VS2019
有不懂的可以评论区留言,我看到了就会回复,不过我也是个菜鸡,不一定能解决你的问题
#include<stdio.h>
#include<windows.h>
#include<conio.h>
#include<time.h>
int height = 20; //界面尺寸
int width = 30;
int bird_x, bird_y; //小鸟坐标
int obstacle_x, obstacle_y1, obstacle_y2; //障碍物坐标
int flag; //游戏结束标志
int score; //游戏得分
void hideCursor() { //隐藏光标
CONSOLE_CURSOR_INFO cursor_info = { 1,0 };//第二个值表示隐藏光标
SetConsoleCursorInfo(GetStdHandle(STD_OUTPUT_HANDLE), &cursor_info);
}
void gotoxy(int x, int y) {//光标移动到(x,y)位置
HANDLE handle = GetStdHandle(STD_OUTPUT_HANDLE);
COORD pos;
pos.X = x;
pos.Y = y;
SetConsoleCursorPosition(handle, pos);
}
void start() { //初始化
bird_x = 7;
bird_y = 5;
obstacle_x = width;
obstacle_y1 = rand() % 14;
obstacle_y2 = obstacle_y1 + (rand() % 4 + 3);
flag = 0;
score = 0;
}
void show() { //展示界面
int i, j;
gotoxy(0, 0);
for (i = 0; i <= height; i++) {
for (j = 0; j <= width; j++) {
if (i == bird_y && j == bird_x)
printf("@");
else if (i == height)
printf("-");
else if (j == obstacle_x && (i <= obstacle_y1 || i >= obstacle_y2))
printf("*");
else
printf(" ");
}
printf("\n");
}
printf("得分:%d", score);
Sleep(150);
}
void WithInput() { //按键控制鸟上升
char input;
if (_kbhit()) {
input = _getch();
if (input == ' ') {
bird_y -= 2;
}
if (bird_y <= 0) //防止飞出界面
bird_y = 0;
}
}
void WithoutInput() {
if (bird_x == obstacle_x - 1 && (bird_y <= obstacle_y2 && bird_y >= obstacle_y1)) //鸟越过障碍物
score += 5;
if (bird_x == obstacle_x - 1 && (bird_y >= obstacle_y2 || bird_y <= obstacle_y1)) //鸟越撞到障碍物
flag = 1;
if (bird_y == height) //鸟越撞到底部
flag = 1;
bird_y++;
obstacle_x--;
if (obstacle_x == 1) { //重新生成障碍物
obstacle_x = width;
obstacle_y1 = rand() % 13;
obstacle_y2 = obstacle_y1 + (rand() % 4 + 3);
}
}
int main() {
system("color 0A");
srand((unsigned)time(NULL)); //随机种子
hideCursor();
start();
int k = 1;
while (1) {
if (k == 1) {
start();
k = 0;
}
else {
gotoxy(0, 0);
for (int i = 0; i < 10; i++) {
printf("\n");
}
printf("游戏结束,最终得分:%d(按任意键继续)", score);
_getch();
system("cls"); //清屏
start();
}
while (!flag) {
show();
WithoutInput();
WithInput();
}
}
return 0;
}