做小鸟游戏的代码,要求用c语言写出。每用鼠标点击一次,小鸟就会弹跳一次,并躲避障碍物。
时间: 2024-03-25 18:38:48 浏览: 8
好的,以下是一个基于C语言的小鸟游戏代码示例,实现了小鸟跳跃和障碍物的自动生成和移动:
```
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
#include <time.h>
#include <windows.h>
#define WIDTH 60
#define HEIGHT 20
#define BIRD '@'
#define OBSTACLE '#'
#define BLANK ' '
int bird_x, bird_y, score;
int obstacle_x, obstacle_y;
void draw_bird() {
printf("\033[%d;%dH%c", bird_y, bird_x, BIRD);
}
void clear_bird() {
printf("\033[%d;%dH%c", bird_y, bird_x, BLANK);
}
void draw_obstacle() {
printf("\033[%d;%dH%c", obstacle_y, obstacle_x, OBSTACLE);
}
void clear_obstacle() {
printf("\033[%d;%dH%c", obstacle_y, obstacle_x, BLANK);
}
void update_score() {
printf("\033[%d;%dHScore: %d", HEIGHT + 1, 1, score);
}
void generate_obstacle() {
obstacle_x = WIDTH;
obstacle_y = rand() % HEIGHT + 1;
}
void update_obstacle() {
clear_obstacle();
obstacle_x--;
if (obstacle_x == bird_x) {
score++;
update_score();
}
if (obstacle_x == 0) {
generate_obstacle();
}
draw_obstacle();
}
void jump() {
clear_bird();
bird_y--;
if (bird_y == 0) {
bird_y = 1;
}
draw_bird();
}
void game_over() {
printf("\033[%d;%dHGame Over!", HEIGHT / 2, WIDTH / 2 - 5);
exit(0);
}
int main() {
srand(time(NULL));
bird_x = 10;
bird_y = HEIGHT / 2;
score = 0;
generate_obstacle();
update_score();
while (1) {
if (_kbhit()) {
_getch();
jump();
}
update_obstacle();
if (obstacle_x == bird_x && obstacle_y == bird_y) {
game_over();
}
Sleep(50);
}
return 0;
}
```
以上代码实现了基本的小鸟游戏,可以在控制台中运行。游戏中,小鸟的位置用 `bird_x` 和 `bird_y` 表示,用 `draw_bird()` 和 `clear_bird()` 函数来绘制和清除小鸟;障碍物的位置用 `obstacle_x` 和 `obstacle_y` 表示,用 `draw_obstacle()` 和 `clear_obstacle()` 函数来绘制和清除障碍物;分数用 `score` 变量表示,用 `update_score()` 函数来更新分数显示;`generate_obstacle()` 函数用于随机生成障碍物,`update_obstacle()` 函数用于更新障碍物位置和判断得分;`jump()` 函数用于让小鸟跳跃;`game_over()` 函数用于游戏结束时输出提示并退出程序。