骰子游戏,使每个骰子滚动不同

Dice Game, making each Die roll differently

本文关键字:滚动 游戏      更新时间:2023-10-16

好的,我刚刚完成了我的练习,并坚持如何让每个骰子掷出自己的随机生成的数字。该程序实际上确实掷出随机数,只是每次您重新掷骰子时总是掷出完全相同的数字。这个简单但令人头疼的问题发生了,出于某种原因,我也有

cout << "Adding both dices up you rolled a total of: " << totalScore() << "." << endl;

一位同学还告诉我,我的面值是非法值,应该设置为合法值。我不太明白他的意思,我相信这会(不是很多)降低我的一些成绩。

#include "stdafx.h"
#include <iostream>
#include <string>
#include <ctime>  
using namespace std;    
class PairOfDice
{

private:
int diceOne;
int diceTwo;
int score;
int faceVaule;
public:
PairOfDice(){
    srand(time(NULL));
    roll();
}
void roll(){
    diceOne = (rand() % 6) + 1;
    diceTwo = (rand() % 6) + 1;
    setdiceOne(diceOne);
    setdiceTwo(diceTwo);
}

void setdiceOne(int value){
    faceVaule = value;
}
int getdiceOne(){
    return faceVaule;
}
void setdiceTwo(int value){
    faceVaule = value;
}
int getdiceTwo(){
    return faceVaule;
}
void totalScore(){
    score = diceOne + diceTwo;
}
void display(){
    cout << "The first Dice rolled a " << getdiceOne() << " ." << endl;
    cout << "The second Dice rolled a " << getdiceTwo() << " ." << endl;
    // adding both dices gives an: No operator " < < " matches these operands
    cout << "Adding both dices up you rolled a total of: " << totalScore() << "." << endl;
}

};
int _tmain(int argc, _TCHAR* argv[])
{
PairOfDice game;
game.roll();
game.display();
game.totalScore();

return 0;
}

首先:你掷两个骰子,将结果存储在 dice1 和 dice2 中,然后你把这些值发送到两个函数,这两个函数将值放入一个名为 faceValue 的变量中。取回值将只返回第二个骰子值是合乎逻辑的,因为这是您上次在 faceValue 中输入的值。

这就是为什么两个骰子都显示相同的值。

现在对于错误:您的 totalScore 函数返回一个 void,而 <<运算符需要某种类型。totalScore 函数将两个骰子相加(顺便说一下,正确的值)并将结果放入 score 中,但无处返回分数中的值。

你的代码真的很乱。不应有一个成员变量 (faceValue) 保存两个不同值的副本。你根本不应该有这个成员。只需使用骰子一和骰子两个值。当设置值时 ( = rand() % 6 + 1 ),不应通过调用 set-function 再次设置它们:要么创建一个正确的 set-函数(因为这个不正确)并将随机作为参数放入其中,要么像您已经做的那样直接在构造函数中设置成员变量 diceOne 和 diceTwo。不要两者兼而有之。当返回两个骰子的总和时,为什么不直接返回这个总和(提示:函数 totalScore 应该返回 int 类型的内容)。为什么要将求和结果放入成员变量中?没有必要这样做。

我可以在这里发布更正后的代码,但似乎您真的必须自己学习。

编辑:顺便说一下:如上所述,学习使用调试器。你很快就会发现我告诉你的事情是正确的。你会注意到,faceValue首先得到diceOne的值,然后得到diceTwo的值,永远不会得到diceOne的值。