c++ - 检查谁在骰子游戏中获胜

标签 c++ dice

我有一个骰子游戏

int userGame()
{
    cout << " User turn --- Press 2 to roll" << endl;
    cin >> userInput;

    if ( userInput == 2 )
    {
        Dice ();
        cout << "The user rolled        Dice 1 =" << die1 << " and Dice 2 = " << die2 << endl;
        cout << "Total = " << die1 + die2 << endl;
    }

    else {
        cout << "Wrong input. Try again";
        //userGame();
    }


    return (die1 + die2);
}

现在在 int main 中,我有 -

int main ()
{
    // set the seed
    srand(time(0));
    userGame();

        while (true)
        {


            if (userGame() == 7 || userGame() == 11)
            {
                cout << "You won" << endl;
                break;
            }

            else if (userGame() == 2)
            {
                cout << "You loose" <<endl;
                break;
            }

            else

            {
                break;

            }


        }




        return 0;

骰子();

#include<iostream>
#include<ctime>      // for the time() function
#include<cstdlib>    // for the srand() and rand() functions
using namespace std;
int compInput;
int userInput;
int die1 = 0;
int die2 = 0;
int Dice ()
{

    // roll the first die
    die1 = (rand() % 6 ) + 1;
    // roll the second die
    die2 = (rand() % 6 ) + 1;


}

但由于某种原因,输出显示不正确。一旦它在输出为 7 和其他时间时显示用户赢了,它就会继续游戏。

我要用 main() 中的循环做什么?

谢谢

最佳答案

if (userGame() == 7 || userGame() == 11)

这一行是你的问题。 C++ 使用短路求值。在这种情况下,如果 userGame() == 7 成功,则不会检查后半部分。但是,如果它失败,将在下半场再次调用 userGame(),这意味着您将在进入 if 的代码部分之前玩两次。

    while (true)
    {
        int result = userGame();
        if (result == 7 || result == 11)
        {
            cout << "You won" << endl;
            break;
        }
        else if (result == 2)
        {
            cout << "You loose" <<endl;
            break;
        }
        else
        {
            break;
        }
    }

关于c++ - 检查谁在骰子游戏中获胜,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12451766/

相关文章:

c++ - 使用字符指针测试条件

algorithm - 生成一个所有可能结果的矩阵,用于 throw n 个骰子(忽略顺序)

c - 掷骰子模拟器 - 直方图中每次掷骰子的输出频率

dice - K个N面骰子的不同掷数

转换后c++读取访问冲突

c# - 在托管代码中调用 SSE 代码(对齐)

c++ - 通过引用 C++ 中的基类循环遍历派生类

c++ - 基本构造函数根据输入调用派生的构造函数-在运行时选择对象子类型

Javascript 骰子游戏 : How to remove HP depending on dice result?

python - 如何划分投资返回率轮廓?