返回动态计算

2024-05-23 21:49:28 发布

您现在位置:Python中文网/ 问答频道 /正文

我确信这是我能忽略的最容易的错误。曾经有过类似的问题,但不记得我是如何为了上帝的爱解决的。。。你知道吗

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)

好吧,我编辑了它和它的工作意图,但即使有教程,我挣扎着与其他东西。你知道吗

How do i save the new value after the calulation so it doesnt always start at 100?


Tags: theimportdef错误randomhpplayerrandint
2条回答

因为你已经编辑了原来的问题,现在你正在问

How do i save the new value after the calulation so it doesnt always start at 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)

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))

您定义的其他函数也是如此。你知道吗

相关问题 更多 >