功能中的变量赋值

时间:2013-04-19 22:12:07

标签: python function variables game-physics

我正在编写一个基本的格斗游戏,我正试图让它成为每次攻击时它从敌人的健康中减去攻击的数量并打印出敌人当前的健康状况。但是,运行脚本一次并循环后,运行状况将重置为其原始数量。如何以当前的健康状况让敌人健康?

这是脚本:

import random

while True:
    HEALTH = 20
    ENEMY_HEALTH = 20

    def punch():
        mylist = (xrange(0,3))
        x = random.choice(mylist)
        if x == 3:
            print"your hit was very effective enemy lost 3 hp"
            print("Enemy Health is" ENEMY_HEALTH - x)
        if x == 2:
            print "Your punch was effective enemy lost 2 hp"
            print("Enemy Health is" ENEMY_HEALTH - x)
        if x == 1:
            print "enemy lost 1 point"
            print("Enemy Health is" ENEMY_HEALTH - x)

    def kick():
        mylist = (xrange(0,5))
        x = random.choice(mylist)
        if x > 3:
            "%d" % x
            print"your kick was very effective enemy lost %d hp"
            print("Enemy Health is", ENEMY_HEALTH - x)
        if x > 1 < 3:
            "%d" % x
            print "Your kick was effective enemy lost %d hp"
            print("Enemy Health is" ENEMY_HEAlTH - x)
        if x == 1:
            print "enemy lost 1 point"
            print("Enemy Health is" ENEMY_HEALTH - x)

    def attackChoice(c):
        if c == "punch":
            punch()
        if c == "kick":
            kick()

    c = raw_input("Choice Attack\nKick Or Punch: ")
    attackChoice(c)

我想要打印:

choose attack
kick or punch:kick
enemy lost 3 hp
enemy's heath is 17
choose attack
kick or punch:punch
enemy lost 1 hp
enemy's health is 16

2 个答案:

答案 0 :(得分:2)

您在每个循环步骤中重置HEALTH和ENEMY_health。你必须在循环之外初始化它们,并在循环内部进行操作,如下所示:

HEALTH = 20
ENEMY_HEALTH = 20    
while True:
    #your code
    ENEMY_HEALTH = ENEMY_HEALTH - x

此外,您需要显式设置新值,如示例代码段所示。

另外,请阅读python样式指南: http://www.python.org/dev/peps/pep-0008/

像HEALTH一样的所有大写名称都用于常量,但你不希望它表示常量,所以请你使用小写...

答案 1 :(得分:1)

  • 正如Blender所指出的那样,你没有改变ENEMY_HEALTH的价值,你只需从中减去x并打印它而不会再分配该值。
  • 将您的初始分配移出while循环。
  • 你的踢法代码中有额外的字符串
  • 使用randint而不是构建列表并选择一个

也许像:

import random
health = 20
enemy_health = 20

def punch():
    global enemy_health
    x = random.randint(1,3)
    enemy_health -= x
    if x == 3:
        print"your hit was very effective enemy lost 3 hp"
    if x == 2:
        print "Your punch was effective enemy lost 2 hp"
    if x == 1:
        print "enemy lost 1 point"
    print "Enemy Health is", enemy_health

def kick():
    global enemy_health
    x = random.randint(1,5)
    enemy_health -= x
    if x > 3:
        print "your kick was very effective enemy lost %d hp" % x
    if x > 1 < 3:
        print "Your kick was effective enemy lost %d hp" % x
    if x == 1:
        print "enemy lost 1 point"
    print "Enemy Health is", enemy_health

def attackChoice(c):
    if c == "punch":
        punch()
    if c == "kick":
        kick()

while True:
    c = raw_input("Choice Attack\nKick Or Punch: ")
    attackChoice(c)