按以下要求定义一个乌龟类和鱼类并尝试编写游戏
学习内容:
按以下要求定义一个乌龟类和鱼类并尝试编写游戏。
#1、假设游戏场景为范围(x,y)为0<= x <=10,0<= y <=10
#2、游戏生成1只乌龟和10条鱼
#3、它们的移动方向是随机的
#4、乌龟的最大移动能力是2(它可以随机选择移动1还是2),鱼儿的最大移动能力是1
#5、当移动到场景边缘,自动反方向移动
#6、乌龟初始化体力为100(上限)
#7、乌龟每移动一次,体力消耗1
#8、当乌龟和鱼坐标重叠,乌龟吃掉鱼,乌龟体力增加20
#9、鱼暂不计体力
#10、当乌龟体力值为0(挂掉)或者鱼儿的数量为0游戏结束
学习产出:
#游戏编程:按以下要求定义一个乌龟类和鱼类并尝试编写游戏。
#1、假设游戏场景为范围(x,y)为0<= x <=10,0<= y <=10
#2、游戏生成1只乌龟和10条鱼
#3、它们的移动方向是随机的
#4、乌龟的最大移动能力是2(它可以随机选择移动1还是2),鱼儿的最大移动能力是1
#5、当移动到场景边缘,自动反方向移动
#6、乌龟初始化体力为100(上限)
#7、乌龟每移动一次,体力消耗1
#8、当乌龟和鱼坐标重叠,乌龟吃掉鱼,乌龟体力增加20
#9、鱼暂不计体力
#10、当乌龟体力值为0(挂掉)或者鱼儿的数量为0游戏结束
import random as r
class Turtle:
def __init__(self):
self.num=1
self.power=100
self.x=r.randint(0,9)
self.y=r.randint(0,9)
print("乌龟初始位置是:(%d %d)"%(self.x,self.y))
def move(self):
random_move=r.randint(1,4) #产生1向左移动,2向右移动,3向上移动,4向下移动
if random_move ==1:
self.x -=r.randint(1,2)
elif random_move ==2:
self.x +=r.randint(1,2)
elif random_move ==3:
self.y +=r.randint(1,2)
else:
self.y -=r.randint(1,2)
self.power -=1
print("乌龟随机移动后的位置是:(%d %d),乌龟体力值:%d"%(self.x,self.y,self.power))
#如果乌龟移动到边缘,则进行自动反方向移动
if self.x==0 or self.x==10 or self.y==0 or self.y==10:
if self.x==0:
self.x +=r.randint(1,2)
elif self.x ==10:
self.x -=r.randint(1,2)
elif self.y ==0:
self.y +=r.randint(1,2)
elif self.y ==10:
self.y -=r.randint(1,2)
self.power -=1
print("乌龟运动到边缘,反向移动后的位置是:(%d %d),乌龟体力值:%d"%(self.x,self.y,self.power))
return (self.x,self.y)
def eat(self):
self.power +=20
if self.power >100:
self.power=100
print("现在乌龟的体力值:",self.power)
class Fish:
def __init__(self):
self.num=10
self.x=r.randint(0,9)
self.y=r.randint(0,9)
print("小鱼鱼初始位置是:(%d %d)"%(self.x,self.y))
def move(self):
random_move=r.randint(1,4) #产生1向左移动,2向右移动,3向上移动,4向下移动
if random_move ==1:
self.x -=1
elif random_move ==2:
self.x +=1
elif random_move ==3:
self.y +=1
else:
self.y -=1
print("小鱼鱼随机移动后的位置是:(%d %d)"%(self.x,self.y))
#如果小鱼鱼移动到边缘,则进行自动反方向移动
if self.x==0 or self.x==10 or self.y==0 or self.y==10:
if self.x==0:
self.x +=1
elif self.x ==10:
self.x -=1
elif self.y ==0:
self.y +=1
elif self.y ==10:
self.y -=1
print("小鱼鱼运动到边缘,反向移动后的位置是:(%d %d)"%(self.x,self.y))
return (self.x,self.y)
#类的实例化对象
a=Turtle()
#产生10条小鱼的坐标————
fish=[]
for i in range(0,10):
b=Fish()
fish.append(b)
#游戏编程
while True:
turtle=a.move()
for each_fish in fish[:]:
xiaoyu=each_fish.move()
if xiaoyu==turtle:
a.eat()
fish.remove(each_fish)
print("有条鱼被吃啦!,现在还剩下%d 条鱼"%(len(fish)))
if not a.power:
print("乌龟的体力值用完啦!游戏结束")
break
if not len(fish):
print("小鱼鱼的数量为0,游戏结束")
break