简体   繁体   中英

c++ Dice Game With Random

You start by rolling m dice. Remove the 6's and sum the rest of the dice to get r_1 . Now roll the remaining dice, remove the 6's and sum the rest of the dice to get r_2 ; continue this until all dice have shown 6 (you have none remaining). Your score is S = r_1 + r_2 + ... + r_t , where t was the number of rolls. If S > 5 m you win, otherwise you lose.

Code:

#include <iostream>
#include <stdio.h>      //  NULL
#include <stdlib.h>     // srand, rand
#include <time.h>       // time
using namespace std;

void cheddar();
void feta();

int main(){
  //cheddar();
  feta();
}

void feta(){
  int count = 1;
  int ri = 0;
  srand(time(0));
  int dice[7];
  int score = 0;
  int m = 7;
  int fiveofm = 5*m;
  int numofdice = 7;
  do{
    cout << count << " & ";
    for(int i=0;i<7;i++){
        dice[i]=rand()%6+1;
    }
    for(int i=0;i<7;i++){
        cout << dice[i] << " & ";
    }
    for(int i=0;i<7;i++){
        if (dice[i] != 6){
            ri += dice[i];
            //score += dice[i];
        }
        if (dice[i] == 6){
            numofdice--;
        }
    }
    cout << ri << endl;
    ri = 0;
    count++;
  }while(numofdice != 0);
  /*
  if (score <= fiveofm){
    cout << "You lose!" << endl;
  }
  else if (score > fiveofm){
    cout << "You win!" << endl;
  }
*/
}

Any help will be appreciated.

EDIT:

Sorry I hit send before I typed the problem. It either causes an endless loop or it doesn't get rid of a 6 and then generate from there. It just renerates 5 new numbers and keeps the same number on the right as before.

Ex:

`2 & 3 & 3 & 4 & 1 & 5 & 6 & 18`

`6 & 1 & 1 & 6 & 1 & 4 & 2 & 9`

`5 & 3 & 6 & 6 & 5 & 5 & 4 & 22`

`5 & 3 & 3 & 3 & 3 & 6 & 5 & 22`

`2 & 5 & 5 & 3 & 6 & 5 & 1 & 21`

You should not keep rolling all the dice:

for(int i=0;i<7;i++)

Instead, reroll only the ones that are still in play:

int m = 7;
int numofdice = m;
do{
  cout << count << " & ";
  for(int i=numofdice-1; i>=0; --i){
    dice[i]=rand()%6+1;
    cout << dice[i] << " & ";
    if (dice[i] == 6){
        numofdice--;
    }
    else{
        ri += dice[i];
        //score += dice[i];
    }
  }
  cout << ri << endl;
  ri = 0;
  count++;
}while(numofdice != 0);

(Notice that when you do it this way, there's really no need for an array.)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM