-5
我正在學習Python的文本冒險。我已經到了我想創建一個戰鬥引擎的地方,並遇到一個問題,其中的錯誤是說我沒有定義一個確實定義好的變量。附件是戰鬥引擎的代碼,然後我會後我收到錯誤:未定義變量
import random
import time
import sys
player_health = 100
enemy_health = random.randint(50,120)
def monster_damage():
global player_health
global enemy_health
mon_dmg = random.randint(5, 25)
enemy_health -= mon_dmg
print('You hit the beast for ' + str(mon_dmg) + ' damage! Which brings its health to ' + str(enemy_health))
if enemy_health < 0:
print('You have vanquished the beast and saved our Chimichongas')
win == True
time.sleep(10)
else:
player_dmg()
def player_dmg():
global player_health
global enemy_health
pla_dmg = random.randint(5, 15)
player_health -= pla_dmg
print(
'The beast strikes out for ' + str(pla_dmg) + ' damage to you. This leaves you with ' + str(player_health))
if player_health > 0 and enemy_health > 0:
player_turn()
elif player_health <= 0:
print('The beast has vanquished you!')
win == False
time.sleep(10)
sys.exit()
def run_away():
run_chance = random.randint(1, 10)
if run_chance > 5:
print('You escape the beast!')
time.sleep(10)
sys.exit()
else:
print('You try to run and fail!')
player_dmg()
def player_turn():
print('Your Turn:')
print('Your Health: ' + str(player_health) + ' Monsters Health: ' + str(enemy_health))
print('What is your next action?')
print('Please Select 1 to attack or 2 to run.')
action = int(input())
if action == 1:
monster_damage()
elif action == 2:
run_away()
def battle_start():
player_turn()
battle_start()
,並且錯誤是:
Traceback (most recent call last):
File "C:/Users/rhood/Documents/python_files/game/rps_exp.py", line 15, in <module>
game()
File "C:\Users\rhood\Documents\python_files\game\main_game.py", line 25, in game
battle()
File "C:\Users\rhood\Documents\python_files\game\battle.py", line 63, in battle
battle_start()
File "C:\Users\rhood\Documents\python_files\game\battle.py", line 61, in battle_start
player_turn()
File "C:\Users\rhood\Documents\python_files\game\battle.py", line 56, in player_turn
monster_damage()
File "C:\Users\rhood\Documents\python_files\game\battle.py", line 14, in monster_damage
enemy_health -= mon_dmg
NameError: name 'enemy_health' is not defined
您沒有在'player_turn'函數中添加'global enemy_health' – Arman
*「錯誤是說我沒有定義一個確實定義好的變量」 - - 你有一個錯誤,而且我不打賭口譯員。 – jonrsharpe
隨機導入後,代碼似乎運行。錯誤發生在哪裏以及如何發生? – timgeb