How to Make a Pig Game in Pseudocode
The dice game, "Pig," has rules that are simple to describe, but designing the pseudocode for a program where the computer plays with optimal strategy is a deceptively tricky puzzle. To play "Pig," players take turns rolling a single die. On any roll other than 1, the number on the die is added to the player's turn score. On a roll of 1, the player's turn ends with no score added to his total. After any roll, the player may decide to end his turn and add his turn score to his total score. The first player to reach 100 points wins.
Instructions
-
-
1
Design a function that will let a player take a turn by choosing to roll or stop. The pseudocode should follow this process, though you will likely express it in more detail:
Function: Turn(Player)
Display TotalScore.Player and TurnScore.Player
Get input
If player chooses to roll
--Generate random number from 1 to 6
--If Result = 1
----TurnScore.Player = 0
----Run Turn(NextPlayer)
--If Result > 1
----TurnScore.Player = TurnScore.Player + Result
----If TotalScore.Player + TurnScore.Player >= 100, Player wins
----Run Turn(Player)
If player chooses to stop
--TotalScore.Player = TotalScore.Player + TurnScore.Player
--Run Turn(NextPlayer)
-
2
Calculate a strategy for the computer to use when the computer player is evaluating whether to roll or stop. A very basic strategy is to have the computer keep rolling until its turn score is above 20, based on the logic that each roll has five chances in six to add an average of 4 points, so until you reach a turn score of 5 * 4, the "wager" is worthwhile. To refine the strategy, come up with a way to evaluate when it is worth pushing past 20 points, such as when your opponent has 99 points and you start a turn with 78.
-
-
3
Design a function that will calculate the computer player's decision. The function should take as inputs variables representing the computer's turn score and (if necessary for the strategic calculation) both players' total scores and return a variable representing the choice to roll or stop after processing the inputs based on the strategy you designed. A basic modification of the "hold until 20" strategy, for example, might look like this:
Function: Choose(TurnScore, OpponentScore)
If OpponentScore > 80
--Return(Roll)
Else If TurnScore < 20
--Return(Roll)
Else Return(Stop)
-
1
References
- Photo Credit Jupiterimages/Photos.com/Getty Images