pygame制作小猫吃鱼1

pygame

界面

创立一个pygame的界面

# python pygame
'''引入模块'''
import pygame, sys, random
from pygame.locals import *
'''模块初始化'''
pygame.init()
'''创立窗口大小和标题'''
size = width, height = 600, 400
# 窗口大小
Surface = pygame.display.set_mode(size) 
# 窗口标题
pygame.display.set_caption('我是标题') 
# 灰色的背景
bg = 33,33,33  

此处会创建一个窗口,宽600高400的灰底窗口,横方向是x,竖方向是y,左上角为x = 0 , y = 0的位置,从左到右,x值增加,从上往下,y值增加。
在这里插入图片描述

引入鱼

需要鱼的素材,利用 pygame.image.load(图片路径) 来导入素材

# python, pygame
# 导入鱼的图片
fish = pygame.image.load(‘images/fish.png’)
# 获得鱼对象的矩形
fish_pos = fish.get_rect()
# 鱼的宽度,高度
fish_widht , fish_height = fish_pos.width, fish_pos.height
# 定义鱼的初始化位置,x坐标是(0,600之间随机)
fish_x, fish_y = random.randint(0, 600) , -50

初始化位置,使得鱼的位置在顶部往上一些些,这样鱼的活动时间会比较久一点,当然可以设置其他的值。
在这里插入图片描述

小鱼的运动

pygame中,可以使用Surface.blit(图片,位置) 的方式来将图片显示到对应的位置。
如果要让鱼往下掉,则将鱼的Y坐标 增大。,并且重复运行;
如果鱼往下掉超出了屏幕,则鱼要从上面再次从上往下运动。

# python pygame
while 1:
	# 判断鱼是否超过下部屏幕
	if fish_y > 400:
		fish_x, fish_y = random.randint(0, 600) , -50
	# 鱼 y 方向自增
	fish_y += 2
	Surface.blit(fish, (fish_x, fish_y))

鱼部分完整代码

# python pygame
import pygame, sys, random
from pygame.locals import *

pygame.init()
screen = pygame.display.set_mode((600,400))
pygame.display.set_caption('猫饿了!')
# 背景颜色
bg = 33,33,33

# 导入鱼
fish = pygame.image.load('猫吃鱼/鱼.png')
fish_pos = fish.get_rect()
fish_width , fish_height = fish_pos.width, fish_pos.height
fish_x = random.randint(50,550)
fish_y = -50

while 1:
    for event in pygame.event.get():
        if event.type == QUIT:
            exit()
    if fish_y > 400:
        fish_x = random.randint(50, 550)
        fish_y = -50
    # fish_pos = fish_pos.move(speed)
    fish_y += 2
    screen.fill(bg)
    screen.blit(fish, (fish_x, fish_y))
    pygame.display.flip()

    pygame.time.delay(10)

猜你喜欢

转载自blog.csdn.net/qq_28404381/article/details/88742369