pygame征途:(一)图片移动反弹

题目大意:

就是弄一张图片在背景画布上移动,然后碰到边界就图片翻转并且反向移动

基本思路:

需要pygame常用的一些常用的函数,然后基本就是在背景画布上blit一张图片,然后移动就是先全刷成背景画布,然后在内存里绘制移动后位置的图片,然后整个绘制像素到背景画布上

#surface对象就是图像对象,背景画布也是surface对象
#图像移动就是将该图像在背景画布上的位置上的像素点改成该图像对应的像素点
#帧率是每秒刷过的图像数量
#pygame支持40~200帧
'''
控制游戏速度常用方法:
clock=pygame.time.Clock()
clock.tick(200)
以200帧的速度运行
'''
#记得要把图片放到工程文件夹里
import pygame
import sys

#初始化python
pygame.init()

size=width,height=600,400
speed=[-2,1]
bg=(255,255,255)

#创建指定大小的窗口
screen=pygame.display.set_mode(size)
#设置窗口标题
pygame.display.set_caption("初次见面,请大家多多指教")
#加载图片
img=pygame.image.load('maomi.png')
#获得图像的矩形位置
position=img.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>
        #翻转图像:
        img=pygame.transform.flip(img,True,False)
        #反方向移动
        speed[0]=-speed[0]

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

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


mainloop()

  

 
原文地址:https://www.cnblogs.com/imzscilovecode/p/8622233.html