0

我正在编写一个基本的格斗游戏,并试图让它在每次攻击时从敌人的生命值中减去攻击量并打印敌人的当前生命值。但是,在我运行脚本一次并循环后,运行状况会重置为其原始数量。我怎样才能用当前的健康放弃敌人的健康?

这是脚本:

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
4

2 回答 2

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 这样的大写名称都用于常量,但您不希望它表示常量,所以请使用小写...

于 2013-04-19T22:17:22.017 回答
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)
于 2013-04-19T22:20:36.633 回答