#include <bits/stdc++.h>
#include <conio.h> // 包含 getch() 函数
#include <unistd.h> // 包含 sleep() 函数
using namespace std;
int main() {
char a[50][50] = {
"####################",
"#o # s ### ###s#",
"# ## -$ ### #",
"# # ##s ##$# ## #",
"## # ######### ## ##",
"## ####### # ##",
"####################"
};
int i, x, y, s = 0, tim = 0;
char ch;
int gameRunning = 1; // 添加一个标志变量来控制游戏循环
// 初始化玩家位置
x = 1, y = 1;
int xc = 2, yc = 8;
bool moveLeft = true; // 控制敌人移动方向的标志
// 打印初始迷宫
for (i = 0; i <= 6; i++) {
cout << a[i] << endl;
}
// 游戏主循环
while (s < 3) {
// 检测玩家输入
if (_kbhit()) {
ch = _getch(); // 获取用户输入
// 根据用户输入移动玩家
switch (ch) {
case 's':
case 'S':
if (a[x + 1][y] == 's') {
s++; // 设置标志变量为 0,退出循环
}
if (a[x + 1][y] != '#') {
a[x][y] = ' ';
x++;
a[x][y] = 'o';
}
break;
case 'w':
case 'W':
if (a[x - 1][y] == 's') {
s++; // 设置标志变量为 0,退出循环
}
if (a[x - 1][y] != '#') {
a[x][y] = ' ';
x--;
a[x][y] = 'o';
}
break;
case 'a':
case 'A':
if (a[x][y - 1] == 's') {
s++; // 设置标志变量为 0,退出循环
}
if (a[x][y - 1] != '#') {
a[x][y] = ' ';
y--;
a[x][y] = 'o';
}
break;
case 'd':
case 'D':
if (a[x][y + 1] == 's') {
s++; // 设置标志变量为 0,退出循环
}
if (a[x][y + 1] != '#') {
a[x][y] = ' ';
y++;
a[x][y] = 'o';
}
break;
}
}
// 移动敌人
if(tim == 25) {
tim = 0;
if (moveLeft) {
if (a[xc][yc - 1] != '#' && a[xc][yc - 1] != '$') {
a[xc][yc] = ' ';
yc--;
a[xc][yc] = '-';
}
else {
moveLeft = false;
}
}
else {
if (a[xc][yc + 1] != '#' && a[xc][yc + 1] != '$') {
a[xc][yc] = ' ';
yc++;
a[xc][yc] = '-';
} else {
moveLeft = true;
}
}
}
// 检查玩家是否与敌人碰撞
if (a[x][y] == a[xc][yc]) {
cout << "You lose" << endl;
return 0;
}
// 清屏并重新打印迷宫
system("cls");
for (i = 0; i <= 6; i++) {
cout << a[i] << endl;
}
cout << "当请金币数:" << s << "\3";
// 等待5秒
sleep(0.5);
tim ++;
}
cout << "当请金币数:" << s << "\3";
system("cls");
cout << "You win!" << endl;
sleep(5); // 等待5秒后退出
return 0;
}