import random as r
class Turtle(object):
def __init__(self):
self.power = 100
# 初始化乌龟的位置
self.x = r.randint(0,10)
self.y = r.randint(0,10)
def move(self):
new\_x = r.choice(\[1,2,-1,-2\]) + self.x
new\_y = r.choice(\[1,2,-1,-2\]) + self.y
# 判断 乌龟的移动是否超出了边界
if new\_x < 0:
self.x = 0 - (new\_x - 0)
elif new\_x > 10:
self.x = 10 - (new\_x - 10)
else:
self.x = new\_x
if new\_y < 0:
self.y = 0 - (new\_y -0)
elif new\_y > 10:
self.y = 10 - (new\_y - 10)
else:
self.y = new\_y
self.power -= 1
return (self.x,self.y)
def eat(self):
self.power += 20
if self.power >= 100:
self.power = 100
class Fish(object):
def \_\_init\_\_(self):
self.x = r.randint(0,10)
self.y = r.randint(0,10)
def move(self):
new\_x = self.x + r.choice(\[1,-1\])
new\_y = self.y + r.choice(\[1,-1\])
if new\_x < 0:
self.x = 0 - (new\_x - 0)
elif new\_x > 10:
self.x = 10 - (new\_x - 10)
else:
self.x = new\_x
if new\_y < 0:
self.y = 0 -(new\_y - 0)
elif new\_y > 10:
self.y = 10 - (new\_y - 10)
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("有一条鱼被吃掉了")
手机扫一扫
移动阅读更方便
你可能感兴趣的文章