定义要在定义的PYTHON中运行的全局变量

时间:2015-03-20 01:40:30

标签: python

所以我正在为学校作业编写一个基于RPG文本的游戏,尽管我在制作玩家健康状况的全局变量方面遇到了麻烦,因为我已经在定义的函数中编写了战斗逻辑。目前,每次该功能播放时都会将playerHealth设置为100,尽管我希望它能使playerHealth等于上次修改时间。例如:如果我参加了一场战斗并失去了10点生命值,那么我的健康状况就会达到90,那么下一次我的战斗就会达到90点生命值。

def battle():
  playerHealth = 100
  enemyHealth = 20


  while enemyHealth > 0:

  attack = input('Melee or Ranged Attack?\n> ').lower()
  if attack[0] == 'm':
      chance = random.randint(0,2)
      if chance == 0:
          print('***********')
          print('You missed!')
          print('***********')
          print('You receive 4 damage')
          playerHealth -= 4
          print('')
          print('Player Health = ' + str(playerHealth))

      else:
          print('You hit the enemy, also causing damage to yourself')
          print('Enemy receives 3 damage')
          print('Player receives 1 damage')
          enemyHealth -= 4
          playerHealth -= 1
          print('')
          print('Enemy Health = ' + str(enemyHealth))
          print('Player Health = ' + str(playerHealth))

  elif attack[0] == 'r':
      chance = random.randint(0,2)
      if chance == 0:
          print('***********')
          print('You missed!')
          print('***********')
          print('The enemy attacks you causing 3 damage')
          playerHealth -= 3
          print('')
          print('Player Health = ' + str(playerHealth))

      else:
          print('-----------')
          print('Direct hit!')
          print('-----------')
          print('Enemy receives 2 damage')
          enemyHealth -= 2
          print('')
          print('Enemy Health = ' + str(enemyHealth))

print('---------------------')           
print('You killed the enemy!') 
print('---------------------')

然后我会使用:

if "enemy" in deadZone[currentArea1]:
  battle()

2 个答案:

答案 0 :(得分:0)

def battle(player_health, enemy_health):
    ...
    ...
    return player_health, enemy_health


player_health, enemy_health = battle(100, 20)

答案 1 :(得分:0)

在函数外部初始化它,将其传递给函数,并让函数返回它。

def battle(playerHealth):
    ...
    return playerHealth

...

if "enemy" in deadZone[currentArea1]:
    playerHealth = battle(playerHealth)