给我用c++511写wsad和 操控的人机坦克大战游戏
下面是一个使用C++编写的简单的人机坦克大战游戏,玩家可以使用WSAD键控制坦克移动,空格键用于开火。
#include <iostream>
#include <conio.h>
#include <windows.h>
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/hTDk 著作权归作者所有。请勿转载和采集!