70 lines
2.4 KiB
Python
70 lines
2.4 KiB
Python
import pygame, json
|
|
|
|
"""
|
|
Todo:
|
|
* Add prop system for Trees, etc. (like off_grid), handle blocked with game objects over props
|
|
"""
|
|
|
|
class Tilemap:
|
|
def __init__(self, game, tile=16):
|
|
self.game = game
|
|
self.tile_size = tile
|
|
self.tilemap = {}
|
|
self.offgrid_tiles = []
|
|
self.waypoints=[]
|
|
|
|
def save(self, path):
|
|
f = open(path, 'w')
|
|
json.dump({'tilemap': self.tilemap, 'tile_size': self.tile_size, 'waypoints': self.waypoints}, f)
|
|
f.close()
|
|
|
|
def load(self, path):
|
|
f = open(path, 'r')
|
|
map_data = json.load(f)
|
|
f.close()
|
|
|
|
self.tilemap = map_data['tilemap']
|
|
self.tile_size = map_data['tile_size']
|
|
self.waypoints = map_data['waypoints']
|
|
|
|
def render(self, surf, offset=(0, 0)):
|
|
for x in range(offset[0] // self.tile_size, (offset[0] + surf.get_width()) // self.tile_size + 1):
|
|
for y in range(offset[1] // self.tile_size, (offset[1] + surf.get_height()) // self.tile_size + 1):
|
|
loc = str(x) + ';' + str(y)
|
|
if loc in self.tilemap:
|
|
tile = self.tilemap[loc]
|
|
surf.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 render_game(self, surf, camera):
|
|
tile_size = self.tile_size
|
|
zoom = camera.zoom
|
|
scaled_tile_size = int(tile_size * zoom)
|
|
|
|
start_x = int(camera.offset.x // tile_size)
|
|
start_y = int(camera.offset.y // tile_size)
|
|
|
|
end_x = int((camera.offset.x + surf.get_width() / zoom) // tile_size) + 2
|
|
end_y = int((camera.offset.y + surf.get_height() / zoom) // tile_size) + 2
|
|
|
|
for x in range(start_x, end_x):
|
|
for y in range(start_y, end_y):
|
|
loc = f"{x};{y}"
|
|
|
|
if loc in self.tilemap:
|
|
tile = self.tilemap[loc]
|
|
image = self.game.assets[tile["type"]][tile["variant"]]
|
|
|
|
scaled_image = pygame.transform.scale(
|
|
image,
|
|
(scaled_tile_size, scaled_tile_size)
|
|
)
|
|
|
|
world_pos = (
|
|
tile["pos"][0] * tile_size,
|
|
tile["pos"][1] * tile_size
|
|
)
|
|
|
|
screen_pos = camera.world_to_screen(world_pos)
|
|
|
|
surf.blit(scaled_image, screen_pos)
|