1
|
|
|
import math |
2
|
|
|
import random |
3
|
|
|
from typing import List |
4
|
|
|
|
5
|
|
|
import pygame |
6
|
|
|
|
7
|
|
|
from src import TEXTURES_FOLDER, HALF_WIDTH, HALF_HEIGHT |
8
|
|
|
from src.functions.loaders import load_sprites_from_dir |
9
|
|
|
|
10
|
|
|
|
11
|
|
|
class Tiles: |
12
|
|
|
SPRITES: List[pygame.Surface] = load_sprites_from_dir( |
13
|
|
|
f"{TEXTURES_FOLDER}/tiles", |
14
|
|
|
( |
15
|
|
|
"wood_0", "wood_1", "wood_2", "wood_3", "wood_4", "wood_5", |
16
|
|
|
"block_gold", "block_wood", |
17
|
|
|
"blue_1", "blue_2", "blue_3", "blue_4", |
18
|
|
|
"blue_5", "blue_6", "blue_7", "blue_8", "blue_9" |
19
|
|
|
) |
20
|
|
|
) |
21
|
|
|
|
22
|
|
|
def __init__(self, height, width): |
23
|
|
|
self.grid_width = width |
24
|
|
|
self.grid_height = height |
25
|
|
|
|
26
|
|
|
self.grid = [ |
27
|
|
|
Tile( |
28
|
|
|
( |
29
|
|
|
(index % height) * Tile.SIZE, |
30
|
|
|
(index // height) * Tile.SIZE |
31
|
|
|
), |
32
|
|
|
random.choice(self.SPRITES) |
33
|
|
|
) for index in range(height * width) |
34
|
|
|
] |
35
|
|
|
|
36
|
|
|
def draw(self, viewport, camera): |
37
|
|
|
for tile in self.grid: |
38
|
|
|
tile.update(camera) |
39
|
|
|
|
40
|
|
|
tile.draw(viewport, camera) |
41
|
|
|
|
42
|
|
|
|
43
|
|
|
class Tile: |
44
|
|
|
SIZE: int = 32 |
45
|
|
|
TILE_COUNT_X: int = math.ceil(HALF_WIDTH / SIZE) + 1 |
46
|
|
|
TILE_COUNT_Y: int = math.ceil(HALF_HEIGHT / SIZE) + 1 |
47
|
|
|
|
48
|
|
|
def __init__(self, coords, sprite): |
49
|
|
|
self.coords = coords |
50
|
|
|
self.sprite = sprite |
51
|
|
|
self.rect = pygame.Rect(coords, (self.SIZE, self.SIZE)) |
52
|
|
|
|
53
|
|
|
def update(self, camera): |
54
|
|
|
if self.rect.x - camera.x < -self.SIZE: |
55
|
|
|
self.rect.x += self.SIZE * self.TILE_COUNT_X |
56
|
|
|
|
57
|
|
|
elif self.rect.x - camera.x > HALF_WIDTH: |
58
|
|
|
self.rect.x -= self.SIZE * self.TILE_COUNT_X |
59
|
|
|
|
60
|
|
|
elif self.rect.y - camera.y < -self.SIZE: |
61
|
|
|
self.rect.y += self.SIZE * self.TILE_COUNT_Y |
62
|
|
|
|
63
|
|
|
elif self.rect.y - camera.y > HALF_HEIGHT: |
64
|
|
|
self.rect.y -= self.SIZE * self.TILE_COUNT_Y |
65
|
|
|
|
66
|
|
|
def draw(self, viewport, camera): |
67
|
|
|
viewport.blit( |
68
|
|
|
self.sprite, |
69
|
|
|
(self.rect.x - camera.x, self.rect.y - camera.y) |
70
|
|
|
) |
71
|
|
|
|