Using pictures to map walls

Asked by At

I was wondering if i could use picture maps to create solid walls within my game, an example is below:

enter image description here

How would I go about making a program that generates a map based on the black wall locations on my picture

Iv been looking into doing this for a while although up to now iv rested on simply drawing in the lines using python.draw. Iv also looked into the use of turtles but i dont think thats what I desire for my program at this time.

1 Answers

sloth On Best Solutions

You can read the color value of each pixel.

The easiest way is to use the get_at function to the Surface class, but for more features and performance, you can also use a PixelArray or the surfarray module.

Another way would be to create a Mask from the images and use that for collision detection.

Here's a simple, hackish but working example:

import pygame

class Player(pygame.sprite.Sprite):
    def __init__(self, image, pos, background):
        self.image = image
        self.pos = pygame.Vector2(pos)
        self.rect = self.image.get_rect(center=self.pos)
        self.background = background

    def update(self, events, dt):
        pressed = pygame.key.get_pressed()
        move = pygame.Vector2((0, 0))
        if pressed[pygame.K_w]: move += (0, -1)
        if pressed[pygame.K_a]: move += (-1, 0)
        if pressed[pygame.K_s]: move += (0, 1)
        if pressed[pygame.K_d]: move += (1, 0)
        if move.length() > 0: move.normalize_ip()

        new_pos = self.pos + move*(dt/5)
        new_rect = self.rect.copy() = new_pos
        new_pos =

        hit_box = self.background.subsurface(new_rect)
        for x in range(new_rect.width):
            for y in range(new_rect.height):
                if sum(hit_box.get_at((x, y))) < 500:

        self.pos = new_pos = self.pos

def main():
    screen = pygame.display.set_mode((284, 384))
    screen_rect = screen.get_rect()

    clock = pygame.time.Clock()
    sprites = pygame.sprite.Group()

    background = pygame.transform.scale2x(pygame.image.load('maze.jpg'))
    pimg = pygame.Surface((10, 10))
    pimg.fill((200, 20, 20))
    sprites.add(Player(pimg, (50, 50), background))

    dt = 0
    while True:
        events = pygame.event.get()
        for e in events:
            if e.type == pygame.QUIT:

        sprites.update(events, dt)
        screen.blit(background, (0, 0))
        dt = clock.tick(60)

if __name__ == '__main__':

enter image description here

Of course this can be improved, for example by using an image with alpha values so you could easily create masks; but you'll get the idea: just "look" at the pixels of your Surface...