马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
from random import *
step_turtle = [-2, -1, 1, 2]
step_fish = [-1, 1]
legal_x = [0,10]
legal_y = [0,10]
class Fish:
def __init__(self):
self.x = randint(legal_x[0], legal_x[1])
self.y = randint(legal_y[0], legal_y[1])
def move(self, step):
new_x = self.x + choice(step)
new_y = self.y + choice(step)
if new_x < legal_x[0]:
self.x = legal_x[0] - (new_x - legal_x[0])
elif new_x > legal_x[1]:
self.x = legal_x[1] -(new_x - legal_x[1])
else:
self.x = new_x
if new_y < legal_y[0]:
self.y = legal_y[0] - (new_y - legal_y[0])
elif new_y > legal_y[1]:
self.y = legal_y[1] - (new_y - legal_y[1])
else:
self.y = new_y
return (self.x, self.y)
class Turtle(Fish):
def __init__(self):
super().__init__()
self.power = 100
def move(self, step):
super().move(step)
new_x = self.x + choice(step)
new_y = self.y + choice(step)
self.power -=1
def eat(self):
self.power += 20
if self.pwoer >100:
self.power = 100
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('乌龟体力耗尽,挂掉了!%d' %len(fish))
break
pos = turtle.move(step_turtle)
for each_fish in fish[:]:
if each_fish.move(step_fish) == pos:
turtle.eat()
fish.remove(each_fish)
print('有一条鱼儿被吃掉了... 还剩%d条鱼' %len(fish))
'''else:
print('乌龟在(%d, %d),鱼儿在(%d, %d)' %(turtle.x, turtle.y, each_fish.x, each_fish.y))'''
这个是对原答案进行小小的改变,就是用类对象的继承省了些代码
但是却发现一个问题,乌龟始终吃不到鱼 |