import random import time # return random number 1 - 6 def dieRoll(): roll = random.randint(1, 6) return roll # see if the user wants to roll or not # returns either R or H as a string def userRollOrHold(roundScore, userScore, compScore): print("You have", userScore, "points.") print("Computer has", compScore, "points.") print("So far this round you have", roundScore, "points.") answer = input("(R)oll or (H)old? ") while answer != "R" and answer != "H": print("Please enter either 'R' or 'H'") answer = input("(R)oll or (H)old? ") return answer def compRollOrHold(roundScore, userScore, compScore): # wait a bit time.sleep(1.0) # if we will win with this round so far, hold if compScore + roundScore >= 100: print("Computer holds with", roundScore, "points.") return "H" # pick goal based on how close we are if userScore - compScore >= 20: # way behind goal = 22 elif compScore - userScore >= 20: # way ahead goal = 10 else: # close goal = 15 if roundScore > goal: print("Computer holds with", roundScore, "points.") return "H" else: print("Computer rolls a ", end="") return "R" # do one round of the game, either for player or computer # returns the points won in the round def gameRound(userTurn, userScore, compScore): roundScore = 0 while True: if userTurn == True: roll = userRollOrHold(roundScore, userScore, compScore) if roll =="R": print("You rolled a ", end="") else: roll = compRollOrHold(roundScore, userScore, compScore) if roll == "R": amount = dieRoll() print(amount) if amount == 1: print("This is the end of your turn") return 0 else: roundScore = roundScore + amount else: return roundScore # function which runs the whole game def game(): userTurn = True userScore = 0 compScore = 0 # keep going until somebody wins while userScore < 100 and compScore < 100: # do one round of the game, and add in the points points = gameRound(userTurn, userScore, compScore) if userTurn == True: userScore = userScore + points else: compScore = compScore + points # switch the turn userTurn = not userTurn # put a blank line print() # announce the winner if userScore > compScore: print("Congratulations! You won!!") else: print("Sorry you lost :(") # run the function to play the whole game game()