-
Notifications
You must be signed in to change notification settings - Fork 0
/
wonder.py
executable file
·1701 lines (1326 loc) · 55.4 KB
/
wonder.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
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""Python Game Engine based on pygame and physics engine box2d
This module includes all classes and functions of the game engine.
.. _wonder game engine web page:
https://github.com/Python-Ninja-Hebi/wonder
Documented with Google Python Style Doctrings
.. _Google Python Style Guide:
http://google.github.io/styleguide/pyguide.html
"""
from __future__ import annotations
from Box2D.Box2D import b2Body, b2Contact, b2ContactImpulse, b2Fixture, b2RevoluteJoint #forward references
import pygame
from pygame import Color, surface, color, Rect
from pygame.math import Vector2, Vector3
from pygame.font import Font
import random
import json
import math
import zmq
from typing import Dict, List, OrderedDict, Set, Optional, Union, Tuple, Any, Type
import traceback
from Box2D import b2World, b2ContactListener, b2_dynamicBody, b2_staticBody, b2_kinematicBody, b2Vec2, b2PolygonShape, b2DistanceJoint, b2AABB, b2QueryCallback
from pygame.surface import Surface
MAROON = (128, 0, 0)
RED = (255, 0, 0)
ORANGE = (255, 165, 0)
YELLOW = (255, 255, 0)
OLIVE = (128, 128, 0)
GREEN = (0, 128, 0)
PURPLE = (128, 0, 128)
FUCHSIA = (255, 0, 255)
LIME = (0, 255, 0)
TEAL = (0, 128, 128)
AQUA = (0, 255, 255)
BLUE = (0, 0, 255)
NAVY = (0, 0, 128)
BLACK = (0, 0, 0)
GRAY = (128, 128, 128)
DARKGRAY = (169,169,169)
SILVER = (192, 192, 192)
WHITE = (255, 255, 255)
# ----- central game engine systems ----
class MixinGameSystem:
"""[summary]
"""
def on_load_scene(self, scene:Scene):
pass
def on_start_load_scene(self):
pass
def on_add_gameobject(self, gameobject:GameObject, layer:str)->None:
pass
def on_remove_gameobject(self, gameobject:GameObject)->None:
pass
# ----- gameobject and scene system ----
class MixinUpdate:
def update(self, delta_time:float):
pass
def late_update(self):
pass
class MixinDraw:
def draw(self, screen:pygame.Surface):
pass
class Transform:
def __init__(self):
self.position:Vector2 = Vector2(0.0, 0.0)
self.rotation:float = 0.0
self.scale:Vector2 = Vector2(1.0, 1.0)
def translate(self,v:Vector2)->None:
self.position = self.position + v
class Component(MixinUpdate):
def __init__(self, gameobject:GameObject):
self.gameobject = gameobject
class GameObject(MixinUpdate):
def __init__(self):
self.transform:Transform = Transform()
self.components = []
def add(self, component:Component):
self.components.append(component)
return component
def on_collision_enter(self, collider:GameObject, impulse:b2ContactImpulse)->None:
pass
def on_trigger_enter(self, collider:GameObject)->None:
pass
def get_component(self, classinfo):
r = None
for c in self.components:
if isinstance(c,classinfo):
r = c
return r
class Scene:
"""[summary]
"""
def __init__(self) -> None:
self.init()
def init(self)->None:
self.name = ""
self.background_color = BLACK
self.dont_destroy_on_load_list = []
self.layers = OrderedDict()
self.layers['default'] = []
def create(self)->None:
pass
def add(self, gameobject:GameObject, layer:str='default')->GameObject:
self.layers[layer].append(gameobject)
Game.instance.on_add_gameobject(self, gameobject, layer)
return gameobject
def add_layer(self, name, to_bottom=False, to_top=False):
if not name in self.layers:
self.layers[name] = []
if to_bottom:
self.layers.move_to_end(name, last=False)
if to_top:
self.layers.move_to_end(name, last=True)
def dont_destroy_on_load(self, gameobject:GameObject, layer:str='default')->None:
self.dont_destroy_on_load_list.append((gameobject, layer))
class SceneSystem(MixinGameSystem):
def __init__(self, scenes) -> None:
self.current_scene:Scene = None
self.current_scene_index:int = 0
if not isinstance(scenes, list):
scenes = [scenes]
self.scenes:List[Scene] = scenes
def load_scene(self, scene_index:int) -> None:
dont_destroy_list = []
if self.current_scene:
dont_destroy_list = self.current_scene.dont_destroy_on_load_list.copy()
scene = self.scenes[scene_index]
self.current_scene = scene
self.current_scene_index = scene_index
scene.init()
for g in dont_destroy_list:
scene.add(g[0],layer=g[1])
scene.dont_destroy_on_load(g[0],layer=g[1])
scene.create()
Game.instance.background_color = self.current_scene.background_color
Game.instance.name = self.current_scene.name
def on_remove_gameobject(self, gameobject: GameObject) -> None:
if self.current_scene:
for l in self.current_scene.layers:
if gameobject in self.current_scene.layers[l]:
self.current_scene.layers[l].remove(gameobject)
class ObserverSet:
def __init__(self,typeinfo) -> None:
self.typeinfo = typeinfo
self.items:Set = None
def init(self, scene:Scene)->None:
self.items = set()
for l in scene.layers:
for g in scene.layers[l]:
self.add(g)
def add(self, gameobject:GameObject)->None:
if isinstance(gameobject, self.typeinfo):
self.items.add(gameobject)
for c in gameobject.components:
if isinstance(c, self.typeinfo):
self.items.add(c)
def remove(self, gameobject:GameObject)->None:
if isinstance(gameobject,self.typeinfo):
if gameobject in self.items: self.items.remove(gameobject)
for c in gameobject.components:
if isinstance(gameobject, self.typeinfo):
if c in self.items: self.items.remove(c)
class ObserverOrderedDict:
def __init__(self, typeinfo) -> None:
self.typeinfo = typeinfo
self.layers:OrderedDict = None
def init(self, scene:Scene)->None:
self.layers = OrderedDict()
for layer_key, layer_value in scene.layers.items():
self.layers[layer_key] = set()
for g in layer_value:
self.add(g, layer_key)
def add(self, gameobject:GameObject, layer:str)->None:
if isinstance(gameobject, self.typeinfo):
self.layers[layer].add(gameobject)
for c in gameobject.components:
if isinstance(c, self.typeinfo):
self.layers[layer].add(c)
def remove(self, gameobject:GameObject)->None:
if isinstance(gameobject,self.typeinfo):
for l in self.layers:
if gameobject in self.layers[l]: self.layers[l].remove(gameobject)
for c in gameobject.components:
if isinstance(c, self.typeinfo):
for l in self.layers:
if c in self.layers[l]: self.layers[l].remove(c)
# ----- event system ----
class MixinEvent:
def on_event(self, event:pygame.eventtype)->None:
pass
class EventSystem(MixinGameSystem):
def __init__(self) -> None:
self.observer = ObserverSet(MixinEvent)
def on_event(self, event:pygame.eventtype)->None:
#print(event,self.observer.items)
for o in self.observer.items:
o.on_event(event)
def on_load_scene(self, scene:Scene):
self.observer.init(scene)
def on_add_gameobject(self, gameobject: GameObject, layer: str) -> None:
self.observer.add(gameobject)
def on_remove_gameobject(self, gameobject: GameObject) -> None:
self.observer.remove(gameobject)
# ----- render system ----
import os
class SpriteRenderer(Component,MixinDraw):
def __init__(self, gameobject, image:pygame.Surface = None, load_from_file:str = None, animator:Animator=None, scale:Vector2=None):
super().__init__(gameobject)
self._image = None
if image:
self._image = image
if load_from_file:
#print('current directory', os.getcwd())
self._image = pygame.image.load(load_from_file)
self.animator = animator
if scale:
if self.animator:
self.animator.scale(scale)
else:
new_size = Vector2(self.image.get_width()*scale.x,self.image.get_height()*scale.y)
self._image = pygame.transform.scale(self.image, (int(new_size.x), int(new_size.y)))
self._rect = self.image.get_rect()
@property
def image(self)->Surface:
if self.animator:
return self.animator.image
else:
return self._image
@image.setter
def image(self,v:Surface)->None:
self._image = v
self._rect = self._image.get_rect()
@property
def rect(self) -> pygame.Rect:
self._rect.center = self.gameobject.transform.position
return self._rect
def draw(self, screen: pygame.Surface):
screen.blit(self.image, self.rect)
#print("SpriteRenderer.draw")
class LineRenderer(Component,MixinDraw):
def __init__(self, gameobject: GameObject, positions:List[Vector2], width:int=1, color:color=GREEN, loop:bool=False,
use_world_space:bool = False):
super().__init__(gameobject)
self.width:int = width
self.color:color = color
self.loop:bool = loop
self.positions:List[Vector2]=positions
self._last_pos = None
self._last_rot = None
self.points = []
if use_world_space:
for i,n in enumerate(self.positions):
self.positions[i] = self.positions[i] - self.gameobject.transform.position
def draw(self, screen: pygame.Surface):
pos = self.gameobject.transform.position
rot = self.gameobject.transform.rotation
#print(f'LineRenderer.draw pos {pos} {self._last_pos} rot {rot} {self._last_rot}')
if self._last_pos != pos or self._last_rot != rot:
self.points = [Vector2(x.x*math.cos(rot)-x.y*math.sin(rot),
x.x*math.sin(rot)+x.y*math.cos(rot)) for x in self.positions]
self.points = [x+pos for x in self.points]
#print(f'LineRender changed')
self._last_pos = Vector2(pos.x,pos.y)
self._last_rot = rot
if self.loop:
pygame.draw.polygon(screen, self.color, self.points, self.width)
class RenderSystem(MixinGameSystem):
def __init__(self) -> None:
self.observer = ObserverOrderedDict(MixinDraw)
def on_load_scene(self, scene: Scene):
self.observer.init(scene)
def on_add_gameobject(self, gameobject: GameObject, layer: str) -> None:
self.observer.add(gameobject, layer)
def on_remove_gameobject(self, gameobject: GameObject) -> None:
self.observer.remove(gameobject)
def draw(self, screen:pygame.Surface)->None:
for layer_key, layer_value in self.observer.layers.items():
for c in layer_value:
c.draw(screen)
class AnimationClip:
def __init__(self,file_name:str, duration:int) -> None:
self.duration = duration
self.image = pygame.image.load(file_name)
def scale(self, v:Vector2)->None:
new_size = Vector2(self.image.get_width()*v.x,self.image.get_height()*v.y)
self.image = pygame.transform.scale(self.image, (int(new_size.x), int(new_size.y)))
class AnimationState:
def __init__(self, name:str, clips:List[AnimationClip]) -> None:
self.name = name
self.clips = clips
self.length = 0
for c in self.clips:
self.length += c.duration
self.duration_dif = 0
self.clip = 0
def scale(self, v:Vector2)->None:
for c in self.clips:
c.scale(v)
def update(self, delta_time:float)->None:
self.duration_dif += delta_time * 1000
while self.duration_dif > self.clips[self.clip].duration:
self.duration_dif -= self.clips[self.clip].duration
self.clip += 1
if self.clip >= len(self.clips):
self.clip = 0
@property
def image(self)->Surface:
return self.clips[self.clip].image
class Animator(Component):
def __init__(self, gameobject: GameObject, states:List[AnimationState],start_state:str):
super().__init__(gameobject)
self.states = {}
for c in states:
self.states[c.name] = c
self.start_state = start_state
self.state = self.start_state
def scale(self, v:Vector2)->None:
for c in self.states.items():
c.scale(v)
@property
def image(self)->Surface:
return self.states[self.state].image
def update(self, delta_time: float)->None:
self.states[self.state].update(delta_time)
# ----- remote system ----
class RemoteCommand:
def __init__(self,name:bytearray) -> None:
self.name:bytearray=name
self.argument:bytearray=None
class RemoteInput:
"""Server to get remote input
"""
def __init__(self,command_list:List[RemoteCommand]) -> None:
self.commands:Dict={}
for j in command_list:
self.commands[j.name]=j
context = zmq.Context()
self.socket = context.socket(zmq.REP)
self.socket.bind('tcp://*:5555')
def command(self,delta_time:float)->RemoteCommand:
result:RemoteCommand = None
try:
message:bytearray = self.socket.recv(flags=zmq.NOBLOCK)
items = message.split(b' ')
result = self.commands[items[0]]
if len(items)>1:
result.argument = items[1]
else:
result.argument = None
except zmq.Again as e:
pass
return result
def ready(self)->None:
self.socket.send(b'ready')
class RemoteControl:
"""Client to control object with remote
"""
def __init__(self) -> None:
context = zmq.Context()
self.socket = context.socket(zmq.REQ)
self.socket.connect('tcp://localhost:5555')
def send(self, command:bytearray)->None:
self.socket.send(command)
message = self.socket.recv()
# ----- particle system ----
class Particle:
def __init__(self,image:Surface = None,
position:Vector2 = None,
velocity:Vector2 = Vector2(1,1),
angle:float = 1,
angle_velocity:float = 0,
color:pygame.Color = YELLOW,
size:float = 1.0,
time:float = 1.0) -> None:
self.image:Surface = image
self.rect:pygame.Rect = self.image.get_rect()
self.position:Vector2 = position
self.velocity:Vector2 = velocity
self.angle:float = angle
self.angle_velocity:float = angle_velocity
self.color:pygame.Color = color
self.size:float = size
self.time:float = time
class ParticleSystem(Component, MixinDraw):
"""
duration .. length of time the system runs
looping .. if enabled, the system starts again at the end of its duration time
Start Lifetime .. initial lifetime for particles
start_speed .. initial speed for particles
Start Size .. initial size for particles
Start Rotation The initial rotation angle of each particle.
Start Color The initial color of each particle.
force .. gravity or other force
Max Particles The maximum number of particles in the system at once. If the limit is reached, some particles are removed.
start_range_from .. angle for start begins
start_range_to .. angle for start ends
image .. image of the particles
rate_over_time .. number of particles emitted per second
"""
def __init__(self, gameobject: GameObject, duration:float=1.0, looping:bool=True, image=None,
rate_over_time:float=1.0, force:Vector2=Vector2(0,0), start_speed:float=10,
start_range_from:float=0, start_range_to:float = 0):
super().__init__(gameobject)
self.duration:float = duration
self.looping:bool = looping
self.active = True
self.particles = []
self.image = image
self.rate_over_time = rate_over_time
self.next_emit = 1 / self.rate_over_time
self.force = force
self.start_speed = start_speed
self.start_range_from = start_range_from
self.start_range_to = start_range_to
self.append_particle()
def append_particle(self):
a = random.uniform(self.start_range_from,self.start_range_to)
v = Vector2(math.cos(a)*self.start_speed,math.sin(a)*self.start_speed)
self.particles.append(Particle(image=self.image,
position=self.gameobject.transform.position, time=8, velocity=v))
def update(self, delta_time: float):
if not self.active: return
if not self.looping:
self.duration -= delta_time
if self.duration <= 0:
self.active = False
return
self.next_emit -= delta_time
if self.next_emit <= 0:
self.append_particle()
self.next_emit = 1 / self.rate_over_time
remove_list = []
for i in self.particles:
i.velocity += self.force * delta_time
i.position += i.velocity * delta_time
i.time -= delta_time
if i.time <= 0:
remove_list.append(i)
for i in remove_list:
self.particles.remove(i)
def draw(self, screen: pygame.Surface):
if not self.active: return
for i in self.particles:
i.rect.center = i.position
screen.blit(i.image,i.rect)
# ----- tile system ----
class TilePaletteItem:
"""Element of a TilePalette
"""
def __init__(self, id:int, tile_type:str,
image:Surface,
scale:float=None,
tile_controller_class:Type[TileController]=None) -> None:
"""Create TilePaletteItem
Args:
id (int): unique id
tile_type (str): unique name
image (Surface): [description]
scale (float, optional): [description]. Defaults to None.
tile_controller_class (Type[TileController], optional): [description]. Defaults to None.
"""
self.id:int = id
self.tile_type = tile_type
self.image:Surface = image
if scale:
self.image = pygame.transform.scale(self.image, (int(self.image.get_width()*scale),
int(self.image.get_height()*scale)))
self.tile_controller_class = tile_controller_class
class Tile:
def __init__(self,tile_palette:TilePaletteItem) -> None:
self.tile_palette:TilePaletteItem = tile_palette
self.visible:bool = True
self._image:Surface = None
self.controller:TileController = None
if tile_palette.tile_controller_class:
self.controller = tile_palette.tile_controller_class(self)
self._position:Vector2=None
self.layer:TileMapLayer = None
@property
def image(self)->Surface:
if self._image:
return self._image
return self.tile_palette.image
@image.setter
def image(self, value:Surface)->None:
self._image = value
def get_position(self)->Vector2:
return self._position
def set_position(self, value:Vector2)->None:
self.layer.tilemap.set_tile(self,value,self.layer.id)
def has_type(self, tile_type:str)->bool:
return self.tile_palette.tile_type == tile_type
class TileController(MixinUpdate):
def __init__(self, tile:Tile) -> None:
self.tile:Tile = tile
def get_position(self)->Vector2:
return self.tile.position
def set_position(self,value:Vector2)->None:
self.tile.set_position(value)
def get_tile(self, pos:Vector2)->Tile:
return self.tile.layer.tilemap.get_tile(pos)
class TileMapRenderer(Component,MixinDraw):
def __init__(self, gameobject: GameObject):
super().__init__(gameobject)
self.tilemap:TileMap = gameobject
def draw(self, screen):
min_x = 0
max_x = self.tilemap.width
min_y = 0
max_y = self.tilemap.height
pos = self.tilemap.transform.position
#if Game.instance.camera and not self._all:
# c = self.gameobject.world_to_cell(Game.instance.camera.transform.position)
# min_x = max(0,int(c.x - self._half_width))
# max_x = min(int(c.x + self._half_width),self.gameobject.width)
# min_y = max(0,int(c.y - self._half_height))
# max_y = min(int(c.y + self._half_height),self.gameobject.height)
for x in range(min_x,max_x):
for y in range(min_y, max_y):
for z in range(len(self.tilemap.layer)):
if isinstance(self.tilemap.layer[z],TileMapLayer):
t = self.tilemap.layer[z].get_tile(x,y)
if t:
if t.visible:
#if not Game.instance.camera:
screen.blit(t.image, (pos.x+self.tilemap.tile_width*x ,pos.y+self.tilemap.tile_height*y ,
self.tilemap.tile_width,self.tilemap.tile_height))
#else:
# screen.blit(t.image, (self.tilemap.tile_width*x-Game.instance.camera.offset_x ,
# self.tilemap.tile_height*y-Game.instance.camera.offset_y,
# self.tilemap.tile_width,
# self.tilemap.tile_height))
class TileMapObject:
"""Part of a TileMapObjectLayer
"""
def __init__(self, heigth:int, width:int, name:str, type:str ,x:int,y:int) -> None:
self.height:int = heigth
self.width:int = width
self.name:str = name
self.type:str = type
self.x:int = x
self.y:int = y
class TileMapAbstractLayer:
def __init__(self,tilemap:TileMap,id:int) -> None:
self.tilemap=tilemap
self.id = id
class TileMapObjectLayer(TileMapAbstractLayer):
"""Layer for objects
"""
def __init__(self,tilemap:TileMap,id:int) -> None:
super().__init__(tilemap,id)
self.objects:List[TileMapObject]=[]
def add (self, object:TileMapObject)->None:
self.objects.append(object)
class TileMapLayer(TileMapAbstractLayer):
def __init__(self,tilemap:TileMap,id:int) -> None:
super().__init__(tilemap,id)
self._tiles = [[None] * self.tilemap.height for _ in range(self.tilemap.width)]
def set_tile(self, tile:Tile, x:int, y:int)->None:
self._tiles[int(x)][int(y)]=tile
if tile:
tile.layer = self
tile.position = Vector2(x,y)
def get_tile(self, x:int, y:int)->Tile:
return self._tiles[int(x)][int(y)]
class TilePalette:
def __init__(self) -> None:
self._store = {}
def __getitem__(self,key)->TilePaletteItem:
if isinstance(key,str):
return self._store[key]
elif isinstance(key,int):
for _, item in self._store.items():
if item.id == key:
return item
return None
def add(self, item:TilePaletteItem)->TilePaletteItem:
self._store[item.tile_type]=item
return item
class TiledReader:
"""Reads a JSON file created with MapEditor Tiled to create a TileMap
"""
def __init__(self,file_name:str, controller_list = None) -> None:
self.file_name=file_name
self.controller_list = controller_list
self.path,_ = os.path.split(file_name)
with open(self.file_name, 'r') as f:
map = json.load(f)
self.height = map['height']
self.width = map['width']
self.tile_height = map['tileheight']
self.tile_width = map['tilewidth']
self.layers = map['layers']
self.tilesets = map['tilesets']
def create_object_layer(self,tilemap:TileMap,objects:List)->TileMapObjectLayer:
layer = tilemap.add_objectlayer()
for o in objects:
layer.add(TileMapObject(
o["height"],o[ "width"],o["name"],o["type"],
o["x"],o["y"]))
return layer
def create(self)->TileMap:
tilemap = TileMap(self.width,self.height,self.tile_width,self.tile_height)
self.create_palette(tilemap)
for l in self.layers:
if l['type'] == 'objectgroup':
self.create_object_layer(tilemap, l['objects'])
elif l['type'] == 'tilelayer':
self.create_map_layer(tilemap, l['data'])
else:
raise Exception(f"unknown layer type {l['type']}")
return tilemap
def create_map_layer(self, tilemap:TileMap, data:List[int])->TileMapLayer:
layer = tilemap.add_tilelayer()
x=0
y=0
for d in data:
if d != 0:
tilemap.create_tile_from_palette(x,y,d,layer.id)
x+=1
if x == tilemap.width:
y+=1
x=0
return layer
def create_palette(self, tilemap:TileMap):
tiles:Dict[int,Surface]={}
tile_types:Dict[int,str]={}
all_data:Set[int]=set()
for l in self.layers:
if l['type'] == 'tilelayer':
all_data = all_data.union(set(l['data']))
for t in self.tilesets:
first_id = t['firstgid']
tile_count = t['tilecount']
file_name = t['image']
if 'tiles' in t:
for tile_type in t['tiles']:
tile_types[tile_type['id']+first_id]=tile_type['type']
if self.path:
file_name = self.path + '/' + file_name
image = pygame.image.load(file_name)
if tile_count == 1 and first_id in all_data:
tiles[first_id] = image
else:
for id in range(first_id,first_id+tile_count):
if id in all_data:
tiles[id] = self.get_tile_from_image(image, t['columns'],
id, first_id, t['tilewidth'],
t['tileheight'],t['spacing'])
for tile_id in tiles:
tile_type = None
if tile_id in tile_types:
tile_type = tile_types[tile_id]
else:
tile_type = 'id_'+str(tile_id)
controller = None
if tile_type in self.controller_list:
controller = self.controller_list[tile_type]
tilemap.palette.add(TilePaletteItem(tile_id, tile_type=tile_type, image=tiles[tile_id],tile_controller_class=controller))
def get_tile_from_image(self, image:Surface, columns:int, id:int, first_id:int ,tile_width:int,tile_height:int,spacing:int)->pygame.Surface:
id -= first_id
x = (id % columns)
y = (id // columns)
x_s = x*tile_width+(x+1)*spacing
y_s = y*tile_height+(y+1)*spacing
rect = (x_s, y_s,
tile_width, tile_height)
return image.subsurface(rect)
class TileMap(GameObject):
@classmethod
def createFromTiledJSON(cls, file_name:str, contoler_list=None)->TileMap:
reader = TiledReader(file_name, contoler_list)
return reader.create()
def __init__(self, width:int, height:int, tile_width:int, tile_height:int) -> None:
super().__init__()
self.width:int = width
self.height:int = height
self.tile_width:int = tile_width
self.tile_height :int= tile_height
self.layer = [TileMapLayer(self,0)]
self.controller_list:List[TileController]=[]
self.palette:TilePalette = TilePalette()
def add_tilelayer(self)->TileMapLayer:
layer = TileMapLayer(self,self.get_next_layer_id())
self.layer.append(layer)
return layer
def add_objectlayer(self)->TileMapObjectLayer:
layer = TileMapObjectLayer(self,self.get_next_layer_id())
self.layer.append(layer)
return layer
def add_layer(self)->int:
layer = self.add_tilelayer()
return layer.id
def get_next_layer_id(self)->int:
return len(self.layer)
def get_tile(self,pos,layer=-1)->Tile:
if layer == -1:
for i in reversed(self.layer):
t = i.get_tile(pos.x,pos.y)
if t:
return t
return None
else:
return self.layer[layer]
def set_tile(self,tile:Tile,pos:Vector2,layer=0)->None:
old_pos = tile.position
old_layer = tile.layer.id
self.layer[layer].set_tile(tile,pos.x,pos.y)
self.layer[old_layer].set_tile(None,old_pos.x,old_pos.y)
def create_tile_from_palette(self, x:int, y:int, tile_type:str|TilePaletteItem, tile_layer = 0)->Tile:
tile = None
item = None
if isinstance(tile_type,TilePaletteItem):
item = tile_type
elif tile_type:
item = self.palette[tile_type]
if item:
tile = Tile(item)
self.layer[tile_layer].set_tile(tile,x,y)
if tile:
if tile.controller:
self.controller_list.append(tile.controller)
return tile
def set_all_tiles(self,all_tiles:List[List[int|str]], tile_layer=0)->None:
for y, line in enumerate(all_tiles):
for x, value in enumerate(line):
self.create_tile_from_palette(x,y,self.palette[value],tile_layer=tile_layer)
def update(self, delta_time: float):
for c in self.controller_list:
c.update(delta_time)
# ----- physic system ----
STATIC_BODY = b2_staticBody
KINEMATIC_BODY = b2_kinematicBody
DYNAMIC_BODY = b2_dynamicBody
FORCE_MODE_FORCE = 1
FORCE_MODE_ACCELERATION = 2
FORCE_MODE_IMPULSE = 3
FORCE_MODE_VELOCITY_CHANGE = 4
class MixinSynchroniser:
def get_position(self)->Vector2:
pass
def set_position(self, value:Vector2)->None:
pass
def get_rotation(self)->float:
pass
def set_rotation(self, value:float)->None:
pass
def get_position_x(self) -> float:
return self.get_position().x
def set_position_x(self, value)->None:
v = self.get_position()
n = Vector2(value, v.y)
self.set_position(n)
def get_position_y(self)-> float:
return self.get_position().y
def set_position_y(self, value)->None:
v = self.get_position()
self.set_position(Vector2(v.x, value))
class SynchronisedVector2(Vector2):
def __init__(self, x: Optional[Union[float, Vector2, Tuple[float, float], List[float]]], y: Optional[float],synchroniser=None) -> None:
super().__init__(x=x, y=y)
self._synchroniser:MixinSynchroniser = synchroniser
@property
def x (self):
return self._synchroniser.get_position_x()
@x.setter
def x (self, v:float)->None:
self._synchroniser.set_position_x(v)
@property
def y (self)->float:
return self._synchroniser.get_position_y()
@y.setter
def y (self,v:float)->None:
self._synchroniser.set_position_y(v)
class SynchronisedTransform:
def __init__(self, transform:Transform, synchroniser:MixinSynchroniser):
self._synchroniser = synchroniser
self.position = transform.position
self.rotation = transform.rotation
self.scale = transform.scale
@property
def position(self)->SynchronisedVector2:
v = self._synchroniser.get_position()
return SynchronisedVector2(v.x,v.y,synchroniser=self._synchroniser)
@position.setter
def position(self, value)->None:
self._synchroniser.set_position(value)
@property
def rotation(self)->float:
return self._synchroniser.get_rotation()
@rotation.setter
def rotation(self,value:float)->None: