以下是使用C++17编写的一个简单的跑酷小游戏示例:

#include <iostream>
#include <conio.h>
#include <chrono>
#include <thread>

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

class Game {
private:
    int playerX;
    int playerY;
    int obstacleX;
    int obstacleY;
    int score;

public:
    Game() : playerX(WIDTH / 2), playerY(HEIGHT - 1), obstacleX(WIDTH - 1), obstacleY(HEIGHT - 1), score(0) {}

    void draw() {
        system("cls");
        for (int y = 0; y < HEIGHT; y++) {
            for (int x = 0; x < WIDTH; x++) {
                if (x == playerX && y == playerY) {
                    std::cout << "P";
                }
                else if (x == obstacleX && y == obstacleY) {
                    std::cout << "O";
                }
                else {
                    std::cout << ".";
                }
            }
            std::cout << std::endl;
        }
        std::cout << "Score: " << score << std::endl;
    }

    void update() {
        if (kbhit()) {
            char key = getch();
            if (key == 'a' && playerX > 0) {
                playerX--;
            }
            else if (key == 'd' && playerX < WIDTH - 1) {
                playerX++;
            }
        }

        if (obstacleX > 0) {
            obstacleX--;
        }
        else {
            obstacleX = WIDTH - 1;
            obstacleY = rand() % HEIGHT;
            score++;
        }
    }

    bool isGameOver() {
        return (playerX == obstacleX && playerY == obstacleY);
    }
};

int main() {
    Game game;

    while (!game.isGameOver()) {
        game.draw();
        game.update();
        std::this_thread::sleep_for(std::chrono::milliseconds(100));
    }

    std::cout << "Game Over!" << std::endl;
    std::cout << "Final Score: " << game.getScore() << std::endl;

    return 0;
}

这个小游戏中,玩家通过按下键盘上的左右箭头来控制一个字母"P"在屏幕上左右移动,避开障碍物字母"O"。随着时间的推移,障碍物会不断从右向左移动,玩家需要适时地移动以躲避障碍物。每当障碍物穿过屏幕最左侧时,玩家的得分就会增加。当玩家与障碍物相撞时,游戏结束,最终得分将显示在屏幕上。

请注意,这只是一个简单的示例,可能还需要进一步的改进和优化

用c++17做一个跑酷小游戏

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

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