c++飞机大战游戏代码
时间: 2024-03-29 11:32:59 浏览: 104
飞机大战游戏代码c++
5星 · 资源好评率100%
C++飞机大战游戏是一款经典的2D射击游戏,玩家操控飞机进行战斗。下面是一个简单的C++飞机大战游戏代码示例:
```cpp
#include <iostream>
#include <conio.h>
#include <windows.h>
using namespace std;
bool gameOver;
const int width = 20;
const int height = 20;
int x, y; // 飞机的坐标
int fruitX, fruitY; // 敌机的坐标
int score; // 得分
enum eDirection { STOP = 0, LEFT, RIGHT, UP, DOWN };
eDirection dir;
void Setup()
{
gameOver = false;
dir = STOP;
x = width / 2;
y = height / 2;
fruitX = rand() % width;
fruitY = rand() % height;
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 << "O";
else if (i == fruitY && j == fruitX)
cout << "F";
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':
dir = LEFT;
break;
case 'd':
dir = RIGHT;
break;
case 'w':
dir = UP;
break;
case 's':
dir = DOWN;
break;
case 'x':
gameOver = true;
break;
}
}
}
void Logic()
{
switch (dir)
{
case LEFT:
x--;
break;
case RIGHT:
x++;
break;
case UP:
y--;
break;
case DOWN:
y++;
break;
default:
break;
}
if (x >= width)
x = 0;
else if (x < 0)
x = width - 1;
if (y >= height)
y = 0;
else if (y < 0)
y = height - 1;
if (x == fruitX && y == fruitY)
{
score += 10;
fruitX = rand() % width;
fruitY = rand() % height;
}
}
int main()
{
Setup();
while (!gameOver)
{
Draw();
Input();
Logic();
// 控制游戏速度
Sleep(10);
}
return 0;
}
```
这是一个简单的飞机大战游戏代码示例,玩家可以通过键盘控制飞机的移动,吃到敌机可以得分。游戏会根据玩家的操作进行刷新,并且控制游戏的速度。你可以根据自己的需求进行修改和扩展。
阅读全文