返回动态计算

时间:2016-06-20 11:13:08

标签: python python-3.x

我很确定这是我可以忽略的最容易犯的错误。曾经有过类似的问题,但是不记得我为了上帝的爱而如何解决它......

import random

enemy_hp = 100
player_hp = 100
enemy_hit = random.randint(1, 10)
enemy_meteor = 8
enemy_heal = 3
player_hit = random.randint(1,10)
player_fireball = 5
player_heal = 7

def eHit(enemy_hit):
    player_hp = 100-enemy_hit
    print (player_hp)

eHit(enemy_hit)

好吧我编辑了它并且它的工作是有意的,但即使有了这个教程,我也在努力解决其他问题。

  

如何在计算后保存新值,因此它始终不是从100开始?

2 个答案:

答案 0 :(得分:1)

print(eHit)错了; eHit是一个函数,而不是一个变量。您应该将其称为print(eHit(somthing))

纯粹基于开头的变量声明的名称,我想你的意思是print(eHit(enemy_hit))

然后您遇到player_hp是局部变量的问题,并在分配前使用,所以现在需要更改eHit()

def eHit(enemy_hit, player_hp):
    player_hp -= enemy_hit
    return player_hp - enemy_hit

现在您的打印声明

print(eHit(enemy_hit, player_hp))

您定义的其他功能也是如此。

答案 1 :(得分:0)

由于您已编辑原始问题,而您现在正在询问

  

如何在计算后保存新值,因此它并非总是如此   从100开始?

您需要return新值并分配给player_hp变量并移动enemy_hit的随机化,以便在您调用eHit()之前实际获取新值,像这样

import random

enemy_hp = 100
player_hp = 100
enemy_meteor = 8
enemy_heal = 3
player_hit = random.randint(1,10)
player_fireball = 5
player_heal = 7

def eHit(enemy_hit, player_hp):
    player_hp = player_hp - enemy_hit
    return player_hp

while player_hp > 0:
    enemy_hit = random.randint(1, 10)
    player_hp = eHit(enemy_hit, player_hp)
    print (player_hp)

我已将while player_hp > 0放在那里进行测试

考虑到这一点,我会再次尝试一下,下面的代码让你自己试试:

import random


player_hp = 100

def random_hit(start = 1, stop = 10):
    return random.randint(start, stop)

def enemy_hit(player_hp):
    return player_hp - random_hit()

while player_hp > 0:
    player_hp = enemy_hit(player_hp)
    print (player_hp)

现在您可以使用默认值调用random_hit(),或使用更改的参数调用"更大"点击random_hit(20, 30),您也可以从其他功能调用random_hit(),无需重复分配。

你可以采取更进一步,因为击中是一个打击,无论谁打谁,所以没有双重功能,这样的事情:

import random


player_hp = 100
enemy_hp = 100

def hit(hp, start = 1, stop = 10):
    return hp - random.randint(start, stop)

while player_hp > 0:  ## while loop only for testing purposes
    # for a enemy hitting a player with normal force, call this:
    player_hp = hit(player_hp)
    print (player_hp)

while enemy_hp > 0:  ## while loop only for testing purposes
    # for a player hitting an enemy with extra force, call this:
    enemy_hp = hit(enemy_hp, 10, 20)
    print (enemy_hp)