My Pygame Game Engine
1## Transform class for a entity
2
3class Transform:
4 def __init__(self) -> None:
5 self.x = 0
6 self.y = 0
7 self.direction = 0
8
9## Base Entity
10
11class Entity:
12
13 ## Add component to entity
14
15 def add_component(self, component):
16 if component not in self.components:
17 self.components.append(component)
18
19 ## Remove component from entity
20
21 def remove_component(self, component):
22 if component in self.components:
23 self.components.remove(self.components.index(component))
24
25 ## Get component
26
27 def get_component(self, component):
28 yes = False
29 for index, item in enumerate(self.components):
30 if type(item) == component:
31 yes = True
32 num = index
33 break
34
35 if yes == True:
36 return self.components[num]
37
38 ## Contains Component
39
40 def contains_component(self, component):
41 if component in self.components:
42 return True
43 return False
44
45 ## Use the update method in all the components
46
47 def update(self):
48 for component in self.components:
49 component.update()
50
51 ## Use the render method in all the components
52
53 def render(self):
54 for component in self.components:
55 component.render()
56
57## Base Components
58
59# Base component for making the entity camera relative
60
61class Camera_Relative_Component():
62 def __init__(self, game, parent) -> None:
63 self.game = game
64 self.parent = parent
65
66 def update(self):
67 self.parent.camera_relative_x = self.parent.transform.x - self.game.renderer.camera.x
68 self.parent.camera_relative_y = self.parent.transform.y - self.game.renderer.camera.y
69
70 def render(self):
71 pass
72
73class Sprite_Renderer_Component():
74 def __init__(self, game, parent) -> None:
75 self.game = game
76 self.parent = parent
77
78 self.surface = None
79 self.sprite = None
80
81 def update(self):
82 pass
83
84 def render(self):
85 if self.sprite != None and self.surface != None:
86 if self.parent.contains_component(Camera_Relative_Component(self.game, self.parent)):
87 self.surface.blit(self.sprite, (self.parent.camera_relative_x, self.parent.camera_relative_y))
88 else:
89 self.surface.blit(self.sprite, (self.parent.transform.x, self.parent.transform.y))