59 lines
2.6 KiB
Python
59 lines
2.6 KiB
Python
import pygame as pg
|
|
NEIGHBOR_OFFSETS = [(0, 0), (-1, 0), (-1, -1), (-1, 1), (0, 1), (0, -1), (1, 1), (1, 0), (1, -1)]
|
|
PHYSICS_TILES = {"grass", "stone"}
|
|
class Tilemap:
|
|
def __init__(self, game, tile_size=16):
|
|
self.game = game
|
|
self.tile_size = tile_size
|
|
self.tilemap = {}
|
|
self.offgrid_tiles = []
|
|
for i in range(10):
|
|
self.tilemap[str(3 + i) + ';10'] = {'type': 'grass', 'variant': 1, 'pos': (3 + i, 10)}
|
|
self.tilemap['10;' + str(5 + i)] = {'type': 'stone', 'variant': 1, 'pos': (10, i + 5)}
|
|
def render(self, surface:pg.Surface, offset:tuple=(0,0)):
|
|
for tile in self.offgrid_tiles:
|
|
surface.blit(self.game.assets[tile['type']][tile['variant']], (tile['pos'][0] - offset[0], tile['pos'][1] - offset[1]))
|
|
for location in self.tilemap:
|
|
tile = self.tilemap[location]
|
|
surface.blit(self.game.assets[tile['type']][tile['variant']], (tile['pos'][0] * self.tile_size - offset[0], tile['pos'][1] * self.tile_size - offset[1]))
|
|
|
|
def tiles_around(self, pos):
|
|
tiles = []
|
|
tile_location = (int(pos[0] // self.tile_size), int(pos[1] // self.tile_size))
|
|
for offset in NEIGHBOR_OFFSETS:
|
|
check_location = str(tile_location[0] + offset[0]) + ';' + str(tile_location[1] + offset[1])
|
|
if check_location in self.tilemap:
|
|
tiles.append(self.tilemap[check_location])
|
|
return tiles
|
|
def physics_rects_around(self, pos):
|
|
# Erzeuge eine leere Liste für die Rechtecke
|
|
rects = []
|
|
# Durchlaufe alle Tiles aus der Umgebung (tiles_around)
|
|
for tile in self.tiles_around(pos):
|
|
|
|
# Prüfe, ob der Tile-Typ in PHYSICS_TILES enthalten ist
|
|
# (nur diese Tiles sollen kollidieren)
|
|
if tile["type"] in PHYSICS_TILES:
|
|
# Rechne die Tile-Position in Pixel-Koordinaten um
|
|
x_pixel = tile['pos'][0] * self.tile_size
|
|
y_pixel = tile['pos'][1] * self.tile_size
|
|
|
|
# Erzeuge ein pygame.Rect mit:
|
|
# - x_pixel
|
|
# - y_pixel
|
|
# - Breite = self.tile_size
|
|
# - Höhe = self.tile_size
|
|
rect = pg.Rect(x_pixel, y_pixel, self.tile_size, self.tile_size)
|
|
# Füge das Rechteck der Liste rects hinzu
|
|
rects.append(rect)
|
|
|
|
# Gib die Liste der Rechtecke zurück
|
|
return rects
|
|
# def test(self):
|
|
# pass
|
|
# print("Hallo")
|
|
# # if __name__ == "__main__":
|
|
# # from ..game import Game
|
|
# # tile = Tilemap(Game())
|
|
|
|
|