1

我做了一个简单的程序,但是当我的怪物死亡时,统计数据不会重置(主要是 hp)我迷失了如何在每次怪物 hp 达到 0 并获得 xp 时重置它。我知道我可以一次又一次地编写代码,但我希望能够让它继续下去是尽可能少的代码。我还在学习python,所以我并不像这里的其他人那样真正了解。我已经上课了,但没有那么深入这里是代码:

import random

def title():
    print"hello Hero, welcome to staghold"
    print"you have traveld along way, and you find yourself"
    print"surrounded by and army of monsters as far as the eye can see"
    print"begin to draw your sword.....you run full speed towards the army"
    print"how many monsters can you kill before the inevatable comes?"
    raw_input("(press enter to continue)")

def stats():
    print"you have 200 health"
    print"your level is 1"
    print"you have 0 exp"
    raw_input("(press enter to continue)")
class monster:
    hp=50
    monsterattack=random.randint
    xp=random.randint(20,50)

health=200
level=1
exp=0
wave=1

title()
stats()
print"you run into a wave"
while level==1:
    if monster.hp<=0:
        print"you have defeated this wave of monsters"
        wave+=1
        exp+=monster.xp
        print" you get, "+str(monster.xp)+" exp from the monster"
        print"you now have, "+str(exp)+" exp"
        if exp>=300:
            level+=1
            if level==2:
                print"CONGRADULATIONS YOU HAVE REACHED LEVEL 2"
    elif monster.hp>=0:
        choice=raw_input("Will you 'fight' or 'run' from this horde?")
        if choice=='fight':
            print"you swing your sword at the monster"
            att=random.randint(2, 13)
            health-=monster.monsterattack(2,15)
            monster.hp-=att
            hp=200-health
            print"you do, "+str(att)+" damage to the monster"
            print"the monster does, "+str(hp)+"  damage to you"
            print"you have, "+str(health)+" health left"
            print"the monster has, "+str(monster.hp)+" health left"
        elif choice=="run":
            print"you got away from this wave safely"
        else:
            print"NOT A VALID CHOICE"
4

1 回答 1

1

我可以看到你的编程之旅还很早-

在你的例子中,怪物是一个类。这意味着它是对对象行为方式的定义。这很好——但你永远不会定义一个怪物的例子。那会是这样的

lion = monster()

这将创建一个名为狮子的新怪物。你需要在怪物类中设置一个构造函数,告诉程序如何构建一个新的怪物,例如

class Monster:
    def __init__(self):
        self.hp = 50
        self.xp = random.randint(20,50)

    def monsterattack(self):
        return random.randint()

这将允许您创建一个怪物,并允许您使用该怪物攻击

damage = lion.monsterattack

然后,您可以在每个循环中创建一个新的狮子级怪物 - 并让您的英雄与之战斗。狮子只会存在于循环的当前运行中,因此每次创建狮子时,它都会是一个全新的怪物。

我喜欢你的奉献精神——坚持下去,阅读一些基本教程!

于 2013-09-18T02:56:35.413 回答