简体   繁体   中英

Checking If a File Exists and Loading its Contents

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

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?"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM