如何循环游戏追踪角色

How to looping a game tracking characters?

本文关键字:游戏 追踪 角色 循环 何循环      更新时间:2023-10-16

我试图创建一个简单的c++循环游戏,其中2名人类玩家,轮流,键入字母序列,必须匹配序列中的最后一个字母到他们的第一个或他们输了。

例如,如果玩家1输入:hey玩家2输入:you,玩家1输入:use,如果玩家2输入:hey,玩家2将会输,因为他没有以玩家1输入的最后一个字母(即使用的"e")开始他的字母序列。

我的代码中的问题是我不知道如何使程序跟踪每个玩家输入的最后一个字母和第一个字母来确定获胜者。

My code:

    #include <iostream>
    #include <cstdlib>
    #include <string>
    using namespace std;
    int main(){
        string word;
        string word2;
        bool userTurn = true;
        cout << "Welcome to the last letter/first letter game! ";
        cout << " Do you want to play first (y/n)? ";
        char response;
        if (!(cin >> response)) die("input failure");
        response = static_cast<char>(toupper(response));
        if (response == 'Y')
            userTurn = true;
        else if (response == 'N')
            userTurn = false;
        else
            die(" youre suppose to answer y or n");
        while (true){
            if (userTurn){
                cout << "Player #1: " << endl;
                cin >> word;
                    cout << "Player #2: " << endl;
                    cin >> word2;
            } if (userTurn && word != word2){
                cout << " Player 2 Wins! ";
            }
            } userTurn != userTurn;
        }

我建议在这个程序中使用OOP过程。

测试程序演示跟踪每次运行的第一个和最后一个字符。

#include <iostream>
#include <string>
int main()
{ 
    std::string word1, word2;
    char last, first;
    std::cout << "player1: ";
    std::cin >> word1;
    last = word1[word1.length() - 1]; //last character of player 1
    while (true)
    {
        std::cout << "player2: ";
        std::cin >> word2;
        first = word2[0];  //first character of player 2
        if (first != last)
        {
            std::cout << "player2 loss" << std::endl;
            break;
        }
        last = word2[word2.length() - 1]; //last character of player 2
        std::cout << "player1: ";
        std::cin >> word1;
        first = word1[0];  //first character of player 1
        if (first != last)
        {
            std::cout << "player1 loss" << std::endl;
            break;
        }
    }
    return 0;
}

要获得std::string的第一个/最后一个字符,使用std::string::front()/std::string::back(),例如word.back() != word2.front()

还有,将来试着和google交朋友。你会找到一个解决方案,虽然不是你给你的问题的标题,但与你的问题没有任何关系。