我最近开始玩 pygame,我想创建一个平铺字段,以突出显示鼠标悬停的瓷砖。为此,我使用了 DirtySprite 和 LayeredDirty,以便只绘制更新的图块。但是,当我运行代码时,FPS 下降到 11,当我检查时,总是绘制整个屏幕。这是我的代码:
import os,sys
import pygame
import OpenGL
from pygame.locals import *
from PIL import Image
import pygame, math, sys
from pygame.locals import *
TILE_SIZE = 128
screen = pygame.display.set_mode((1920, 1080))
screen_height = pygame.display.get_surface().get_height()
screen_width = pygame.display.get_surface().get_width()
background = pygame.Surface(screen.get_size())
background = background.convert()
background.fill((250, 250, 250))
X_TILES = screen_width/TILE_SIZE
Y_TILES = screen_height/TILE_SIZE
class Tiles(pygame.sprite.DirtySprite):
ground = Image.open('grass20.png')
select_rect = Image.open('Select_rect.png')
fore = Image.open('grass20.png')
fore.paste(select_rect,(0,0),select_rect)
select_rect = fore
del fore
select_rect =select_rect.resize((TILE_SIZE,TILE_SIZE),Image.ANTIALIAS)
ground =ground.resize((TILE_SIZE,TILE_SIZE),Image.ANTIALIAS)
size = ground.size
mode = ground.mode
bytes = ground.tobytes()
ground = pygame.image.fromstring(bytes,size,mode)
size = select_rect.size
mode = select_rect.mode
bytes = select_rect.tobytes()
select_rect = pygame.image.fromstring(bytes,size,mode)
del size
del mode
del bytes
def __init__(self,position):
pygame.sprite.DirtySprite.__init__(self)
self.rect = pygame.Rect(self.ground.get_rect())
self.rect.topleft=position
self.coords = (position[0]/TILE_SIZE,position[1]/TILE_SIZE)
self.image = self.ground
def update(self, hit_list):
if hit_list != self:
if self.image == self.select_rect:
self.dirty = 1
self.image = self.ground
else:
self.dirty = 0
elif self.image != self.select_rect:
self.dirty = 1
self.image = self.select_rect
else: self.dirty = 0
#print self.dirty, self.coords
class Mouse_pos(pygame.sprite.Sprite):
def __init__(self):
pygame.sprite.Sprite.__init__(self)
self.rect = pygame.Rect((0,0),(1,1))
####
pygame.display.init()
clock = pygame.time.Clock()
city.set_position(screen_width/2,screen_height/2)
tiles = []
for x in xrange(X_TILES):
for y in xrange(Y_TILES):
tiles.append(Tiles((x*TILE_SIZE,y*TILE_SIZE)))
Tile_group = pygame.sprite.LayeredDirty(*tiles)
Tile_group.clear(screen,background)
del tiles
Tile_group.draw(screen)
mouse_pos = Mouse_pos()
tiles = []
while 1:
clock.tick(60)
for event in pygame.event.get():
if not hasattr(event, 'key'):
continue
down = event.type == KEYDOWN # key down or up?
if event.key == K_ESCAPE: sys.exit(0) # quit the game
mouse_pos.rect.center = pygame.mouse.get_pos()
collided_tile = pygame.sprite.spritecollideany(mouse_pos,Tile_group)
Tile_group.update(collided_tile)
allsprites = Tile_group.draw(screen)
pygame.display.update(allsprites)
当我检查脏瓷砖时,只有 2 块看起来很脏(应该是这样)。但是,当我打印allsprites
Rect 时,我总是得到(0,0,1920,1080)
. 为什么总是重新绘制整个屏幕而不仅仅是更新的图块?
更新
当我打印时:
print [a.rect for a in Tile_group if a.dirty == 1]
和
print allsprites
我得到不同的结果;a.rect
打印返回两个要更新的矩形,但是allsprites
返回(0,0,1920,1080)