第二次运行的问题:石头,纸张,剪刀问题-Python [重复]

问题描述 投票:-1回答:2

此问题已经在这里有了答案:

因此,我创建了一个代码来模拟石头,纸,剪刀的游戏。当我第一次打开程序时,它可以工作!从一开始就新鲜,它有效。

问题是第二次运行时。由于某种原因,我的“ while”不再起作用。当任何玩家达到3胜时,while循环都应停止。 can可以看到我达到了17胜13胜,而且事情并没有停止...

enter image description here

这仅在程序的首次运行时发生。

代码:

###########function of the random module
import random

###########possible options of play and the number of single wins to win the match
options = ["stone", "paper", "scissors"]
win_the_game = 3

############function that randomly returns one of the 3 options

def machine_play(a):
    return(random.choice(a))

############function that asks your choice: 'stone', 'paper' or 'scissors'

def user_play():
    a = input("Enter your choice: ")
    if a not in options:
            print("Not a valid option, try again ('stone', 'paper', 'scissors')")
    while a not in options:
        a = input("Enter your choice: ")
        if a not in options:
            print("Not a valid option, try again ('stone', 'paper', 'scissors')")
    return a

############function that resolves a combat

def combat(mchoice,uchoice):
    if mchoice == uchoice:
        return 0
    elif uchoice == "stone":
        if mchoice == "scissors":
            return 2
        else:
            return 1
    elif uchoice == "paper":
        if mchoice == "stone":
            return 2
        else:
            return 1
    elif uchoice == "scissors":
        if mchoice == "paper":
            return 2
        else:
            return 1

############variables that accumulate the wins of each participant
machine_wins = 0
user_wins = 0

#######################     The final loop or program     ######################
while machine_wins or user_wins < win_the_game:
    user_choice = user_play()
    machine_choice = random.choice(options)
    print("The machine choice is: ", machine_choice)

    the_game = combat(machine_choice, user_choice)
    if the_game == 1:
        machine_wins += 1
    elif the_game == 2:
        user_wins += 1
    else:
        print("Its a tie!! continue")

    print("\nUser wins: ", user_wins, "\nMachine wins: ", machine_wins) 
python
2个回答
1
投票
while machine_wins or user_wins < win_the_game:

此解析为

while machine_wins or (user_wins < win_the_game):

只要machine_wins是“真实的”,即肯定的,游戏将永远持续下去。我相信您需要的是

while machine_wins < win_the_game and \
         user_wins < win_the_game:
© www.soinside.com 2019 - 2024. All rights reserved.