2014-12-04 52 views
0

我想在C++中實現craps遊戲,規則如下。所以我創建了一個函數,它會爲我生成兩個數字,有時這個函數需要被調用兩次,但是當它第二次被調用時,它給了我相同的隨機數,它第一次給了我。在第二次調用中生成不同的隨機數

我想將我在第二次調用中獲得的數字隨機化爲rollDice()函數。我怎麼做?

實施例輸出1:
播放機軋製3 + 4 = 7
玩家嬴得!

實施例輸出2:
播放機軋製2 + 2 = 4
點是4
播放機軋製2 + 2 = 4 玩家嬴得!

實施例輸出3:
播放機軋製1 + 5 = 6
點是6
播放機軋製1 + 5 = 6
玩家嬴得!

遊戲規則: 規則:玩家拋出兩個六面骰子,如果他們的總和或,他們贏了。 如果總數是2,3或12他們鬆動。 如果它是4,5,6,8,9,10,12它變成「點」並且玩家必須再次滾動。 然後玩家繼續轉動,直到他再次擊中「點數」,並且他贏得 ,如果他擊中,則獲勝。

代碼:

#include<iostream> 
#include<ctime> 
#include <cstdlib> 

using namespace std; 

//Generating two rand numbers from 1 to 6 
int rollDice() 
{ 
    srand(time(0)); 
    int face1 = 1 + rand()%6; 
    int face2 = 1 + rand()%6; 
    int sum = face1 + face2; 

    cout << "Player rolled " << face1 << " + " << face2 << " = " << sum << endl; 
    return sum; 
} 

string gameStatus; //Hold status of game; WIN, CONTINUE, LOST 
int sumOfDice = rollDice(); 
int point = 0; //This will hold sum of dice if it's default case defined below in Switch. 

int main() 
{ 
    switch(sumOfDice) 
    { 
     case 7: 
     case 11: 
      gameStatus = "WIN"; 
      break; 

     case 2: 
     case 3: 
     case 12: 
      gameStatus = "LOST"; 
      break; 

     default: 
      gameStatus = "CONTINUE"; 
      point = sumOfDice; 
      cout << "Point is " << point << endl; 
    } 

    while (gameStatus == "CONTINUE") 
    { 
     int rollAgain = rollDice(); 
     if (rollAgain == point) 
      gameStatus = "WIN"; 
     else if (rollAgain == 7) 
      gameStatus = "LOST"; 
    } 
    if (gameStatus == "WIN") 
     cout << "Player won!"; 
    if (gameStatus == "LOST") 
     cout << "Player lost!"; 
} 
+1

你應該每次都調用'srand()'一次。您將重新播種具有相同種子的隨機序列,因此您將獲得相同的第一個序列號。在main的開始處調用srand。或者,如果你可以使用C++ 11使用''(我需要這個評論的模板,我幾乎每個星期都會使用這個建議...) – Borgleader 2014-12-04 13:50:39

+0

@Borgleader你可以詳細自我回答的問題,然後標記所有其他人作爲重複。 – 2014-12-04 13:54:37

回答

3
srand(time(0)); 

這將重置爲隨機數發生器爲當前時間的種子。程序啓動時只做一次。如果你在同一秒內做兩次(這樣time返回相同的值),那麼每次都會得到相同的隨機數序列。

相關問題