创建Yahtzee游戏并遇到Re-Roller(C ++)问题

时间:2013-08-22 19:53:06

标签: c++

我目前无法让我的重新滚轮在100%的时间内正常工作。有时它行为正确,只会改变我选择的内容,但有时它似乎有自己的想法。以下是我的代码中的一些片段。

  Int main()
  ...
  while (counter<13){
        cout<< playName << " please roll the dice."<<endl;
        system("pause");
        roll();
        reRoll();
        reRoll();
        score();}



  void reRoll(){
cout<< playName << " please select which dice you would like to re-roll by entering
   a y or n."<<endl;
cout<< "Would you like to re-roll die 1?";
cin>>dieOne;
cout<< "Would you like to re-roll die 2?";
cin>>dieTwo;
cout<< "Would you like to re-roll die 3?";
cin>>dieThree;
cout<< "Would you like to re-roll die 4?";
cin>>dieFour;
cout<< "Would you like to re-roll die 5?";
cin>>dieFive;

srand(static_cast<unsigned int>(time(0)));
const int dice = 6;
int die[6] = {1, 2, 3, 4, 5, 6};

if (dieOne=="y"){
    int dice1Roll = (rand() % dice);
    currentDice[0] = die[dice1Roll];}
if (dieOne!="y"){}
if (dieTwo=="y"){
    int dice2Roll = (rand() % dice);
    currentDice[1] = die[dice2Roll];}
if (dieTwo!="y"){}
if (dieThree=="y"){
    int dice3Roll = (rand() % dice);
    currentDice[2] = die[dice3Roll];}
if (dieThree!="y"){}
if (dieFour=="y"){
    int dice4Roll = (rand() % dice);
    currentDice[3] = die[dice4Roll];}
if (dieFour!="y"){}
if (dieFive=="y"){
    int dice5Roll = (rand() % dice);
    currentDice[4] = die[dice5Roll];}
if (dieFive!="y"){}
cout<<playName<<"'s die are now "<<currentDice[0]<<" "<<currentDice[1]<<" "
    <<currentDice[2]<<" "<<currentDice[3]<<" "<<currentDice[4]<<endl;}

1 个答案:

答案 0 :(得分:2)

在使用rand函数之前,每次都不必调用srand。只需在main中调用一次就足够了,无论你做什么:

#include <cstdlib>

int main(void) {
    srand(static_cast<unsigned int>(time(NULL)));

    while(...) {}
    return 0
}

此外,如果您尝试在1到6之间滚动数字,您的滚轴应采用以下形式:

int dice1Roll = (rand() % dice) + 1;