-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtest.py
394 lines (290 loc) · 9.85 KB
/
test.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
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
import itertools
import abc
import sys
from dataclasses import dataclass, field
import pyxel
from physics import Static, Dynamic, World, Vec2
class GraphicsComponent(abc.ABC):
@abc.abstractmethod
def render(self, offset_x, offset_y):
raise NotImplementedError
class InputComponent(abc.ABC):
@abc.abstractmethod
def process_input(self):
raise NotImplementedError
class PhysicsComponent(abc.ABC):
pass
@dataclass
class TileGraphicsComponent(GraphicsComponent):
fill: bool = True
color: int = 1
def render(self, offset_x, offset_y):
func = pyxel.rect if self.fill else pyxel.rectb
func(offset_x + self.x,
offset_y + self.y,
self.w,
self.h,
self.color)
@dataclass
class Tile(TileGraphicsComponent, PhysicsComponent, Static):
def to_shadow_tile(self, **kwargs):
return ShadowTile(x=self.x, y=self.y, w=self.w, h=self.h, **kwargs)
@dataclass
class ShadowTile(TileGraphicsComponent, Static):
pass
@dataclass
class Map:
tiles: list = field(default_factory=list)
spawn_points: list = field(default_factory=list)
w: int = 0
h: int = 0
@dataclass
class MapList:
maps: list = field(default_factory=list)
current_index: int = 0
@property
def current(self):
return self.maps[self.current_index]
@property
def previous(self):
if self.current_index > 0:
return self.maps[self.current_index - 1]
return None
@property
def next(self):
if self.current_index < len(self.maps) - 1:
return self.maps[self.current_index + 1]
return None
def move_back(self):
if self.previous:
self.current_index -= 1
def move_forward(self):
if self.next:
self.current_index += 1
def parse_map(string, tile_size):
tiles = []
spawn_points = []
width = None
for j, line in enumerate(string.strip().splitlines()):
chars = line.split()
if j == 0:
width = len(chars)
else:
assert len(chars) == width, "wrong width at row %i" % j
for i, char in enumerate(chars):
if char == '.':
continue
elif char == '@':
spawn_points.append((i * tile_size, j * tile_size))
elif char == 't':
tiles.append(Tile(
x=i * tile_size,
y=j * tile_size,
w=tile_size,
h=tile_size,
))
else:
assert False, "unknown tile char: %r" % char
height = j + 1
return Map(tiles, spawn_points, width * tile_size, height * tile_size)
TILE_SIZE = 8
MAP_LIST = MapList([
parse_map("""
t . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . t t t t .
. . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . .
. . . . @ . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . .
. . t t t . . . . . . t t t t t t . . .
. . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . @ . . . .
. t t t t t t t t t t t t t t t t t . .
. . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . t t
""", TILE_SIZE),
parse_map("""
. . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . .
. . . . . . . t t t t . . . . . . . . .
. . . . @ . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . .
. t t t t t . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . @ . . . .
. . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . t t t . . .
. . . . . . . . . . . . . . . . . . . .
""", TILE_SIZE),
parse_map("""
. . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . t t t . . . . . .
. . . . . . . . . . . . . . . . . . . .
. . . . @ . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . @ . . . .
. . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . .
. . . . t t t t t t t t t . . . . . . .
. . . . . . . . . . . . . . . . . . . .
""", TILE_SIZE),
])
SCREEN_W, SCREEN_H = 160, 120
@dataclass
class GuyInputComponent(InputComponent):
"""Implements moving based on input.
Features:
* horizontal movement (constant velocity)
* jumping
* jump higher if jump key is pressed longer
"""
left_pressed: bool = False
right_pressed: bool = False
jump_pressed: bool = False
jump_pressed_now: bool = False
keymap: dict = field(default_factory=lambda: dict(
left=pyxel.KEY_LEFT,
right=pyxel.KEY_RIGHT,
jump=pyxel.KEY_CONTROL,
))
jump_frame: int = 0
_jump_state: str = 'falling'
@property
def jump_state(self):
return self._jump_state
@jump_state.setter
def jump_state(self, value):
print("{:10} -> {:10} {:>3} {:>3} {:>3}".format(
self._jump_state, value, self.y, self.velocity.y, self.jump_frame))
self._jump_state = value
def _jump_state_machine(self):
if self.jump_state == 'standing':
self.velocity.y = 0
if not self.had_collision:
self.jump_state = 'falling'
return
if self.jump_pressed_now:
self.jump_state = 'jumping'
self.had_collision = False
return self._jump_state_machine()
elif self.jump_state == 'jumping':
if self.had_collision:
self.jump_frame = 0
self.jump_state = 'falling'
return
if self.jump_pressed:
self.velocity.y = JUMP_VELOCITY
self.jump_frame += 1
if self.jump_frame > MAX_JUMP_FRAME:
self.jump_frame = 0
self.jump_state = 'falling'
elif self.jump_state == 'falling':
if self.had_collision:
self.jump_state = 'standing'
return
else:
assert False, "invalid state: %s" % self.jump_state
def process_input(self):
self.left_pressed = pyxel.btn(self.keymap['left'])
self.right_pressed = pyxel.btn(self.keymap['right'])
self.jump_pressed = pyxel.btn(self.keymap['jump'])
self.jump_pressed_now = pyxel.btnp(self.keymap['jump'])
if self.left_pressed + self.right_pressed == 1:
if self.left_pressed:
self.velocity.x = -HORIZONTAL_VELOCITY
if self.right_pressed:
self.velocity.x = +HORIZONTAL_VELOCITY
else:
self.velocity.x = 0
self._jump_state_machine()
HORIZONTAL_VELOCITY = 1.2
MAX_JUMP_FRAME = 5
JUMP_VELOCITY = -3.6
GRAVITY = Vec2(0, .5)
@dataclass
class GuyGraphicsComponent(GraphicsComponent):
color: int = 2
def render(self, offset_x, offset_y):
pyxel.rectb(round(offset_x + self.x),
round(offset_y + self.y),
round(self.w),
round(self.h),
self.color)
@dataclass
class Guy(GuyInputComponent, GuyGraphicsComponent, PhysicsComponent, Dynamic): pass
def update():
if pyxel.btnp(pyxel.KEY_Q):
pyxel.quit()
if pyxel.btnp(pyxel.KEY_C):
cycle_camera()
if pyxel.btnr(pyxel.KEY_Z):
MAP_LIST.move_back()
if pyxel.btnr(pyxel.KEY_X):
MAP_LIST.move_forward()
update_entities()
for entity in filter_entities(ENTITIES, InputComponent):
entity.process_input()
WORLD.simulate()
def center_on_guy():
return -GUY.x + SCREEN_W // 2, -GUY.y + SCREEN_H // 2
def center_on_map():
MAP = MAP_LIST.current
return - MAP.w // 2 + SCREEN_W // 2, - MAP.h // 2 + SCREEN_H // 2
CENTER_FUNC_ITER = itertools.cycle([center_on_map, center_on_guy])
def cycle_camera():
global CENTER_FUNC
CENTER_FUNC = next(CENTER_FUNC_ITER)
CENTER_FUNC = None
cycle_camera()
def draw():
pyxel.cls(0)
offset_x, offset_y = CENTER_FUNC()
for entity in filter_entities(ENTITIES, GraphicsComponent):
entity.render(offset_x, offset_y)
def filter_entities(entities, *classinfos):
for entity in entities:
if all(isinstance(entity, ci) for ci in classinfos):
yield entity
pyxel.init(SCREEN_W, SCREEN_H)
GUY = Guy(x=MAP_LIST.current.spawn_points[0][0], y=MAP_LIST.current.spawn_points[0][1], w=3, h=7)
if sys.platform == "darwin":
GUY.keymap['jump'] = pyxel.KEY_SUPER
TWO = Guy(x=MAP_LIST.current.spawn_points[1][0], y=MAP_LIST.current.spawn_points[1][1], w=3, h=7,
color=3,
keymap=dict(left=pyxel.KEY_A, right=pyxel.KEY_D, jump=pyxel.KEY_SPACE))
ENTITIES = None
WORLD = None
def update_entities():
global ENTITIES, WORLD
ENTITIES = []
# TODO: we shouldn't process input here
# TODO: avoid copying tiles needlessly (a real ECS wouldn't?)
if pyxel.btn(pyxel.KEY_Z):
if MAP_LIST.previous:
ENTITIES.extend(
t.to_shadow_tile(fill=False, color=5)
for t in MAP_LIST.previous.tiles
)
ENTITIES.extend(MAP_LIST.current.tiles)
ENTITIES.append(GUY)
if pyxel.btn(pyxel.KEY_X):
if MAP_LIST.next:
ENTITIES.extend(
t.to_shadow_tile(fill=False, color=7)
for t in MAP_LIST.next.tiles
)
WORLD = World(filter_entities(ENTITIES, PhysicsComponent), GRAVITY)
update_entities()
pyxel.run(update, draw)