用c++实现一个火柴人的游戏
时间: 2024-03-21 14:39:00 浏览: 14
好的,下面是一个用C++实现的火柴人小游戏的示例代码:
```cpp
#include <iostream>
#include <conio.h>
#include <windows.h>
using namespace std;
const int width = 20;
const int height = 20;
int x, y; // 火柴人的初始位置
int obstacle_x, obstacle_y; // 障碍物的位置
bool gameOver;
void setup()
{
gameOver = false;
x = width / 2;
y = height / 2;
obstacle_x = rand() % width;
obstacle_y = rand() % height;
}
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 == obstacle_y && j == obstacle_x)
cout << "X"; // 障碍物
else
cout << " ";
if (j == width - 1)
cout << "#";
}
cout << endl;
}
for (int i = 0; i < width + 2; i++)
cout << "#";
cout << endl;
}
void input()
{
if (_kbhit())
{
switch (_getch())
{
case 'a':
x--;
break;
case 'd':
x++;
break;
case 'w':
y--;
break;
case 's':
y++;
break;
case 'x':
gameOver = true;
break;
}
}
}
void logic()
{
if (x < 0)
x = width - 1;
else if (x > width - 1)
x = 0;
if (y < 0)
y = height - 1;
else if (y > height - 1)
y = 0;
if (x == obstacle_x && y == obstacle_y)
{
obstacle_x = rand() % width;
obstacle_y = rand() % height;
}
}
int main()
{
setup();
while (!gameOver)
{
draw();
input();
logic();
Sleep(50); // 延迟50毫秒
}
return 0;
}
```
这是一个简单的控制台游戏,玩家可以使用字母键来控制火柴人的移动,避开障碍物。障碍物的位置是随机生成的。当火柴人碰到障碍物时,障碍物会重新生成。