我想知道如何解决我在第一段OOP代码中遇到的这个问题。问题在于Snake类的攻击方法。我有两条蛇在游戏中,并试图让蛇攻击另一条。目前我使用两个变量来记录它是哪条蛇的回合,然后用这个来攻击另一条蛇。然而,这是行不通的。有人知道怎么解决这个问题吗?非常感谢你。在
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
我看到两个问题。第一个是传递变量的名称,而不是变量本身。在
更改此项:
为此:
^{pr2}$另外,在Snake类中定义了两次攻击字段。在
以下是我玩了你的代码后想到的:
{{{cd2>当你没有调用任何参数时。我想你想要
beta.attack(alpha,beta)
但是你可以重构这个方法,只需要对手作为参数(因为你知道谁在攻击(它是调用攻击方法的对象))
在“攻击”中你试图进入对面.hp“,但此方法是用字符串而不是对象调用的:
=>;将此更改为
^{pr2}$另外,类中还有一个同名的字段和方法:attack。我建议将该字段重命名为“attackpoints”或其他名称。在
另外,你打电话给我”贝塔攻击()". 你忘了方法。在
相关问题 更多 >
编程相关推荐