尝试这样做:如果我的分数(变量)达到10,程序结束并说“你赢了”。每当我做这样的事情时10.什么也没发生

2024-10-03 17:24:00 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图做到这一点,当分数变量达到10时,它会说“你赢了!”或类似的话。有人能帮忙吗?这是一个测验,python从文件中选择一行,当它读取文件时,它知道要输入的密码。剩下的基本上是你猜测歌曲的名字,从一个文件中提取出来。我已经包括了下面的所有文件。 https://github.com/zobr0toN/Music-quiz-files

import random
score = 0
print("Welcome to my quiz. The task is to name 10 of Juice Wrld's songs. You get two wrong answers, and if you pass that margin you lose. Good luck!")
    
def login(): #defines the function
    file = open("musicpass.txt", "r")
    password = file.read()
    userguess = input("Enter password for access: ")
    if password == userguess:
        print("Access Granted!")
        game(song)
        ransong()
    else:
        print("Access Denied!")
        login()

def ransong():
    with open("musicsongs.txt", "r") as file:
        content= file.read()
        words = content.splitlines()
  
    # print random string
    #print(random.choice(words))
    return words


def game(song):
    songlist = song
    guess=0
    score=0
    while guess != 2:
        usguess1 = input("Enter your choice here: ")
        if usguess1 in songlist:
            print("Correct!")
            score = score + 1
        else:
            print("Incorrect, one more guess allowed")
            guess = guess + 1
    else:
        print("Incorrect, game over")
        print("Your score is:",score)
        print("Incorrect, no more guesses left.")
    while score != 10:
        print("Well done, you win!")    



def main():
    login()
song=ransong()
main()

Tags: 文件yougameifsongdefloginrandom
2条回答

如果分数达到10分,你可以增加休息时间。然后游戏停止

while guess != 2:
    if score == 10:
       print("Well done, you win!")
       break
    usguess1 = input("Enter your choice here: ")
    if usguess1 in songlist:
        print("Correct!")
        score = score + 1
    else:
        print("Incorrect, one more guess allowed")
        guess = guess + 1

这是编程时相当常见的情况。考虑到即使在输入猜测后仍需要保持程序运行,但在分数达到10分后退出,这是使用while循环的好机会,条件是猜测!=2和分数<;10while循环将不断重复,直到满足某些条件

def game(song):
    songlist = song
    guess=0
    score=0
    while guess != 2 and score < 10:
        usguess1 = input("Enter your choice here: ")
        if usguess1 in songlist:
            score += 1
            print("Correct!")

相关问题 更多 >