乌龟吃鱼游戏编程
游戏场景为范围(x,y)为0<=x<=10,0<=y<=10
参与对象:1只王八和10条鱼
要求:它们的移动方向均随机;王八的最大移动能力为2(它可以随机选择1还是2移动),鱼儿的最大移动能力是1
移动机制:当移动到场景边缘,自动向反方向移动
初始条件:王八初始化体力为100(上限)
体力增减:王八每移动一次,体力消耗1,当王八和鱼坐标重叠,乌龟吃掉鱼,乌龟体力增加20
结束条件:当王八体力值为0(挂掉)或者鱼儿的数量为0游戏结束
import random
class Trutle(object):
def __init__(self):
self.x = random.randint(0, 10)
self.y = random.randint(0, 10)
self.power = 100
def move(self):
move_skill = [-2, -1, 0, 1, 2]
new_x = self.x + random.choice(move_skill)
new_y = self.y + random.choice(move_skill)
self.x = self.is_vaild(new_x)
self.y = self.is_vaild(new_y)
self.power -= 1
def is_vaild(self, value):
"""判断坐标值是否合法(0~10之间), 返回合法的值"""
if value < 0:
return abs(value)
elif value > 10:
return 10 - (value - 10)
return value
def eat(self):
self.power += 20
class Fish(object):
def __init__(self):
self.x = random.randint(0, 10)
self.y = random.randint(0, 10)
def move(self):
move_skill = [-1, 0, 1, ]
new_x = self.x + random.choice(move_skill)
new_y = self.y + random.choice(move_skill)
self.x = self.is_vaild(new_x)
self.y = self.is_vaild(new_y)
def is_vaild(self, value):
"""判断坐标值是否合法(0~10之间), 返回合法的值"""
if value < 0:
return abs(value)
elif value > 10:
return 10 - (value - 10)
return value
def start_game():
t1 = Trutle()
fishs = [Fish( ) for i in range(10)]
while True:
if t1.power <= 0:
print("乌龟没体力了, Game over.........")
break
elif len(fishs) == 0:
print("鱼被吃光了, Game over......... ")
break
else:
t1.move()
for index, fish in enumerate(fishs):
fish.move()
if t1.x == fish.x and t1.y == fish.y:
t1.eat()
fishs.remove(fish)
print("鱼被吃掉, 还剩%d条鱼......." %(len(fishs)))
print("乌龟最新体能为%s" %(t1.power))
else:
print("乌龟没有吃到鱼, 最新体能为%s" %(t1.power))
如果这个脚本(模块), 没有被调用, 则执行下面的代码
if __name__ == "__main__":
print("游戏开始".center(50, '*'))
start_game()
继承方式实现游戏
import random
class Animals(object):
def __init__(self):
self.x=random.randint(0,10)
self.y=random.randint(0,10)
def move(self,move_skill):
new_x=self.x+random.choice(move_skill)
new_y=self.y+random.choice(move_skill)
self.x=self.is_vaild(new_x)
self.y=self.is_vaild(new_y)
def is_vaild(self,value):
if value<0:
return abs(value)
elif value>10:
return 10-(value-10)
return value
class Trutle(Animals):
def __init__(self):
super(Trutle, self).__init__()
self.power=100
def move(self,move_skill=[-2,-1,0,1,2]):
super(Trutle, self).move(move_skill)
self.power-=1
def eat(self):
self.power+=20
class Fish(Animals):
def move(self,move_skill=[-1,0,1]):
super(Fish,self).move(move_skill)
def start_game():
t1=Trutle()
fishs=[Fish() for i in range(10)]
while True:
if t1.power<=0:
print('\033[94m'+'乌龟没体力,gameover')
break
elif len(fishs)==0:
print('鱼被吃光,gameover')
break
else:
t1.move()
for index,fish in enumerate(fishs):
fish.move()
if t1.x==fish.x and t1.y==fish.y:
t1.eat()
fishs.remove(fish)
print('\033[93m'+'鱼被吃掉,还剩%d条鱼' %(len(fishs)))
print('乌龟最新体能为%s' %(t1.power))
else:
print('\033[94m'+'乌龟没有吃到鱼,最新体能为%s' %(t1.power))
如果这个脚本(模块)没有被调用,则执行下边的代码
if __name__=='__main__':
print('游戏开始'.center(50,'*'))
start_game()