在课堂上重置统计数据的想法

时间:2013-09-18 01:58:02

标签: python python-2.7 reset

我制作了一个简单的程序但是当我的怪物死亡时,统计数据不会重置(主要是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"

1 个答案:

答案 0 :(得分: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

然后你可以在每个循环中创建一个新的狮子,类怪物,并让你的英雄战斗它。狮子只存在于当前的循环中,所以每当你创造一只狮子时,它就会成为一个全新的怪物。

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