编辑代码


#include <windows.h>
#include<iostream>
using namespace std;

class SubwayRun {
private:
    int subwayWidth;    //地铁宽度
    int time;       //游戏时间
    int score;      //分数

public:
    SubwayRun(int w) {   //类构造函数,初始化变量
        subwayWidth = w;
        time = 0;
        score = 0;
    }

    void startGame() {    //游戏开始
        int x = subwayWidth / 2 - 1;  //定义起始位置

        char ch, key;
        int y = 0;
        while (true) {
            for (int i = 0; i < subwayWidth; i++) {
                if (i == x) cout << 'O';
                else cout << '-';
            }
            cout << "  Score:" << score << endl;

            ch = ' '; key = ' ';

            if (kbhit()) {
                ch = getch();
                if (ch == '\r') ch = getch();
                key = ch;
            }

            switch (key) {
            case 'a': x--; break;
            case 'd': x++; break;
            default: break;
            }


            //把每一行的障碍物打印出来
            if (time % 2 == 0) {
                int randNum = rand() % 4;
                for (int i = 0; i < subwayWidth; i++) {
                    if (i == randNum || i == randNum + 1 || i == randNum + 2)
                        cout << 'X';
                    else
                        cout << '-';
                }
                y = 0;       //把y重新设为0
            }
            else {
                for (int i = 0; i < subwayWidth; i++) {
                    cout << '-';
                }
                y += 2;     //y增加2
            }

            cout << endl;

            //检测撞到障碍物游戏结束
            if (x == randNum || x == randNum + 1 || x == randNum + 2) {
                system("cls");  //清屏
                cout << "Game Over!Your score is:" << score << endl;
                break;
            }

            if (y >= 8) {  //每过8行,加10分
                y = 0;
                score += 10;
            }

            time++;
        }
    }

};
 
int main()
{
    SubWayRun sw(8);    //创建一个 SubWayRun 对象,地铁宽度为 8
	sw.startGame();     //开始游戏
	return 0;
}