如果该elif语句应当运行却没有运行的话

2024-05-14 09:09:05 发布

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

elif语句“elif compScore>;14 and compScore<;18 and choice!=“y”:“似乎没有运行。这是一个学校掷骰子游戏,重点是不超过18。这台电脑有一些规则,比如如果它有15或更高的分数,它就不会滚动。你知道吗

from random import randint

playerScore = compScore = 0
choice = "y"

def RollD6():
    return(randint(1, 6))

def CompTurn():
    global compScore
    if compScore <= 14:
        compScore += RollD6()
    print("compScore = '%s'" % compScore)

def PlayerTurn():
    global playerScore
    choice = input("\nYour current score is %s. Would you like to roll a d6? [y/n] " % playerScore).lower()
    print("choice = '%s'" % choice)
    if choice == "y":
        playerScore += RollD6()
    CompTurn()

print("Welcome to a Black Jack-ish Dice Game!\nThe goal is to roll a D6 until either you or the computer gets to exactly 18.\nBut if you roll over 18 you lose.")
while True:
    if compScore == 18:
        print("The computer rolled to 18 faster, better luck next time.")
        break

    elif playerScore == 18:
        print("Your score was %s." % playerScore)
        print("Congrats, you ended up beating the computer by %s points." % str(playerScore - compScore))
        break
# V This is the elif statement, I've tried changing it quite a bit, along with the order V
    elif compScore > 14 and compScore < 18 and choice != "y": 
        print("Your score was %s." % playerScore)
        print("It seems you would've gotten into a loop with the computer, so the computer wins.")
        break

    elif playerScore > 18:
        print("Your score was %s." % playerScore)
        print("Whoops, guess you got a little greedy. The computer won because you rolled over 18.")
        break

    elif compScore > 18:
        print("Your score was %s." % playerScore)
        print("The computer ended up rolling over 18, so you win!")
        break
    PlayerTurn()

Tags: andthetoyouyourifcomputerscore
2条回答

虽然global可能会使这项工作正常,但也许一种更为python的方法是让PlayerTurn函数返回一个要使用的值。例如:


def PlayerTurn():
   ...
   return choice

...

while True:
   ...
   choice = PlayerTurn()
   CompTurn() # Optional, but I recommend removing this function call  from the PlayerTurn() call. 
   #If someone was to look at your code cold, they may wonder where the CompTurn() gets called, 
   #because it is inconsistent for that to be in the PlayerTurn() function.

它永远不会进入这种情况的原因是choice变量实际上没有被更新。在最外层作用域中定义的选项必须在PlayerTurn函数中标记为global,就像playerScore一样。你知道吗

def PlayerTurn():
    global playerScore
    global choice # < - You need this line
    choice = input("\nYour current score is %s. Would you like to roll a d6? [y/n] " % playerScore).lower()
    print("choice = '%s'" % choice)
    if choice == "y":
        playerScore += RollD6()

相关问题 更多 >

    热门问题