HiveBrain v1.2.0
Get Started
← Back to all entries
patterncppMinor

Yahtzee game in C++

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
yahtzeegamestackoverflow

Problem

I am doing a little in-between semester reading in my C++ book, and I came up with the wonderful idea to try to make Yahtzee in C++. So far the code generates 5 random numbers and then calls the function that I made to display a rendering of the die. I cannot figure out how to allow the users to hold the dice that they want to keep for scoring, and I haven't developed a scoring system yet. I have essentially figured out how to roll some dice.

I know somebody is going to get on me for using using namespace std;. But basically I am looking for some direction on what to do next for re-rolling and keeping score.

```
// dice.cpp :
//

#include "stdafx.h"
#include
#include
#include

void diceRoll();
void dice1();
void dice2();
void dice3();
void dice4();
void dice5();
void dice6();
using namespace std;

int getNum();
int main()
{
srand(static_cast(time(0)));
diceRoll();
cout>choice1;
if(choice1=='y')
{
re1=true;
}
if(re1=true)
{
roll1=getNum();
switch(roll1)
{
case 1:
dice1();
break;

case 2:
dice2();
break;

case 3:
dice3();
break;

case 4:
dice4();
break;

case 5:
dice5();
break;

case 6:
dice6();
break;

}//endSwitch
}//endif
if(choice1=='n')
{
cout>choice2;
if(choice2=='y')
{
re2=true;
}
if(re2=true)
{
roll2=getNum();
switch(roll2)
{
case 1:
dice1();
break;

case 2:
dice2();
break;

case 3:
dice3();
break;

case 4:
dice4();
break;

case 5:
dice5();
break;

case 6:
dice6();
break;

}//endSwitch
}//endif

cout>choice3;
if(choice3=='y')
{
re3=true;
}
if(re3=true)
{
roll3=getNum();
switch(roll3)
{
case 1:
dice1();
break;

case 2:
dice2();
break;

case 3:
dice3();
break;

case 4:
dice4();
break;

case 5:

Solution

Here's how you can improve your code:

  • Declaring function prototypes and function definitions in the same file just doesn't make sense. Just declare and define them before their use.



  • Don't use using namespace std;: you are basically defeating the purpose of namespace. Get used to the std:: prefix instead.



  • Don't use srand or rand for uniform distributions: use std::uniform_int_distribution instead.



  • When you are using variables postfixed with incrementing numbers (like roll1, roll2, roll3...), it's probably a good idea to use an std::array or std::vector instead.



  • When you are duplicating a lot of code (like all those identical switch statements), it's usually the sign that you either need a loop or a function.

Context

StackExchange Code Review Q#38847, answer score: 4

Revisions (0)

No revisions yet.