2016-02-22 222 views
-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 
+1

您没有在'player_turn'函数中添加'global enemy_health' – Arman

+7

*“错误是说我没有定义一个确实定义好的变量” - - 你有一个错误,而且我不打赌口译员。 – jonrsharpe

+1

随机导入后,代码似乎运行。错误发生在哪里以及如何发生? – timgeb

回答

0

所有你需要做的是进口sysrandomtime模块并定义变量win

+0

我有他们导入,但我没有复制它们时,在代码中,我只是看到,我很抱歉,它可能是我运行的IDE,它是Pycharms。我将在今晚晚些时候从另一个系统尝试它,看它是否会运行 –