我想知道如何解决这个问题,我用我的第一块OOP代码。问题在于Snake类的攻击方法。我在比赛中有两条蛇,并试图让蛇去攻击另一条蛇。目前我使用两个变量来记录Snake的轮到它,然后使用它来尝试攻击另一个蛇。但是这不起作用。任何人有任何想法如何解决这个问题?非常感谢。Python面向对象编程新手
class Snake:
hp=100
attack=25
defense=1
def set_name(self, name):
self.name=name
def shed(self):
self.defense=self.defense+1
def attack(self, opposite, current):
opposite.hp=opposite.hp-(current.attack-opposite.defense)
def eat(self):
self.attack=self.attack+5
print(str(self.name) + " eats a rat!")
print(str(self.name) + "'s attack dmg is now " + str(self.attack))
def sleep(self):
print (str(self.name) + " goes to sleep")
self.hp=self.hp+10
if self.hp>100:
self.hp=100
print (str(self.name) + " wakes up with " + str(self.hp) + "hp")
##initialises the snakes
alpha=Snake()
beta=Snake()
## gives the snakes names of the user's choice
alpha_name=raw_input("What would you like to name your snake? ")
alpha.set_name(alpha_name)
beta_name=raw_input("What would you like to name the other snake? ")
beta.set_name(beta_name)
##starts the game
turn=True
while alpha.hp>0 and beta.hp>0:
while turn==True:
opposite="beta"
current="alpha"
action=raw_input("attack, sleep, eat or shed? ")
try:
if action=="attack":
alpha.attack(opposite, current)
if action=="sleep":
alpha.sleep()
if action=="eat":
alpha.eat()
if action=="shed":
alpha.shed()
turn=False
except IOError:
print("Please chose only one action, exaclty how it is typed")
while turn==False:
opposite="alpha"
current="beta"
if beta.hp<15:
beta.sleep()
elif alpha.hp>75:
beta.attack()
else:
index=random.randint(1, 3)
if index==1:
beta.shed()
elif index==2:
beta.eat()
else:
beta.attack(opposite, current)
turn=True
“不工作”是完全无用的报告。会发生什么,如果发生错误,您准备发生什么,确切的消息和追溯等等。 – delnan 2011-06-09 14:27:29
请告诉我们究竟发生了什么。问一个问题的好方法是:1.问题背景2.你期望发生什么3.发生什么4.有问题的代码 – JackMc 2011-06-09 14:28:07
@JackMc:允许窃取该评论并使用它? – Trufa 2011-06-09 14:38:46