当前位置: 移动技术网 > IT编程>脚本编程>Python > python笔记 (三十四) pygame(1) 图片移动 事件

python笔记 (三十四) pygame(1) 图片移动 事件

2020年07月20日  | 移动技术网IT编程  | 我要评论

实列

import pygame
import sys

# 初始化pygame
pygame.init()

size = width ,height = 900, 500
speed = [-2,1]
bg = (255,255,255)

# 创建指定大小的窗口
screen = pygame.display.set_mode(size)
# 设置窗口标题
pygame.display.set_caption("闲得发慌")

# 加载图片
people = pygame.image.load("p.gif")
# 获得图像位置矩形
position = people.get_rect()

while True:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            sys.exit()

    # 移动图像
    position = position.move(speed)

    if position.left < 0 or position.right > width:
        # 反转图像
        people = pygame.transform.flip(people,True,False)
        # 反向移动
        speed[0] = -speed[0]

    if position.top < 0 or position.bottom > height:
        speed[1] = -speed[1]

    # 填充背景
    screen.fill(bg)
    # 更新图像位置
    screen.blit(people,position)
    # 更新界面
    pygame.display.flip()
    # 延迟5毫秒
    pygame.time.delay(5)

导入sys用来关闭程序
首先初始化pygame,使用init函数

设置参数值
bg背景颜色是按照调色板的RGU调试的

加载图片会返回一个surface对象,将这个图片搞成一个矩形,方便后面更改位置坐标

图像反转people = pygame.transform.flip(people,True,False)后面的truefalse,第一个表示水平翻转,第二个表示竖直反转

关闭程序的原理是基于pygame是根据事件循环来运行的,使用一次迭代来寻找有没有事件是关闭程序的,如果有就QUIT


我们最后是用time模块使图片暂停5毫秒来控制速度
当然也可以控制帧率来控制速度
使用time模块的Clock对象
首先实例化一个Clock对象 clock = pygame.time.Clock()
最后控制帧率 clock.tick(200)


事件

在这里插入图片描述

本文地址:https://blog.csdn.net/yogur_father/article/details/107425116

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网