2021年2月17日 / 6次阅读 / Last Modified 2021年2月17日
pygame
import sys
import random
import time
import pygame
size = width, height = 800, 600
speed = [1,1]
pygame.init()
screen = pygame.display.set_mode(size)
pygame.display.set_caption('Here is topleft title')
clock = pygame.time.Clock()
bg = pygame.image.load('bz.jpg').convert()
screen.blit(bg, (0,0))
imgrect = pygame.draw.rect(screen, (100,20,30,5), (0,0,100,100))
while True:
# frame rate per second
clock.tick(240)
# event list
for event in pygame.event.get():
print(event)
if event.type == pygame.QUIT:
pygame.quit()
sys.exit(0)
# adjust speed
if imgrect.left<0 or imgrect.right>width:
speed[0] = -speed[0]
if imgrect.top<0 or imgrect.bottom>height:
speed[1] = -speed[1]
# draw and flip
screen.blit(bg, imgrect, imgrect)
imgrect = imgrect.move(speed)
pygame.draw.rect(screen, (100,20,30,5), imgrect)
pygame.display.flip()
第1处,screen.blit(bg, (0,0)),将bg图片的数据,copy到0,0这个topleft位置;
第2处,screen.blit(bg, imgrect, imgrect),将bg图片中位于imgrect(第3个参数)位置的部分数据,更新到imgrect所在位置。结合上面这段代码,其实就是将imgrect所占用的位置,重新更新为bg。部分更新,速度会更快!
pygame.image.load('bz.jpg').convert(),会自动将图片数据,convert为display对应的format,如果不显式调用这个convert,每一次blit的时候,都会convert,会拖慢速度。display所用的format,有底层sdl库自动确定。
In pygame it is simple to create a new window for graphics. The code to create a 640x480 surface is below. By passing no other arguments, pygame will just pick the best color depth and pixel format for us.
screen = pygame.display.set_mode((640, 480))
以上为两个加速blit函数执行的小技巧。
-- EOF --
本文链接:https://www.pynote.net/archives/3521
前一篇:pygame.draw的使用
后一篇:设置pygame窗口大小可调节
Ctrl+D 收藏本页
©Copyright 麦新杰 Since 2019 Python笔记