Skip to content

Instantly share code, notes, and snippets.

@f0ursqu4r3
Created September 10, 2021 03:58
Show Gist options
  • Save f0ursqu4r3/eb296cfe1e7e2980168d4e636b540a0a to your computer and use it in GitHub Desktop.
Save f0ursqu4r3/eb296cfe1e7e2980168d4e636b540a0a to your computer and use it in GitHub Desktop.
Loading a game map from a image file.
import pygame
class GameMap:
def __init__(self, path, tile_map_def):
self.map_surf = pygame.image.load(path)
self.tile_map_def = tile_map_def
self.map_data = self.load_map_image_from_surface()
self.width = self.map_surf.get_width()
self.height = self.map_surf.get_height()
def load_map_image_from_surface(self):
return [
self.color_to_tile(self.map_surf.get_at((x, y)))
for y in range(self.map_surf.get_height())
for x in range(self.map_surf.get_width())
]
def color_to_tile(self, color):
r, g, b = color.r, color.g, color.b
return self.tile_map_def.get(f'{r},{g},{b}', ' ')
def get_tile(self, x, y):
return self.map_data[(y * self.height) + x]
# setup the keys that should map to a value which will later be used
# to get the surface to be blitted to the screen. Generally, this
# should be an integer tile id.
#
# key should be an rgb value
# value should be the tile id.
tile_map_def = {
'160,91,83': '0',
'122,68,74': 'O',
'94,54,67': 'o',
'71,45,60': '.'
}
game_map = GameMap('./dirt.png', tile_map_def)
for y in range(game_map.height):
for x in range(game_map.width):
print(game_map.get_tile(x, y), end=' ')
print()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment