In: Computer Science
MATLAB code for the following question.
In the game of Monopoly, a pair of dice are rolled to move a player's piece around the board. If a double is rolled (the dice show the same number), the player receives another roll of the dice. If a double is rolled a second time, a third roll of the dice is received. If a double is rolled on the third occasion, the player forfeits their turn (and goes to Jail). Write a program which simulates two players having 50 turns each (a turn is however many dice rolls a player has in a row before it's the other player's turn) and determines:
a) the total number of spaces moved by each player; and
b) how many times a player rolls a double which results in movement of a piece.
Use the randi function.
For fun, incorporate the rule that a player cannot leave Jail (cannot move) unless they either roll a double or three turns have passed without rolling a double.
Note: Done accordingly. Please comment for any problem. Please Uprate. Thanks.
Code:
player1Turns=0;
player2Turns=0;
totalSpacePlayer1=0;
totalSpacePlayer2=0;
totalDoublesPlayer1=0;
totalDoublesPlayer2=0;
turn=1;
timesOfDouble1=0;
timesOfDouble2=0;
jailed1=false;
jailed2=false;
turnsInjail1=0;
turnsInjail2=0;
while player2Turns<50
if turn == 1
player1Turns=player1Turns+1;
dice1=randi(6);
dice2=randi(6);
fprintf("%d : %d %d Player 1\n",player1Turns,dice1,dice2);
if jailed1
if (dice1==6 && dice2==6) || turnsInJail1==2
jailed1=false;
turnsInJail1=0;
fprintf("Player 1 released");
else
turnsInJail1=turnsInJail1+1;
end
else
if dice1==6 && dice2==6
if timesOfDouble1==2
turn=2;
jailed1=true;
timesOfDouble1=0;
fprintf("Player 1 jailed");
else
timesOfDouble1=timesOfDouble1+1;
player1Turns=player1Turns-1;
end
else
if timesOfDouble1~=0
totalDoublesPlayer1=totalDoublesPlayer1+dice1+dice2;
timesOfDouble1=0;
end
totalSpacePlayer1=totalSpacePlayer1+dice1+dice2;
turn = 2;
end
end
else
player2Turns=player2Turns+1;
dice1=randi(6);
dice2=randi(6);
fprintf("%d : %d %d Player 2\n",player1Turns,dice1,dice2);
if jailed2
if (dice1==6 && dice2==6) || turnsInJail2==2
jailed2=false;
turnsInJail2=0;
else
turnsInJail2=turnsInJail2+1;
end
else
if dice1==6 && dice2==6
if timesOfDouble2==2
turn=2;
jailed2=true;
timesOfDouble2=0;
else
timesOfDouble2=timesOfDouble2+1;
player2Turns=player2Turns-1;
end
else
if timesOfDouble2~=0
totalDoublesPlayer2=totalDoublesPlayer2+dice1+dice2;
timesOfDouble2=0;
end
totalSpacePlayer2=totalSpacePlayer2+dice1+dice2;
turn = 1;
end
end
end
end
fprintf("Space moved by 1: %d\n",totalSpacePlayer1);
fprintf("Space moved by 2: %d\n",totalSpacePlayer2);
fprintf("Double result in move player 1:
%d\n",totalDoublesPlayer1);
fprintf("Double result in move player 2:
%d\n",totalDoublesPlayer2);
Output:
More results: