用c++编写打飞机小游戏
时间: 2023-08-20 09:07:17 浏览: 96
好的,以下是一个简单的打飞机小游戏的 C++ 代码:
```cpp
#include <iostream>
#include <conio.h>
#include <windows.h>
using namespace std;
const int width = 30;
const int height = 20;
int x, y;
int enemyX, enemyY;
int score = 0;
bool gameOver;
void Setup()
{
gameOver = false;
x = width / 2;
y = height - 1;
enemyX = rand() % width;
enemyY = 0;
score = 0;
}
void Draw()
{
system("cls");
for (int i = 0; i < width + 2; i++)
cout << "#";
cout << endl;
for (int i = 0; i < height; i++)
{
for (int j = 0; j < width; j++)
{
if (j == 0)
cout << "#";
if (i == y && j == x)
cout << "A";
else if (i == enemyY && j == enemyX)
cout << "X";
else
cout << " ";
if (j == width - 1)
cout << "#";
}
cout << endl;
}
for (int i = 0; i < width + 2; i++)
cout << "#";
cout << endl;
cout << "Score: " << score << endl;
}
void Input()
{
if (_kbhit())
{
switch (_getch())
{
case 'a':
x--;
break;
case 'd':
x++;
break;
case 'q':
gameOver = true;
break;
}
}
}
void Logic()
{
enemyY++;
if (enemyY == y && enemyX == x)
{
score++;
enemyY = 0;
enemyX = rand() % width;
}
if (enemyY == height - 1)
{
gameOver = true;
}
}
int main()
{
Setup();
while (!gameOver)
{
Draw();
Input();
Logic();
Sleep(50);
}
cout << "Game Over!" << endl;
return 0;
}
```
这个小游戏中,你需要控制字母 "A" 移动左右来躲避从上往下掉落的字母 "X",并且尽可能多地吃到它们来获得分数。你可以使用 "a" 和 "d" 键控制 "A" 字母左右移动,按 "q" 键退出游戏。游戏结束条件为 "X" 字母掉落到屏幕底部或者你主动退出游戏。
阅读全文