第37讲动手题1
import random as rlegal_x =
legal_y =
class Turtle:
def __int__(self):
self.power = 100
self.x = r.randint(legal_x,legal_x)
self.y = r.randint(legal_y,legal_y)
def move(self):
new_x = self.x + r.choice()
new_y = self.y + r.choice()
if new_x < legal_x:
self.x = legal_x - (new_x - legal_x)
elif new_x > legal_x:
self.x = legal_x - (new_x - legal_x)
else:
self.x = new_x
if new_y < legal_y:
self.y = legal_y - (new_y - legal_y)
elif new_y > legal_y:
self.y = legal_y - (new_y - legal_y)
else:
self.y = new_y
self.power -= 1
return (self.x,self.y)
def eat(self):
self.power += 2
if self.power > 100:
self.power = 100
class Fish:
def __int__(self):
self.x = r.randint(legal_x,legal_x)
self.y = r.randint(legal_y,legal_y)
def move(self):
new_x = self.x + r.choice()
new_y = self.y + r.choice()
if new_x < legal_x:
self.x = legal_x - (new_x - legal_x)
elif new_x > legal_x:
self.x = legal_x - (new_x - legal_x)
else:
self.x = new_x
if new_y < legal_y:
self.y = legal_y - (new_y - legal_y)
elif new_y > legal_y:
self.y = legal_y - (new_y - legal_y)
else:
self.y = new_y
return (self.x,self.y)
turtle = Turtle()
fish = []
for i in range(10):
new_fish = Fish()
fish.append(new_fish)
while True:
if not len(fish):
print('鱼儿吃完了,游戏结束')
break
if not turtle.power:
print('乌龟体力耗尽,挂掉了')
break
pos = turtle.move()
for each_fish in fish[:]:
if each_fish.move() == pos:
turtle.eat()
fish.remove(each_fish)
print("有一条鱼儿被吃掉了")
我按照答案的代码输入的,为啥显示
Traceback (most recent call last):
File "E:\360MoveData\Users\Administrator\Desktop\统计软件\python\定义乌龟类和鱼类,编写游戏.py", line 73, in <module>
if not turtle.power:
AttributeError: 'Turtle' object has no attribute 'power' 原来是__init__输入错误,很容易输入成int{:5_104:}{:5_104:}{:5_104:}{:5_104:}
页:
[1]