- 小书童——凯撒密码
H
- 2025-5-4 19:31:01 @
#include #include <windows.h> #include <conio.h> #include #include #include
// 定义火柴人结构体 struct Stickman { int x; int y; int health; int color; Stickman(int _x, int _y, int _health, int _color) : x(_x), y(_y), health(_health), color(_color) {} };
// 移动光标到指定位置 void gotoxy(int x, int y) { COORD coord; coord.X = x; coord.Y = y; SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), coord); }
// 设置文本颜色 void setColor(int color) { SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), color); }
// 绘制火柴人 void drawStickman(const Stickman& stickman) { gotoxy(stickman.x, stickman.y); setColor(stickman.color); std::cout << "A"; gotoxy(0, 0); setColor(7); }
// 清除火柴人 void clearStickman(const Stickman& stickman) { gotoxy(stickman.x, stickman.y); std::cout << " "; gotoxy(0, 0); }
// 移动火柴人 void moveStickman(Stickman& stickman, int dx, int dy) { clearStickman(stickman); stickman.x += dx; stickman.y += dy; drawStickman(stickman); }
// 攻击判定 void attack(Stickman& attacker, Stickman& target) { if (abs(attacker.x - target.x) <= 1 && abs(attacker.y - target.y) <= 1) { target.health -= 10; if (target.health < 0) { target.health = 0; } } }
// 显示生命值 void showHealth(const Stickman& stickman, int num) { gotoxy(0, num); std::cout << "Stickman " << num + 1 << " Health: " << stickman.health; }
// 电脑控制火柴人移动和攻击 void computerControl(Stickman& computerStickman, Stickman& playerStickman) { int dx = 0, dy = 0; if (computerStickman.x < playerStickman.x) { dx = 1; } else if (computerStickman.x > playerStickman.x) { dx = -1; } if (computerStickman.y < playerStickman.y) { dy = 1; } else if (computerStickman.y > playerStickman.y) { dy = -1; }
// 有一定概率随机移动
if (rand() % 3 == 0) {
dx = rand() % 3 - 1;
dy = rand() % 3 - 1;
}
moveStickman(computerStickman, dx, dy);
// 尝试攻击
attack(computerStickman, playerStickman);
showHealth(playerStickman, 0);
}
int main() { srand(time(NULL)); system("mode con cols=80 lines=25"); system("title Stickman War");
Stickman stickman1(10, 10, 100, 9);
Stickman stickman2(60, 10, 100, 12);
drawStickman(stickman1);
drawStickman(stickman2);
showHealth(stickman1, 0);
showHealth(stickman2, 1);
while (stickman1.health > 0 && stickman2.health > 0) {
if (_kbhit()) {
char key = _getch();
switch (key) {
case 'w':
moveStickman(stickman1, 0, -1);
break;
case 's':
moveStickman(stickman1, 0, 1);
break;
case 'a':
moveStickman(stickman1, -1, 0);
break;
case 'd':
moveStickman(stickman1, 1, 0);
break;
case ' ':
attack(stickman1, stickman2);
showHealth(stickman2, 1);
break;
}
}
// 电脑控制的火柴人行动
computerControl(stickman2, stickman1);
}
if (stickman1.health > 0) {
std::cout << "Stickman 1 wins!" << std::endl;
} else {
std::cout << "Stickman 2 wins!" << std::endl;
}
return 0;
}
0 条评论
信息
- ID
- 1976
- 时间
- 1000ms
- 内存
- 256MiB
- 难度
- 5
- 标签
- 递交数
- 64
- 已通过
- 25
- 上传者