#include <iostream>
#include <conio.h>
#include <windows.h>
#include <bits/stdc++.h>
using namespace std;
// 定义游戏窗口大小
const int width = 30;
const int height = 20;
// 定义游戏角色
class Player {
public:
int x, y; // 角色坐标
Player(int _x, int _y) : x(_x), y(_y) {}
void move(int dx, int dy) { // 移动角色
x += dx;
y += dy;
if (x < 0) x = 0;
if (x >= width) x = width - 1;
if (y < 0) y = 0;
if (y >= height) y = height - 1;
}
};
// 定义游戏障碍物
class Obstacle {
public:
int x, y; // 障碍物坐标
Obstacle(int _x, int _y) : x(_x), y(_y) {}
void move() { // 移动障碍物
x--;
if (x < 0) { // 障碍物到达左边界,重新生成
x = width - 1;
y = rand() % height;
}
}
};
int main() {
srand(time(NULL)); // 初始化随机数种子
Player player(width / 2, height / 2); // 初始化角色
Obstacle obstacle(width - 1, rand() % height); // 初始化障碍物
int score = 0; // 初始化得分
while (true) {
// 清空屏幕
system("cls");
// 绘制游戏界面
for (int i = 0; i < height; i++) {
for (int j = 0; j < width; j++) {
if (i == player.y && j == player.x) cout << "O"; // 绘制角色
else if (i == obstacle.y && j == obstacle.x)
{
cout<<"XXX"<<endl;
}
else if (i == obstacle.y && j == obstacle.x)
{
cout<<"XXX"<<endl;
}// 绘制障碍物
else cout << " ";
}
cout << endl;
}
// 显示得分
cout << "Score: " << score << endl;
// 处理用户输入
if (_kbhit()) { // 检测键盘输入
char c = _getch();
if (c == 'a') player.move(-1, 0); // 左移
if (c == 'd') player.move(1, 0); // 右移
if (c == 'w') player.move(0, -1); // 上移
if (c == 's') player.move(0, 1); // 下移
}
// 更新游戏状态
obstacle.move();
if (obstacle.x == player.x && obstacle.y == player.y) { // 角色与障碍物碰撞
cout << "Game Over!" << endl;
break;
}
score++; // 更新得分
}
return 0;
}