0

In my programming class we are to make a Rock, Paper, Scissors Game that can load previous saves of the game, display the statistics of the game, and allow the user to continue playing if desired. I have a good chunk of the program created, I just need help with the loading of the file as I just get an endless loop of "What is your name?". My code is below and any help would be appreciated!

#Rock, Paper, Scissors Program
#A menu-based RPS program that keeps stats of wins, losses, and 
ties
#12/2/18

import sys, os, random, pickle

#Functions
def print_menu():
    print("\n1. Start New Game")
    print("2. Load Game")
    print("3. Quit")

def print_roundmenu():
    print("What would you like to do?")
    print("\n1. Play Again")
    print("2. View Statistics")
    print("3. Quit")

def start_game(username, playing):
    print("Hello", username + ".", "let's play!")
    playAgain = play_game()
    if playAgain == True:
        playing = True
    elif playAgain == False:
        playing = False
    return playing

def play_game():
    roundNo = 1
    wins = 0
    losses = 0 
    ties = 0
    playing_round = True

    while playing_round:
        print("Round number", roundNo)
        print("1. Rock")
        print("2. Paper")
        print("3. Scissors")

        roundNo += 1
        choices = ["Rock", "Paper", "Scissors"]
        play = get_choice()
        comp_idx = random.randrange(0,2)
        comp_play = choices[comp_idx]
        print("You chose", play, "the computer chose", 
 comp_play+".")

        if (play == comp_play):
            print("It's a tie!")
            ties += 1
            print_roundmenu()
            gameFile.write(str(ties))
        elif (play == "Rock" and comp_play == "Scissors" or play == "Paper" and comp_play == "Rock" or play == "Scissors" and comp_play == "Paper"):
            print("You win!")
            wins += 1
            print_roundmenu()
            gameFile.write(str(wins))
        elif (play == "Scissors" and comp_play == "Rock" or play == "Rock" and comp_play == "Paper" or play == "Paper" and comp_play == "Scissors"):
            print("You lose!")
            losses += 1
            print_roundmenu()
            gameFile.write(str(losses))
        response = ""
        while response != 1 and response != 2 and response != 3:
            try:
                response = int(input("\nEnter choice: "))
            except ValueError:
                print("Please enter either 1, 2, or 3.")
        if response == 1:
            continue
        elif response == 2:
            print(username, ", here are your game play statistics...")
            print("Wins: ", wins)
            print("Losses: ", losses)
            print("Ties: ", ties)
            print("Win/Loss Ratio: ", wins, "-", losses)
            return False
        elif response == 3:
            return False

def get_choice():
    play = ""
    while play != 1 and play != 2 and play != 3:
        try:
            play = int(input("What will it be? "))
        except ValueError:
            print("Please enter either 1, 2, or 3.")
    if play == 1:
         play = "Rock"
    if play == 2:
        play = "Paper"
    if play == 3:
        play = "Scissors"
    return play

playing = True
print("Welcome to the Rock Paper Scissors Simulator")
print_menu()
response = ""
while playing:
    while response != 1 and response != 2 and response != 3:
        try:
            response = int(input("Enter choice: "))
        except ValueError:
            print("Please enter either 1, 2, or 3.")
    if response == 1:
        username = input("What is your name? ")
        gameFile = open(username + ".rps", "w+")
        playing = start_game(username, playing)
    elif response == 2:
        while response == 2:
            username = input("What is your name? ")
            try:
                gameFile = open("username.rps", "wb+")
                pickle.dump(username, gameFile)
            except IOError:
                print(username + ", your game could not be found.")
    elif response ==3:
        playing = False
  • 1
    `while response == 2:` will never be false since you never change the value of response inside the while loop. – Loocid Dec 07 '18 at 05:22
  • This might be what you're looking for to check if a file exists: [https://stackoverflow.com/questions/82831/how-do-i-check-whether-a-file-exists-without-exceptions](https://stackoverflow.com/questions/82831/how-do-i-check-whether-a-file-exists-without-exceptions) – Josh Kearney Dec 07 '18 at 05:44

1 Answers1

0

This code block:

    while response == 2:
        username = input("What is your name? ")
        try:
            gameFile = open("username.rps", "wb+")
            pickle.dump(username, gameFile)
        except IOError:
            print(username + ", your game could not be found.")

will repeat infinitely unless you set response to something other than 2. Notice here that all you're doing in this block is (1) asking for username, (2) opening the file, and (3) dumping the file contents with pickle. You're not actually starting the game, like you are in the if response == 1 block. So the same prompt keeps repeating infinitely.

A good thing to do in these situations is to manually step through your code by hand - "what did I do to get here, and what is happening as a result of that?"

Green Cloak Guy
  • 23,793
  • 4
  • 33
  • 53
  • Okay, so I see that error and thanks for pointing it out for me! I am still a little fuzzy on how to go about checking to see if that file exists in the working directory – Mason Adrales Dec 07 '18 at 05:37
  • The way you're doing it is pretty much correct - Python encourages a "ask forgiveness, not permission" approach, which is what you're doing here. Trying with `open()` and then catching an `IOError` if the file can't be found. If you really wanted to check for the existence of the file, you could use `os.path.exists("username.rps")` (which returns `True` if the file exists and `False` otherwise), but since you intend to open the file anyway this is a good way of doing it. – Green Cloak Guy Dec 07 '18 at 05:52