#include <iostream>
#include <conio.h>
#include <windows.h>
using namespace std;
const int width = 20;
const int height = 20;
bool gameOver;
int x, y; // 坦克的当前位置
int bulletX, bulletY; // 子弹的当前位置
int bulletDirection; // 子弹的方向(0:停止, 1:左, 2:右, 3:上, 4:下)
int enemyX, enemyY; // 敌人坦克的位置
int enemyDirection; // 敌人坦克的方向(1:左, 2:右, 3:上, 4:下)
int score;
void Setup() {
gameOver = false;
x = width / 2;
y = height - 1;
bulletX = -1;
bulletY = -1;
bulletDirection = 0;
enemyX = width / 2;
enemyY = 0;
enemyDirection = 4;
score = 0;
}
void Draw() {
system("cls");
for (int i = 0; i < width + 2; i++)
cout << "#";
cout << endl;
for (int i = 0; i < height; i++) {
for (int j = 0; j < width; j++) {
if (j == 0)
cout << "#";
if (i == y && j == x)
cout << "T";
else if (i == bulletY && j == bulletX)
cout << "-";
else if (i == enemyY && j == enemyX)
cout << "E";
else
cout << " ";
if (j == width - 1)
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':
x--;
break;
case 'd':
x++;
break;
case 'w':
y--;
break;
case 's':
y++;
break;
case ' ':
if (bulletX == -1 && bulletY == -1) {
bulletX = x;
bulletY = y - 1;
bulletDirection = 3;
}
break;
case 'x':
gameOver = true;
break;
}
}
}
void Logic() {
if (bulletX != -1 && bulletY != -1) {
switch (bulletDirection) {
case 1:
bulletX--;
break;
case 2:
bulletX++;
break;
case 3:
bulletY--;
break;
case 4:
bulletY++;
break;
}
}
if (bulletX < 0 || bulletX >= width || bulletY < 0 || bulletY >= height) {
bulletX = -1;
bulletY = -1;
bulletDirection = 0;
}
switch (enemyDirection) {
case 1:
if (enemyX > 0)
enemyX--;
else
enemyDirection = 2;
break;
case 2:
if (enemyX < width - 1)
enemyX++;
else
enemyDirection = 1;
break;
case 3:
if (enemyY > 0)
enemyY--;
else
enemyDirection = 4;
break;
case 4:
if (enemyY < height - 1)
enemyY++;
else
enemyDirection = 3;
break;
}
if (bulletX == enemyX && bulletY == enemyY) {
score += 10;
bulletX = -1;
bulletY = -1;
bulletDirection = 0;
enemyX = rand() % width;
enemyY = 0;
enemyDirection = 4;
}
if ((x == enemyX && y == enemyY) || (x == enemyX && y == enemyY + 1))
gameOver = true;
}
int main() {
Setup();
while (!gameOver) {
Draw();
Input();
Logic();
Sleep(50); // 控制游戏速度
}
cout << "Game Over!" << endl;
cout << "Final Score: " << score << endl;
return 0;
}
AI-c++小游戏-坦克大战
于 2024-10-10 23:08:00 首次发布