【发布时间】:2023-01-08 02:40:43
【问题描述】:
我是编码新手,我正在尝试构建一个简单的剪刀石头布游戏。
在尝试在游戏中实现生命时,我似乎无法在生命 > 0 时循环。尽管我试图将 lives 变量设置为全局变量以便能够在函数外使用它,但它似乎不起作用。相反,当我运行程序时出现这样的错误:
NameError: 名称 'lives' 未定义
也许我对全局变量的理解是错误的。任何帮助将非常感激。先感谢您。
这是我的代码
import random def play(): player = input("Choose 'r' for rock, 'p' for paper, 's' for scissor or 'q' to quit: ") choices = ['r', 'p', 's', 'q'] global lives lives = 3 if player in choices: if player == 'q': exit() computer = random.choice(['r', 'p', 's']) print(f'Computer chose {computer}') if player == computer: return f"It's a tie! You still have {lives} lives" if is_win(player, computer): lives += 1 print('+1 life') return f'You now have {lives} lives' lives -= 1 print('-1 life') return f'You now have {lives} lives' else: print('Invalid input. Please enter a valid value') return play() def is_win(user, opponent): if (user == 'r' and opponent == 's') or (user == 's' and opponent == 'p') or (user == 'p' and opponent == 'r'): return True while lives > 0: print(play()) else: print('You have 0 lives left. GAME OVER')
【问题讨论】:
-
global lives表示从全局范围获取变量lives。在调用global lives之前,您没有定义lives变量,因此它会给您一个错误。另请注意,全局变量是considered bad