AI-c++小游戏-坦克大战

#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;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值