gpt4 book ai didi

python - 重置类统计数据的想法

转载 作者:太空宇宙 更新时间:2023-11-03 18:48:47 25 4
gpt4 key购买 nike

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

最佳答案

我可以看到您的编程之旅还处于早期阶段 -

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

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

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

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

关于python - 重置类统计数据的想法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18862710/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com