繁体   English   中英

检查文件是否存在并加载其内容

[英]Checking If a File Exists and Loading its Contents

在我的编程课程中,我们将制作一个石头,纸,剪刀游戏,该游戏可以加载以前的游戏保存,显示游戏的统计信息,并允许用户根据需要继续玩游戏。 我已经创建了一个很好的程序块,我只需要帮助加载文件,因为我无休止地循环了“您叫什么名字?”。 我的代码在下面,任何帮助将不胜感激!

#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

此代码块:

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

除非您将response设置为2以外的其他值,否则它将无限重复。 请注意,在此块中,您要做的就是(1)询问用户名,(2)打开文件,以及(3)用pickle转储文件内容。 您实际上并没有像在if response == 1块中那样开始游戏。 因此,同一提示会不断重复无限。

在这种情况下,要做的一件好事是手动手动遍历您的代码-“到达这里我做了什么,结果是什么?”

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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