未定义已定义的变量

时间:2016-02-22 21:23:53

标签: python variables import nameerror

我正在进行文本冒险以学习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

1 个答案:

答案 0 :(得分:0)

您需要做的就是导入sysrandomtime模块并定义变量win