c++游戏(躲避障碍)

#include <iostream>
#include <conio.h>
#include <windows.h>
#include <bits/stdc++.h>
using namespace std;

// 定义游戏窗口大小
const int width = 30;
const int height = 20;

// 定义游戏角色
class Player {
public:
    int x, y; // 角色坐标
    Player(int _x, int _y) : x(_x), y(_y) {}
    void move(int dx, int dy) { // 移动角色
        x += dx;
        y += dy;
        if (x < 0) x = 0;
        if (x >= width) x = width - 1;
        if (y < 0) y = 0;
        if (y >= height) y = height - 1;
    }
};

// 定义游戏障碍物
class Obstacle {
public:
    int x, y; // 障碍物坐标
    Obstacle(int _x, int _y) : x(_x), y(_y) {}
    void move() { // 移动障碍物
        x--;
        if (x < 0) { // 障碍物到达左边界,重新生成
            x = width - 1;
            y = rand() % height;
        }
    }
};

int main() {
    srand(time(NULL)); // 初始化随机数种子
    Player player(width / 2, height / 2); // 初始化角色
    Obstacle obstacle(width - 1, rand() % height); // 初始化障碍物
    int score = 0; // 初始化得分
    while (true) {
        // 清空屏幕
        system("cls");
        // 绘制游戏界面
        for (int i = 0; i < height; i++) {
            for (int j = 0; j < width; j++) {
                if (i == player.y && j == player.x) cout << "O"; // 绘制角色
                else if (i == obstacle.y && j == obstacle.x)
                {
                    cout<<"XXX"<<endl;
                } 
                else if (i == obstacle.y && j == obstacle.x)
                {
                    cout<<"XXX"<<endl;
                }// 绘制障碍物
                else cout << " ";
            }
            cout << endl;
        }
        // 显示得分
        cout << "Score: " << score << endl;
        // 处理用户输入
        if (_kbhit()) { // 检测键盘输入
            char c = _getch();
            if (c == 'a') player.move(-1, 0); // 左移
            if (c == 'd') player.move(1, 0); // 右移
            if (c == 'w') player.move(0, -1); // 上移
            if (c == 's') player.move(0, 1); // 下移
        }
        // 更新游戏状态
        obstacle.move();
        if (obstacle.x == player.x && obstacle.y == player.y) { // 角色与障碍物碰撞
            cout << "Game Over!" << endl;
            break;
        }
        score++; // 更新得分
    }
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值