编写飞机游戏devc++代码
时间: 2023-10-16 09:32:38 浏览: 69
以下是一个简单的飞机游戏的 Dev-C++ 代码示例:
```c++
#include <graphics.h>
#include <conio.h>
#include <stdio.h>
int main()
{
initwindow(640, 480, "Plane Game"); // 初始化窗口
setbkcolor(WHITE); // 设置背景色为白色
int planeX = 300, planeY = 400; // 飞机初始位置
int planeSpeed = 10; // 飞机移动速度
int score = 0; // 分数
while (1) {
if (kbhit()) { // 若有键盘输入
char key = getch();
if (key == 'a' && planeX > 0) { // 左移
planeX -= planeSpeed;
}
if (key == 'd' && planeX < getmaxx() - 80) { // 右移
planeX += planeSpeed;
}
}
cleardevice(); // 清空画布
// 画飞机
setfillstyle(SOLID_FILL, BLUE);
bar(planeX, planeY, planeX + 80, planeY + 50);
// 画敌机
static int enemyX = 0, enemyY = 0;
static int enemySpeed = 5;
if (enemyY > getmaxy()) { // 敌机已经飞出屏幕
enemyX = rand() % (getmaxx() - 80);
enemyY = -50;
score++; // 分数加一
}
setfillstyle(SOLID_FILL, RED);
bar(enemyX, enemyY, enemyX + 80, enemyY + 50);
enemyY += enemySpeed;
// 检测碰撞
if (planeX < enemyX + 80 && planeX + 80 > enemyX && planeY < enemyY + 50 && planeY + 50 > enemyY) {
outtextxy(250, 200, "Game Over!"); // 显示游戏结束
getch();
closegraph(); // 关闭窗口
return 0;
}
// 显示分数
char scoreStr[20];
sprintf(scoreStr, "Score: %d", score);
outtextxy(10, 10, scoreStr);
delay(30);
}
return 0;
}
```
这个代码实现了一个简单的飞机游戏,玩家通过键盘左右移动飞机躲避从上往下飞来的敌机,每躲避一个敌机得到一分,当飞机与敌机碰撞时游戏结束,最后会显示得分并等待玩家按下任意键退出游戏。