-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathblockmap.py
279 lines (219 loc) · 8.2 KB
/
blockmap.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
'''
This module is mainly about a data structure 'block map'.
'''
import decimal
from queue import Queue
from typing import Callable, List, Optional, Tuple
import pygame
from pygame import Rect, draw
from pygame import Color, Surface
import gamebase
from scene import DynamicEntity, SingletonEntity
from utils import ColorValue
from decimal import Decimal
BLOCK_SIDE_LEN = 40
class Block:
'''
A data structure representing a square block that the player can't touch.
'''
color: Color
def __init__(self, color_value: ColorValue):
self.color = Color(color_value)
BLOCK_MAP_SURFACE_WIDTH = gamebase.WINDOW_DIMENSION[0]
BLOCK_MAP_SURFACE_HEIGHT = gamebase.WINDOW_DIMENSION[1]
BLOCK_MAP_WIDTH = BLOCK_MAP_SURFACE_WIDTH // BLOCK_SIDE_LEN
BLOCK_MAP_HEIGHT = BLOCK_MAP_SURFACE_HEIGHT // BLOCK_SIDE_LEN
BLOCK_MAP_SIZE = BLOCK_MAP_WIDTH * BLOCK_MAP_HEIGHT
class BlockMap:
'''
A data structure representing a two-dimensional block map.
This map contains an list of Optional[Block](None represent no block) and a corresponding pygame.Surface instance. The surface is the same size as the game window.
'''
__blocks: List[Optional[Block]]
__surface: Surface
__offset_x: Decimal = Decimal(BLOCK_MAP_SURFACE_WIDTH)
def __init__(self):
self.__blocks = [None] * BLOCK_MAP_SIZE
self.__surface = Surface(
(BLOCK_MAP_SURFACE_WIDTH, BLOCK_MAP_SURFACE_HEIGHT), flags = pygame.SRCALPHA)
@property
def surface(self) -> Surface:
'''
Returns the corresponding Surface instance.
'''
return self.__surface
@property
def offset_x(self) -> Decimal:
'''
Returns the offset as a world position X.
'''
return self.__offset_x
@property
def is_invalid(self) -> bool:
'''
Returns whether this block map is out of the game window.
Calling method recycle can make it usable again.
'''
return self.__offset_x <= -BLOCK_MAP_SURFACE_WIDTH
def get_block(self, x: int, y: int) -> Optional[Block]:
'''
Returns the block at the specified block position.
Args:
x: Block position X.
y: Block position Y.
Raises:
IndexError: The specified position is out of the range.
'''
return self.__blocks[x * BLOCK_MAP_HEIGHT + y]
def set_block(self, x: int, y: int, block: Optional[Block]):
'''
Set the block at the specified block position.
Args:
x: Block position X.
y: Block position Y.
block: The Block instance to set.
Raises:
IndexError: The specified position is out of the range.
'''
self.__blocks[x * BLOCK_MAP_HEIGHT + y] = block
def pos_world_to_block(self, x: Decimal, y: Decimal) -> Tuple[int, int]:
'''
Convert a world position to a block position.
Args:
x: World position X.
y: World position Y.
Returns:
The corresponding block position as a tuple.
'''
origin_x = self.__offset_x
block_x = int(((x - origin_x) / BLOCK_SIDE_LEN).quantize(
Decimal(1), rounding = decimal.ROUND_FLOOR))
block_y = int((y / BLOCK_SIDE_LEN).quantize(
Decimal(1), rounding = decimal.ROUND_FLOOR))
return (block_x, block_y)
def refresh(self):
'''
Refresh the Surface instance according to the block map.
'''
self.__surface.fill((0, 0, 0, 0))
for x in range(BLOCK_MAP_WIDTH):
for y in range(BLOCK_MAP_HEIGHT):
block = self.get_block(x, y)
if block != None:
draw.rect(
self.__surface, block.color,
Rect(
x * BLOCK_SIDE_LEN, y * BLOCK_SIDE_LEN, BLOCK_SIDE_LEN, BLOCK_SIDE_LEN
)
)
def move(self, dx: Decimal):
'''
Move the block map.
Args:
dx: The world distance to move on the X-axis.
'''
self.__offset_x -= dx
@offset_x.setter
def offset_x(self, x: Decimal):
'''
Set the world offset x directly to avoid precision issue.
Args:
x: The world position x to set.
'''
self.__offset_x = x
def recycle(self):
'''
Reset the block map and make it usable again.
'''
for i in range(BLOCK_MAP_SIZE):
self.__blocks[i] = None
self.__offset_x = Decimal(BLOCK_MAP_SURFACE_WIDTH)
BLOCK_MAP_POOL_SIZE = 2 + 2
_blockmap_pool: List[BlockMap] = [
BlockMap() for _ in range(BLOCK_MAP_POOL_SIZE)
]
class BlockMapManager(SingletonEntity, DynamicEntity):
'''
A manager of all block maps in a game scene.
'''
__blockmap1: BlockMap # a blockmap closer to the player
__blockmap2: BlockMap # a blockmap farther away the player
__ready_blockmaps: Queue[BlockMap] # generated blockmaps ready to use
__unready_blockmaps: Queue[BlockMap] # blockmaps that need to be generated
__is_stopped: bool = False
@property
def is_stopped(self):
return self.__is_stopped
@is_stopped.setter
def is_stopped(self, stopped: bool):
self.__is_stopped = stopped
def launch(self, init_callback: Callable[[BlockMap], None]):
global _blockmap_pool
# get all blockmaps from the pool.
self.__blockmap1 = _blockmap_pool.pop()
self.__blockmap1.refresh()
self.__blockmap1.offset_x = Decimal(0)
self.__blockmap2 = _blockmap_pool.pop()
self.__ready_blockmaps = Queue()
self.__unready_blockmaps = Queue()
while len(_blockmap_pool) > 0:
self.__unready_blockmaps.put(_blockmap_pool.pop())
init_callback(self.__blockmap2)
def on_destroy(self):
super().on_destroy()
global _blockmap_pool
# return all blockmaps to the pool.
self.__blockmap1.recycle()
self.__blockmap2.recycle()
_blockmap_pool += (self.__blockmap1, self.__blockmap2)
while len(_blockmap_pool) != BLOCK_MAP_POOL_SIZE:
try:
bmap = self.__ready_blockmaps.get_nowait()
bmap.recycle()
_blockmap_pool.append(bmap)
except:
pass
try:
bmap = self.__unready_blockmaps.get_nowait()
_blockmap_pool.append(bmap)
except:
pass
def __test_touch_block_for_blockmap(self, bmap: BlockMap, x: Decimal, y: Decimal) -> bool:
bpos_x, bpos_y = bmap.pos_world_to_block(x, y)
if bpos_x < 0 or bpos_x >= BLOCK_MAP_WIDTH:
return False
if bpos_y < 0 or bpos_y >= BLOCK_MAP_HEIGHT:
return False
block = bmap.get_block(bpos_x, bpos_y)
return block != None
def test_touch_block(self, x: Decimal, y: Decimal) -> bool:
if self.__test_touch_block_for_blockmap(self.__blockmap1, x, y):
return True
if self.__test_touch_block_for_blockmap(self.__blockmap2, x, y):
return True
return False
def on_tick(self):
dt = gamebase.TICK_TIME
if self.__blockmap1.is_invalid:
unready_blockmap = self.__blockmap1
unready_blockmap.recycle()
self.__unready_blockmaps.put(unready_blockmap)
self.__blockmap1 = self.__blockmap2
self.__blockmap2 = self.__ready_blockmaps.get()
screen = gamebase.get_screen()
screen.blit(
self.__blockmap1.surface, (int(self.__blockmap1.offset_x), 0)
)
screen.blit(
self.__blockmap2.surface, (int(self.__blockmap2.offset_x), 0)
)
def move(self, dx: Decimal):
self.__blockmap1.move(dx)
self.__blockmap2.offset_x = self.__blockmap1.offset_x + BLOCK_MAP_SURFACE_WIDTH
def try_get_unready_blockmap(self) -> Optional[BlockMap]:
try:
return self.__unready_blockmaps.get_nowait()
except:
return None
def put_ready_blockmap(self, blockmap: BlockMap):
self.__ready_blockmaps.put(blockmap)