Instantly share code, notes, and snippets.

Embed
What would you like to do?
simple script to locate sprites in a sprite sheet
import pygame
import pygame.locals as locals
def check_adjacency(rect, px):
test_rect = pygame.Rect(rect.left-1, rect.top-1, rect.width+2, rect.height+2)
return test_rect.collidepoint(px[0], px[1])
def find_groups(groups, px):
return [grp for grp in groups if check_adjacency(grp, px)]
def merge_rects(rect1, rect2):
if rect1.height == 0 or rect1.width == 0:
return rect2
if rect2.height == 0 or rect2.width == 0:
return rect1
top = min(rect1.top, rect2.top)
bottom = max(rect1.bottom, rect2.bottom)
left = min(rect1.left, rect2.left)
right = max(rect1.right, rect2.right)
return pygame.Rect(left, top, right-left, bottom-top)
def extend_rect(rect, px):
"""Extend rect to make it contain px."""
top = min(rect.top, px[1])
left = min(rect.left, px[0])
bottom = rect.bottom if rect.bottom > px[1] else px[1]+1
right = rect.right if rect.right > px[0] else px[0]+1
rect.top = top
rect.left = left
rect.height = bottom - top
rect.width = right - left
if __name__ == "__main__":
time = pygame.time.Clock()
pygame.font.init()
font = pygame.font.SysFont("Courier", 15)
loading_font = pygame.font.SysFont("Courier", 30)
# image = pygame.image.load("sprite/test2.png")
image = pygame.image.load("sprite/travis2.png")
screen = pygame.display.set_mode(image.get_size(), 0, 32)
image = image.convert()
colorkey = (39, 83, 83, 255)
size = image.get_size()
total_pixels = size[0] * size[1]
processed_pixels = 0
last_load = 0
groups = []
for y in xrange(size[1]):
for x in xrange(size[0]):
for event in pygame.event.get():
if event.type == locals.QUIT:
exit(0)
processed_pixels += 1
load = str(int(float(processed_pixels) * 100 / total_pixels)) + "%"
if load != last_load:
screen.blit(loading_font.render(load, True, (255, 255, 255), (0, 0, 0)), (0, 0))
pygame.display.flip()
last_load = load
px = (x, y)
if image.get_at(px) != colorkey:
grps = find_groups(groups, px)
if grps:
# TODO: maybe extend_rect should change first rect in-place
groups.remove(grps[0])
extend_rect(grps[0], px)
if len(grps) > 1:
for grp in grps[1:]:
grps[0] = merge_rects(grps[0], grp)
groups.remove(grp)
groups.append(grps[0])
else:
groups.append(pygame.Rect(px[0], px[1], 1, 1))
running = True
while running:
for event in pygame.event.get():
if event.type == locals.QUIT:
running = False
screen.blit(image, (0, 0))
for rect in groups:
pygame.draw.rect(screen, (255, 0, 0), rect, 1)
mousepos = pygame.mouse.get_pos()
for rect in groups:
if rect.collidepoint(mousepos[0], mousepos[1]):
text = font.render(
"%s, %s, %s, %s" % (rect.top, rect.left, rect.width, rect.height),
True, (255, 255, 255), (0, 0, 0))
screen.blit(text, rect)
pygame.display.flip()
time.tick(30)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment