lundi 19 février 2018

monte carlo of a preexisting program

This is the Problem Set Up. I have to answer these questions:

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))




Aucun commentaire:

Enregistrer un commentaire