optimize tiles drawing

This commit is contained in:
= 2021-03-14 18:42:40 +01:00
parent 04efd8876a
commit e0ca3c5f87
3 changed files with 14 additions and 2 deletions

View File

@ -4,15 +4,19 @@ import pygame
class TextureAtlas(object):
def __init__(self, filename):
self.atlas = pygame.image.load(filename).convert()
self.images = {}
def image_at(self, origin, target, color_key=None):
if origin in self.images:
return self.images[origin]
rect = pygame.Rect(origin, target)
image = pygame.Surface(rect.size).convert()
image.blit(self.atlas, (0, 0), rect)
if color_key is not None:
if color_key is -1:
if color_key == -1:
color_key = image.get_at((0, 0))
image.set_colorkey(color_key, pygame.RLEACCEL)
self.images[origin] = image
return image
def images_at(self, rects, color_key=None):

View File

@ -1,3 +1,4 @@
class Tile:
def __init__(self):
self.origin = (0, 0)
self.image = None

View File

@ -10,8 +10,15 @@ class TileLayer:
self.height = height
self.tiles = [[Tile() for x in range(self.width)] for y in range(self.height)]
self.atlas = TextureAtlas(os.path.join('..', 'assets', 'atlas.png'))
self.loadTiles()
def loadTiles(self):
for y in range(self.height):
for x in range(self.width):
self.tiles[y][x].image = self.atlas.image_at(self.tiles[y][x].origin, (32, 32))
def draw(self, window):
for y in range(self.height):
for x in range(self.width):
window.blit(self.atlas.image_at(self.tiles[y][x].origin, (32, 32)), (x * 32, y * 32))
if self.tiles[y][x] is not None:
window.blit(self.tiles[y][x].image, (x * 32, y * 32))