C++ 控制台马里奥游戏:简单示例代码

以下是一个简单的 C++ 马里奥游戏的示例代码:

#include <iostream>
#include <string>

using namespace std;

const int WIDTH = 20;
const int HEIGHT = 10;

class MarioGame {
private:
    int playerX;
    int playerY;
    string board[HEIGHT][WIDTH];

public:
    MarioGame() {
        playerX = 0;
        playerY = HEIGHT - 1;

        for (int i = 0; i < HEIGHT; i++) {
            for (int j = 0; j < WIDTH; j++) {
                board[i][j] = "-";
            }
        }

        board[playerY][playerX] = "M";
    }

    void printBoard() {
        for (int i = 0; i < HEIGHT; i++) {
            for (int j = 0; j < WIDTH; j++) {
                cout << board[i][j];
            }
            cout << endl;
        }
    }

    void movePlayerLeft() {
        if (playerX > 0) {
            board[playerY][playerX] = "-";
            playerX--;
            board[playerY][playerX] = "M";
        }
    }

    void movePlayerRight() {
        if (playerX < WIDTH - 1) {
            board[playerY][playerX] = "-";
            playerX++;
            board[playerY][playerX] = "M";
        }
    }

    void jumpPlayer() {
        if (playerY > 0) {
            board[playerY][playerX] = "-";
            playerY--;
            board[playerY][playerX] = "M";
        }
    }
};

int main() {
    MarioGame game;

    game.printBoard();

    while (true) {
        string input;
        cout << "Enter your move (left, right, jump): ";
        cin >> input;

        if (input == "left") {
            game.movePlayerLeft();
        } else if (input == "right") {
            game.movePlayerRight();
        } else if (input == "jump") {
            game.jumpPlayer();
        } else {
            cout << "Invalid move!" << endl;
        }

        game.printBoard();
    }

    return 0;
}

这个示例代码实现了一个简单的控制台版马里奥游戏。玩家可以使用 'left'、'right' 和 'jump' 命令来控制马里奥的移动。游戏板由 '-' 字符表示空格,'M' 字符表示马里奥的位置。玩家可以通过输入命令来移动马里奥,并在控制台上打印出更新后的游戏板。循环将一直进行,直到玩家输入无效的移动命令为止。

C++ 控制台马里奥游戏:简单示例代码

原文地址: https://www.cveoy.top/t/topic/pQQm 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录