以下是一个简单的地铁跑酷的C++代码,基于控制台:
#include <iostream>
#include <conio.h>
#include <ctime>
#include <windows.h>
using namespace std;
// 地铁跑酷游戏
int main()
{
const int width = 20; // 游戏区域宽度
const int height = 20; // 游戏区域高度
const int playerX = 2; // 初始玩家位置
const int playerY = height - 2;
const char playerChar = '^'; // 玩家表示字符
const char obstacleChar = '='; // 障碍物表示字符
const int obstacleChance = 30; // 障碍物出现几率,百分比
const int obstacleSpeed = 100; // 障碍物移动速度,毫秒
const int scoreWeight = 10; // 得分权重
const int maxObstacles = 5; // 最大障碍物数量
const int jumpHeight = 3; // 跳跃高度
int score = 0; // 得分
bool isJumping = false; // 是否跳跃
int jumpCount = 0; // 跳跃计数器
int jumpHeightCount = 0; // 跳跃高度计数器
int playerPosX = playerX; // 玩家当前位置
int playerPosY = playerY;
srand(time(NULL)); // 初始化随机数种子
// 游戏主循环
while (true)
{
// 生成新障碍物
if (rand() % 100 < obstacleChance)
{
int obstacleCount = 0;
for (int i = 1; i < width - 1; i++)
{
if (rand() % 100 < obstacleChance && obstacleCount < maxObstacles)
{
cout << obstacleChar;
obstacleCount++;
}
else
{
cout << " ";
}
}
}
else
{
cout << string(width - 2, ' ');
}
// 更新玩家位置
if (isJumping)
{
if (jumpCount < jumpHeight)
{
jumpCount++;
playerPosY--;
}
else if (jumpHeightCount < jumpHeight)
{
jumpHeightCount++;
playerPosY++;
}
else
{
isJumping = false;
jumpCount = 0;
jumpHeightCount = 0;
}
}
// 输出玩家位置和得分
cout << endl;
for (int i = 0; i < playerPosY; i++)
{
cout << endl;
}
cout << string(playerPosX, ' ') << playerChar << endl;
for (int i = playerPosY + 1; i < height - 1; i++)
{
cout << endl;
}
cout << "Score: " << score << endl;
// 判断是否撞到障碍物
if (playerPosY == height - 3)
{
for (int i = 0; i < width - 2; i++)
{
if (i != playerPosX - 1 && i != playerPosX && i != playerPosX + 1 && cin.get() == obstacleChar)
{
cout << "Game Over!" << endl;
cout << "Your Score: " << score << endl;
return 0;
}
}
score += scoreWeight;
}
Sleep(obstacleSpeed); // 暂停一段时间
system("cls"); // 清屏
}
return 0;
}
代码解析:
首先定义了一些常量,包括游戏区域大小、玩家和障碍物的表示字符、障碍物的出现几率和移动速度等等。
在主循环中,首先判断是否需要生成新的障碍物,如果需要,则随机生成一些障碍物,并输出到控制台上;否则,输出一行空格。
然后根据玩家位置和是否跳跃,输出玩家的位置和得分。
接着判断玩家是否撞到了障碍物。如果撞到了,就输出游戏结束并显示得分,并退出程序。否则,增加得分。
最后暂停一段时间,清屏,再次进入主循环。
在主循环中,还有一些逻辑判断,如玩家是否跳跃、跳跃高度等等。
注意:本代码仅用于学习交流,实际游戏需求可能会更加复杂。