为什么我的while条件对某些情况无效?

-1 投票
1 回答
52 浏览
提问于 2025-04-14 16:46

我正在用Python制作一个石头剪刀布的游戏,里面还加了水、火和草。请问我怎么才能让游戏在达到targetScore的时候结束呢?

这是我的代码,但当我想玩三局两胜的时候,游戏一直在继续。

import random
choices = ["water",
           "grass",
           "fire"]
bestOf = [1, 3, 5, 7]

userChoice = ""
userScore = 0
compScore = 0
targetScore = input("Pick number to play up to (1, 3, 5, or 7): ")

while userChoice != "quit" or userScore == targetScore or compScore == targetScore:
    compChoice = random.choice(choices)
    userChoice = input("Pick either water, grass, or fire: ")
    userChoice = userChoice.lower()

    print ("The CPU called out %s and you called out %s!" %(compChoice, userChoice))
    # if the answers are the same
    if userChoice == compChoice:
        print("Tie game.")
        print("Scores: User: %d CPU: %d" %(userScore, compScore))
    # if the user beats the cpu
    elif userChoice == "water" and compChoice == "fire" or userChoice == "grass" and compChoice == "water" or userChoice == "fire" and compChoice == "grass":
        print("You win!")
        userScore += 1
        print("Scores: User: %d CPU: %d" %(userScore, compScore))
    # if the cpu beats the user
    elif userChoice == "water" and compChoice == "grass" or userChoice == "grass" and compChoice == "fire" or userChoice == "fire" and compChoice == "water":
        print("You lose!")
        compScore += 1
        print("Scores: User: %d CPU: %d" %(userScore, compScore))
    elif userChoice == "quit":
        print("Final scores: User: %d CPU: %d" %(userScore, compScore))
        print("Thanks for playing!")

我在循环里加了一个条件,谁的分数达到最高分,游戏就应该结束。

1 个回答

1

问题出在 while 条件上:

while userChoice != "quit" or userScore == targetScore or compScore == targetScore:

也就是说,只要用户选择的不是 'quit',就继续游戏。或者只要 userScore 等于 targetScore,也继续游戏。再或者只要 compScore 等于 targetScore,就继续游戏。

对于后面两个条件,你其实想要的是相反的效果。看起来你希望游戏在用户输入 'quit' 或者任一分数达到 targetScore 时结束。

userChoice == 'quit' or userScore == targetScore or compScore == targetScore

如果这个条件 成立,游戏就需要继续进行,所以:

while not (userChoice == 'quit' or userScore == targetScore or compScore == targetScore):

得益于布尔逻辑,这个条件可以改写成(这可能是你想要的):

while userChoice != 'quit' and userScore != targetScore and compScore != targetScore:

不过,我觉得用 not 的表达方式更清晰(而且是等价的)。

顺便提一下,Python 中变量命名的惯例是用 'snake_case',也就是避免使用大写字母。虽然这是一种风格选择,但这样可以让你的代码更容易被别人阅读,也更容易与他人的代码结合——你最好尽早采用这个标准。(如果你感兴趣,可以看看 PEP8

撰写回答