c++横板过关游戏代码
时间: 2023-09-26 15:08:00 浏览: 58
以下是一个简单的横板过关游戏的 C++ 代码示例,仅供参考:
```cpp
#include <iostream>
#include <conio.h> // 用于控制台输入输出
#include <windows.h> // 用于控制台窗口操作
using namespace std;
const int WIDTH = 40; // 游戏窗口宽度
const int HEIGHT = 20; // 游戏窗口高度
const int block_width = 5; // 每个方块的宽度
const int block_height = 3; // 每个方块的高度
const int num_blocks = 4; // 方块数量
// 方块的结构体
struct Block {
int x, y; // 方块的位置
int width, height; // 方块的宽度和高度
};
// 玩家的结构体
struct Player {
int x, y; // 玩家的位置
int width, height; // 玩家的宽度和高度
int speed; // 玩家的速度
};
int main() {
// 设置控制台窗口大小
HANDLE console = GetStdHandle(STD_OUTPUT_HANDLE);
SMALL_RECT windowSize = {0, 0, WIDTH, HEIGHT};
SetConsoleWindowInfo(console, TRUE, &windowSize);
// 隐藏控制台光标
CONSOLE_CURSOR_INFO cursorInfo;
cursorInfo.dwSize = 1;
cursorInfo.bVisible = false;
SetConsoleCursorInfo(console, &cursorInfo);
// 初始化玩家和方块
Player player = {2, HEIGHT - 3, 3, 3, 1};
Block blocks[num_blocks] = {
{WIDTH - 10, HEIGHT - block_height, block_width, block_height},
{WIDTH - 20, HEIGHT - block_height * 2, block_width, block_height},
{WIDTH - 30, HEIGHT - block_height, block_width, block_height},
{WIDTH - 40, HEIGHT - block_height * 2, block_width, block_height}
};
// 游戏主循环
while (true) {
// 清空控制台
system("cls");
// 绘制玩家
for (int i = 0; i < player.width; i++) {
for (int j = 0; j < player.height; j++) {
cout << "O";
}
cout << endl;
}
// 绘制方块
for (int i = 0; i < num_blocks; i++) {
for (int j = 0; j < blocks[i].width; j++) {
for (int k = 0; k < blocks[i].height; k++) {
cout << "#";
}
cout << endl;
}
}
// 接收玩家输入
if (_kbhit()) {
char input = _getch();
if (input == 'a') {
player.x -= player.speed;
} else if (input == 'd') {
player.x += player.speed;
}
}
// 更新玩家位置
if (player.x < 0) {
player.x = 0;
} else if (player.x + player.width > WIDTH) {
player.x = WIDTH - player.width;
}
// 检测碰撞
for (int i = 0; i < num_blocks; i++) {
if (player.x + player.width > blocks[i].x && player.x < blocks[i].x + blocks[i].width &&
player.y + player.height > blocks[i].y && player.y < blocks[i].y + blocks[i].height) {
cout << "Game over!" << endl;
return 0;
}
}
// 检测胜利
bool win = true;
for (int i = 0; i < num_blocks; i++) {
if (blocks[i].x > 0) {
win = false;
break;
}
}
if (win) {
cout << "You win!" << endl;
return 0;
}
// 更新方块位置
for (int i = 0; i < num_blocks; i++) {
blocks[i].x--;
}
// 延时
Sleep(50);
}
return 0;
}
```
这个示例代码中,游戏主要包含玩家和方块两个元素,玩家可以通过输入左右键移动,方块随时间向左移动,当玩家碰到方块时游戏结束,当所有方块都移除屏幕时玩家获胜。