python 第37讲 课后动动手第二题 乌龟吃鱼游戏
花了一下午时间终于做出来了,第一次做出这么酷的小程序,真高兴{:5_109:}有不足的地方请指教
1. 游戏编程:按以下要求定义一个乌龟类和鱼类并尝试编写游戏。(初学者不一定可以完整实现,但请务必先自己动手,你会从中学习到很多知识的^_^)
假设游戏场景为范围(x, y)为0<=x<=10,0<=y<=10
游戏生成1只乌龟和10条鱼
它们的移动方向均随机
乌龟的最大移动能力是2(Ta可以随机选择1还是2移动),鱼儿的最大移动能力是1
当移动到场景边缘,自动向反方向移动
乌龟初始化体力为100(上限)
乌龟每移动一次,体力消耗1
当乌龟和鱼坐标重叠,乌龟吃掉鱼,乌龟体力增加20
鱼暂不计算体力
当乌龟体力值为0(挂掉)或者鱼儿的数量为0游戏结束
import random
class Tortoise:
""""乌龟类"""
def __init__(self,name):
"""初始化属性"""
self.name = name
self.physical_power = 100
self.x = random.randint(1,9)
self.y = random.randint(1,9)
print(f'{self.name}出现在{self.x},{self.y}')
def eat(self, goal):
"""乌龟吃鱼方法"""
if self.physical_power < 100:
self.physical_power += 20
else:
self.physical_power = 100
print(f'{self.name}吃掉{goal}')
def move(self):
"""移动方法"""
self.i = random.randint(-2,2)
self.x += self.i
self.i = random.randint(-2, 2)
self.y += self.i
self.physical_power -= 1
if self.x > 9 or self.x < 0:
if self.x > 9:
self.x = self.x - (self.x - 9)
elif self.x < 0:
self.x = self.x - (self.x - 0)
if self.y > 9 or self.y < 0:
if self.y > 9:
self.y = self.y - (self.y - 9)
elif self.y < 0:
self.y = self.y - (self.y - 0)
print(f'{self.name}移动到{self.x},{self.y}')
class Fish:
"""鱼类"""
def __init__(self,name):
"""初始化属性"""
self.name = name
self.x = random.randint(1, 9)
self.y = random.randint(1, 9)
print(f'{self.name}出现在{self.x},{self.y}')
def move(self):
"""移动方法"""
self.i = random.randint(-1, 1)
self.x += self.i
self.i = random.randint(-1, 1)
self.y += self.i
if self.x > 9 or self.x < 0:
if self.x > 9:
self.x = self.x - (self.x - 9)
elif self.x < 0:
self.x = self.x - (self.x - 0)
if self.y > 9 or self.y < 0:
if self.y > 9:
self.y = self.y - (self.y - 9)
elif self.y < 0:
self.y = self.y - (self.y - 0)
print(f'{self.name}移动到{self.x},{self.y}')
"""生成1只乌龟和10只鱼"""
tortoise = Tortoise('乌龟')
fish_list = []
for i in range(1,11):
fish = 'Fish' + str(i)
fish = Fish(fish)
fish_list.append(fish)
"""移动并判断是否碰撞"""
while True:
if tortoise.physical_power == 0:
print('乌龟体力耗尽,游戏结束!')
break
if len(fish_list) == 0:
print('鱼已被消灭,游戏结束!')
break
else:
tortoise.move()
for each_fish in fish_list:
each_fish.move()
for each_fish in fish_list:
if tortoise.x == each_fish.x and tortoise.y == each_fish.y:
tortoise.eat(each_fish.name)
fish_list.remove(each_fish)
print('')
{:5_106:} 我什么时候才可以写出来啊,加油 {:7_136:}
页:
[1]