用c++帮我写个2d射击游戏
以下是一个简单的C++ 2D射击游戏的示例代码:
#include <iostream>
#include <conio.h>
#include <Windows.h>
using namespace std;
const int WIDTH = 20;
const int HEIGHT = 20;
int playerX, playerY;
int bulletX, bulletY;
int enemyX, enemyY;
bool isBulletActive;
void Setup()
{
playerX = WIDTH / 2;
playerY = HEIGHT - 1;
bulletX = playerX;
bulletY = playerY;
enemyX = rand() % WIDTH;
enemyY = 0;
isBulletActive = false;
}
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 == playerY && j == playerX)
cout << "P";
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;
}
void Input()
{
if (_kbhit())
{
switch (_getch())
{
case 'a':
playerX--;
break;
case 'd':
playerX++;
break;
case ' ':
if (!isBulletActive)
{
isBulletActive = true;
bulletX = playerX;
bulletY = playerY;
}
break;
case 'x':
exit(0);
break;
}
}
}
void Logic()
{
if (isBulletActive)
{
bulletY--;
if (bulletY < 0)
isBulletActive = false;
}
enemyY++;
if (enemyY >= HEIGHT)
{
enemyX = rand() % WIDTH;
enemyY = 0;
}
if (bulletX == enemyX && bulletY == enemyY)
{
isBulletActive = false;
enemyX = rand() % WIDTH;
enemyY = 0;
}
if (playerX < 0)
playerX = 0;
else if (playerX >= WIDTH)
playerX = WIDTH - 1;
}
int main()
{
Setup();
while (true)
{
Draw();
Input();
Logic();
Sleep(50); // 控制游戏速度
}
return 0;
}
这是一个简单的2D射击游戏,玩家通过键盘上的字母'a'和'd'控制玩家的水平移动,按空格键发射子弹。游戏中有一个敌人,玩家需要射击敌人以获得得分。敌人每次到达屏幕底部后会重新生成在屏幕顶部
原文地址: https://www.cveoy.top/t/topic/ir1x 著作权归作者所有。请勿转载和采集!