尝试在Python中使用重启功能[已关闭]

问题描述 投票:0回答:1

不确定如何为玩家提供重新启动的选项,我尝试了多种方法,但没有任何效果 - 我们将不胜感激:)

#player authentication
thefile = open("player.txt", "r")
score = 0
point = 0
rnd = 0
valid = True
#user being input and checked
user = ""
while valid:
    user = input("input your name: ")
    if len(user) == 0:
        print("oh oh")
    else:
        valid = False

#find the name in file
while True:
    Line = thefile.readline()
    Line=Line.strip("\n")
    if Line == user:
        print("user found, access granted")
        print("you have 2 lives within this game - take caution")
        rnd = rnd + 1
        print("")
        print("round", rnd)
        break
    if Line == False:
        print("invalid")
while score < 3:            
#Importing Random and Selecting Line
    print("")
    import random
    lines = open('Songs.txt') .read() .splitlines()
    myline = random.choice(lines)                                   

#Finding Comma and Seperating Title and Artist
    comma = myline.find(",")
    artist = myline[0:comma]
    title = myline[comma+2:]                                            


    fl = next(zip(*title.split()))
    print(artist, fl)                                                           

#Playing the Song


    guess = input("What is the name of the song? ")
    if guess == title:
        print("Well done! Correct!")
        point = point + 1
        print("")
        print("your current value of points: ", point)
        print("")
        rnd = rnd + 1
        print("round", rnd)
    else:
        print("incorrect")
        print("the answer was", title)
        score =  score + 1
        print("")
        print("your current value of points: ", point)
        print("")
        rnd = rnd + 1

        if score == 3:
            print("game over")
            print("your final score was", point)
          

我尝试使用在堆栈溢出中找到的随机代码,但我总是收到语法错误,指出它无法识别,我希望能够在生命耗尽后重新启动代码的游戏部分

python restart
1个回答
0
投票

重复游戏循环的正确方法是将其放入自己的函数中,即

play_game()

其次,由于您不断获取用户输入,因此您可以将其变成可重用的函数,即

request_input()

此外,您可以在调用时解压变量

str.split()

最后,在管理资源时使用上下文管理器。当您打开文件时,仅在需要时保持打开状态。

#!/usr/bin/env python3

import random
import sys

def read_first_line(filename):
    line = None
    with open(filename, "r") as f:
        line = f.readline().strip()
    return line


def read_all_lines(filename):
    lines = None
    with open(filename, "r") as f:
        lines = f.read().splitlines()
    return lines


def request_input(prompt_message, error_message = None):
    username, is_valid_input = None, False
    while not is_valid_input:
        username = input(prompt_message).strip()
        if not username:
            if error_message:
                print(error_message)
        else:
            is_valid_input = True
    return username


def make_guess():
    print()
    lines = read_all_lines("Songs.txt")
    random_line = random.choice(lines)                                   
    title, artist = random_line.split(",", 1)
    print(f'"{title}" by {artist}')
    response = request_input("Input song name: ", "Uh oh, please enter a song.")
    return response.lower() == title.lower()


def play_game():
    print("You have 2 lives within this game - take caution")
    lives, score = 2, 0
    while lives and score < 3:
        print(f"Current score: {score} | Remaining lives: {lives}")
        if make_guess():
            print("Correct, +1 point")
            score += 1
        else:
            print("Incorrect, -1 live")
            lives -= 1
    if score == 3:
        print("You win")
        
    if not lives:
        print("You lose")


if __name__ == "__main__":
    authorized_username = read_first_line("player.txt")
    username = request_input("Input username: ", "Uh oh, please enter a username.")

    if username != authorized_username:
        print("Unauthorized")
        sys.exit()

    keep_going = True
    while keep_going:
        play_game()
    
        response = request_input("Do you wish to play again?: ").lower()
        if response not in ("y", "yes"):
            keep_going = False
    
    print("Goodbye, thanks for playing!")
   
© www.soinside.com 2019 - 2024. All rights reserved.