Jack Lorenzo Kurtz
Jack Lorenzo Kurtz

Reputation: 25

monte carlo of a preexisting program

The python code in diceGame.py (below) contains a python implementation of the dice game we discussed in class. Assume we run the code N times and estimate the probability of a certain event A, P r{A}, based on the number of times A occurs divided by N. We then repeat this process M times collecting the probabilities pi, i = 1, . . . , M. Under the assumption that both dices are fair, modify the main routine of diceGame.py using N = 10, 100, 1000 and M = 100 for the following probabilities:

The probability of winning the game at the first dice roll.

The probability of winning the game if the first roll gives a 4.

The probability of winning the game.

The probability of a game to require more than 5 dice rolls.

I know that all of these answers can easily be supplied through the code itself. My problem is that I have no idea how to edit the python code to give these desired outputs.

Here is the code:

# ===============================
# IMPORTS RANDOM NUMBER GENERATOR
# ===============================
import random

# ================================================================
# GENERATES RANDOMLY THE SUM OF TWO INTEGERS IN THE [1,6] INTERVAL
# ================================================================
def rollDices():
  return int(random.randint(1,6) + random.randint(1,6))

# ================================================
# RETURN THE OUTCOME STRING GIVEN AN INTEGER STATE
# ================================================
def getOutcome(outcome):  
  if(outcome == 0):
    result = "Lost at first roll."
  elif(outcome == 1):
    result = "Won at first roll."
  elif(outcome == 2):
    result = "Won on [4,5,6,8,9,10]"
  elif(outcome == 3):
    result = "Lost on [4,5,6,8,9,10]"
  return result

# ==============
# PLAYS THE GAME
# ==============
def playGame():

  # Define Variables
  gameFinished = False
  wonGame = False
  totRolls = 0

  while (not(gameFinished)):

    # ROLL DICES
    totScore = rollDices()
    totRolls += 1;

    # GAME IS LOST
    if(totScore in [2,3,12]):
      gameFinished = True
      wonGame = False
      return 0,wonGame,totRolls,totScore

    # GAME IS WON
    if(totScore in [7,11]):
      gameFinished = True
      wonGame = True
      return 1,wonGame,totRolls,totScore

    # JUST CONTINUE PLAYING
    if(totScore in [4,5,6,8,9,10]):      

      # REPEAT UNTIL YOU FIND THE SCORE AGAIN OR 7
      newScore = 0
      while((newScore != totScore)and(newScore != 7)):

        newScore = rollDices()
        totRolls += 1;

        # CHECK IF YOU WIN OR LOOSE
        if(newScore == totScore):
          gameFinished = True
          wonGame = True
          return 2,wonGame,totRolls,totScore

        if(newScore == 7):
          gameFinished = True
          wonGame = False
          return 3,wonGame,totRolls,totScore

# ============
# MAIN PROGRAM
# ============
if __name__ == "__main__":

  intVal,wonGame,numRolls,lastScore = playGame()

  print("Outcome: %s" % (getOutcome(intVal)))
  if(wonGame):
    print("You have won the game.")
  else:
    print("You have lost the game.")
  print("Total rolls needed for this game: %d" % (numRolls))
  print("Last outcome: %d" % (lastScore))

New main function as I attempt the problem:

if __name__ == "__main__":
    m = 100
    n = 10
    FRwins = 0
    for i in range(m):
        for j in range(n):
            intVal,wonGame,numRolls,lastScore = playGame()
            if getOutcome(intVal) == 1:
                FRwins += 1
        FRwins = FRwins/float(n)
        print(FRwins)

Upvotes: 0

Views: 116

Answers (1)

Jacob Stringer
Jacob Stringer

Reputation: 51

Currently this programme is playing the game once. If you look at the final 10 lines of code, that is what you want to adjust in order to do this. The important line is this:

intVal,wonGame,numRolls,lastScore = playGame()

It is only being called once, so you only get one result out of it. Since you need to do a Monte Carlo simulation (i.e. playing over and over again and tracking the probabilities), you just need to replay this line lots of times, and keep track of the results each time.

From there, you will need to set up some for loops, such as:

for i in range(m):

and keep track of results from each simulation. Since you are working with m and n, you will need nested loops surrounding your playGame(). Then you just need to tally the results as you go, and divide by the total attempts to get your probabilities.

Hopefully this is helpful. Feel free to ask further questions - I'm trying to keep it general enough that I'm not actually writing the code for what seems to be your homework!

Upvotes: 1

Related Questions