使用 C++ 实现游戏机排队系统:模拟多人游戏排队机制

本文将使用 C++ 语言实现一个游戏机排队系统,模拟多人游戏排队的机制。

问题描述:

机厅里有一台游戏机,每次可供最多两人同时游玩。但是来玩的人显然不止两个!这个时候他们就需要排队了,而你需要写一个程序维护这个队列,并在他人游玩结束后通知接下来上场的人。在整个过程中,有以下几种事件可能发生:

  • start: 一局游戏开始。若这不是第一局游戏,则上一局的参与者按照原本的顺序回到队尾。此时你应该按在队列中的顺序输出这一局上场的人的名字(正常来讲是队列前两位或者唯一一个人),若有两个则以空格分割。若这一局无人上场,则输出 'Error' 并忽略这条事件。
  • arrive x: x 到达机厅并且将自己加入队尾,此时 x 不应该在排队,否则输出 'Error' 并忽略这条事件。若该事件成功执行则输出 'OK'。
  • leave x: x 离开机厅并离开队列。此时 x 应该在排队但不应该在游玩,否则输出 'Error' 并忽略这条事件。若该事件成功执行则输出 'OK'。

你需要维护队列信息,并输出上述事件中要求的输出。

代码实现:

#include <iostream>
#include <queue>
#include <unordered_set>
using namespace std;

int main() {
    queue<string> players;
    unordered_set<string> playing;
    
    string event;
    while (cin >> event) {
        if (event == "start") {
            if (players.empty()) {
                cout << "Error" << endl;
            } else {
                if (players.size() >= 2) {
                    cout << players.front() << " " << players.back() << endl;
                } else {
                    cout << players.front() << endl;
                }
                playing.insert(players.front());
                if (players.size() >= 2) {
                    playing.insert(players.back());
                }
            }
        } else if (event == "arrive") {
            string player;
            cin >> player;
            if (playing.count(player) > 0 || players.size() >= 2) {
                cout << "Error" << endl;
            } else {
                players.push(player);
                cout << "OK" << endl;
            }
        } else if (event == "leave") {
            string player;
            cin >> player;
            if (playing.count(player) == 0 || (players.size() > 0 && players.front() != player)) {
                cout << "Error" << endl;
            } else {
                players.pop();
                playing.erase(player);
                cout << "OK" << endl;
            }
        }
    }
    
    return 0;
}

代码解析:

  • 使用 queue 来维护玩家的排队顺序,使用 unordered_set 来记录当前正在游玩的玩家。
  • 根据不同的事件类型,进行相应的操作并输出结果。

总结:

本文通过 C++ 代码实现了一个游戏机排队系统,该系统能够模拟多人游戏排队的机制,并根据不同的事件类型进行相应的操作,最终输出相应的结果。该代码展示了使用数据结构和算法来解决现实问题的典型应用。

C++ 实现游戏机排队系统:模拟多人游戏排队机制

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

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