import random as r
class Turtle:
brawn = 100
def __init__(self,x,y):
self.x = x
self.y = y
def recover(self):
self.brawn += 20
def move(self,xrange,yrange):#需要传入两个列表
'需要传入可移动的范围参数'
direction = r.choice([-1,1,-2,2])# 1上,-1下,2左,-2右
if direction == 1:
d = r.choice([1,2])
if self.y + d <= yrange[1]:
self.y += d
else:
self.y = yrange[1]-(self.y+d-yrange[1])
if direction == -1:
d = r.choice([1,2])
if self.y - d >= yrange[0]:
self.y -= d
else:
self.y = yrange[0]+(d-self.y)
if direction == -2:
d = r.choice([1,2])
if self.x + d <= xrange[1]:
self.x += d
else:
self.x = xrange[1]-(self.x+d-xrange[1])
if direction == 2:
d = r.choice([1,2])
if self.x - d >= xrange[0]:
self.x -= d
else:
self.x = xrange[0]+(d-self.x)
self.brawn -= 1
class Fish:
def __init__(self,x,y):
self.x = x
self.y = y
def move(self,xrange,yrange):#需要传入两个列表
'需要传入可移动的范围参数'
direction = r.choice([-1,1,-2,2])# 1上,-1下,2左,-2右
if direction == 1:
if self.y + 1 <= yrange[1]:
self.y += 1
else:
self.y = yrange[1]-(self.y+1-yrange[1])
if direction == -1:
if self.y - 1 >= yrange[0]:
self.y -= 1
else:
self.y = yrange[0]+(1-self.y)
if direction == -2:
if self.x + 1 <= xrange[1]:
self.x += 1
else:
self.x = xrange[1]-(self.x+1-xrange[1])
if direction == 2:
if self.x - 1 >= xrange[0]:
self.x -= 1
else:
self.x = xrange[0]+(1-self.x)
#乌龟的初始位置
turtle_x = r.randint(0,10)
turtle_y = r.randint(0,10)
turtle = Turtle(turtle_x,turtle_y)
t_fish = [turtle]
for i in range(1,11):
fish_x = r.randint(0,10)
fish_y = r.randint(0,10)
exec('fish{} = Fish(fish_x,fish_y)'.format(i))
exec('t_fish.append(fish{})'.format(i))
#游戏开始
while 1:
movegay = r.choice(t_fish)
movegay.move([0,10],[0,10])
for each in t_fish[1:]:
if (each.x,each.y) == (turtle.x,turtle.y):
print("%s在(%d,%d)被吃掉啦!"%(each,each.x,each.y))
t_fish.remove(each)
turtle.recover()
print("乌龟的体力还剩余%d"%(turtle.brawn))
if turtle.brawn == 0 or len(t_fish) == 1:
break
|