这篇文章主要介绍“Python怎么实现大鱼吃小鱼游戏”的相关知识,小编通过实际案例向大家展示操作过程,操作方法简单快捷,实用性强,希望这篇“Python怎么实现大鱼吃小鱼游戏”文章能帮助大家解决问题。
大鱼吃小鱼.py
注意程序的mouth对象,它并不是"隐藏"的,虽然它看不见。
小鱼碰到mouth会被“吃掉”。如果把mouth用hide命令设为隐藏,那么是无法获取到mouth的绑定盒,从而碰撞检测失效。
from sprites import *
def calculate_pos(obj):
"""obj:精灵对象。这个函数计算矩形下右角的一个坐标并返回它。
"""
x,y = obj.position() # 角色的坐标
mx,my = mouse_position() # 鼠标指针的坐标
k = 1 if mx > x else -1 # 在右则为1,否则为-1
left,top,right,bottom = obj.bbox()# 获取绑定盒
w = right-left # 大鱼的宽度
h = top - bottom # 大鱼的高度
x0 = x + k * w//2.5 # 嘴巴大概的x坐标
y0 = y - h//12 # 嘴巴大概的y坐标
return x0,y0
width,height = 480,360
screen = Screen() # 新建宽高
screen.setup(width,height) # 设置宽高
screen.bgpic('res/underwater.png') # 设背景图
screen.title("图灵大海之大鱼吃小鱼")
fish_group = Group(tag='fish') # 新建组,标签为fish
fishes = ['res/fish2.png','res/fish3.png','res/fish4.png','res/crab-b.png']
# 由于下面的鱼的标签都是fish,所以会自动加入到fish_group中
for x in range(10):
x = random.randint(-200,200)
y = random.randint(-140,140)
f = Sprite(shape=random.choice(fishes),tag='fish',pos=(x,y))
f.scale(0.5)
[fish.setheading(random.randint(1,360)) for fish in fish_group]
m1 = Mouse(1) # 鼠标左键
fish = Sprite('res/fish2-a.png') # 实例化大鱼
fish.rotatemode(1) # 左右翻转
fishscale= 0.6
fish.scale(fishscale)
mouth = Sprite(shape='circle') # 实例化嘴巴,用于碰撞检测
mouthscale = 0.4
mouth.scale(mouthscale) # 缩放嘴巴大小
mouth.setalpha(0) # 把它设为透明,改为非0它会显示出来
clock = Clock() # 新建时钟对象
while True:
for f in fish_group:
if f.isvisible():f.fd(1) # 在可见的情况下才移动
# 小鱼碰到嘴巴及单击鼠标则被吃掉,大鱼长大
if f.collide(mouth,0.5) and m1.down() :
fishscale += 0.01
fish.scale(fishscale) # 大鱼长大
mouthscale += 0.01
mouth.scale(mouthscale) # 嘴巴跟着加大
x = random.randint(-200,200)
y = random.randint(-140,140)
# 注意这里调用了reborn后,鱼会立即隐藏,3后后出现
# 在3秒内碰撞检测无效,所以鱼不能动
f.reborn(x,y,delay=3)
f.shape(random.choice(fishes))
f.bounce_on_edge()
fish.heading(mouse_pos()) # 大鱼跟随鼠标指针
x0,y0 = calculate_pos(fish) # 计算嘴巴的大概坐标
mouth.goto(x0,y0) # 嘴巴大这个坐标
md = fish.distance(mouse_pos()) # 计算鱼到鼠标指针距离
if md > 50:fish.fd(min(md,4)) # 如果距离大于50则游
# 张嘴与合嘴
if m1.down():
fish.shape('res/fish2-a.png')
else:
fish.shape('res/fish2-b.png')
screen.update()
clock.tick(60)
fish.shape('res/fish2-a.png')
else:
fish.shape('res/fish2-b.png')
screen.update()
clock.tick(60)
关于“Python怎么实现大鱼吃小鱼游戏”的内容就介绍到这里了,感谢大家的阅读。如果想了解更多行业相关的知识,可以关注亿速云行业资讯频道,小编每天都会为大家更新不同的知识点。
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。