#include <iostream>
#include <conio.h>
#include <windows.h>
using namespace std;
const int WIDTH = 20;
const int HEIGHT = 20;
bool gameOver;
int tankX, tankY;
int enemyX, enemyY;
int bulletX, bulletY;
int score;
enum Direction { STOP = 0, LEFT, RIGHT, UP, DOWN };
Direction dir;
void Setup() {
gameOver = false;
dir = STOP;
tankX = WIDTH / 2;
tankY = HEIGHT - 1;
enemyX = WIDTH / 2;
enemyY = 0;
bulletX = -1;
bulletY = -1;
score = 0;
}
void Draw() {
system("cls");
// 绘制顶部边框
for (int i = 0; i < WIDTH + 2; i++) {
cout << "#";
}
cout << endl;
// 绘制游戏区域
for (int y = 0; y < HEIGHT; y++) {
for (int x = 0; x < WIDTH; x++) {
if (x == 0 || x == WIDTH - 1) {
cout << "#"; // 绘制左右边框
} else if (y == tankY && x == tankX) {
cout << "@"; // 绘制坦克
} else if (y == enemyY && x == enemyX) {
cout << "*"; // 绘制敌人坦克
} else if (y == bulletY && x == bulletX) {
cout << "|"; // 绘制子弹
} else {
cout << " ";
}
}
cout << endl;
}
// 绘制底部边框
for (int i = 0; i < WIDTH + 2; i++) {
cout << "#";
}
cout << endl;
cout << "Score: " << score << endl;
}
void Input() {
if (_kbhit()) {
switch (_getch()) {
case 'a':
dir = LEFT;
break;
case 'd':
dir = RIGHT;
break;
case 'w':
dir = UP;
break;
case 's':
dir = DOWN;
break;
case ' ':
bulletX = tankX;
bulletY = tankY - 1;
break;
case 'x':
gameOver = true;
break;
}
}
}
void Logic() {
switch (dir) {
case LEFT:
tankX--;
break;
case RIGHT:
tankX++;
break;
case UP:
tankY--;
break;
case DOWN:
tankY++;
break;
}
if (bulletY >= 0) {
bulletY--;
}
if (tankX < 0) {
tankX = 0;
}
if (tankX >= WIDTH) {
tankX = WIDTH - 1;
}
if (tankY < 0) {
tankY = 0;
}
if (tankY >= HEIGHT) {
tankY = HEIGHT - 1;
}
if (bulletY == enemyY && bulletX == enemyX) {
score++;
bulletY = -1;
bulletX = -1;
enemyY = 0;
enemyX = rand() % WIDTH;
}
if (tankY == enemyY && tankX == enemyX) {
gameOver = true;
}
}
void GameLoop() {
while (!gameOver) {
Draw();
Input();
Logic();
Sleep(50); // 控制游戏速度
}
}
int main() {
Setup();
GameLoop();
return 0;
}
坦克大战2.0
最新推荐文章于 2024-09-27 11:26:03 发布