Feb-19-2020, 11:27 AM
1. Tile map wouldn't use a big surface. You would loop through the tiles.
I have more time this weekend to give a working example. Code below will probably change.
This is very rough an unfinished an untested at the moment.
I have more time this weekend to give a working example. Code below will probably change.
This is very rough an unfinished an untested at the moment.
import pygame from itertools import product # Optional class TileLayer: def __init__(self): self.background = None self.foreground = None self.foreground_rect = None def draw(self, surface, position, images, player): surface.blit(images[self.background], position) if foreground_rect: if player.rect.bottom < self.foreground_rect.top: player.draw(surface) surface.blit(images[self.foreground], position) else: surface.blit(images[self.foreground], position) player.draw(surface) elif foreground: surface.blit(images[self.foreground], position) class TileSprite(Sprite): def __init__(self, image, position, anchor="topleft"): self.image = image self.rect = self.image.get_rect(**{anchor: position}) self.tile_position = pygame.Vector2(self.rect.center) self.map_position = pygame.Vector2(self.rect.center) def move(self, position, camera_position): self.tile_position += pygame.Vector2(position) self.map_position = self.tile_position - camera_position self.rect.center = self.map_position def update(self, camera_position): self.map_position = self.tile_position - camera_position self.rect.center = self.map_position class TileMap: def __init__(self, images, screen_rect, tilesize): self.images = images self.map_data = [[]] self.tilesize = tilesize self.display_size = pygame.Vector2(int(screen_rect.w / tilesize.x) + 1, int(screen_rect.h / tilesize.y) + 1) def draw(self, surface, camera, player): start = int(camera.position.x) x_range = range(start, int(start + self.display_size.x)) start = int(camera.position.y) y_range = range(start, int(start + self.display_size.y)) for x, y in product(x_range, y_range): try: position = x * self.tilesize.x , y * self.tilesize.y # TileLayer optional self.map_data[y][x]].draw(surface, position, self.images, player) # else # surface.blit(self.images[self.map_data[y][x]], position) except: pass # TileCamera moves the map. Not the player. Player would remain in the center. class TileCamera: def __init__(self): self.tilemap = TileMap() self.sprites = Group() self.position = pygame.Vector2() self.speed = 0.08 def draw(self, surface): self.tilemap(surface, self) def update(self, delta): keys_pressed = pygame.key.get_pressed() direction = pygame.Vector2(0, 0) if keys_pressed[pygame.K_w]: direction.y -= 1 if keys_pressed[pygame.K_s]: direction.y += 1 if keys_pressed[pygame.K_a]: direction.x -= 1 if keys_pressed[pygame.K_d]: direction.x += 1 if direction = pygame.Vector2(0, 0): direction.normlize_ip() self.position = direction * self.speed * delta self.sprites.update(self.position)
99 percent of computer problems exists between chair and keyboard.