C++ 坦克大战游戏:WSAD 操控,空格键开火
#include
using namespace std;
const int WIDTH = 20; const int HEIGHT = 10;
struct Tank { int x; int y; char symbol; };
struct Bullet { int x; int y; bool active; };
Tank player; Tank enemy; Bullet bullet;
void DrawScreen() { system("cls");
for (int i = 0; i < HEIGHT; i++) {
for (int j = 0; j < WIDTH; j++) {
if (i == player.y && j == player.x) {
cout << player.symbol;
} else if (i == enemy.y && j == enemy.x) {
cout << enemy.symbol;
} else if (i == bullet.y && j == bullet.x && bullet.active) {
cout << "*";
} else {
cout << " ";
}
}
cout << endl;
}
}
void Initialize() { player.x = WIDTH / 2; player.y = HEIGHT - 1; player.symbol = '^';
enemy.x = WIDTH / 2;
enemy.y = 0;
enemy.symbol = 'v';
bullet.active = false;
}
void UpdatePlayer() { if (_kbhit()) { char key = _getch();
if (key == 'a' && player.x > 0) {
player.x--;
} else if (key == 'd' && player.x < WIDTH - 1) {
player.x++;
} else if (key == 'w' && player.y > 0) {
player.y--;
} else if (key == 's' && player.y < HEIGHT - 1) {
player.y++;
} else if (key == ' ' && !bullet.active) {
bullet.active = true;
bullet.x = player.x;
bullet.y = player.y - 1;
}
}
}
void UpdateEnemy() { if (bullet.active && bullet.y > 0) { bullet.y--; } else { bullet.active = false; }
if (enemy.y < HEIGHT - 1) {
enemy.y++;
} else {
enemy.y = 0;
enemy.x = rand() % WIDTH;
}
}
bool CheckCollision() { if (bullet.active && bullet.x == enemy.x && bullet.y == enemy.y) { bullet.active = false; return true; }
if (player.x == enemy.x && player.y == enemy.y) {
return true;
}
return false;
}
int main() { srand(time(NULL));
Initialize();
while (true) {
DrawScreen();
UpdatePlayer();
UpdateEnemy();
if (CheckCollision()) {
cout << "Game Over!" << endl;
break;
}
Sleep(100);
}
return 0;
}
原文地址: https://www.cveoy.top/t/topic/pCFD 著作权归作者所有。请勿转载和采集!