├── .gitignore
├── Changelog.md
├── LICENSE
├── Logo.png
├── MANIFEST.in
├── README.md
├── pyengine
├── Components
│ ├── AnimComponent.py
│ ├── ControlComponent.py
│ ├── LifeComponent.py
│ ├── MoveComponent.py
│ ├── PhysicsComponent.py
│ ├── PositionComponent.py
│ ├── SpriteComponent.py
│ ├── TextComponent.py
│ └── __init__.py
├── Entities
│ ├── Entity.py
│ ├── Tilemap.py
│ └── __init__.py
├── Exceptions.py
├── Network
│ ├── Client.py
│ ├── NetworkManager.py
│ ├── Packet.py
│ ├── Server.py
│ └── __init__.py
├── Systems
│ ├── CameraSystem.py
│ ├── EntitySystem.py
│ ├── MusicSystem.py
│ ├── SoundSystem.py
│ ├── UISystem.py
│ └── __init__.py
├── Utils
│ ├── Color.py
│ ├── Config.py
│ ├── Font.py
│ ├── Lang.py
│ ├── Logger.py
│ ├── Others.py
│ ├── Vec2.py
│ └── __init__.py
├── Widgets
│ ├── AnimatedImage.py
│ ├── Button.py
│ ├── Checkbox.py
│ ├── Console.py
│ ├── Entry.py
│ ├── Image.py
│ ├── Label.py
│ ├── MultilineLabel.py
│ ├── ProgressBar.py
│ ├── Selector.py
│ ├── Widget.py
│ └── __init__.py
├── Window.py
├── World.py
└── __init__.py
├── setup.py
├── test
├── game.py
├── images
│ ├── idle.png
│ ├── sprite0.png
│ ├── sprite1.png
│ └── test.gif
└── tilemap
│ ├── TESTMAP.json
│ └── tileset
│ ├── Test.tsx
│ ├── sprite0.png
│ └── sprite1.png
└── tests
├── ComponentsTests.py
├── EntitiesTests.py
├── NetworkTests.py
├── SystemsTests.py
├── UtilsTests.py
├── WidgetsTests.py
├── WindowTests.py
├── WorldTests.py
├── files
├── en.lang
├── fr.lang
├── sprite0.png
├── sprite1.png
└── tilemap
│ ├── TESTMAP.json
│ ├── Test.tsx
│ ├── sprite0.png
│ └── sprite1.png
├── launch_server_for_test.py
└── launch_tests.py
/.gitignore:
--------------------------------------------------------------------------------
1 | .idea/
2 | # Byte-compiled / optimized / DLL files
3 | __pycache__/
4 | *.py[cod]
5 | *$py.class
6 |
7 | # C extensions
8 | *.so
9 |
10 | # Distribution / packaging
11 | .Python
12 | build/
13 | develop-eggs/
14 | dist/
15 | downloads/
16 | eggs/
17 | .eggs/
18 | lib/
19 | lib64/
20 | parts/
21 | sdist/
22 | var/
23 | wheels/
24 | *.egg-info/
25 | .installed.cfg
26 | *.egg
27 | MANIFEST
28 |
29 | # PyInstaller
30 | # Usually these files are written by a python script from a template
31 | # before PyInstaller builds the exe, so as to inject date/other infos into it.
32 | *.manifest
33 | *.spec
34 |
35 | # Installer logs
36 | pip-log.txt
37 | pip-delete-this-directory.txt
38 |
39 | # Unit test / coverage reports
40 | htmlcov/
41 | .tox/
42 | .nox/
43 | .coverage
44 | .coverage.*
45 | .cache
46 | nosetests.xml
47 | coverage.xml
48 | *.cover
49 | .hypothesis/
50 | .pytest_cache/
51 |
52 | # Translations
53 | *.mo
54 | *.pot
55 |
56 | # Django stuff:
57 | *.log
58 | local_settings.py
59 | db.sqlite3
60 |
61 | # Flask stuff:
62 | instance/
63 | .webassets-cache
64 |
65 | # Scrapy stuff:
66 | .scrapy
67 |
68 | # Sphinx documentation
69 | docs/_build/
70 |
71 | # PyBuilder
72 | target/
73 |
74 | # Jupyter Notebook
75 | .ipynb_checkpoints
76 |
77 | # IPython
78 | profile_default/
79 | ipython_config.py
80 |
81 | # pyenv
82 | .python-version
83 |
84 | # celery beat schedule file
85 | celerybeat-schedule
86 |
87 | # SageMath parsed files
88 | *.sage.py
89 |
90 | # Environments
91 | .env
92 | .venv
93 | env/
94 | venv/
95 | ENV/
96 | env.bak/
97 | venv.bak/
98 |
99 | # Spyder project settings
100 | .spyderproject
101 | .spyproject
102 |
103 | # Rope project settings
104 | .ropeproject
105 |
106 | # mkdocs documentation
107 | /site
108 |
109 | # mypy
110 | .mypy_cache/
111 | .dmypy.json
112 | dmypy.json
113 |
114 | # Pyre type checker
115 | .pyre/
116 |
--------------------------------------------------------------------------------
/Changelog.md:
--------------------------------------------------------------------------------
1 | # Changelog
2 |
3 | ## V 1.6.1 - XX/XX/19
4 |
5 | - Bug Fix : Physics Objects without gravity can't move
6 | - Bug Fix : MoveComponent save the old movement
7 | - Bug Fix : Physics movement are saved between World
8 | - Bug Fix : OUTOFWINDOW is trigerred in wrong pos
9 |
10 | ## V 1.6.0 - 24/08/19
11 |
12 | - Window : Add limit_fps property
13 | - WindowCallbacks : Add RUNWINDOW Callback
14 | - ControlComponent : Rework to work with physic engine
15 | - ControlComponent : Remove DOUBLEJUMP ControlType
16 | - SpriteComponent : Set origin of sprite to center
17 | - SpriteComponent-AnimComponent : Add flipx and flipy properties
18 | - PhysicsComponent : Rework with a physic engine (Pymunk)
19 | - Selector : Remove background by default
20 |
21 | - Optimization
22 |
23 | - Bug Fix : Check if object is a Vec2 doesn't work with operations
24 | - Bug Fix : OutOfWindow Callback return wrong object
25 |
26 | - Crash Fix : Crash in debug mode with Widgets added
27 |
28 | ## V 1.5.1 - 04/08/19
29 |
30 | - Unlock FPS
31 | - Font : Rework on Font System
32 |
33 | - Optimization
34 |
35 | - Bug Fix : Has_component doesn't work with custom component
36 |
37 | Cette MAJ ne casse pas la combatilbilité avec la précédente.
38 |
39 | ## V 1.5.0 - 28/07/19
40 |
41 | - Entity-Tilemap : Move to "Entities" folder
42 | - ControlComponent : Add MOUSEFOLLOW ControlType
43 | - PhysicsComponent : Add MOUSEFOLLOW and MOUSECLICK CollisionCauses
44 | - Client : Send type, author and message. Packet are used only in PyEngine
45 | - Button : Add enabled property
46 | - Entry : Add Ctrl-C and Ctrl-V
47 | - Entry : Remove limit of caracters
48 | - Entry : Repeats the characters if the key is kept pressed
49 | - Console : Create console widget
50 | - MultilineLabel : Create Label widget for multiline
51 | - Label : Replace \n to void. Label doesn't support break lines
52 | - AnimatedImage : Create Image widget which support multiple images
53 | - Selector : Create selector widget
54 | - Others : Rename Maths to Others
55 | - Others : Add wrap_text and get_images_from_gif functions
56 | - Unit Tests : Fix Vec2 and Color tests
57 | - Unit Tests : Add Console and MultilineLabel tests
58 |
59 | - Optimization
60 |
61 | - Bug Fix : ControlComponent make weird movements with MOUSECLICK ControlType
62 |
63 | - Crash Fix : Crash when use show or hide
64 | - Crash Fix : Crash when Client doesn't have callback
65 | - Crash Fix : Crash when UISystem must show widgets without image or rect
66 |
67 | ## V 1.4.2 - 17/07/19
68 |
69 | - PhysicsComponent : Add callback parameters of constructor
70 | - Tilemap : place tile at bottom
71 |
72 | - Optimization
73 |
74 | - Bug Fix : OUTOFWINDOW doesn't work with CameraSystem
75 | - Bug Fix : Remove offset when change position
76 | - Bug Fix : Hide and Show doesn't spread to child in Widgets
77 | - Bug Fix : Focus stays when widget is hide
78 |
79 | Cette MAJ ne casse pas la combatilbilité avec la précédente.
80 |
81 | ## V 1.4.1 - 14/07/19
82 |
83 | - Color : Add parameter to apply darker or lighter x times
84 |
85 | - Optimization
86 |
87 | - Bug Fix : Fix Diagonal movement from MoveComponent
88 | - Bug Fix : EntitySystem give wrong id to tiles of Tilemap
89 | - Bug Fix : Sprite is rescale at every change of sprite in SpriteComponent
90 | - Bug Fix : If tileset isn't in the same director than tilemap, sprites isn't found
91 | - Bug Fix : ControlComponent save the keypressed when change world
92 |
93 | Cette MAJ ne casse pas la combatilbilité avec la précédente.
94 |
95 | ## V 1.4.0 : All Update - 13/07/19
96 |
97 | - AnimComponent : Add play attribute
98 | - AnimComponent : Use clamp function to set timer
99 | - PositionComponent : Offset is now a property
100 | - PositionComponent : position return the position without offset
101 | - SpriteComponent : Scale don't modify width and height
102 | - LifeComponent : Add callback which is trigger when entity has 0 pv
103 | - Network : If packet have "TOALL" as type, author will recieve the packet
104 | - Tilemap : Create basic tilemap (using Tiled)
105 | - Button-Image : size is now a Vec2
106 | - Button : Only Left Button of Mouse trigger Button
107 | - Button : Remove btn argument on command of Button
108 | - Checkbox : Create checkbox widget
109 | - ProgressBar : Create progressbar widget
110 | - Entry : Add accents letters in accepted and remove some weird symbol
111 | - Color : Use clamp function
112 | - Maths : Clamp function can be use without max or/and min value
113 | - Font : Add rendered_size function
114 | - Vec2 : Add divide operator
115 | - Vec2 : Add iterator
116 | - Vec2 : Change representation in string to "Vec2(X, Y)"
117 | - Unit Tests : Add Tilemap, Prefabs and Network tests
118 | - Unit Tests : Update Components and Widgets tests
119 | - Setup : Add numpy as dependances
120 | - README : Add version of pygame
121 | - README : Remove useless section
122 |
123 | - Optimization
124 |
125 | - Bug Fix : Button must be focused to be hover
126 | - Bug Fix : Rescale SpriteComponent can make weird result
127 | - Bug Fix : Shift-capitals must be typed twice in Entry to be writed
128 | - Bug Fix : Text can be more longer than the Entry
129 | - Bug Fix : Press an other key than the actuel break the movement with ControlComponent
130 |
131 | - Crash Fix : Crash sometimes to create hover button with sprite
132 | - Crash Fix : Crash when import Vec2 at first
133 |
134 | ## V 1.3.0 : Utils Update - 07/07/19
135 |
136 | - Window : Add is_running and update_rate property
137 | - Window : In debug, show fps in console (must be around 60)
138 | - Window-World : Rename and move WorldCallbacks to WindowCallbacks
139 | - WindowCallbacks : Add CHANGEWORLD and STOPWINDOW
140 | - Entity : Can't have the same type of component two times
141 | - EntitySystem-UISystem : Change debug color to blue for ui and red for entity
142 | - EntitySystem : Add get_all_entities function
143 | - PhysicsComponent : Create CollisionInfos
144 | - MoveComponent : Unlock diagonal movement
145 | - LifeComponent : Use clamp function to set life
146 | - AnimComponent : Create basic animator system
147 | - Entry : Add width and sprite property
148 | - Entry : Add color and front parameters
149 | - Entry : Define accepted letters
150 | - Network : Create basic network system
151 | - Vec2 : Add normalized function
152 | - Color : Add to_hex and from_hex function
153 | - Colors : Add new colors
154 | - loggers : Create logging System
155 | - Lang : Create translate system
156 | - Config : Create Config system
157 | - Maths : Create usefull functions (clamp)
158 | - Unit Tests : Add AnimComponent, loggers, config and lang tests
159 | - Unit Tests : Update Window, Color, Entry and World tests
160 | - Optimization and fix some little errors
161 |
162 | - Bug Fix : Entry is update without focus
163 |
164 | - Crash Fix : Crash when show id of Entity Texts
165 | - Crash Fix : Crash when use entity_follow of CameraSystem
166 |
167 | ## V 1.2.0 : Property Update - 09/06/19
168 |
169 | - All : Use property decorator
170 | - All : Add annotation on function will be used by users
171 | - Window : Modify management of Worlds
172 | - Window : Created in middle of the screen
173 | - Window : Can modify size
174 | - GameState : Rename to World
175 | - World : Remove has system function
176 | - Entity-Exception : Replace WrongObjectError to TypeError
177 | - Entity : Can remove component
178 | - CameraSystem : Create basic camera
179 | - MoveComponent : Remove speed
180 | - TextComponent : Add background color
181 | - TextComponent : Add scale
182 | - TextComponent : Add rendered_size
183 | - Label : Add background color
184 | - Button : Add white filter when it is hovered
185 | - Button : Can change image
186 | - Vec2 : Create vector 2
187 | - Color : Can be add, substact and compared
188 | - Font : Can be compared
189 | - Unit Tests : Create
190 |
191 | - Bug Fix : Entity Text is not updated
192 | - Bug Fix : Entity Text is not count in get_entity
193 | - Bug Fix : MusicSystem return wrong volume
194 | - Bug Fix : Window return wrong title
195 |
196 | - Crash Fix : Crash when use Entry
197 | - Crash Fix : Crash when use length setter of Vec2
198 | - Crash Fix : Crash when use TextComponent
199 | - Crash Fix : Crash when we use size of SpriteComponent
200 | - Crash Fix : Crash when we use LifeComponent
201 |
202 | ## V 1.1.2 : Patch Update 2 - 01/06/19
203 |
204 | - UISystem : Add a show_debug function
205 | - Optimization
206 | - Bug Fix : EntitySystem give wrong id to Entities
207 | - Bug Fix : EntitySystem is render after UISystem
208 | - Bug Fix : Window is always in debug mode
209 |
210 | Cette MAJ ne casse pas la combatilbilité avec la précédente.
211 |
212 | ## V 1.1.1 : Patch Update - 30/05/19
213 |
214 | - Create and add PyEngine Logo
215 | - Window : Add icon parameter
216 | - Window : Use Color class
217 | - TextComponent : Add text management
218 |
219 | - Bug Fix : OutOfWindow don't take sprite size
220 | - Critical Bug Fix : CollisionCallbacks is not defined in ControlComponent
221 |
222 | Cette MAJ ne casse pas la combatilbilité avec la précédente.
223 |
224 | ## V 1.1.0 : General Update - 25/05/19
225 |
226 | - LifeComponent : Remove creation of sprite
227 | - LifeComponent : Add get_life and get_maxlife functions
228 | - Entity : Add get_system function
229 | - World : Remove world
230 | - Enums : Move Enums in classes
231 | - EntitySystem : Add function to remove entity
232 | - UISystem : Add function to remove widget
233 | - SoundSystem : Create
234 | - Widgets : You can hide and show widgets
235 | - Entry : You can use your own background
236 | - Color-Colors : Create color class and colors enums
237 | - Font : Create font class
238 | - Optimisation of lib
239 |
240 | - Bug Fix : Rotation of SpriteComponent don't work
241 |
242 | ## V 1.0.2 : Fix Update 2 - 11/05/19
243 |
244 | - Entity : Can get custom component
245 | - Setup : Fix crash when pygame is not installed
246 | - Setup : Don't get PyGame2
247 |
248 | Cette MAJ ne casse pas la combatilbilité avec la précédente.
249 |
250 | ## V 1.0.1 : Fix Update - 10/05/19
251 |
252 | - Enums : Add Controls in __all__
253 | - Entity : Can add custom component
254 |
255 | Cette MAJ ne casse pas la combatilbilité avec la précédente.
256 |
257 | ## V 1.0.0 : First Update - 09/05/19
258 |
259 | - Components : Create LifeBarComponent, MoveComponent
260 | - Components : Rework on system (Work with constructor)
261 | - World-Enums : Create WorldCallbacks (OUTOFWINDOW)
262 | - Components/SpriteComponent : Add set_size function
263 | - Components/PhysicsComponent-Enums : Add CollisionCauses in CollisionCallback
264 | - Components/PhysicsComponent : Add gravity management
265 | - Components/ControlComponent : Add speed management
266 | - Components/ControlComponent : Add controls management
267 | - Components/ControlComponent-Enums : Add LEFTRIGHT and UPDOWN ControlType
268 | - Components/ControlComponent-Enums : Add Controls Enums
269 | - GameState-Window-World : Create GameState System
270 | - Systems/UISystem : Create Wigets System
271 | - Widgets : Create Label, Image, Button, Entry widget
272 | - Window : Add title and background color management
273 | - Exceptions : Rework on system (rename and remove useless exceptions
274 |
275 | ## V 0.2.0-DEV : Little Update - 25/04/19
276 |
277 | - Components/PhysicsComponent : Collision Callback return object
278 | - Systems/EntitySystem : Remove condition to add entity
279 | - Window : Add a function to end game
280 | - Setup.py : Add dependances (PyGame)
281 |
282 | ## V 0.1.0-DEV : Initial Update - 19/04/19
283 |
284 | - First Version
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | GNU GENERAL PUBLIC LICENSE
2 | Version 3, 29 June 2007
3 |
4 | Copyright (C) 2007 Free Software Foundation, Inc.
5 | Everyone is permitted to copy and distribute verbatim copies
6 | of this license document, but changing it is not allowed.
7 |
8 | Preamble
9 |
10 | The GNU General Public License is a free, copyleft license for
11 | software and other kinds of works.
12 |
13 | The licenses for most software and other practical works are designed
14 | to take away your freedom to share and change the works. By contrast,
15 | the GNU General Public License is intended to guarantee your freedom to
16 | share and change all versions of a program--to make sure it remains free
17 | software for all its users. We, the Free Software Foundation, use the
18 | GNU General Public License for most of our software; it applies also to
19 | any other work released this way by its authors. You can apply it to
20 | your programs, too.
21 |
22 | When we speak of free software, we are referring to freedom, not
23 | price. Our General Public Licenses are designed to make sure that you
24 | have the freedom to distribute copies of free software (and charge for
25 | them if you wish), that you receive source code or can get it if you
26 | want it, that you can change the software or use pieces of it in new
27 | free programs, and that you know you can do these things.
28 |
29 | To protect your rights, we need to prevent others from denying you
30 | these rights or asking you to surrender the rights. Therefore, you have
31 | certain responsibilities if you distribute copies of the software, or if
32 | you modify it: responsibilities to respect the freedom of others.
33 |
34 | For example, if you distribute copies of such a program, whether
35 | gratis or for a fee, you must pass on to the recipients the same
36 | freedoms that you received. You must make sure that they, too, receive
37 | or can get the source code. And you must show them these terms so they
38 | know their rights.
39 |
40 | Developers that use the GNU GPL protect your rights with two steps:
41 | (1) assert copyright on the software, and (2) offer you this License
42 | giving you legal permission to copy, distribute and/or modify it.
43 |
44 | For the developers' and authors' protection, the GPL clearly explains
45 | that there is no warranty for this free software. For both users' and
46 | authors' sake, the GPL requires that modified versions be marked as
47 | changed, so that their problems will not be attributed erroneously to
48 | authors of previous versions.
49 |
50 | Some devices are designed to deny users access to install or run
51 | modified versions of the software inside them, although the manufacturer
52 | can do so. This is fundamentally incompatible with the aim of
53 | protecting users' freedom to change the software. The systematic
54 | pattern of such abuse occurs in the area of products for individuals to
55 | use, which is precisely where it is most unacceptable. Therefore, we
56 | have designed this version of the GPL to prohibit the practice for those
57 | products. If such problems arise substantially in other domains, we
58 | stand ready to extend this provision to those domains in future versions
59 | of the GPL, as needed to protect the freedom of users.
60 |
61 | Finally, every program is threatened constantly by software patents.
62 | States should not allow patents to restrict development and use of
63 | software on general-purpose computers, but in those that do, we wish to
64 | avoid the special danger that patents applied to a free program could
65 | make it effectively proprietary. To prevent this, the GPL assures that
66 | patents cannot be used to render the program non-free.
67 |
68 | The precise terms and conditions for copying, distribution and
69 | modification follow.
70 |
71 | TERMS AND CONDITIONS
72 |
73 | 0. Definitions.
74 |
75 | "This License" refers to version 3 of the GNU General Public License.
76 |
77 | "Copyright" also means copyright-like laws that apply to other kinds of
78 | works, such as semiconductor masks.
79 |
80 | "The Program" refers to any copyrightable work licensed under this
81 | License. Each licensee is addressed as "you". "Licensees" and
82 | "recipients" may be individuals or organizations.
83 |
84 | To "modify" a work means to copy from or adapt all or part of the work
85 | in a fashion requiring copyright permission, other than the making of an
86 | exact copy. The resulting work is called a "modified version" of the
87 | earlier work or a work "based on" the earlier work.
88 |
89 | A "covered work" means either the unmodified Program or a work based
90 | on the Program.
91 |
92 | To "propagate" a work means to do anything with it that, without
93 | permission, would make you directly or secondarily liable for
94 | infringement under applicable copyright law, except executing it on a
95 | computer or modifying a private copy. Propagation includes copying,
96 | distribution (with or without modification), making available to the
97 | public, and in some countries other activities as well.
98 |
99 | To "convey" a work means any kind of propagation that enables other
100 | parties to make or receive copies. Mere interaction with a user through
101 | a computer network, with no transfer of a copy, is not conveying.
102 |
103 | An interactive user interface displays "Appropriate Legal Notices"
104 | to the extent that it includes a convenient and prominently visible
105 | feature that (1) displays an appropriate copyright notice, and (2)
106 | tells the user that there is no warranty for the work (except to the
107 | extent that warranties are provided), that licensees may convey the
108 | work under this License, and how to view a copy of this License. If
109 | the interface presents a list of user commands or options, such as a
110 | menu, a prominent item in the list meets this criterion.
111 |
112 | 1. Source Code.
113 |
114 | The "source code" for a work means the preferred form of the work
115 | for making modifications to it. "Object code" means any non-source
116 | form of a work.
117 |
118 | A "Standard Interface" means an interface that either is an official
119 | standard defined by a recognized standards body, or, in the case of
120 | interfaces specified for a particular programming language, one that
121 | is widely used among developers working in that language.
122 |
123 | The "System Libraries" of an executable work include anything, other
124 | than the work as a whole, that (a) is included in the normal form of
125 | packaging a Major Component, but which is not part of that Major
126 | Component, and (b) serves only to enable use of the work with that
127 | Major Component, or to implement a Standard Interface for which an
128 | implementation is available to the public in source code form. A
129 | "Major Component", in this context, means a major essential component
130 | (kernel, window system, and so on) of the specific operating system
131 | (if any) on which the executable work runs, or a compiler used to
132 | produce the work, or an object code interpreter used to run it.
133 |
134 | The "Corresponding Source" for a work in object code form means all
135 | the source code needed to generate, install, and (for an executable
136 | work) run the object code and to modify the work, including scripts to
137 | control those activities. However, it does not include the work's
138 | System Libraries, or general-purpose tools or generally available free
139 | programs which are used unmodified in performing those activities but
140 | which are not part of the work. For example, Corresponding Source
141 | includes interface definition files associated with source files for
142 | the work, and the source code for shared libraries and dynamically
143 | linked subprograms that the work is specifically designed to require,
144 | such as by intimate data communication or control flow between those
145 | subprograms and other parts of the work.
146 |
147 | The Corresponding Source need not include anything that users
148 | can regenerate automatically from other parts of the Corresponding
149 | Source.
150 |
151 | The Corresponding Source for a work in source code form is that
152 | same work.
153 |
154 | 2. Basic Permissions.
155 |
156 | All rights granted under this License are granted for the term of
157 | copyright on the Program, and are irrevocable provided the stated
158 | conditions are met. This License explicitly affirms your unlimited
159 | permission to run the unmodified Program. The output from running a
160 | covered work is covered by this License only if the output, given its
161 | content, constitutes a covered work. This License acknowledges your
162 | rights of fair use or other equivalent, as provided by copyright law.
163 |
164 | You may make, run and propagate covered works that you do not
165 | convey, without conditions so long as your license otherwise remains
166 | in force. You may convey covered works to others for the sole purpose
167 | of having them make modifications exclusively for you, or provide you
168 | with facilities for running those works, provided that you comply with
169 | the terms of this License in conveying all material for which you do
170 | not control copyright. Those thus making or running the covered works
171 | for you must do so exclusively on your behalf, under your direction
172 | and control, on terms that prohibit them from making any copies of
173 | your copyrighted material outside their relationship with you.
174 |
175 | Conveying under any other circumstances is permitted solely under
176 | the conditions stated below. Sublicensing is not allowed; section 10
177 | makes it unnecessary.
178 |
179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
180 |
181 | No covered work shall be deemed part of an effective technological
182 | measure under any applicable law fulfilling obligations under article
183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or
184 | similar laws prohibiting or restricting circumvention of such
185 | measures.
186 |
187 | When you convey a covered work, you waive any legal power to forbid
188 | circumvention of technological measures to the extent such circumvention
189 | is effected by exercising rights under this License with respect to
190 | the covered work, and you disclaim any intention to limit operation or
191 | modification of the work as a means of enforcing, against the work's
192 | users, your or third parties' legal rights to forbid circumvention of
193 | technological measures.
194 |
195 | 4. Conveying Verbatim Copies.
196 |
197 | You may convey verbatim copies of the Program's source code as you
198 | receive it, in any medium, provided that you conspicuously and
199 | appropriately publish on each copy an appropriate copyright notice;
200 | keep intact all notices stating that this License and any
201 | non-permissive terms added in accord with section 7 apply to the code;
202 | keep intact all notices of the absence of any warranty; and give all
203 | recipients a copy of this License along with the Program.
204 |
205 | You may charge any price or no price for each copy that you convey,
206 | and you may offer support or warranty protection for a fee.
207 |
208 | 5. Conveying Modified Source Versions.
209 |
210 | You may convey a work based on the Program, or the modifications to
211 | produce it from the Program, in the form of source code under the
212 | terms of section 4, provided that you also meet all of these conditions:
213 |
214 | a) The work must carry prominent notices stating that you modified
215 | it, and giving a relevant date.
216 |
217 | b) The work must carry prominent notices stating that it is
218 | released under this License and any conditions added under section
219 | 7. This requirement modifies the requirement in section 4 to
220 | "keep intact all notices".
221 |
222 | c) You must license the entire work, as a whole, under this
223 | License to anyone who comes into possession of a copy. This
224 | License will therefore apply, along with any applicable section 7
225 | additional terms, to the whole of the work, and all its parts,
226 | regardless of how they are packaged. This License gives no
227 | permission to license the work in any other way, but it does not
228 | invalidate such permission if you have separately received it.
229 |
230 | d) If the work has interactive user interfaces, each must display
231 | Appropriate Legal Notices; however, if the Program has interactive
232 | interfaces that do not display Appropriate Legal Notices, your
233 | work need not make them do so.
234 |
235 | A compilation of a covered work with other separate and independent
236 | works, which are not by their nature extensions of the covered work,
237 | and which are not combined with it such as to form a larger program,
238 | in or on a volume of a storage or distribution medium, is called an
239 | "aggregate" if the compilation and its resulting copyright are not
240 | used to limit the access or legal rights of the compilation's users
241 | beyond what the individual works permit. Inclusion of a covered work
242 | in an aggregate does not cause this License to apply to the other
243 | parts of the aggregate.
244 |
245 | 6. Conveying Non-Source Forms.
246 |
247 | You may convey a covered work in object code form under the terms
248 | of sections 4 and 5, provided that you also convey the
249 | machine-readable Corresponding Source under the terms of this License,
250 | in one of these ways:
251 |
252 | a) Convey the object code in, or embodied in, a physical product
253 | (including a physical distribution medium), accompanied by the
254 | Corresponding Source fixed on a durable physical medium
255 | customarily used for software interchange.
256 |
257 | b) Convey the object code in, or embodied in, a physical product
258 | (including a physical distribution medium), accompanied by a
259 | written offer, valid for at least three years and valid for as
260 | long as you offer spare parts or customer support for that product
261 | model, to give anyone who possesses the object code either (1) a
262 | copy of the Corresponding Source for all the software in the
263 | product that is covered by this License, on a durable physical
264 | medium customarily used for software interchange, for a price no
265 | more than your reasonable cost of physically performing this
266 | conveying of source, or (2) access to copy the
267 | Corresponding Source from a network server at no charge.
268 |
269 | c) Convey individual copies of the object code with a copy of the
270 | written offer to provide the Corresponding Source. This
271 | alternative is allowed only occasionally and noncommercially, and
272 | only if you received the object code with such an offer, in accord
273 | with subsection 6b.
274 |
275 | d) Convey the object code by offering access from a designated
276 | place (gratis or for a charge), and offer equivalent access to the
277 | Corresponding Source in the same way through the same place at no
278 | further charge. You need not require recipients to copy the
279 | Corresponding Source along with the object code. If the place to
280 | copy the object code is a network server, the Corresponding Source
281 | may be on a different server (operated by you or a third party)
282 | that supports equivalent copying facilities, provided you maintain
283 | clear directions next to the object code saying where to find the
284 | Corresponding Source. Regardless of what server hosts the
285 | Corresponding Source, you remain obligated to ensure that it is
286 | available for as long as needed to satisfy these requirements.
287 |
288 | e) Convey the object code using peer-to-peer transmission, provided
289 | you inform other peers where the object code and Corresponding
290 | Source of the work are being offered to the general public at no
291 | charge under subsection 6d.
292 |
293 | A separable portion of the object code, whose source code is excluded
294 | from the Corresponding Source as a System Library, need not be
295 | included in conveying the object code work.
296 |
297 | A "User Product" is either (1) a "consumer product", which means any
298 | tangible personal property which is normally used for personal, family,
299 | or household purposes, or (2) anything designed or sold for incorporation
300 | into a dwelling. In determining whether a product is a consumer product,
301 | doubtful cases shall be resolved in favor of coverage. For a particular
302 | product received by a particular user, "normally used" refers to a
303 | typical or common use of that class of product, regardless of the status
304 | of the particular user or of the way in which the particular user
305 | actually uses, or expects or is expected to use, the product. A product
306 | is a consumer product regardless of whether the product has substantial
307 | commercial, industrial or non-consumer uses, unless such uses represent
308 | the only significant mode of use of the product.
309 |
310 | "Installation Information" for a User Product means any methods,
311 | procedures, authorization keys, or other information required to install
312 | and execute modified versions of a covered work in that User Product from
313 | a modified version of its Corresponding Source. The information must
314 | suffice to ensure that the continued functioning of the modified object
315 | code is in no case prevented or interfered with solely because
316 | modification has been made.
317 |
318 | If you convey an object code work under this section in, or with, or
319 | specifically for use in, a User Product, and the conveying occurs as
320 | part of a transaction in which the right of possession and use of the
321 | User Product is transferred to the recipient in perpetuity or for a
322 | fixed term (regardless of how the transaction is characterized), the
323 | Corresponding Source conveyed under this section must be accompanied
324 | by the Installation Information. But this requirement does not apply
325 | if neither you nor any third party retains the ability to install
326 | modified object code on the User Product (for example, the work has
327 | been installed in ROM).
328 |
329 | The requirement to provide Installation Information does not include a
330 | requirement to continue to provide support service, warranty, or updates
331 | for a work that has been modified or installed by the recipient, or for
332 | the User Product in which it has been modified or installed. Access to a
333 | network may be denied when the modification itself materially and
334 | adversely affects the operation of the network or violates the rules and
335 | protocols for communication across the network.
336 |
337 | Corresponding Source conveyed, and Installation Information provided,
338 | in accord with this section must be in a format that is publicly
339 | documented (and with an implementation available to the public in
340 | source code form), and must require no special password or key for
341 | unpacking, reading or copying.
342 |
343 | 7. Additional Terms.
344 |
345 | "Additional permissions" are terms that supplement the terms of this
346 | License by making exceptions from one or more of its conditions.
347 | Additional permissions that are applicable to the entire Program shall
348 | be treated as though they were included in this License, to the extent
349 | that they are valid under applicable law. If additional permissions
350 | apply only to part of the Program, that part may be used separately
351 | under those permissions, but the entire Program remains governed by
352 | this License without regard to the additional permissions.
353 |
354 | When you convey a copy of a covered work, you may at your option
355 | remove any additional permissions from that copy, or from any part of
356 | it. (Additional permissions may be written to require their own
357 | removal in certain cases when you modify the work.) You may place
358 | additional permissions on material, added by you to a covered work,
359 | for which you have or can give appropriate copyright permission.
360 |
361 | Notwithstanding any other provision of this License, for material you
362 | add to a covered work, you may (if authorized by the copyright holders of
363 | that material) supplement the terms of this License with terms:
364 |
365 | a) Disclaiming warranty or limiting liability differently from the
366 | terms of sections 15 and 16 of this License; or
367 |
368 | b) Requiring preservation of specified reasonable legal notices or
369 | author attributions in that material or in the Appropriate Legal
370 | Notices displayed by works containing it; or
371 |
372 | c) Prohibiting misrepresentation of the origin of that material, or
373 | requiring that modified versions of such material be marked in
374 | reasonable ways as different from the original version; or
375 |
376 | d) Limiting the use for publicity purposes of names of licensors or
377 | authors of the material; or
378 |
379 | e) Declining to grant rights under trademark law for use of some
380 | trade names, trademarks, or service marks; or
381 |
382 | f) Requiring indemnification of licensors and authors of that
383 | material by anyone who conveys the material (or modified versions of
384 | it) with contractual assumptions of liability to the recipient, for
385 | any liability that these contractual assumptions directly impose on
386 | those licensors and authors.
387 |
388 | All other non-permissive additional terms are considered "further
389 | restrictions" within the meaning of section 10. If the Program as you
390 | received it, or any part of it, contains a notice stating that it is
391 | governed by this License along with a term that is a further
392 | restriction, you may remove that term. If a license document contains
393 | a further restriction but permits relicensing or conveying under this
394 | License, you may add to a covered work material governed by the terms
395 | of that license document, provided that the further restriction does
396 | not survive such relicensing or conveying.
397 |
398 | If you add terms to a covered work in accord with this section, you
399 | must place, in the relevant source files, a statement of the
400 | additional terms that apply to those files, or a notice indicating
401 | where to find the applicable terms.
402 |
403 | Additional terms, permissive or non-permissive, may be stated in the
404 | form of a separately written license, or stated as exceptions;
405 | the above requirements apply either way.
406 |
407 | 8. Termination.
408 |
409 | You may not propagate or modify a covered work except as expressly
410 | provided under this License. Any attempt otherwise to propagate or
411 | modify it is void, and will automatically terminate your rights under
412 | this License (including any patent licenses granted under the third
413 | paragraph of section 11).
414 |
415 | However, if you cease all violation of this License, then your
416 | license from a particular copyright holder is reinstated (a)
417 | provisionally, unless and until the copyright holder explicitly and
418 | finally terminates your license, and (b) permanently, if the copyright
419 | holder fails to notify you of the violation by some reasonable means
420 | prior to 60 days after the cessation.
421 |
422 | Moreover, your license from a particular copyright holder is
423 | reinstated permanently if the copyright holder notifies you of the
424 | violation by some reasonable means, this is the first time you have
425 | received notice of violation of this License (for any work) from that
426 | copyright holder, and you cure the violation prior to 30 days after
427 | your receipt of the notice.
428 |
429 | Termination of your rights under this section does not terminate the
430 | licenses of parties who have received copies or rights from you under
431 | this License. If your rights have been terminated and not permanently
432 | reinstated, you do not qualify to receive new licenses for the same
433 | material under section 10.
434 |
435 | 9. Acceptance Not Required for Having Copies.
436 |
437 | You are not required to accept this License in order to receive or
438 | run a copy of the Program. Ancillary propagation of a covered work
439 | occurring solely as a consequence of using peer-to-peer transmission
440 | to receive a copy likewise does not require acceptance. However,
441 | nothing other than this License grants you permission to propagate or
442 | modify any covered work. These actions infringe copyright if you do
443 | not accept this License. Therefore, by modifying or propagating a
444 | covered work, you indicate your acceptance of this License to do so.
445 |
446 | 10. Automatic Licensing of Downstream Recipients.
447 |
448 | Each time you convey a covered work, the recipient automatically
449 | receives a license from the original licensors, to run, modify and
450 | propagate that work, subject to this License. You are not responsible
451 | for enforcing compliance by third parties with this License.
452 |
453 | An "entity transaction" is a transaction transferring control of an
454 | organization, or substantially all assets of one, or subdividing an
455 | organization, or merging organizations. If propagation of a covered
456 | work results from an entity transaction, each party to that
457 | transaction who receives a copy of the work also receives whatever
458 | licenses to the work the party's predecessor in interest had or could
459 | give under the previous paragraph, plus a right to possession of the
460 | Corresponding Source of the work from the predecessor in interest, if
461 | the predecessor has it or can get it with reasonable efforts.
462 |
463 | You may not impose any further restrictions on the exercise of the
464 | rights granted or affirmed under this License. For example, you may
465 | not impose a license fee, royalty, or other charge for exercise of
466 | rights granted under this License, and you may not initiate litigation
467 | (including a cross-claim or counterclaim in a lawsuit) alleging that
468 | any patent claim is infringed by making, using, selling, offering for
469 | sale, or importing the Program or any portion of it.
470 |
471 | 11. Patents.
472 |
473 | A "contributor" is a copyright holder who authorizes use under this
474 | License of the Program or a work on which the Program is based. The
475 | work thus licensed is called the contributor's "contributor version".
476 |
477 | A contributor's "essential patent claims" are all patent claims
478 | owned or controlled by the contributor, whether already acquired or
479 | hereafter acquired, that would be infringed by some manner, permitted
480 | by this License, of making, using, or selling its contributor version,
481 | but do not include claims that would be infringed only as a
482 | consequence of further modification of the contributor version. For
483 | purposes of this definition, "control" includes the right to grant
484 | patent sublicenses in a manner consistent with the requirements of
485 | this License.
486 |
487 | Each contributor grants you a non-exclusive, worldwide, royalty-free
488 | patent license under the contributor's essential patent claims, to
489 | make, use, sell, offer for sale, import and otherwise run, modify and
490 | propagate the contents of its contributor version.
491 |
492 | In the following three paragraphs, a "patent license" is any express
493 | agreement or commitment, however denominated, not to enforce a patent
494 | (such as an express permission to practice a patent or covenant not to
495 | sue for patent infringement). To "grant" such a patent license to a
496 | party means to make such an agreement or commitment not to enforce a
497 | patent against the party.
498 |
499 | If you convey a covered work, knowingly relying on a patent license,
500 | and the Corresponding Source of the work is not available for anyone
501 | to copy, free of charge and under the terms of this License, through a
502 | publicly available network server or other readily accessible means,
503 | then you must either (1) cause the Corresponding Source to be so
504 | available, or (2) arrange to deprive yourself of the benefit of the
505 | patent license for this particular work, or (3) arrange, in a manner
506 | consistent with the requirements of this License, to extend the patent
507 | license to downstream recipients. "Knowingly relying" means you have
508 | actual knowledge that, but for the patent license, your conveying the
509 | covered work in a country, or your recipient's use of the covered work
510 | in a country, would infringe one or more identifiable patents in that
511 | country that you have reason to believe are valid.
512 |
513 | If, pursuant to or in connection with a single transaction or
514 | arrangement, you convey, or propagate by procuring conveyance of, a
515 | covered work, and grant a patent license to some of the parties
516 | receiving the covered work authorizing them to use, propagate, modify
517 | or convey a specific copy of the covered work, then the patent license
518 | you grant is automatically extended to all recipients of the covered
519 | work and works based on it.
520 |
521 | A patent license is "discriminatory" if it does not include within
522 | the scope of its coverage, prohibits the exercise of, or is
523 | conditioned on the non-exercise of one or more of the rights that are
524 | specifically granted under this License. You may not convey a covered
525 | work if you are a party to an arrangement with a third party that is
526 | in the business of distributing software, under which you make payment
527 | to the third party based on the extent of your activity of conveying
528 | the work, and under which the third party grants, to any of the
529 | parties who would receive the covered work from you, a discriminatory
530 | patent license (a) in connection with copies of the covered work
531 | conveyed by you (or copies made from those copies), or (b) primarily
532 | for and in connection with specific products or compilations that
533 | contain the covered work, unless you entered into that arrangement,
534 | or that patent license was granted, prior to 28 March 2007.
535 |
536 | Nothing in this License shall be construed as excluding or limiting
537 | any implied license or other defenses to infringement that may
538 | otherwise be available to you under applicable patent law.
539 |
540 | 12. No Surrender of Others' Freedom.
541 |
542 | If conditions are imposed on you (whether by court order, agreement or
543 | otherwise) that contradict the conditions of this License, they do not
544 | excuse you from the conditions of this License. If you cannot convey a
545 | covered work so as to satisfy simultaneously your obligations under this
546 | License and any other pertinent obligations, then as a consequence you may
547 | not convey it at all. For example, if you agree to terms that obligate you
548 | to collect a royalty for further conveying from those to whom you convey
549 | the Program, the only way you could satisfy both those terms and this
550 | License would be to refrain entirely from conveying the Program.
551 |
552 | 13. Use with the GNU Affero General Public License.
553 |
554 | Notwithstanding any other provision of this License, you have
555 | permission to link or combine any covered work with a work licensed
556 | under version 3 of the GNU Affero General Public License into a single
557 | combined work, and to convey the resulting work. The terms of this
558 | License will continue to apply to the part which is the covered work,
559 | but the special requirements of the GNU Affero General Public License,
560 | section 13, concerning interaction through a network will apply to the
561 | combination as such.
562 |
563 | 14. Revised Versions of this License.
564 |
565 | The Free Software Foundation may publish revised and/or new versions of
566 | the GNU General Public License from time to time. Such new versions will
567 | be similar in spirit to the present version, but may differ in detail to
568 | address new problems or concerns.
569 |
570 | Each version is given a distinguishing version number. If the
571 | Program specifies that a certain numbered version of the GNU General
572 | Public License "or any later version" applies to it, you have the
573 | option of following the terms and conditions either of that numbered
574 | version or of any later version published by the Free Software
575 | Foundation. If the Program does not specify a version number of the
576 | GNU General Public License, you may choose any version ever published
577 | by the Free Software Foundation.
578 |
579 | If the Program specifies that a proxy can decide which future
580 | versions of the GNU General Public License can be used, that proxy's
581 | public statement of acceptance of a version permanently authorizes you
582 | to choose that version for the Program.
583 |
584 | Later license versions may give you additional or different
585 | permissions. However, no additional obligations are imposed on any
586 | author or copyright holder as a result of your choosing to follow a
587 | later version.
588 |
589 | 15. Disclaimer of Warranty.
590 |
591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
599 |
600 | 16. Limitation of Liability.
601 |
602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
610 | SUCH DAMAGES.
611 |
612 | 17. Interpretation of Sections 15 and 16.
613 |
614 | If the disclaimer of warranty and limitation of liability provided
615 | above cannot be given local legal effect according to their terms,
616 | reviewing courts shall apply local law that most closely approximates
617 | an absolute waiver of all civil liability in connection with the
618 | Program, unless a warranty or assumption of liability accompanies a
619 | copy of the Program in return for a fee.
620 |
621 | END OF TERMS AND CONDITIONS
622 |
623 | How to Apply These Terms to Your New Programs
624 |
625 | If you develop a new program, and you want it to be of the greatest
626 | possible use to the public, the best way to achieve this is to make it
627 | free software which everyone can redistribute and change under these terms.
628 |
629 | To do so, attach the following notices to the program. It is safest
630 | to attach them to the start of each source file to most effectively
631 | state the exclusion of warranty; and each file should have at least
632 | the "copyright" line and a pointer to where the full notice is found.
633 |
634 |
635 | Copyright (C)
636 |
637 | This program is free software: you can redistribute it and/or modify
638 | it under the terms of the GNU General Public License as published by
639 | the Free Software Foundation, either version 3 of the License, or
640 | (at your option) any later version.
641 |
642 | This program is distributed in the hope that it will be useful,
643 | but WITHOUT ANY WARRANTY; without even the implied warranty of
644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
645 | GNU General Public License for more details.
646 |
647 | You should have received a copy of the GNU General Public License
648 | along with this program. If not, see .
649 |
650 | Also add information on how to contact you by electronic and paper mail.
651 |
652 | If the program does terminal interaction, make it output a short
653 | notice like this when it starts in an interactive mode:
654 |
655 | Copyright (C)
656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
657 | This is free software, and you are welcome to redistribute it
658 | under certain conditions; type `show c' for details.
659 |
660 | The hypothetical commands `show w' and `show c' should show the appropriate
661 | parts of the General Public License. Of course, your program's commands
662 | might be different; for a GUI interface, you would use an "about box".
663 |
664 | You should also get your employer (if you work as a programmer) or school,
665 | if any, to sign a "copyright disclaimer" for the program, if necessary.
666 | For more information on this, and how to apply and follow the GNU GPL, see
667 | .
668 |
669 | The GNU General Public License does not permit incorporating your program
670 | into proprietary programs. If your program is a subroutine library, you
671 | may consider it more useful to permit linking proprietary applications with
672 | the library. If this is what you want to do, use the GNU Lesser General
673 | Public License instead of this License. But first, please read
674 | .
--------------------------------------------------------------------------------
/Logo.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/pyengine3/PyEngine/61378943657bf8a3b0e59ab422dd040fec2bed2a/Logo.png
--------------------------------------------------------------------------------
/MANIFEST.in:
--------------------------------------------------------------------------------
1 | include *.md
2 | include *.png
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | 
2 |
3 | # PyEngine
4 |
5 | A lib to build 2D Games.
6 |
7 | ## Dependencies
8 |
9 | - Python 3.5+
10 | - PyGame
11 | - NumPy
12 | - PIL
13 | - Pymunk
14 |
15 | ## Other information
16 |
17 | - Main Developer : LavaPower
18 | - Contributors : X
19 | - Develop on :
20 | - System :
21 | - Windows 10 (V 0.1.0-DEV --> Latest)
22 | - Version of Python :
23 | - 3.7.1 (V 0.1.0-DEV --> Latest)
24 | - Library :
25 | - PyGame 1.9.6 (V 0.1.0-DEV --> Latest)
26 | - NumPy 1.16.2 (V 1.2.0 --> Latest)
27 | - PIL 5.4.1 (V 1.5.0 --> Latest)
28 | - Pymunk 5.5.0 (V 1.6.0 --> Latest)
--------------------------------------------------------------------------------
/pyengine/Components/AnimComponent.py:
--------------------------------------------------------------------------------
1 | from pyengine.Components.SpriteComponent import SpriteComponent
2 | from pyengine.Exceptions import NoObjectError
3 | from pyengine.Utils import clamp
4 |
5 | __all__ = ["AnimComponent"]
6 |
7 |
8 | class AnimComponent:
9 | def __init__(self, timer: int, images, flipx: bool = False, flipy: bool = False):
10 | self.__entity = None
11 | self.time = timer
12 | self.images = images
13 | self.flipx = flipx
14 | self.flipy = flipy
15 | self.current_sprite = 0
16 | self.play: bool = True
17 |
18 | @property
19 | def entity(self):
20 | return self.__entity
21 |
22 | @entity.setter
23 | def entity(self, entity):
24 |
25 | if not entity.has_component(SpriteComponent):
26 | raise NoObjectError("AnimComponent require SpriteComponent")
27 |
28 | self.__entity = entity
29 | self.images = self.images # Trigger setter of images
30 | self.flipx = self.flipx # Trigger setter of images
31 | self.flipy = self.flipy # Trigger setter of images
32 |
33 | @property
34 | def flipx(self):
35 | return self.__flipx
36 |
37 | @flipx.setter
38 | def flipx(self, val):
39 | if self.entity is not None:
40 | self.entity.get_component(SpriteComponent).flipx = val
41 | self.__flipx = val
42 |
43 | @property
44 | def flipy(self):
45 | return self.__flipy
46 |
47 | @flipy.setter
48 | def flipy(self, val):
49 | if self.entity is not None:
50 | self.entity.get_component(SpriteComponent).flipy = val
51 | self.__flipy = val
52 |
53 | @property
54 | def images(self):
55 | return self.__images
56 |
57 | @images.setter
58 | def images(self, val):
59 | self.__images = val
60 |
61 | self.current_sprite = 0
62 | self.timer = self.time
63 | if self.entity is not None:
64 | self.entity.get_component(SpriteComponent).sprite = self.__images[0]
65 |
66 | @property
67 | def time(self):
68 | return self.__time
69 |
70 | @time.setter
71 | def time(self, val):
72 | self.__time = clamp(val, 0)
73 | self.timer = self.__time
74 |
75 | def update(self):
76 | if self.play:
77 | if self.timer <= 0:
78 | if self.current_sprite + 1 == len(self.images):
79 | self.current_sprite = 0
80 | else:
81 | self.current_sprite += 1
82 | self.entity.get_component(SpriteComponent).sprite = self.images[self.current_sprite]
83 | self.timer = self.time
84 |
85 | self.timer -= 1
86 |
--------------------------------------------------------------------------------
/pyengine/Components/ControlComponent.py:
--------------------------------------------------------------------------------
1 | from enum import Enum
2 |
3 | from pygame import locals as const
4 |
5 | from pyengine.Components.PhysicsComponent import PhysicsComponent
6 | from pyengine.Components.PositionComponent import PositionComponent
7 | from pyengine.Utils.Vec2 import Vec2
8 |
9 | __all__ = ["ControlComponent", "Controls", "ControlType", "MouseButton"]
10 |
11 |
12 | class ControlType(Enum):
13 | FOURDIRECTION = 1
14 | CLASSICJUMP = 2
15 | CLICKFOLLOW = 3
16 | LEFTRIGHT = 4
17 | UPDOWN = 5
18 | MOUSEFOLLOW = 6
19 |
20 |
21 | class Controls(Enum):
22 | UPJUMP = 1
23 | LEFT = 2
24 | DOWN = 3
25 | RIGHT = 4
26 |
27 |
28 | class MouseButton(Enum):
29 | LEFTCLICK = 1
30 | MIDDLECLICK = 2
31 | RIGHTCLICK = 3
32 |
33 |
34 | class ControlComponent:
35 | def __init__(self, controltype: ControlType, speed: int = 20):
36 | self.entity = None
37 | self.controltype = controltype
38 | self.speed = speed
39 | self.goto = Vec2(-1, -1)
40 | self.force = (0, 0)
41 | self.keypressed = set()
42 | self.controles = {
43 | Controls.UPJUMP: const.K_UP,
44 | Controls.LEFT: const.K_LEFT,
45 | Controls.RIGHT: const.K_RIGHT,
46 | Controls.DOWN: const.K_DOWN
47 | }
48 |
49 | @property
50 | def entity(self):
51 | return self.__entity
52 |
53 | @entity.setter
54 | def entity(self, entity):
55 | self.__entity = entity
56 |
57 | @property
58 | def speed(self):
59 | return self.__speed
60 |
61 | @speed.setter
62 | def speed(self, speed):
63 | self.__speed = speed
64 |
65 | def set_control(self, name: Controls, key: const) -> None:
66 | if not isinstance(name, Controls):
67 | raise TypeError("Name must be a Controls type")
68 | self.controles[name] = key
69 |
70 | def get_control(self, name: Controls) -> const:
71 | if not isinstance(name, Controls):
72 | raise TypeError("Name must be a Controls type")
73 | return self.controles[name]
74 |
75 | def update(self):
76 | self.force = (0, 0)
77 |
78 | if (self.controltype == ControlType.CLICKFOLLOW or self.controltype == ControlType.MOUSEFOLLOW) \
79 | and self.goto.coords != (-1, -1):
80 | self.movebymouse()
81 | else:
82 | for i in self.keypressed:
83 | self.movebykey(i)
84 |
85 | if self.force != (0, 0):
86 | phys = self.entity.get_component(PhysicsComponent)
87 | phys.body.apply_impulse_at_local_point(self.force, (0, 0))
88 |
89 | def mousepress(self, evt):
90 | if self.controltype == ControlType.CLICKFOLLOW and evt.button == MouseButton.LEFTCLICK.value:
91 | self.goto = Vec2(evt.pos[0], evt.pos[1])
92 |
93 | def mousemotion(self, evt):
94 | if self.controltype == ControlType.MOUSEFOLLOW:
95 | self.goto = Vec2(evt.pos[0], evt.pos[1])
96 |
97 | def keyup(self, evt):
98 | if evt.key in self.keypressed:
99 | self.keypressed.remove(evt.key)
100 |
101 | def keypress(self, evt):
102 | if evt.key not in self.keypressed:
103 | self.keypressed.add(evt.key)
104 |
105 | def movebymouse(self):
106 | if self.entity.has_component(PositionComponent):
107 | position = self.entity.get_component(PositionComponent).position
108 | if position.x - 10 < self.goto.x < position.x + 10 and position.y - 10 < self.goto.y < position.y + 10:
109 | self.goto = Vec2(-1, -1)
110 | else:
111 | if (self.entity.has_component(PhysicsComponent) and
112 | self.entity.get_component(PhysicsComponent).affectbygravity):
113 | if position.x - 10 > self.goto.x:
114 | self.force = (self.force[0] - self.speed, self.force[1])
115 | elif position.x + 10 < self.goto.x:
116 | self.force = (self.force[0] + self.speed, self.force[1])
117 | if position.y - 10 > self.goto.y:
118 | self.force = (self.force[0], self.force[1] + self.speed*20)
119 | elif position.y + 10 < self.goto.y:
120 | self.force = (self.force[0], self.force[1] - self.speed*20)
121 | else:
122 | pos = Vec2()
123 | if position.x - 10 > self.goto.x:
124 | pos.x = position.x - self.speed
125 | elif position.x + 10 < self.goto.x:
126 | pos.x = position.x + self.speed
127 | else:
128 | pos.x = position.x
129 | if position.y - 10 > self.goto.y:
130 | pos.y = position.y - self.speed
131 | elif position.y + 10 < self.goto.y:
132 | pos.y = position.y + self.speed
133 | else:
134 | pos.y = position.y
135 |
136 | self.entity.get_component(PositionComponent).position = pos
137 |
138 | def movebykey(self, eventkey):
139 | if eventkey == self.controles[Controls.LEFT]:
140 | if self.controltype == ControlType.FOURDIRECTION or self.controltype == ControlType.CLASSICJUMP \
141 | or self.controltype == ControlType.LEFTRIGHT:
142 | if (self.entity.has_component(PhysicsComponent) and
143 | self.entity.get_component(PhysicsComponent).affectbygravity):
144 | self.force = (-self.speed, 0)
145 | elif self.entity.has_component(PositionComponent):
146 | pos = self.entity.get_component(PositionComponent)
147 | pos.position = Vec2(pos.position.x - self.speed, pos.position.y)
148 | pos.update_phys()
149 | elif eventkey == self.controles[Controls.RIGHT]:
150 | if self.controltype == ControlType.FOURDIRECTION or self.controltype == ControlType.CLASSICJUMP \
151 | or self.controltype == ControlType.LEFTRIGHT:
152 | if (self.entity.has_component(PhysicsComponent) and
153 | self.entity.get_component(PhysicsComponent).affectbygravity):
154 | self.force = (self.speed, 0)
155 | elif self.entity.has_component(PositionComponent):
156 | pos = self.entity.get_component(PositionComponent)
157 | pos.position = Vec2(pos.position.x + self.speed, pos.position.y)
158 | pos.update_phys()
159 | elif eventkey == self.controles[Controls.UPJUMP]:
160 | if self.controltype == ControlType.FOURDIRECTION or self.controltype == ControlType.UPDOWN:
161 | if (self.entity.has_component(PhysicsComponent) and
162 | self.entity.get_component(PhysicsComponent).affectbygravity):
163 | self.force = (0, self.speed*20)
164 | elif self.entity.has_component(PositionComponent):
165 | pos = self.entity.get_component(PositionComponent)
166 | pos.position = Vec2(pos.position.x, pos.position.y - self.speed)
167 | pos.update_phys()
168 | elif self.controltype == ControlType.CLASSICJUMP:
169 | if self.entity.has_component(PhysicsComponent):
170 | phys = self.entity.get_component(PhysicsComponent)
171 | grounding = phys.check_grounding()
172 | if grounding['body'] is not None and abs(grounding['normal'].x / grounding['normal'].y) < \
173 | phys.shape.friction:
174 | self.force = (0, self.speed*20)
175 | elif eventkey == self.controles[Controls.DOWN]:
176 | if self.controltype == ControlType.FOURDIRECTION or self.controltype == ControlType.UPDOWN:
177 | if (self.entity.has_component(PhysicsComponent) and
178 | self.entity.get_component(PhysicsComponent).affectbygravity):
179 | self.force = (0, -self.speed)
180 | elif self.entity.has_component(PositionComponent):
181 | pos = self.entity.get_component(PositionComponent)
182 | pos.position = Vec2(pos.position.x, pos.position.y + self.speed)
183 | pos.update_phys()
184 |
185 |
--------------------------------------------------------------------------------
/pyengine/Components/LifeComponent.py:
--------------------------------------------------------------------------------
1 | from pyengine.Utils.Others import clamp
2 |
3 | __all__ = ["LifeComponent"]
4 |
5 |
6 | class LifeComponent:
7 | def __init__(self, maxlife: int = 100, callback=None):
8 | self.entity = None
9 | self.maxlife = maxlife
10 | self.life = maxlife
11 | self.callback = callback
12 |
13 | @property
14 | def entity(self):
15 | return self.__entity
16 |
17 | @entity.setter
18 | def entity(self, entity):
19 | self.__entity = entity
20 |
21 | @property
22 | def life(self):
23 | return self.__life
24 |
25 | @life.setter
26 | def life(self, life):
27 | self.__life = clamp(life, 0, self.maxlife)
28 | if self.__life == 0 and self.callback is not None:
29 | self.callback()
30 |
31 | @property
32 | def maxlife(self):
33 | return self.__maxlife
34 |
35 | @maxlife.setter
36 | def maxlife(self, maxi):
37 | self.__maxlife = maxi
38 |
--------------------------------------------------------------------------------
/pyengine/Components/MoveComponent.py:
--------------------------------------------------------------------------------
1 | import pygame
2 |
3 | from pyengine.Components.PhysicsComponent import PhysicsComponent
4 | from pyengine.Components.PositionComponent import PositionComponent
5 | from pyengine.Utils.Vec2 import Vec2
6 |
7 | __all__ = ["MoveComponent"]
8 |
9 |
10 | class MoveComponent:
11 | def __init__(self, direction: Vec2):
12 | self.entity = None
13 | self.direction = direction
14 |
15 | @property
16 | def entity(self):
17 | return self.__entity
18 |
19 | @entity.setter
20 | def entity(self, entity):
21 | self.__entity = entity
22 |
23 | @property
24 | def direction(self):
25 | return self.__direction
26 |
27 | @direction.setter
28 | def direction(self, direction):
29 | if not isinstance(direction, pygame.Vector2):
30 | raise TypeError("Direction must be a Vec2")
31 |
32 | self.__direction = direction
33 | if self.entity is not None and self.entity.has_component(PhysicsComponent):
34 | self.entity.get_component(PhysicsComponent).body.velocity = self.direction
35 |
36 | def update(self):
37 | if self.entity.has_component(PhysicsComponent):
38 | self.entity.get_component(PhysicsComponent).body.velocity = self.direction
39 |
40 | elif self.entity.has_component(PositionComponent):
41 | position = self.entity.get_component(PositionComponent)
42 | pos = position.position
43 |
44 | self.entity.get_component(PositionComponent).position += self.direction
45 |
--------------------------------------------------------------------------------
/pyengine/Components/PhysicsComponent.py:
--------------------------------------------------------------------------------
1 | import math
2 |
3 | import pymunk
4 |
5 | from pyengine.Components.PositionComponent import PositionComponent
6 | from pyengine.Components.SpriteComponent import SpriteComponent
7 | from pyengine.Utils.Vec2 import Vec2
8 |
9 | __all__ = ["PhysicsComponent"]
10 |
11 |
12 | class PhysicsComponent:
13 | def __init__(self, affectbygravity: bool = True, friction: float = .5, elasticity: float = .5, mass: int = 1,
14 | solid: bool = True, can_rot: bool = True, callback=None):
15 | self.__entity = None
16 | self.orig_image = None
17 | self.body = None
18 | self.shape = None
19 | self.__affectbygravity = affectbygravity
20 | self.__friction = friction
21 | self.__elasticity = elasticity
22 | self.__mass = mass
23 | self.can_rot = can_rot
24 | self.solid = solid
25 | self.callback = callback
26 |
27 | @property
28 | def affectbygravity(self):
29 | return self.__affectbygravity
30 |
31 | @affectbygravity.setter
32 | def affectbygravity(self, val):
33 | if val:
34 | self.body.body_type = self.body.DYNAMIC
35 | else:
36 | self.body.body_type = self.body.KINEMATIC
37 | self.__affectbygravity = val
38 |
39 | @property
40 | def friction(self):
41 | return self.__friction
42 |
43 | @friction.setter
44 | def friction(self, val):
45 | self.shape.friction = val
46 | self.__friction = val
47 |
48 | @property
49 | def elasticity(self):
50 | return self.__elasticity
51 |
52 | @elasticity.setter
53 | def elasticity(self, val):
54 | self.shape.elasticity = val
55 | self.__elasticity = val
56 |
57 | @property
58 | def mass(self):
59 | return self.__mass
60 |
61 | @mass.setter
62 | def mass(self, val):
63 | moment = pymunk.moment_for_box(self.mass, (self.entity.rect.width, self.entity.rect.height))
64 | self.body = pymunk.Body(self.mass, moment)
65 | self.body.center_of_gravity = (self.entity.rect.width/2, self.entity.rect.height/2)
66 | self.shape.body = self.body
67 |
68 | @property
69 | def entity(self):
70 | return self.__entity
71 |
72 | @entity.setter
73 | def entity(self, entity):
74 | self.__entity = entity
75 | self.orig_image = entity.image
76 | if self.entity.has_component(SpriteComponent):
77 | temp = self.entity.get_component(SpriteComponent).origin_image.get_rect()
78 | temp2 = temp.height/2
79 | temp = temp.width/2
80 | else:
81 | temp = entity.rect.width/2
82 | temp2 = entity.rect.height/2
83 | vc = [(-temp, -temp2), (temp, -temp2), (-temp, temp2), (temp, temp2)]
84 | moment = pymunk.moment_for_box(self.mass, (temp*2, temp2*2))
85 | self.body = pymunk.Body(self.mass, moment)
86 | if not self.affectbygravity:
87 | self.body.body_type = self.body.KINEMATIC
88 | self.shape = pymunk.Poly(self.body, vc)
89 | self.shape.friction = self.friction
90 | self.shape.elasticity = self.elasticity
91 | if self.entity.has_component(SpriteComponent):
92 | self.update_rot(self.entity.get_component(SpriteComponent).rotation)
93 |
94 | def flipy(self, pos):
95 | return [pos[0], -pos[1] + self.entity.system.world.window.height]
96 |
97 | def update(self):
98 | if not self.can_rot:
99 | self.body.angular_velocity = 0
100 | self.body.angle = 0
101 |
102 | if self.entity.has_component(PositionComponent):
103 | if str(self.body.position[0]) != "nan" and str(self.body.position[1]) != "nan":
104 | pos = Vec2(self.flipy(self.body.position))
105 | self.entity.get_component(PositionComponent).position = pos
106 |
107 | if self.entity.has_component(SpriteComponent):
108 | self.entity.get_component(SpriteComponent).make_rotation(math.degrees(self.body.angle))
109 |
110 | def update_pos(self, pos):
111 | self.body.position = self.flipy(pos)
112 |
113 | def update_rot(self, rot):
114 | self.body.angle = math.radians(rot)
115 |
116 | def check_grounding(self):
117 | """ See if the player is on the ground. Used to see if we can jump. """
118 | grounding = {
119 | 'normal': pymunk.Vec2d.zero(),
120 | 'penetration': pymunk.Vec2d.zero(),
121 | 'impulse': pymunk.Vec2d.zero(),
122 | 'position': pymunk.Vec2d.zero(),
123 | 'body': None
124 | }
125 |
126 | def f(arbiter):
127 | n = -arbiter.contact_point_set.normal
128 | if n.y > grounding['normal'].y:
129 | grounding['normal'] = n
130 | grounding['penetration'] = -arbiter.contact_point_set.points[0].distance
131 | grounding['body'] = arbiter.shapes[1].body
132 | grounding['impulse'] = arbiter.total_impulse
133 | grounding['position'] = arbiter.contact_point_set.points[0].point_b
134 |
135 | self.body.each_arbiter(f)
136 |
137 | return grounding
138 |
139 |
140 |
--------------------------------------------------------------------------------
/pyengine/Components/PositionComponent.py:
--------------------------------------------------------------------------------
1 | import pygame
2 |
3 | from pyengine.Utils.Vec2 import Vec2
4 |
5 | __all__ = ["PositionComponent"]
6 |
7 |
8 | class PositionComponent:
9 | def __init__(self, position: Vec2, offset: Vec2 = Vec2()):
10 | self.__entity = None
11 |
12 | if not isinstance(position, pygame.Vector2):
13 | raise TypeError("Position must be a Vec2")
14 | if not isinstance(offset, pygame.Vector2):
15 | raise TypeError("Offset must be a Vec2")
16 |
17 | self.__offset = offset
18 | self.__position = position
19 |
20 | @property
21 | def entity(self):
22 | return self.__entity
23 |
24 | @entity.setter
25 | def entity(self, entity):
26 | self.__entity = entity
27 | self.update_dependances()
28 |
29 | @property
30 | def offset(self):
31 | return self.__offset
32 |
33 | @offset.setter
34 | def offset(self, val):
35 | if not isinstance(val, pygame.Vector2):
36 | raise TypeError("Offset must be a Vec2")
37 |
38 | self.__offset = val
39 | self.update_dependances()
40 |
41 | @property
42 | def position(self):
43 | return self.__position
44 |
45 | @position.setter
46 | def position(self, position):
47 | if not isinstance(position, pygame.Vector2):
48 | raise TypeError("Position must be a Vec2")
49 |
50 | self.__position = position
51 | self.update_dependances()
52 |
53 | def update_phys(self):
54 | from pyengine.Components import PhysicsComponent
55 |
56 | if self.entity.has_component(PhysicsComponent):
57 | self.entity.get_component(PhysicsComponent).update_pos(self.position.coords)
58 |
59 | def update_dependances(self):
60 | from pyengine.Components import SpriteComponent, TextComponent # Avoid import cycle
61 |
62 | if self.entity.has_component(SpriteComponent):
63 | self.entity.get_component(SpriteComponent).update_position()
64 |
65 | if self.entity.has_component(TextComponent):
66 | self.entity.get_component(TextComponent).update_position()
67 |
68 | for i in self.entity.attachedentities:
69 | if i.has_component(PositionComponent):
70 | i.get_component(PositionComponent).position = self.position
71 |
--------------------------------------------------------------------------------
/pyengine/Components/SpriteComponent.py:
--------------------------------------------------------------------------------
1 | import pygame
2 |
3 | from pyengine.Components.PositionComponent import PositionComponent
4 | from pyengine.Exceptions import CompatibilityError
5 | from pyengine.Utils.Vec2 import Vec2
6 |
7 | __all__ = ["SpriteComponent"]
8 |
9 |
10 | class SpriteComponent:
11 | def __init__(self, image: str, scale: int = 1, rotation: int = 0, flipx: bool = False, flipy: bool = False):
12 | self.__entity = None
13 | self.__sprite = image
14 | self.__scale = scale
15 | self.__rotation = rotation
16 | self.__flipx = flipx
17 | self.__flipy = flipy
18 | self.origin_image = None
19 | self.width = 0
20 | self.height = 0
21 |
22 | @property
23 | def entity(self):
24 | return self.__entity
25 |
26 | @entity.setter
27 | def entity(self, entity):
28 | from pyengine.Components.TextComponent import TextComponent
29 |
30 | if entity.has_component(TextComponent):
31 | raise CompatibilityError("SpriteComponent is not compatible with TextComponent")
32 |
33 | self.__entity = entity
34 | self.__entity.image = pygame.image.load(self.sprite)
35 | self.__entity.rect = self.entity.image.get_rect()
36 | self.width = self.entity.rect.width
37 | self.height = self.entity.rect.height
38 | self.scale = self.scale
39 | self.origin_image = self.__entity.image
40 | self.rotation = self.rotation
41 | self.flipx = self.flipx
42 | self.flipy = self.flipy
43 |
44 | @property
45 | def scale(self):
46 | return self.__scale
47 |
48 | @scale.setter
49 | def scale(self, scale):
50 | self.__scale = scale
51 | center = self.entity.rect.center
52 | self.entity.image = pygame.transform.scale(self.entity.image, (round(self.width * scale),
53 | round(self.height * scale)))
54 | self.origin_image = self.__entity.image
55 | self.entity.rect = self.entity.image.get_rect(center=center)
56 | self.update_position()
57 |
58 | @property
59 | def size(self):
60 | return Vec2(self.width, self.height)
61 |
62 | @size.setter
63 | def size(self, size):
64 | if not isinstance(size, pygame.Vector2):
65 | raise TypeError("Size must be a Vec2")
66 | center = self.entity.rect.center
67 | self.width, self.height = size.coords
68 | self.entity.image = pygame.transform.scale(self.entity.image, size.coords)
69 | self.origin_image = self.__entity.image
70 | self.scale = 1
71 | self.entity.rect = self.entity.image.get_rect(center=center)
72 | self.update_position()
73 |
74 | @property
75 | def rotation(self):
76 | return self.__rotation
77 |
78 | @rotation.setter
79 | def rotation(self, rotation):
80 | from pyengine.Components.PhysicsComponent import PhysicsComponent
81 | if self.entity.has_component(PhysicsComponent):
82 | self.entity.get_component(PhysicsComponent).update_rot(rotation)
83 | else:
84 | self.make_rotation(rotation)
85 |
86 | def make_rotation(self, rotation):
87 | center = self.entity.rect.center
88 | self.entity.image = pygame.transform.rotate(self.origin_image, rotation)
89 | self.__rotation = rotation
90 | self.entity.rect = self.entity.image.get_rect(center=center)
91 | self.update_position()
92 |
93 | @property
94 | def sprite(self):
95 | return self.__sprite
96 |
97 | @sprite.setter
98 | def sprite(self, sprite):
99 | self.__sprite = sprite
100 | self.entity.image = pygame.image.load(sprite)
101 | self.width = self.entity.rect.width
102 | self.height = self.entity.rect.height
103 | self.entity.image = pygame.transform.scale(self.entity.image, (round(self.width * self.scale),
104 | round(self.height * self.scale)))
105 | self.origin_image = self.entity.image
106 | self.update_position()
107 |
108 | @property
109 | def flipx(self):
110 | return self.__flipx
111 |
112 | @flipx.setter
113 | def flipx(self, val):
114 | self.entity.image = pygame.transform.flip(self.origin_image, val, 0)
115 | self.__flipx = val
116 |
117 | @property
118 | def flipy(self):
119 | return self.__flipy
120 |
121 | @flipy.setter
122 | def flipy(self, val):
123 | self.entity.image = pygame.transform.flip(self.origin_image, 0, val)
124 | self.__flipy = val
125 |
126 | def update_position(self):
127 | if self.entity.has_component(PositionComponent):
128 | position = self.entity.get_component(PositionComponent)
129 | self.entity.rect = self.entity.image.get_rect(center=position.position + position.offset)
130 |
--------------------------------------------------------------------------------
/pyengine/Components/TextComponent.py:
--------------------------------------------------------------------------------
1 | from typing import Union
2 |
3 | import pygame
4 |
5 | from pyengine.Components import PositionComponent
6 | from pyengine.Exceptions import CompatibilityError
7 | from pyengine.Utils.Font import Font
8 | from pyengine.Utils.Color import Color, Colors
9 |
10 | __all__ = ["TextComponent"]
11 |
12 |
13 | class TextComponent:
14 | def __init__(self, text: str, color: Color = Colors.WHITE.value, font: Font = Font(),
15 | background: Union[None, Color] = None, scale: int = 1):
16 | if not isinstance(font, Font):
17 | raise TypeError("Font have not a Font type")
18 | if not isinstance(color, Color):
19 | raise TypeError("Color have not a Color type")
20 | if not isinstance(background, Color) and background is not None:
21 | raise TypeError("Background must be a Color")
22 |
23 | self.__entity = None
24 | self.__text = text
25 | self.__font = font
26 | self.__scale = scale
27 | self.__color = color
28 | self.__background = background
29 | self.image = None
30 |
31 | @property
32 | def scale(self):
33 | return self.__scale
34 |
35 | @scale.setter
36 | def scale(self, val):
37 | self.__scale = val
38 | self.update_render()
39 |
40 | @property
41 | def background(self):
42 | return self.__background
43 |
44 | @background.setter
45 | def background(self, color):
46 | if not isinstance(color, Color) and color is not None:
47 | raise TypeError("Background must be a Color")
48 |
49 | self.__background = color
50 | self.update_render()
51 |
52 | @property
53 | def text(self):
54 | return self.__text
55 |
56 | @text.setter
57 | def text(self, text):
58 | self.__text = text
59 | self.update_render()
60 |
61 | @property
62 | def color(self):
63 | return self.__color
64 |
65 | @color.setter
66 | def color(self, color):
67 | if not isinstance(color, Color):
68 | raise TypeError("Color have not a Color type")
69 |
70 | self.__color = color
71 | self.update_render()
72 |
73 | @property
74 | def font(self):
75 | return self.__font
76 |
77 | @font.setter
78 | def font(self, font):
79 | if not isinstance(font, Font):
80 | raise TypeError("Font have not a Font type")
81 |
82 | self.__font = font
83 | self.update_render()
84 |
85 | @property
86 | def entity(self):
87 | return self.__entity
88 |
89 | @entity.setter
90 | def entity(self, entity):
91 |
92 | from pyengine.Components.SpriteComponent import SpriteComponent
93 |
94 | if entity.has_component(SpriteComponent):
95 | raise CompatibilityError("TextComponent is not compatible with SpriteComponent")
96 |
97 | self.__entity = entity
98 | self.update_render()
99 |
100 | @property
101 | def size(self):
102 | return self.image.get_rect().width, self.image.get_rect().height
103 |
104 | def update_render(self):
105 | self.font.color = self.color
106 | self.font.background = self.background
107 | self.image = self.font.render(self.text)
108 | self.image = pygame.transform.scale(self.image, (self.scale*self.image.get_rect().width,
109 | self.scale*self.image.get_rect().height))
110 |
111 | if self.entity is not None:
112 | self.entity.image = self.image
113 | self.entity.rect = self.image.get_rect()
114 | self.update_position()
115 |
116 | def update_position(self):
117 | if self.entity.has_component(PositionComponent):
118 | position = self.entity.get_component(PositionComponent)
119 | self.entity.rect.x = position.position.x + position.offset.x
120 | self.entity.rect.y = position.position.y + position.offset.y
121 |
--------------------------------------------------------------------------------
/pyengine/Components/__init__.py:
--------------------------------------------------------------------------------
1 | from pyengine.Components.AnimComponent import AnimComponent
2 | from pyengine.Components.ControlComponent import ControlComponent
3 | from pyengine.Components.LifeComponent import LifeComponent
4 | from pyengine.Components.MoveComponent import MoveComponent
5 | from pyengine.Components.PhysicsComponent import PhysicsComponent
6 | from pyengine.Components.PositionComponent import PositionComponent
7 | from pyengine.Components.SpriteComponent import SpriteComponent
8 | from pyengine.Components.TextComponent import TextComponent
9 |
--------------------------------------------------------------------------------
/pyengine/Entities/Entity.py:
--------------------------------------------------------------------------------
1 | from typing import Union, Type
2 |
3 | import pygame
4 |
5 | from pyengine.Components import *
6 | from pyengine.Utils.Logger import loggers
7 |
8 | cunion = Union[PositionComponent, SpriteComponent, ControlComponent,
9 | PhysicsComponent, TextComponent, LifeComponent, MoveComponent, AnimComponent]
10 | ctypes = Union[Type[PositionComponent], Type[SpriteComponent], Type[ControlComponent],
11 | Type[PhysicsComponent], Type[TextComponent], Type[LifeComponent], Type[MoveComponent],
12 | Type[AnimComponent]]
13 |
14 | __all__ = ["Entity"]
15 |
16 |
17 | class Entity(pygame.sprite.Sprite):
18 | def __init__(self):
19 | super(Entity, self).__init__()
20 | self.identity = -1
21 | self.components = set()
22 | self.attachedentities = set()
23 | self.__system = None
24 | self.image = None
25 |
26 | @property
27 | def identity(self):
28 | return self.__identity
29 |
30 | @identity.setter
31 | def identity(self, identity):
32 | self.__identity = identity
33 |
34 | @property
35 | def system(self):
36 | return self.__system
37 |
38 | @system.setter
39 | def system(self, system):
40 | self.__system = system
41 | if self.has_component(PhysicsComponent) and self.has_component(PositionComponent):
42 | self.get_component(PhysicsComponent).update_pos(self.get_component(PositionComponent).position.coords)
43 |
44 | def attach_entity(self, entity):
45 | self.attachedentities.add(entity)
46 |
47 | def add_component(self, component: cunion) -> cunion:
48 | if isinstance(component, (PositionComponent, SpriteComponent, ControlComponent, PhysicsComponent,
49 | TextComponent, LifeComponent, MoveComponent, AnimComponent)):
50 | if isinstance(component, tuple([type(c) for c in self.components])):
51 | raise TypeError("Entity already have " + str(component) + " as component.")
52 | component.entity = self
53 | self.components.add(component)
54 | return component
55 | else:
56 | raise TypeError("Entity can't have "+str(component)+" as component.")
57 |
58 | def remove_component(self, component: ctypes) -> None:
59 | for i in [i for i in self.components if isinstance(i, component)]:
60 | loggers.get_logger("PyEngine").debug("Deleting "+str(component))
61 | self.components.remove(i)
62 | loggers.get_logger("PyEngine").info("Deleting component can be dangerous.")
63 |
64 | def has_component(self, component: ctypes) -> bool:
65 | if len([c for c in self.components if isinstance(c, component)]):
66 | return True
67 | return False
68 |
69 | def get_component(self, component: ctypes) -> cunion:
70 | liste = [i for i in self.components if isinstance(i, component)]
71 | try:
72 | return liste[0]
73 | except IndexError:
74 | loggers.get_logger("PyEngine").warning("Try to get "+str(component)+" but Entity don't have it")
75 |
76 | def update(self):
77 | if self.has_component(PhysicsComponent):
78 | self.get_component(PhysicsComponent).update()
79 |
80 | if self.has_component(ControlComponent):
81 | self.get_component(ControlComponent).update()
82 |
83 | if self.has_component(MoveComponent):
84 | self.get_component(MoveComponent).update()
85 |
86 | if self.has_component(AnimComponent):
87 | self.get_component(AnimComponent).update()
88 |
--------------------------------------------------------------------------------
/pyengine/Entities/Tilemap.py:
--------------------------------------------------------------------------------
1 | import json
2 | from xml.etree import ElementTree
3 |
4 | from pyengine.Components import PositionComponent, SpriteComponent, PhysicsComponent, TextComponent
5 | from pyengine.Entities import Entity
6 | from pyengine.Utils.Vec2 import Vec2
7 | from pyengine.Utils.Logger import loggers
8 |
9 | __all__ = ["Tilemap"]
10 |
11 |
12 | class Tilemap(Entity):
13 | def __init__(self, pos, file, scale=1):
14 | super(Tilemap, self).__init__()
15 |
16 | self.folder = "/".join(file.split("/")[:-1])+"/"
17 |
18 | self.add_component(PositionComponent(pos))
19 | self.add_component(TextComponent(""))
20 |
21 | with open(file, "r") as f:
22 | datas = json.load(f)
23 |
24 | if datas["infinite"]:
25 | raise ValueError("PyEngine can't use infinite map")
26 | if len(datas["tilesets"]) > 1:
27 | loggers.get_logger("PyEngine").warning("Tilemap use only 1 tileset.")
28 | if len(datas["layers"]) > 1:
29 | loggers.get_logger("PyEngine").warning("Tilemap use only 1 layer.")
30 |
31 | self.height = datas["height"]
32 | self.width = datas["width"]
33 | self.tileheight = datas["tileheight"]
34 | self.tilewidth = datas["tilewidth"]
35 |
36 | tileset = ElementTree.parse(self.folder+datas["tilesets"][0]["source"])
37 | idtiles = {}
38 | for tile in tileset.getroot():
39 | if tile.tag == 'tile':
40 | idtiles[tile.attrib["id"]] = tile[0].attrib["source"]
41 |
42 | self.tiles = [self.create_tile(datas, idtiles, pos, x, y)
43 | for y in range(self.height) for x in range(self.width)]
44 | self.tiles = [x for x in self.tiles if x is not None]
45 |
46 | self.scale = scale
47 |
48 | def create_tile(self, datas, idtiles, pos, x, y):
49 | if datas["layers"][0]["data"][y*self.width+x] - 1 != -1:
50 | offset = Vec2(x * self.tilewidth, y * self.tileheight)
51 | idtile = str(datas["layers"][0]["data"][y*self.width+x]-1)
52 | tilesetfolder = "/".join(datas["tilesets"][0]["source"].split("/")[:-1])+"/"
53 | return Tile(pos, offset, self.folder + tilesetfolder + idtiles[idtile], [x, y], self.tileheight)
54 |
55 | @property
56 | def scale(self):
57 | return self.__scale
58 |
59 | @scale.setter
60 | def scale(self, val):
61 | for i in self.tiles:
62 | i.get_component(SpriteComponent).scale = val
63 | i.get_component(PositionComponent).offset = Vec2(
64 | i.pos_in_grid[0] * self.tilewidth * val,
65 | i.pos_in_grid[1] * self.tileheight * val + (self.tileheight - i.image.get_height())
66 | )
67 | self.__scale = val
68 |
69 | @property
70 | def system(self):
71 | return self.__system
72 |
73 | @system.setter
74 | def system(self, system):
75 | self.__system = system
76 | for i in self.tiles:
77 | self.attach_entity(i)
78 | system.add_entity(i)
79 |
80 |
81 | class Tile(Entity):
82 | def __init__(self, pos, offset, sprite, pos_in_grid, tileheight):
83 | super(Tile, self).__init__()
84 |
85 | self.pos_in_grid = pos_in_grid
86 | poscomp = self.add_component(PositionComponent(pos, offset))
87 | self.add_component(SpriteComponent(sprite))
88 | poscomp.offset = Vec2(
89 | offset.x,
90 | offset.y + (tileheight - self.image.get_height())
91 | )
92 | self.add_component(PhysicsComponent(False))
93 |
--------------------------------------------------------------------------------
/pyengine/Entities/__init__.py:
--------------------------------------------------------------------------------
1 | from pyengine.Entities.Entity import Entity
2 | from pyengine.Entities.Tilemap import Tilemap
3 |
--------------------------------------------------------------------------------
/pyengine/Exceptions.py:
--------------------------------------------------------------------------------
1 | class NoObjectError(Exception):
2 | def __init__(self, text):
3 | super(NoObjectError, self).__init__(text)
4 |
5 |
6 | class CompatibilityError(Exception):
7 | def __init__(self, text):
8 | super(CompatibilityError, self).__init__(text)
9 |
10 |
--------------------------------------------------------------------------------
/pyengine/Network/Client.py:
--------------------------------------------------------------------------------
1 | import socket
2 | import threading
3 |
4 | from pyengine.Network.Packet import Packet
5 |
6 |
7 | class ReseauClient(threading.Thread):
8 | def __init__(self, client):
9 | threading.Thread.__init__(self)
10 | self.client = client
11 | self.connected = True
12 |
13 | def run(self):
14 | while self.connected:
15 | try:
16 | r = self.client.s.recv(9999999)
17 | self.client.recieve(Packet().from_recieve(r))
18 | except ConnectionResetError:
19 | self.connected = False
20 | except ConnectionAbortedError:
21 | self.connected = False
22 | except OSError:
23 | self.connected = False
24 |
25 |
26 | class Client:
27 | def __init__(self, ip, port, callback=None):
28 | self.s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
29 | self.s.connect((ip, port))
30 |
31 | self.t = ReseauClient(self)
32 | self.t.start()
33 |
34 | self.callback = callback
35 |
36 | def stop(self):
37 | self.t.connected = False
38 | self.s.close()
39 |
40 | def recieve(self, packet):
41 | if self.callback is not None:
42 | self.callback(packet.type_, packet.author, packet.message)
43 |
44 | def send(self, type_, author, message):
45 | self.s.send(Packet(type_, author, message).to_send())
46 |
47 |
48 |
49 |
--------------------------------------------------------------------------------
/pyengine/Network/NetworkManager.py:
--------------------------------------------------------------------------------
1 | from pyengine.Network.Client import Client
2 | from pyengine.Network.Server import Server
3 |
4 | __all__ = ["NetworkManager"]
5 |
6 |
7 | class NetworkManager:
8 | def __init__(self):
9 | self.client = None
10 | self.server = None
11 |
12 | def create_server(self, port):
13 | if self.server is None:
14 | self.server = Server(port)
15 | self.server.run()
16 |
17 | def stop_server(self):
18 | if self.server is not None:
19 | self.server.stop()
20 | self.server = None
21 |
22 | def stop_client(self):
23 | if self.client is not None:
24 | self.client.stop()
25 | self.client = None
26 |
27 | def create_client(self, ip, port, callback):
28 | if self.client is None:
29 | self.client = Client(ip, port, callback)
30 |
--------------------------------------------------------------------------------
/pyengine/Network/Packet.py:
--------------------------------------------------------------------------------
1 | __all__ = ["Packet"]
2 |
3 |
4 | class Packet:
5 | def __init__(self, type_: str = None, author: int = None, message: str = None):
6 | self.type_ = type_
7 | self.author = author
8 | self.message = message
9 |
10 | def to_send(self):
11 | return str.encode(str(self.type_)+"|"+str(self.author)+"|"+str(self.message))
12 |
13 | def from_recieve(self, recieve: bytearray):
14 | m = recieve.decode()
15 | if len(m.split("|", 2)) == 3:
16 | self.type_, self.author, self.message = m.split("|", 2)
17 | if self.author != "None":
18 | self.author = int(self.author)
19 | else:
20 | self.author = None
21 | return self
22 |
--------------------------------------------------------------------------------
/pyengine/Network/Server.py:
--------------------------------------------------------------------------------
1 | import socket
2 | import threading
3 |
4 | from pyengine.Network.Packet import Packet
5 |
6 |
7 | class ClientThread(threading.Thread):
8 | def __init__(self, server, clientsocket, nb):
9 | super(ClientThread, self).__init__()
10 | self.server = server
11 | self.clientsocket = clientsocket
12 | self.nb = nb
13 | self.connected = True
14 |
15 | def run(self):
16 | print("NEW CLIENT :", str(self.nb))
17 | while self.connected:
18 | try:
19 | r = self.clientsocket.recv(2048)
20 | r = Packet().from_recieve(r)
21 | r.author = self.nb
22 | self.server.recieve(r)
23 | except ConnectionAbortedError:
24 | self.connected = False
25 | except ConnectionResetError:
26 | self.connected = False
27 | self.server.clientquit(self.nb)
28 |
29 |
30 | class Server(threading.Thread):
31 | def __init__(self, port):
32 | super(Server, self).__init__()
33 | self.tcpsock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
34 | self.tcpsock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
35 | self.tcpsock.bind(("localhost", port))
36 | self.nbclient = 0
37 | self.liste = {}
38 |
39 | def stop(self):
40 | for i in self.liste.values():
41 | i.connected = False
42 | self.tcpsock.close()
43 |
44 | def recieve(self, packet):
45 | if packet.message is not None and len(packet.message):
46 | self.sendall(packet)
47 |
48 | def clientquit(self, nb):
49 | print("END CLIENT :", str(nb))
50 | self.sendall(Packet("END", nb, ""))
51 | del self.liste[nb]
52 |
53 | def run(self):
54 | while True:
55 | self.tcpsock.listen(10)
56 | (clientsocket, (ip, port)) = self.tcpsock.accept()
57 | newthread = ClientThread(self, clientsocket, self.nbclient)
58 | self.liste[self.nbclient] = newthread
59 | self.sendall(Packet("NEW", self.nbclient, ""))
60 | self.nbclient += 1
61 | newthread.start()
62 |
63 | def sendto(self, nb, packet):
64 | try:
65 | self.liste[nb].clientsocket.send(packet.to_send())
66 | except KeyError:
67 | pass
68 |
69 | def sendall(self, packet):
70 | temp = self.liste.copy()
71 | for i in temp.values():
72 | if packet.author is None:
73 | i.clientsocket.send(packet.to_send())
74 | elif i != self.liste[packet.author] or packet.type_ == "TOALL":
75 | i.clientsocket.send(packet.to_send())
76 |
--------------------------------------------------------------------------------
/pyengine/Network/__init__.py:
--------------------------------------------------------------------------------
1 | from pyengine.Network.NetworkManager import NetworkManager
2 |
--------------------------------------------------------------------------------
/pyengine/Systems/CameraSystem.py:
--------------------------------------------------------------------------------
1 | import pygame
2 |
3 | from pyengine import World
4 | from pyengine.Components import PositionComponent, SpriteComponent, TextComponent
5 | from pyengine.Systems import EntitySystem
6 | from pyengine.Utils.Vec2 import Vec2
7 |
8 | __all__ = ["CameraSystem"]
9 |
10 |
11 | class CameraSystem:
12 | def __init__(self, world: World):
13 | self.world = world
14 | self.__position = Vec2()
15 | self.offset = Vec2()
16 | self.entity_follow = None
17 | self.__zoom = 1
18 |
19 | @property
20 | def entity_follow(self):
21 | return self.__ef
22 |
23 | @entity_follow.setter
24 | def entity_follow(self, entity):
25 | self.__ef = entity
26 | if entity is not None:
27 | if entity.rect:
28 | self.offset = Vec2(
29 | self.world.window.size[0] / 2 - entity.rect.width / 2,
30 | self.world.window.size[1] / 2 - entity.rect.height / 2
31 | )
32 | else:
33 | self.offset = Vec2(
34 | self.world.window.size[0] / 2,
35 | self.world.window.size[1] / 2
36 | )
37 |
38 | @property
39 | def position(self):
40 | return self.__position
41 |
42 | @position.setter
43 | def position(self, position):
44 | if not isinstance(position, pygame.Vector2):
45 | raise TypeError("Position must be a Vec2")
46 |
47 | self.__position = position
48 | for i in self.world.get_system(EntitySystem).entities:
49 | pos = i.get_component(PositionComponent)
50 | pos.position = Vec2(pos.position.x - self.position.x + self.offset.x,
51 | pos.position.y - self.position.y + self.offset.y)
52 |
53 | @property
54 | def zoom(self):
55 | return self.__zoom
56 |
57 | @zoom.setter
58 | def zoom(self, val):
59 | self.__zoom = val
60 | for i in self.world.get_system(EntitySystem).entities:
61 | if i.has_component(SpriteComponent):
62 | comp = i.get_component(SpriteComponent)
63 | else:
64 | comp = i.get_component(TextComponent)
65 | comp.scale = val
66 |
67 | @property
68 | def offset(self):
69 | return self.__offset
70 |
71 | @offset.setter
72 | def offset(self, offset):
73 | if not isinstance(offset, pygame.Vector2):
74 | raise TypeError("Offset must be a Vec2")
75 |
76 | self.__offset = offset
77 |
78 | def update(self):
79 | if self.entity_follow.has_component(PositionComponent):
80 | self.position = self.entity_follow.get_component(PositionComponent).position
81 |
--------------------------------------------------------------------------------
/pyengine/Systems/EntitySystem.py:
--------------------------------------------------------------------------------
1 | import pygame
2 |
3 | from pyengine import World
4 | from pyengine.Components import PositionComponent, SpriteComponent, TextComponent, ControlComponent, PhysicsComponent
5 | from pyengine.Entities.Entity import Entity
6 | from pyengine.Exceptions import NoObjectError
7 | from pyengine.Utils.Logger import loggers
8 | from pyengine.Utils.Font import Font
9 | from pyengine.Utils.Color import Colors
10 |
11 | __all__ = ["EntitySystem"]
12 |
13 |
14 | class EntitySystem:
15 | def __init__(self, world: World):
16 | self.world = world
17 | self.entities = pygame.sprite.Group()
18 | self.debugfont = Font("arial", 15, color=Colors.RED.value)
19 |
20 | def get_entity(self, identity: int) -> Entity:
21 | for i in self.entities:
22 | if i.identity == identity:
23 | return i
24 | loggers.get_logger("PyEngine").warning("Try to get entity with id "+str(identity)+" but it doesn't exist")
25 |
26 | def add_entity(self, entity: Entity) -> Entity:
27 | if not isinstance(entity, Entity):
28 | raise TypeError("Argument is not type of "+str(Entity)+" but "+str(type(entity))+".")
29 | if not entity.has_component(PositionComponent):
30 | raise NoObjectError("Entity must have PositionComponent to be add in a world.")
31 | if not entity.has_component(SpriteComponent) and not entity.has_component(TextComponent):
32 | raise NoObjectError("Entity must have SpriteComponent or TextComponent to be add in a world.")
33 | if entity.has_component(PhysicsComponent):
34 | phys = entity.get_component(PhysicsComponent)
35 | self.world.space.add(phys.body, phys.shape)
36 | if len(self.entities):
37 | entity.identity = self.entities.sprites()[-1].identity + 1
38 | else:
39 | entity.identity = 0
40 | self.entities.add(entity)
41 | entity.system = self
42 | return entity
43 |
44 | def has_entity(self, entity: Entity) -> bool:
45 | return entity in self.entities
46 |
47 | def remove_entity(self, entity: Entity) -> None:
48 | if entity in self.entities:
49 | self.entities.remove(entity)
50 | else:
51 | raise ValueError("Entity has not in EntitySystem")
52 |
53 | def update(self):
54 | for i in self.entities:
55 | i.update()
56 |
57 | from pyengine.Systems import CameraSystem
58 | if self.world.get_system(CameraSystem).entity_follow is None and i.has_component(PositionComponent):
59 | from pyengine import WindowCallbacks
60 | # Verify if entity is not out of window
61 | position = i.get_component(PositionComponent)
62 | height = i.image.get_rect().height / 2
63 | width = i.image.get_rect().width / 2
64 | if (position.position.y >= self.world.window.height - height or
65 | position.position.y < height or
66 | position.position.x >= self.world.window.width - width or
67 | position.position.x < width):
68 | self.world.window.call(WindowCallbacks.OUTOFWINDOW, i, position.position)
69 |
70 | def stop_world(self):
71 | for i in self.entities:
72 | if i.has_component(ControlComponent):
73 | i.get_component(ControlComponent).keypressed = []
74 | if i.has_component(PhysicsComponent):
75 | i.get_component(PhysicsComponent).body.velocity = [0, 0]
76 | i.get_component(PhysicsComponent).body.angular_velocity = 0
77 |
78 | def keypress(self, evt):
79 | [i.get_component(ControlComponent).keypress(evt) for i in self.entities if i.has_component(ControlComponent)]
80 |
81 | def keyup(self, evt):
82 | [i.get_component(ControlComponent).keyup(evt) for i in self.entities if i.has_component(ControlComponent)]
83 |
84 | def mousepress(self, evt):
85 | [i.get_component(ControlComponent).mousepress(evt) for i in self.entities if i.has_component(ControlComponent)]
86 |
87 | def mousemotion(self, evt):
88 | [i.get_component(ControlComponent).mousemotion(evt) for i in self.entities if i.has_component(ControlComponent)]
89 |
90 | def show(self, screen):
91 | self.entities.draw(screen)
92 |
93 | def show_debug(self, screen):
94 | for i in self.entities.sprites():
95 | render = self.debugfont.render("ID : "+str(i.identity))
96 | screen.blit(render, (i.rect.x + i.rect.width / 2 - render.get_width()/2, i.rect.y - 20))
97 |
--------------------------------------------------------------------------------
/pyengine/Systems/MusicSystem.py:
--------------------------------------------------------------------------------
1 | import pygame
2 |
3 | from pyengine.Exceptions import NoObjectError
4 |
5 | __all__ = ["MusicSystem"]
6 |
7 |
8 | class MusicSystem:
9 | def __init__(self):
10 | pygame.mixer.init()
11 | self.queue = []
12 | self.ENDSOUND = 231
13 | self.volume = 100
14 | self.loop = False
15 | pygame.mixer.music.set_endevent(self.ENDSOUND)
16 |
17 | @property
18 | def loop(self):
19 | return self.__loop
20 |
21 | @loop.setter
22 | def loop(self, loop):
23 | self.__loop = loop
24 |
25 | @property
26 | def volume(self):
27 | return round(pygame.mixer.music.get_volume()*100)
28 |
29 | @volume.setter
30 | def volume(self, volume):
31 | if volume < 0 or volume > 100:
32 | raise ValueError("Volume can't be lower than 0 and bigger than 100")
33 | pygame.mixer.music.set_volume(volume/100)
34 |
35 | def next_song(self) -> None:
36 | if len(self.queue):
37 | pygame.mixer.music.load(self.queue[0])
38 | pygame.mixer.music.play()
39 | if self.loop:
40 | self.queue.append(self.queue[0])
41 | del self.queue[0]
42 |
43 | def clear_queue(self) -> None:
44 | self.queue = []
45 |
46 | def play(self) -> None:
47 | if len(self.queue):
48 | pygame.mixer.music.load(self.queue[0])
49 | pygame.mixer.music.play()
50 | if self.loop:
51 | self.queue.append(self.queue[0])
52 | del self.queue[0]
53 | else:
54 | raise NoObjectError("MusicSystem have any music to play")
55 |
56 | def add(self, file: str) -> None:
57 | self.queue.append(file)
58 |
59 | @staticmethod
60 | def stop() -> None:
61 | pygame.mixer.music.stop()
62 |
63 | @staticmethod
64 | def pause() -> None:
65 | pygame.mixer.music.pause()
66 |
67 | @staticmethod
68 | def unpause() -> None:
69 | pygame.mixer.music.unpause()
70 |
71 |
--------------------------------------------------------------------------------
/pyengine/Systems/SoundSystem.py:
--------------------------------------------------------------------------------
1 | import pygame
2 |
3 | __all__ = ["SoundSystem"]
4 |
5 |
6 | class SoundSystem:
7 | def __init__(self):
8 | self.volume = 100
9 |
10 | @property
11 | def volume(self):
12 | return self.__volume
13 |
14 | @volume.setter
15 | def volume(self, volume):
16 | if volume < 0 or volume > 100:
17 | raise ValueError("Volume can't be lower than 0 and bigger than 100")
18 | self.__volume = volume
19 |
20 | @property
21 | def number_channel(self):
22 | return pygame.mixer.get_num_channels()
23 |
24 | @number_channel.setter
25 | def number_channel(self, nb):
26 | pygame.mixer.set_num_channels(nb)
27 |
28 | def play(self, file: str) -> None:
29 | sound = pygame.mixer.Sound(file)
30 | sound.set_volume(self.volume/100)
31 | sound.play()
32 |
--------------------------------------------------------------------------------
/pyengine/Systems/UISystem.py:
--------------------------------------------------------------------------------
1 | import pygame
2 |
3 | from pyengine import World
4 | from pyengine.Utils.Logger import loggers
5 | from pyengine.Utils.Color import Colors
6 | from pyengine.Utils.Font import Font
7 | from pyengine.Widgets.Entry import Entry
8 | from pyengine.Widgets.Button import Button
9 | from pyengine.Widgets.AnimatedImage import AnimatedImage
10 | from pyengine.Widgets.Widget import Widget
11 |
12 | __all__ = ["UISystem"]
13 |
14 |
15 | class UISystem:
16 | def __init__(self, world: World):
17 | self.world = world
18 | self.widgets = pygame.sprite.Group()
19 | self.focus = None
20 | self.debugfont = Font("arial", 15, color=Colors.BLUE.value)
21 |
22 | def get_widget(self, identity: int) -> Widget:
23 | liste = [i for i in self.widgets if i.identity == identity]
24 | if len(liste):
25 | return liste[0]
26 | loggers.get_logger("PyEngine").warning("Try to get widget with id "+str(identity)+" but it doesn't exist")
27 |
28 | def add_widget(self, widget: Widget) -> Widget:
29 | if not isinstance(widget, Widget):
30 | raise TypeError("Argument is not type of "+str(Widget)+" but "+str(type(widget))+".")
31 | if len(self.widgets):
32 | widget.identity = self.widgets.sprites()[-1].identity + 1
33 | else:
34 | widget.identity = 0
35 | self.widgets.add(widget)
36 | widget.system = self
37 | return widget
38 |
39 | def has_widget(self, widget: Widget) -> bool:
40 | return widget in self.widgets
41 |
42 | def remove_widget(self, widget: Widget) -> None:
43 | if widget in self.widgets:
44 | self.widgets.remove(widget)
45 | else:
46 | raise ValueError("Widget has not in UISystem")
47 |
48 | def mousepress(self, evt):
49 | focustemp = None
50 | for i in self.widgets.sprites():
51 | if i.mousepress(evt):
52 | while i.parent is not None:
53 | i = i.parent
54 | focustemp = i
55 | i.focusin()
56 | else:
57 | if self.focus == i:
58 | self.focus.focusout()
59 | self.focus = focustemp
60 |
61 | def mousemotion(self, evt):
62 | [i.mousemotion(evt) for i in self.widgets if isinstance(i, Button)]
63 |
64 | def keyup(self, evt):
65 | [i.keyup(evt) for i in self.widgets if self.focus == i and isinstance(i, Entry)]
66 |
67 | def keypress(self, evt):
68 | [i.keypress(evt) for i in self.widgets if self.focus == i and isinstance(i, Entry)]
69 |
70 | def update(self):
71 | [i.update() for i in self.widgets if self.focus == i and isinstance(i, Entry)]
72 | [i.update() for i in self.widgets if isinstance(i, AnimatedImage)]
73 |
74 | def show(self, screen):
75 | [screen.blit(i.image, i.rect) for i in self.widgets if i.isshow and i.image is not None]
76 |
77 | def show_debug(self, screen):
78 | for i in self.widgets:
79 | if i.isshow and i.image is not None:
80 | render = self.debugfont.render("ID : "+str(i.identity))
81 | screen.blit(render, (i.rect.x + i.rect.width / 2 - render.get_width()/2, i.rect.y - 20))
82 |
--------------------------------------------------------------------------------
/pyengine/Systems/__init__.py:
--------------------------------------------------------------------------------
1 | from pyengine.Systems.CameraSystem import CameraSystem
2 | from pyengine.Systems.EntitySystem import EntitySystem
3 | from pyengine.Systems.MusicSystem import MusicSystem
4 | from pyengine.Systems.SoundSystem import SoundSystem
5 | from pyengine.Systems.UISystem import UISystem
6 |
--------------------------------------------------------------------------------
/pyengine/Utils/Color.py:
--------------------------------------------------------------------------------
1 | from enum import Enum
2 | from typing import Tuple
3 |
4 | import pygame
5 |
6 | from pyengine.Utils.Others import clamp
7 |
8 | __all__ = ["Color", "Colors"]
9 |
10 |
11 | class Color(pygame.Color):
12 | def __init__(self, r: int = 255, g: int = 255, b: int = 255, a: int = 255):
13 | super(Color, self).__init__(r, g, b, a)
14 |
15 | def get(self) -> Tuple[int, int, int, int]:
16 | return self.r, self.g, self.b, self.a
17 |
18 | def set(self, color):
19 | if not isinstance(color, Color):
20 | raise TypeError("Color have not a Color type")
21 | self.r = color.r
22 | self.g = color.g
23 | self.b = color.b
24 | self.a = color.a
25 | return self
26 |
27 | def to_hex(self):
28 | return ("#"+hex(self.r)[2:]+hex(self.g)[2:]+hex(self.b)[2:]+hex(self.a)[2:]).upper()
29 |
30 | def from_hex(self, hexa: str):
31 | if len(hexa) == 7:
32 | self.r = int(hexa[1:3], 16)
33 | self.g = int(hexa[3:5], 16)
34 | self.b = int(hexa[5:7], 16)
35 | self.a = 255
36 | elif len(hexa) == 9:
37 | self.r = int(hexa[1:3], 16)
38 | self.g = int(hexa[3:5], 16)
39 | self.b = int(hexa[5:7], 16)
40 | self.a = int(hexa[7:9], 16)
41 | else:
42 | raise ValueError("Hexa must be a 7 or 9 lenght string (#RRGGBBAA)")
43 |
44 | def darker(self, nb=1):
45 | nb = clamp(nb, 1)
46 | r = clamp(self.r - 10*nb, 0, 255)
47 | b = clamp(self.b - 10*nb, 0, 255)
48 | g = clamp(self.g - 10*nb, 0, 255)
49 | return Color(r, g, b, self.a)
50 |
51 | def lighter(self, nb=1):
52 | nb = clamp(nb, 1)
53 | r = clamp(self.r + 10*nb, 0, 255)
54 | b = clamp(self.b + 10*nb, 0, 255)
55 | g = clamp(self.g + 10*nb, 0, 255)
56 | return Color(r, g, b, self.a)
57 |
58 | def __repr__(self) -> str:
59 | return str(self.get())
60 |
61 |
62 | class Colors(Enum):
63 | WHITE = Color(255, 255, 255)
64 | BLACK = Color(0, 0, 0)
65 | RED = Color(255, 0, 0)
66 | GREEN = Color(0, 255, 0)
67 | BLUE = Color(0, 0, 255)
68 | FUCHSIA = Color(255, 0, 255)
69 | GRAY = Color(128, 128, 128)
70 | LIME = Color(0, 128, 0)
71 | MAROON = Color(128, 0, 0)
72 | NAVYBLUE = Color(0, 0, 128)
73 | OLIVE = Color(128, 128, 0)
74 | PURPLE = Color(128, 0, 128)
75 | SILVER = Color(192, 192, 192)
76 | TEAL = Color(0, 128, 128)
77 | YELLOW = Color(255, 255, 0)
78 | ORANGE = Color(255, 128, 0)
79 | CYAN = Color(0, 255, 255)
80 |
--------------------------------------------------------------------------------
/pyengine/Utils/Config.py:
--------------------------------------------------------------------------------
1 | import json
2 | import os
3 |
4 | from pyengine.Utils.Logger import loggers
5 |
6 | __all__ = ["Config"]
7 |
8 |
9 | class Config:
10 | def __init__(self, file: str):
11 | self.dic = {}
12 | self.created = False
13 | self.file = file
14 |
15 | def get(self, key):
16 | try:
17 | return self.dic[key]
18 | except KeyError:
19 | loggers.to_all("warning", "Key '"+key+"' doesn't exist in Config File")
20 |
21 | def set(self, key, val):
22 | self.dic[key] = val
23 |
24 | def save(self):
25 | with open(self.file, "w") as f:
26 | f.write(json.dumps(self.dic, indent=4))
27 | loggers.to_all("info", "Config File saved")
28 |
29 | @property
30 | def file(self):
31 | return self.__file
32 |
33 | @file.setter
34 | def file(self, val):
35 | self.__file = val
36 | if os.path.exists(val):
37 | self.created = True
38 | with open(val, "r") as f:
39 | self.dic = json.load(f)
40 | else:
41 | self.created = False
42 |
43 | def create(self, dic):
44 | if self.created:
45 | loggers.to_all("warning", "Config File already exist but recreated")
46 | else:
47 | loggers.to_all("info", "Config File created")
48 | with open(self.file, "w") as f:
49 | f.write(json.dumps(dic, indent=4))
50 | self.dic = dic
51 |
52 |
--------------------------------------------------------------------------------
/pyengine/Utils/Font.py:
--------------------------------------------------------------------------------
1 | import pygame
2 |
3 | from pyengine.Utils.Color import Color, Colors
4 |
5 | __all__ = ["Font"]
6 |
7 |
8 | class Font:
9 | def __init__(self, name: str = "arial", size: int = 15, bold: bool = False, italic: bool = False,
10 | underline: bool = False, color: Color = Colors.WHITE.value, background: Color = None,
11 | antialias: bool = True):
12 | pygame.font.init()
13 | try:
14 | self.font = pygame.font.Font(name, size)
15 | except FileNotFoundError:
16 | self.font = pygame.font.SysFont(name, size)
17 | self.name = name
18 | self.size = size
19 | self.bold = bold
20 | self.italic = italic
21 | self.underline = underline
22 | self.color = color
23 | self.background = background
24 | self.antialias = antialias
25 | self.parent = None
26 |
27 | def get_ascent(self):
28 | return self.font.get_ascent()
29 |
30 | def get_bold(self):
31 | return self.font.get_bold()
32 |
33 | def get_descent(self):
34 | return self.font.get_descent()
35 |
36 | def get_height(self):
37 | return self.font.get_height()
38 |
39 | def get_italic(self):
40 | return self.font.get_italic()
41 |
42 | def get_linesize(self):
43 | return self.font.get_linesize()
44 |
45 | def get_underline(self):
46 | return self.font.get_underline()
47 |
48 | def get_antialias(self):
49 | return self.__antialias
50 |
51 | def get_color(self):
52 | return self.__color
53 |
54 | def get_background(self):
55 | return self.__background
56 |
57 | def metrics(self, text):
58 | return self.font.get_metrics(text)
59 |
60 | def render(self, text):
61 | return self.font.render(text, self.antialias, self.color.get(), self.background)
62 |
63 | def set_bold(self, boldbool):
64 | self.font.set_bold(boldbool)
65 |
66 | def set_italic(self, italicbool):
67 | self.font.set_italic(italicbool)
68 |
69 | def set_underline(self, underlinebool):
70 | self.font.set_underline(underlinebool)
71 |
72 | def set_antialias(self, antialiasebool):
73 | self.__antialias = antialiasebool
74 |
75 | def set_color(self, color):
76 | if not isinstance(color, Color):
77 | raise TypeError("Color must be a color")
78 | self.__color = color
79 |
80 | def set_background(self, background):
81 | if not isinstance(background, Color) and background is not None:
82 | raise TypeError("Background must be a color")
83 | self.__background = background
84 |
85 | def rendered_size(self, text):
86 | return self.font.size(text)
87 |
88 | bold = property(get_bold, set_bold)
89 | italic = property(get_italic, set_italic)
90 | underline = property(get_underline, set_underline)
91 | antialias = property(get_antialias, set_antialias)
92 | color = property(get_color, set_color)
93 | background = property(get_background, set_background)
94 |
95 | def __eq__(self, other):
96 | print(isinstance(other, Font) and self.name == other.name and self.color == other.color and
97 | self.background == other.background and self.bold == other.bold and self.italic == other.italic and
98 | self.underline == other.underline and self.antialias == other.antialias)
99 | return (isinstance(other, Font) and self.name == other.name and self.color == other.color and
100 | self.background == other.background and self.bold == other.bold and self.italic == other.italic and
101 | self.underline == other.underline and self.antialias == other.antialias)
102 |
--------------------------------------------------------------------------------
/pyengine/Utils/Lang.py:
--------------------------------------------------------------------------------
1 | import os
2 |
3 | __all__ = ["Lang"]
4 |
5 |
6 | class Lang:
7 | def __init__(self, file: str):
8 | self.file = file
9 |
10 | @property
11 | def file(self):
12 | return self.__file
13 |
14 | @file.setter
15 | def file(self, file):
16 | self.dic = {}
17 | self.__file = file
18 | if os.path.exists(file):
19 | with open(file) as f:
20 | for i in f.readlines():
21 | if len(i.split(": ")) == 2:
22 | self.dic[i.split(": ")[0]] = i.split(": ")[1].replace("\n", "")
23 | else:
24 | raise ValueError("Unknown format of lang : '"+i+"'")
25 | else:
26 | raise ValueError("File don't exist.")
27 |
28 | def get_translate(self, key: str, default: str) -> str:
29 | try:
30 | return self.dic[key]
31 | except KeyError:
32 | return default
33 |
--------------------------------------------------------------------------------
/pyengine/Utils/Logger.py:
--------------------------------------------------------------------------------
1 | import logging
2 | import os
3 | from logging.handlers import RotatingFileHandler
4 |
5 | __all__ = ["loggers"]
6 |
7 |
8 | class Logger(logging.Logger):
9 | def __init__(self, name, file=None, stream=False):
10 | super(Logger, self).__init__(name)
11 |
12 | self.file_formatter = logging.Formatter('%(asctime)s - %(levelname)s: %(message)s',
13 | datefmt='%d/%m/%Y %H:%M:%S')
14 |
15 | self.stream_formatter = logging.Formatter('FROM '+name+' - %(asctime)s - %(levelname)s: %(message)s',
16 | datefmt='%d/%m/%Y %H:%M:%S')
17 |
18 | if file is not None:
19 | self.file_handler = RotatingFileHandler(file, "a", 1000000, 1)
20 | self.file_handler.setFormatter(self.file_formatter)
21 | self.addHandler(self.file_handler)
22 | else:
23 | self.file_handler = None
24 |
25 | if stream:
26 | self.stream_handler = logging.StreamHandler()
27 | self.stream_handler.setFormatter(self.stream_formatter)
28 | self.addHandler(self.stream_handler)
29 | else:
30 | self.stream_handler = None
31 |
32 | def setLevel(self, level):
33 | super(Logger, self).setLevel(level)
34 | if self.stream_handler:
35 | self.stream_handler.setLevel(level)
36 | if self.file_handler:
37 | self.file_handler.setLevel(level)
38 |
39 |
40 | class Loggers:
41 | def __init__(self):
42 | if not os.path.exists("logs"):
43 | os.mkdir("logs")
44 |
45 | self.loggers = {
46 | "PyEngine": Logger("PyEngine", "logs/pyengine.log", True)
47 | }
48 |
49 | def create_logger(self, name, file=None, stream=False):
50 | self.loggers[name] = Logger(name, file, stream)
51 | self.loggers[name].setLevel(self.loggers["PyEngine"].getEffectiveLevel())
52 | return self.loggers[name]
53 |
54 | def get_logger(self, name):
55 | try:
56 | return self.loggers[name]
57 | except KeyError:
58 | raise KeyError("Logger '"+name+"' doesn't exist")
59 |
60 | def get_all(self):
61 | return list(self.loggers.items())
62 |
63 | def to_all(self, action: str, message: str) -> None:
64 | for i in self.loggers.values():
65 | if action == "debug":
66 | i.debug(message)
67 | elif action == "warning":
68 | i.warning(message)
69 | elif action == "error":
70 | i.error(message)
71 | elif action == "critical":
72 | i.critical(message)
73 | else:
74 | i.info(message)
75 |
76 |
77 | loggers = Loggers()
78 |
79 |
--------------------------------------------------------------------------------
/pyengine/Utils/Others.py:
--------------------------------------------------------------------------------
1 | from PIL import Image
2 |
3 |
4 | def clamp(val, mini=None, maxi=None):
5 | if mini is None and maxi is None:
6 | return val
7 | elif mini is None:
8 | return val if val < maxi else maxi
9 | elif maxi is None:
10 | return val if val > mini else mini
11 | else:
12 | if val < mini:
13 | return mini
14 | elif val > maxi:
15 | return maxi
16 | else:
17 | return val
18 |
19 |
20 | def wrap_text(text, font, width):
21 | if width == 0:
22 | return ""
23 | line_width = font.rendered_size(text)[0]
24 | if line_width > width:
25 | words = text.split(' ')
26 | for i in range(len(words)-1, 0, -1):
27 | curr_line = ' '.join(words[:-i])
28 | if font.rendered_size(curr_line)[0] <= width:
29 | return curr_line + "\n" + str(wrap_text(' '.join(words[len(words)-i:]), font, width))
30 | return text
31 | else:
32 | return text
33 |
34 |
35 | def get_images_from_gif(file):
36 | frames = []
37 | im = Image.open(file)
38 | results = {
39 | 'size': im.size,
40 | 'mode': 'full',
41 | }
42 | try:
43 | while True:
44 | if im.tile:
45 | tile = im.tile[0]
46 | update_region = tile[1]
47 | update_region_dimensions = update_region[2:]
48 | if update_region_dimensions != im.size:
49 | results['mode'] = 'partial'
50 | break
51 | im.seek(im.tell() + 1)
52 | except EOFError:
53 | pass
54 | mode = results['mode']
55 |
56 | im = Image.open(file)
57 |
58 | i = 0
59 | p = im.getpalette()
60 | last_frame = im.convert('RGBA')
61 |
62 | try:
63 | while True:
64 |
65 | from pyengine.Utils import loggers
66 | loggers.get_logger("PyEngine").debug("saving %s (%s) frame %d, %s %s" % (file, mode, i, im.size, im.tile))
67 |
68 | if not im.getpalette():
69 | im.putpalette(p)
70 |
71 | new_frame = Image.new('RGBA', im.size)
72 |
73 | if mode == 'partial':
74 | new_frame.paste(last_frame)
75 |
76 | name = '%s-%d.png' % (''.join(file.split('.')[:-1]), i)
77 |
78 | new_frame.paste(im, (0, 0), im.convert('RGBA'))
79 | new_frame.save(name, 'PNG')
80 | frames.append(name)
81 |
82 | i += 1
83 | last_frame = new_frame
84 | im.seek(im.tell() + 1)
85 | except EOFError:
86 | pass
87 | return frames
88 |
--------------------------------------------------------------------------------
/pyengine/Utils/Vec2.py:
--------------------------------------------------------------------------------
1 | from typing import Tuple
2 |
3 | import pygame
4 |
5 | __all__ = ["Vec2"]
6 |
7 |
8 | class Vec2(pygame.Vector2):
9 | def __init__(self, x: int = 0, y: int = 0):
10 | super(Vec2, self).__init__(x, y)
11 |
12 | @property
13 | def coords(self) -> Tuple[int, int]:
14 | return round(self.x), round(self.y)
15 |
16 | @coords.setter
17 | def coords(self, dic: Tuple[int, int]) -> None:
18 | self.x = dic[0]
19 | self.y = dic[1]
20 |
21 | @property
22 | def fcoords(self) -> Tuple[float, float]:
23 | return self.x, self.y
24 |
25 | @fcoords.setter
26 | def fcoords(self, dic: Tuple[float, float]) -> None:
27 | self.x = dic[0]
28 | self.y = dic[1]
29 |
30 |
--------------------------------------------------------------------------------
/pyengine/Utils/__init__.py:
--------------------------------------------------------------------------------
1 | from pyengine.Utils.Color import Color, Colors
2 | from pyengine.Utils.Config import Config
3 | from pyengine.Utils.Font import Font
4 | from pyengine.Utils.Lang import Lang
5 | from pyengine.Utils.Logger import loggers
6 | from pyengine.Utils.Others import clamp, wrap_text, get_images_from_gif
7 | from pyengine.Utils.Vec2 import Vec2
8 |
--------------------------------------------------------------------------------
/pyengine/Widgets/AnimatedImage.py:
--------------------------------------------------------------------------------
1 | from typing import List
2 |
3 | from pyengine.Utils.Vec2 import Vec2
4 | from pyengine.Utils.Logger import loggers
5 | from pyengine.Widgets.Image import Image
6 |
7 | __all__ = ["AnimatedImage"]
8 |
9 |
10 | class AnimatedImage(Image):
11 | def __init__(self, position: Vec2, sprites: List, timer: int = 20, size: Vec2 = None):
12 | if not isinstance(sprites, (list, tuple)) and len(sprites) == 0:
13 | raise ValueError("Sprites must be a List with minimum one sprite")
14 | elif len(sprites) == 1:
15 | loggers.get_logger("PyEngine").info("AnimatedImage is useless with only one sprite. Use Image.")
16 | super(AnimatedImage, self).__init__(position, sprites[0], size)
17 | self.__sprites = sprites
18 | self.timer = timer - 1
19 | self.current_sprite = 0
20 | self.play = True
21 |
22 | @property
23 | def timer(self):
24 | return self.__timer
25 |
26 | @timer.setter
27 | def timer(self, timer):
28 | self.__timer = timer
29 | self.timerinterne = timer
30 |
31 | @property
32 | def sprites(self):
33 | return self.__sprites
34 |
35 | @sprites.setter
36 | def sprites(self, sprites: List):
37 | if not (isinstance(sprites, list) or isinstance(sprites, tuple)) and len(sprites) == 0:
38 | raise ValueError("Sprites must be a List with minimum one sprite")
39 | elif len(sprites) == 1:
40 | loggers.get_logger("PyEngine").info("AnimatedImage is useless with only one sprite. Use Image.")
41 | self.__sprites = sprites
42 | self.sprite = sprites[0]
43 | self.current_sprite = 0
44 |
45 | def update(self):
46 | if self.play:
47 | if self.timerinterne <= 0:
48 | if self.current_sprite + 1 < len(self.sprites):
49 | self.current_sprite += 1
50 | else:
51 | self.current_sprite = 0
52 | self.sprite = self.sprites[self.current_sprite]
53 | self.timerinterne = self.timer
54 | self.timerinterne -= 1
55 |
--------------------------------------------------------------------------------
/pyengine/Widgets/Button.py:
--------------------------------------------------------------------------------
1 | from typing import Union, Callable
2 |
3 | import pygame
4 |
5 | from pyengine.Utils.Vec2 import Vec2
6 | from pyengine.Widgets.Label import Label
7 | from pyengine.Widgets.Widget import Widget
8 |
9 | __all__ = ["Button"]
10 |
11 |
12 | class Button(Widget):
13 | def __init__(self, position: Vec2, text: str, command: Union[None, Callable[[], None]] = None,
14 | size: Vec2 = Vec2(100, 40), sprite: Union[None, str] = None):
15 | super(Button, self).__init__(position)
16 |
17 | if sprite is None:
18 | self.image = pygame.Surface(size.coords)
19 | self.image.fill((50, 50, 50))
20 | else:
21 | image = pygame.image.load(sprite)
22 | self.image = pygame.transform.scale(image, size.coords)
23 |
24 | self.label = Label(position, text)
25 | self.label.parent = self
26 | self.rect = self.image.get_rect()
27 | self.position = position
28 | self.size = size
29 | self.sprite = sprite
30 | self.ishover = False
31 | self.__enabled = True
32 | self.command = command
33 | self.update_render()
34 |
35 | def update_render(self):
36 | self.update_rect()
37 | self.label.position = Vec2(self.rect.x+self.rect.width/2-self.label.rect.width/2,
38 | self.rect.y+self.rect.height/2-self.label.rect.height/2)
39 |
40 | def hide(self):
41 | super(Button, self).hide()
42 | self.label.hide()
43 |
44 | def show(self):
45 | super(Button, self).show()
46 | self.label.show()
47 |
48 | @property
49 | def enabled(self):
50 | return self.__enabled
51 |
52 | @enabled.setter
53 | def enabled(self, value):
54 | self.ishover = False
55 | t = pygame.surfarray.array3d(self.image)
56 | if value and not self.__enabled:
57 | for i in t:
58 | for j in i:
59 | j += 50
60 | elif not value and self.__enabled:
61 | for i in t:
62 | for j in i:
63 | j -= 50
64 | try:
65 | pygame.surfarray.blit_array(self.image, t)
66 | except ValueError:
67 | pass
68 | self.__enabled = value
69 |
70 | @property
71 | def sprite(self):
72 | return self.__sprite
73 |
74 | @sprite.setter
75 | def sprite(self, val):
76 | self.__sprite = val
77 | if val is None:
78 | self.image = pygame.Surface(self.size.coords)
79 | self.image .fill((50, 50, 50))
80 | else:
81 | image = pygame.image.load(val)
82 | self.image = pygame.transform.scale(image, self.size.coords)
83 | self.update_render()
84 |
85 | @property
86 | def size(self):
87 | return self.__size
88 |
89 | @size.setter
90 | def size(self, size):
91 | if not isinstance(size, Vec2):
92 | raise TypeError("Position must be a Vec2")
93 |
94 | self.__size = size
95 | self.image = pygame.transform.scale(self.image, size.coords)
96 | self.update_render()
97 |
98 | @property
99 | def command(self):
100 | return self.__command
101 |
102 | @command.setter
103 | def command(self, command):
104 | self.__command = command
105 |
106 | @property
107 | def system(self):
108 | return self.__system
109 |
110 | @system.setter
111 | def system(self, system):
112 | self.__system = system
113 | system.add_widget(self.label)
114 |
115 | @property
116 | def position(self):
117 | return self.__position
118 |
119 | @position.setter
120 | def position(self, position):
121 | self.__position = position
122 | self.rect.x = self.position.x
123 | self.rect.y = self.position.y
124 | self.label.position = Vec2(self.rect.x+self.rect.width/2-self.label.rect.width/2,
125 | self.rect.y+self.rect.height/2-self.label.rect.height/2)
126 |
127 | def mousepress(self, evt):
128 | from pyengine import MouseButton # Avoid import error
129 |
130 | if self.rect.x <= evt.pos[0] <= self.rect.x + self.rect.width and self.rect.y <= evt.pos[1] <= self.rect.y +\
131 | self.rect.height and self.command and evt.button == MouseButton.LEFTCLICK.value and self.enabled:
132 | self.command()
133 | return True
134 |
135 | def mousemotion(self, evt):
136 | if self.rect.x <= evt.pos[0] <= self.rect.x + self.rect.width and self.rect.y <= evt.pos[1] <= self.rect.y + \
137 | self.rect.height:
138 | if not self.ishover and self.enabled:
139 | t = pygame.surfarray.array3d(self.image)
140 | for i in t:
141 | for j in i:
142 | j += 10
143 | try:
144 | pygame.surfarray.blit_array(self.image, t)
145 | except ValueError:
146 | pass
147 | self.ishover = True
148 | elif self.ishover and self.enabled:
149 | t = pygame.surfarray.array3d(self.image)
150 | for i in t:
151 | for j in i:
152 | j -= 10
153 | try:
154 | pygame.surfarray.blit_array(self.image, t)
155 | except ValueError:
156 | pass
157 | self.ishover = False
158 |
159 |
160 |
--------------------------------------------------------------------------------
/pyengine/Widgets/Checkbox.py:
--------------------------------------------------------------------------------
1 | import pygame
2 |
3 | from pyengine.Utils.Vec2 import Vec2
4 | from pyengine.Widgets.Label import Label
5 | from pyengine.Widgets.Widget import Widget
6 |
7 | __all__ = ["Checkbox"]
8 |
9 |
10 | class Checkbox(Widget):
11 | def __init__(self, position: Vec2, text: str, checked: bool = False, scale: float = 1):
12 | super(Checkbox, self).__init__(position)
13 |
14 | self.__checked = checked
15 | self.__scale = scale
16 |
17 | self.label = Label(position, text)
18 | self.label.parent = self
19 |
20 | self.create_image()
21 |
22 | def update_render(self):
23 | self.update_rect()
24 | self.label.position = Vec2(self.rect.x + 20 * self.scale + 5,
25 | self.rect.y + self.rect.height / 2 - self.label.rect.height / 2)
26 |
27 | def hide(self):
28 | super(Checkbox, self).hide()
29 | self.label.hide()
30 |
31 | def show(self):
32 | super(Checkbox, self).show()
33 | self.label.show()
34 |
35 | def create_image(self):
36 | self.image = pygame.Surface([20 * self.scale, 20 * self.scale])
37 | self.image.fill((50, 50, 50))
38 | iiwhite = pygame.Surface([16 * self.scale, 16 * self.scale])
39 | iiwhite.fill((255, 255, 255))
40 | self.image.blit(iiwhite, (self.image.get_width() / 2 - iiwhite.get_width() / 2,
41 | self.image.get_height() / 2 - iiwhite.get_height() / 2))
42 | if self.checked:
43 | iiblack = pygame.Surface([14 * self.scale, 14 * self.scale])
44 | iiblack.fill((0, 0, 0))
45 | self.image.blit(iiblack, (self.image.get_width() / 2 - iiblack.get_width() / 2,
46 | self.image.get_height() / 2 - iiblack.get_height() / 2))
47 | self.update_render()
48 |
49 | @property
50 | def checked(self):
51 | return self.__checked
52 |
53 | @checked.setter
54 | def checked(self, val: bool):
55 | self.__checked = val
56 | self.create_image()
57 |
58 | @property
59 | def scale(self):
60 | return self.__scale
61 |
62 | @scale.setter
63 | def scale(self, val: float):
64 | self.__scale = val
65 | self.create_image()
66 |
67 | @property
68 | def system(self):
69 | return self.__system
70 |
71 | @system.setter
72 | def system(self, system):
73 | self.__system = system
74 | system.add_widget(self.label)
75 |
76 | def mousepress(self, evt):
77 | from pyengine import MouseButton # Avoid import error
78 |
79 | if ((self.rect.x <= evt.pos[0] <= self.rect.x + self.rect.width and self.rect.y <= evt.pos[1] <= self.rect.y +
80 | self.rect.height) or self.label.mousepress(evt)) and evt.button == MouseButton.LEFTCLICK.value:
81 | self.checked = not self.checked
82 | self.create_image()
83 | return True
84 |
85 |
--------------------------------------------------------------------------------
/pyengine/Widgets/Console.py:
--------------------------------------------------------------------------------
1 | from pygame import locals as const
2 |
3 | from pyengine.Utils.Color import Colors
4 | from pyengine.Utils.Font import Font
5 | from pyengine.Utils.Logger import loggers
6 | from pyengine.Utils.Vec2 import Vec2
7 | from pyengine.Widgets.Entry import Entry
8 | from pyengine.Widgets.Label import Label
9 |
10 | __all__ = ["Console"]
11 |
12 |
13 | def print_command(console, window, args):
14 | console.reply(" ".join(args))
15 |
16 |
17 | def debug_command(console, window, args):
18 | if window.debug:
19 | console.reply("Debug desactivated")
20 | else:
21 | console.reply("Debug activated")
22 | window.debug = not window.debug
23 |
24 |
25 | class Console(Entry):
26 | def __init__(self, window, pos=Vec2(), width=600):
27 | pos = Vec2(pos.x, pos.y + 20)
28 | super(Console, self).__init__(pos, width)
29 | self.window = window
30 | self.commands = {
31 | "print": print_command, "debug": debug_command
32 | }
33 | self.lastscommands = []
34 | self.current_command = len(self.lastscommands)
35 | self.font = Font(size=18)
36 |
37 | self.retour = Label(Vec2(pos.x, pos.y - 21), ">", Colors.BLACK.value, Font(size=18), Colors.WHITE.value)
38 | self.retour.parent = self
39 |
40 | def reply(self, texte=""):
41 | self.retour.text = "> "+texte
42 |
43 | def hide(self):
44 | super(Console, self).hide()
45 | self.retour.hide()
46 |
47 | def show(self):
48 | super(Console, self).show()
49 | self.retour.show()
50 |
51 | @property
52 | def system(self):
53 | return self.__system
54 |
55 | @system.setter
56 | def system(self, system):
57 | self.__system = system
58 | system.add_widget(self.retour)
59 |
60 | def add_command(self, name, function):
61 | if name in self.commands:
62 | loggers.get_logger("PyEngine").warning("Command overrided : "+name)
63 | self.commands[name] = function
64 |
65 | def delete_command(self, name):
66 | try:
67 | del self.commands[name]
68 | except KeyError:
69 | raise ValueError("Command '"+name+"' doesn't exist")
70 |
71 | def keypress(self, evt):
72 | temp = self.text
73 | super(Console, self).keypress(evt)
74 | if temp == self.text:
75 | if evt.key == const.K_RETURN:
76 | self.lastscommands.append(self.text)
77 | self.current_command = len(self.lastscommands)
78 | self.execute_command(self.text)
79 | self.text = ""
80 | elif evt.key == const.K_UP:
81 | if self.current_command > 0:
82 | self.current_command -= 1
83 | self.text = self.lastscommands[self.current_command]
84 | elif evt.key == const.K_DOWN:
85 | if self.current_command < len(self.lastscommands) - 1:
86 | self.current_command += 1
87 | self.text = self.lastscommands[self.current_command]
88 | elif self.current_command < len(self.lastscommands):
89 | self.text = ""
90 | self.current_command += 1
91 |
92 | def execute_command(self, command):
93 | if len(command.split(" ")) > 1:
94 | args = command.split(" ")[1:]
95 | else:
96 | args = []
97 | command = command.split(" ")[0]
98 | if command in self.commands:
99 | self.commands[command](self, self.window, args)
100 | else:
101 | loggers.get_logger("PyEngine").warning("Unknown command : " + command)
102 |
--------------------------------------------------------------------------------
/pyengine/Widgets/Entry.py:
--------------------------------------------------------------------------------
1 | import string
2 | from typing import Union
3 |
4 | import pygame
5 | from pygame import locals as const
6 |
7 | from pyengine.Utils.Color import Colors, Color
8 | from pyengine.Utils.Font import Font
9 | from pyengine.Utils.Vec2 import Vec2
10 | from pyengine.Widgets.Widget import Widget
11 |
12 | __all__ = ["Entry"]
13 |
14 |
15 | class Entry(Widget):
16 | accepted = "éèàçù€ " + string.digits + string.ascii_letters + string.punctuation
17 |
18 | def __init__(self, position: Vec2, width: int = 200, image: Union[None, str] = None,
19 | color: Union[None, Color] = Colors.BLACK.value, font: Union[None, Font] = Font()):
20 | super(Entry, self).__init__(position)
21 |
22 | if image is None:
23 | self.hasimage = False
24 | else:
25 | self.hasimage = True
26 | self.iiwhite = None # Respect PEP8
27 |
28 | self.__width = width
29 |
30 | self.color = color
31 | self.font = font
32 | self.cursortimer = 20
33 | self.cursor = False
34 | self.keypressed = None
35 | self.keytimer = 10
36 | self.__text = ""
37 | self.sprite = image
38 |
39 | def hide(self):
40 | super(Entry, self).hide()
41 |
42 | def show(self):
43 | super(Entry, self).show()
44 |
45 | @property
46 | def sprite(self):
47 | return self.__imagestr
48 |
49 | @sprite.setter
50 | def sprite(self, val):
51 | self.__imagestr = val
52 | self.update_render()
53 |
54 | @property
55 | def width(self):
56 | return self.__width
57 |
58 | @width.setter
59 | def width(self, val):
60 | self.__width = val
61 | if self.hasimage:
62 | self.image = pygame.transform.scale(self.image, [self.width, 35])
63 | else:
64 | self.image = pygame.Surface([self.width, 35])
65 | self.image.fill((50, 50, 50))
66 | self.iiwhite = pygame.Surface([self.width - 8, 28])
67 | self.iiwhite.fill((255, 255, 255))
68 | self.image.blit(self.iiwhite, (4, 4))
69 | self.update_render()
70 |
71 | @property
72 | def text(self):
73 | if self.cursor:
74 | return self.__text[:-1]
75 | return self.__text
76 |
77 | @text.setter
78 | def text(self, text):
79 | if self.cursor:
80 | self.__text = text+"I"
81 | else:
82 | self.__text = text
83 | self.update_render()
84 |
85 | def focusout(self):
86 | if self.cursor:
87 | self.__text = self.__text[:-1]
88 | self.cursor = False
89 | self.update_render()
90 |
91 | def keyup(self, evt):
92 | self.keypressed = None
93 |
94 | def keypress(self, evt):
95 | if evt.key == const.K_BACKSPACE:
96 | if len(self.__text):
97 | if self.cursor:
98 | self.__text = self.__text[:-2]+"I"
99 | else:
100 | self.__text = self.__text[:-1]
101 | elif evt.key == const.K_v and (evt.mod == const.KMOD_CTRL or evt.mod == const.KMOD_LCTRL):
102 | clipboard = pygame.scrap.get(const.SCRAP_TEXT)
103 | if clipboard:
104 | clipboard = clipboard.decode()[:-1]
105 | self.add_text(clipboard)
106 | elif evt.key == const.K_c and (evt.mod == const.KMOD_CTRL or evt.mod == const.KMOD_LCTRL):
107 | pygame.scrap.put(pygame.SCRAP_TEXT, self.text.encode())
108 | elif evt.unicode != '' and evt.unicode in self.accepted:
109 | self.add_text(evt.unicode)
110 | self.keypressed = evt
111 | self.keytimer = 10
112 |
113 | def update_render(self):
114 | self.font.color = self.color
115 | renderer = self.font.render(self.__text)
116 | x = self.width - renderer.get_rect().width - 10
117 | if x > 2:
118 | x = 2
119 | if self.sprite is None:
120 | self.image = pygame.Surface([self.width, 35])
121 | self.image.fill((50, 50, 50))
122 | self.iiwhite = pygame.Surface([self.width - 8, 28])
123 | self.iiwhite.fill((255, 255, 255))
124 | self.iiwhite.blit(renderer, (x, self.iiwhite.get_rect().height / 2 - renderer.get_rect().height/2))
125 | self.image.blit(self.iiwhite, (4, 4))
126 | self.hasimage = False
127 | else:
128 | self.image = pygame.image.load(self.sprite)
129 | self.image = pygame.transform.scale(self.image, [self.width, 35])
130 | self.image.blit(renderer, (x, self.image.get_rect().height / 2 - renderer.get_rect().height/2))
131 | self.hasimage = True
132 | self.update_rect()
133 |
134 | def add_text(self, texte):
135 | if self.cursor:
136 | text = self.__text[:-1] + texte + "I"
137 | else:
138 | text = self.__text + texte
139 | self.__text = text
140 | self.update_render()
141 |
142 | def update(self):
143 | if self.cursortimer <= 0:
144 | if self.cursor:
145 | self.__text = self.__text[:-1]
146 | else:
147 | self.__text = self.__text+"I"
148 | self.cursor = not self.cursor
149 | self.cursortimer = 20
150 | self.update_render()
151 | self.cursortimer -= 1
152 |
153 | if self.keytimer <= 0 and self.keypressed is not None:
154 | self.keypress(self.keypressed)
155 | self.keytimer = 10
156 | self.keytimer -= 1
157 |
--------------------------------------------------------------------------------
/pyengine/Widgets/Image.py:
--------------------------------------------------------------------------------
1 | import pygame
2 |
3 | from pyengine.Utils.Vec2 import Vec2
4 | from pyengine.Widgets.Widget import Widget
5 |
6 | __all__ = ["Image"]
7 |
8 |
9 | class Image(Widget):
10 | def __init__(self, position: Vec2, sprite: str, size: Vec2 = None):
11 | super(Image, self).__init__(position)
12 |
13 | self.sprite = sprite
14 | self.image = pygame.image.load(sprite)
15 |
16 | if size is not None:
17 | self.size = size
18 |
19 | @property
20 | def size(self):
21 | return Vec2(self.rect.width, self.rect.height)
22 |
23 | @size.setter
24 | def size(self, size):
25 | if not isinstance(size, Vec2):
26 | raise TypeError("Position must be a Vec2")
27 |
28 | self.image = pygame.transform.scale(self.image, size.coords)
29 | self.update_rect()
30 |
31 | @property
32 | def sprite(self):
33 | return self.__sprite
34 |
35 | @sprite.setter
36 | def sprite(self, sprite):
37 | self.__sprite = sprite
38 | self.image = pygame.image.load(sprite)
39 | self.update_rect()
40 |
--------------------------------------------------------------------------------
/pyengine/Widgets/Label.py:
--------------------------------------------------------------------------------
1 | from typing import Union
2 |
3 | from pyengine.Utils.Color import Colors, Color
4 | from pyengine.Utils.Font import Font
5 | from pyengine.Utils.Logger import loggers
6 | from pyengine.Utils.Vec2 import Vec2
7 | from pyengine.Widgets.Widget import Widget
8 |
9 | __all__ = ["Label"]
10 |
11 |
12 | class Label(Widget):
13 | def __init__(self, position: Vec2, text: str, color: Color = Colors.WHITE.value,
14 | font: Font = Font(), background: Union[None, Color] = None):
15 | super(Label, self).__init__(position)
16 |
17 | if not isinstance(font, Font):
18 | raise TypeError("Font have not a Font type")
19 | if not isinstance(color, Color):
20 | raise TypeError("Color have not a Color type")
21 | if not isinstance(background, Color) and background is not None:
22 | raise TypeError("Background must be a Color")
23 |
24 | if "\n" in text:
25 | loggers.get_logger("PyEngine").warning("Line break doesn't work with Label. Use MultilineLabel")
26 | text = text.replace("\n", "")
27 |
28 | self.__color = color
29 | self.__font = font
30 | self.__background = background
31 | self.text = text
32 | self.update_render()
33 |
34 | @property
35 | def background(self):
36 | return self.__background
37 |
38 | @background.setter
39 | def background(self, color):
40 | if not isinstance(color, Color) and color is not None:
41 | raise TypeError("Background must be a Color")
42 |
43 | self.__background = color
44 | self.update_render()
45 |
46 | @property
47 | def color(self):
48 | return self.__color
49 |
50 | @color.setter
51 | def color(self, color):
52 | if not isinstance(color, Color):
53 | raise TypeError("Color have not a Color type")
54 |
55 | self.__color = color
56 | self.update_render()
57 |
58 | @property
59 | def font(self):
60 | return self.__font
61 |
62 | @font.setter
63 | def font(self, font):
64 | if not isinstance(font, Font):
65 | raise TypeError("Font have not a Font type")
66 |
67 | self.__font = font
68 | self.update_render()
69 |
70 | @property
71 | def text(self):
72 | return self.__text
73 |
74 | @text.setter
75 | def text(self, text):
76 | self.__text = text
77 | self.update_render()
78 |
79 | def update_render(self):
80 | self.font.background = self.background
81 | self.font.color = self.color
82 | self.image = self.font.render(self.text)
83 | self.update_rect()
84 | if self.parent:
85 | self.parent.update_render()
86 |
87 |
--------------------------------------------------------------------------------
/pyengine/Widgets/MultilineLabel.py:
--------------------------------------------------------------------------------
1 | from typing import Union
2 |
3 | from pyengine.Utils.Color import Colors, Color
4 | from pyengine.Utils.Font import Font
5 | from pyengine.Utils.Logger import loggers
6 | from pyengine.Utils.Vec2 import Vec2
7 | from pyengine.Widgets import Label
8 | from pyengine.Widgets.Widget import Widget
9 |
10 | __all__ = ["MultilineLabel"]
11 |
12 |
13 | class MultilineLabel(Widget):
14 | def __init__(self, position: Vec2, text: str, color: Color = Colors.WHITE.value,
15 | font: Font = Font(), background: Union[None, Color] = None):
16 | super(MultilineLabel, self).__init__(position)
17 |
18 | if not isinstance(font, Font):
19 | raise TypeError("Font have not a Font type")
20 | if not isinstance(color, Color):
21 | raise TypeError("Color have not a Color type")
22 | if not isinstance(background, Color) and background is not None:
23 | raise TypeError("Background must be a Color")
24 |
25 | if "\n" not in text:
26 | loggers.get_logger("PyEngine").info("MultilineLabel without Line break is useless. Use Label.")
27 |
28 | self.__text = text
29 | self.labels = [Label(Vec2(self.position.x, self.position.y + 20*(k+1)), v)
30 | for k, v in enumerate(text.split("\n"))]
31 |
32 | self.__color = color
33 | self.__font = font
34 | self.__background = background
35 | self.update_render()
36 |
37 | @property
38 | def background(self):
39 | return self.__background
40 |
41 | @background.setter
42 | def background(self, color):
43 | if not isinstance(color, Color) and color is not None:
44 | raise TypeError("Background must be a Color")
45 |
46 | self.__background = color
47 | self.update_render()
48 |
49 | @property
50 | def color(self):
51 | return self.__color
52 |
53 | @color.setter
54 | def color(self, color):
55 | if not isinstance(color, Color):
56 | raise TypeError("Color have not a Color type")
57 |
58 | self.__color = color
59 | self.update_render()
60 |
61 | @property
62 | def font(self):
63 | return self.__font
64 |
65 | @font.setter
66 | def font(self, font):
67 | if not isinstance(font, Font):
68 | raise TypeError("Font have not a Font type")
69 |
70 | self.__font = font
71 | self.update_render()
72 |
73 | @property
74 | def system(self):
75 | return self.__system
76 |
77 | @system.setter
78 | def system(self, system):
79 | self.__system = system
80 | [system.add_widget(i) for i in self.labels if i != self]
81 |
82 | @property
83 | def text(self):
84 | return self.__text
85 |
86 | @text.setter
87 | def text(self, text):
88 | if len(self.labels):
89 | [self.system.remove_widget(i) for i in self.labels]
90 | if "\n" not in text:
91 | loggers.get_logger("PyEngine").info("MultilineLabel without Line break is useless. Use Label.")
92 |
93 | self.__text = text
94 | self.labels = [Label(Vec2(self.position.x, self.position.y + 20 * (k + 1)), v)
95 | for k, v in enumerate(text.split("\n"))]
96 | [self.system.add_widget(i) for i in self.labels]
97 | self.update_render()
98 |
99 | def update_render(self):
100 | for i in self.labels:
101 | self.font.color = self.color
102 | self.font.background = self.background
103 | i.image = self.font.render(i.text)
104 | i.update_rect()
105 | if self.parent:
106 | self.parent.update_render()
107 |
108 |
--------------------------------------------------------------------------------
/pyengine/Widgets/ProgressBar.py:
--------------------------------------------------------------------------------
1 | from typing import Tuple
2 |
3 | import pygame
4 |
5 | from pyengine.Utils.Vec2 import Vec2
6 | from pyengine.Utils.Others import clamp
7 | from pyengine.Widgets.Widget import Widget
8 |
9 | __all__ = ["ProgressBar"]
10 |
11 |
12 | class ProgressBar(Widget):
13 | def __init__(self, pos: Vec2, size: Vec2 = Vec2(150, 10), sprites: Tuple[str, str] = None):
14 | super(ProgressBar, self).__init__(pos)
15 |
16 | self.__value = 0
17 | self.__size = size
18 |
19 | self.sprites = sprites
20 |
21 | @property
22 | def value(self):
23 | return self.__value
24 |
25 | @value.setter
26 | def value(self, val):
27 | self.__value = clamp(val, 0, 100)
28 | self.create_image()
29 |
30 | @property
31 | def size(self):
32 | return self.__size
33 |
34 | @size.setter
35 | def size(self, val: Vec2):
36 | self.__size = val
37 | self.create_image()
38 |
39 | @property
40 | def sprites(self):
41 | return self.__sprites
42 |
43 | @sprites.setter
44 | def sprites(self, val: Tuple[str, str]):
45 | self.__sprites = val
46 | self.create_image()
47 |
48 | def create_image(self):
49 | if self.sprites is None:
50 | self.image = pygame.Surface(self.size.coords)
51 | self.image.fill((50, 50, 50))
52 | iiwhite = pygame.Surface([self.size.x - 2, self.size.y - 2])
53 | iiwhite.fill((255, 255, 255))
54 | self.image.blit(iiwhite, (self.image.get_width() / 2 - iiwhite.get_width() / 2,
55 | self.image.get_height() / 2 - iiwhite.get_height() / 2))
56 | iigreen = pygame.Surface([int((self.size.x - 4) * (self.value / 100)), int(self.size.y - 4)])
57 | iigreen.fill((0, 255, 0))
58 | self.image.blit(iigreen, (2, self.image.get_height() / 2 - iigreen.get_height() / 2))
59 | else:
60 | self.image = pygame.image.load(self.sprites[0])
61 | self.image = pygame.transform.scale(self.image, self.size.coords)
62 | barre = pygame.image.load(self.sprites[1])
63 | barre = pygame.transform.scale(barre, [int((self.size.x - 4) * (self.value / 100)), int(self.size.y - 4)])
64 | self.image.blit(barre, (2, self.image.get_height() / 2 - barre.get_height() / 2))
65 |
66 | self.update_rect()
67 |
--------------------------------------------------------------------------------
/pyengine/Widgets/Selector.py:
--------------------------------------------------------------------------------
1 | from pyengine.Utils.Color import Colors
2 | from pyengine.Utils.Font import Font
3 | from pyengine.Utils.Vec2 import Vec2
4 | from pyengine.Widgets import Label, Button
5 | from pyengine.Widgets.Widget import Widget
6 |
7 | __all__ = ["Selector"]
8 |
9 |
10 | class Selector(Widget):
11 | def __init__(self, position: Vec2, strings: (list, tuple)):
12 | super(Selector, self).__init__(position)
13 | if not isinstance(strings, (list, tuple)) or len(strings) == 0:
14 | raise ValueError("Strings must be a list with minimum one str.")
15 |
16 | self.__strings = strings
17 | self.current_index = 0
18 | self.bprecedent = Button(position, "<", self.precedent, size=Vec2(25, 25))
19 | self.label = Label(Vec2(position.x+30, position.y), self.strings[0],
20 | Colors.BLACK.value, Font(size=18))
21 | self.bnext = Button(Vec2(position.x+35+self.maxsize_string(), position.y), ">", self.next, size=Vec2(25, 25))
22 | self.bprecedent.parent = self
23 | self.label.parent = self
24 | self.bnext.parent = self
25 | self.update_render()
26 |
27 | @property
28 | def strings(self):
29 | return self.__strings
30 |
31 | @strings.setter
32 | def strings(self, val: (list, tuple)):
33 | if not isinstance(val, (list, tuple)) or len(val) == 0:
34 | raise ValueError("Strings must be a list with minimum one str.")
35 | self.__strings = val
36 | self.current_index = 0
37 | self.label.text = self.strings[0]
38 | self.bnext.position = Vec2(self.position.x+35+self.maxsize_string(), self.position.y)
39 |
40 | @property
41 | def system(self):
42 | return self.__system
43 |
44 | @system.setter
45 | def system(self, system):
46 | self.__system = system
47 | self.system.add_widget(self.bprecedent)
48 | self.system.add_widget(self.label)
49 | self.system.add_widget(self.bnext)
50 |
51 | def maxsize_string(self):
52 | maxi = 0
53 | for i in self.strings:
54 | size = self.label.font.rendered_size(i)[0]
55 | if maxi < size:
56 | maxi = size
57 | return maxi
58 |
59 | def precedent(self):
60 | if self.current_index == 0:
61 | self.current_index = len(self.strings)-1
62 | else:
63 | self.current_index -= 1
64 | self.label.text = self.strings[self.current_index]
65 |
66 | def next(self):
67 | if self.current_index == len(self.strings) - 1:
68 | self.current_index = 0
69 | else:
70 | self.current_index += 1
71 | self.label.text = self.strings[self.current_index]
72 |
73 | def get(self):
74 | return self.label.text
75 |
76 | def update_render(self):
77 | self.label.position = Vec2(self.position.x + 30 + self.maxsize_string() / 2 -
78 | self.label.font.rendered_size(self.label.text)[0] / 2, self.position.y)
79 |
80 |
81 |
--------------------------------------------------------------------------------
/pyengine/Widgets/Widget.py:
--------------------------------------------------------------------------------
1 | import pygame
2 |
3 | from pyengine.Utils.Vec2 import Vec2
4 |
5 | __all__ = ["Widget"]
6 |
7 |
8 | class Widget(pygame.sprite.Sprite):
9 | def __init__(self, position: Vec2):
10 | super(Widget, self).__init__()
11 |
12 | if not isinstance(position, pygame.Vector2):
13 | raise TypeError("Position must be a Vec2")
14 |
15 | self.identity = -1
16 | self.__position = position
17 | self.__system = None
18 | self.parent = None
19 | self.isshow = True
20 |
21 | self.rect = None # Respect PEP8
22 | self.image = None # Respect PEP8
23 |
24 | @property
25 | def identity(self):
26 | return self.__identity
27 |
28 | @identity.setter
29 | def identity(self, identity):
30 | self.__identity = identity
31 |
32 | @property
33 | def system(self):
34 | return self.__system
35 |
36 | @system.setter
37 | def system(self, system):
38 | self.__system = system
39 |
40 | @property
41 | def position(self):
42 | return self.__position
43 |
44 | @position.setter
45 | def position(self, position):
46 | if not isinstance(position, Vec2):
47 | raise TypeError("Position must be a Vec2")
48 |
49 | self.__position = position
50 | self.update_rect()
51 |
52 | def focusin(self):
53 | pass
54 |
55 | def focusout(self):
56 | pass
57 |
58 | def is_show(self) -> bool:
59 | return self.isshow
60 |
61 | def show(self) -> None:
62 | self.isshow = True
63 | if self.system is not None and self.system.focus != self:
64 | self.system.focus = self
65 | self.focusin()
66 |
67 | def hide(self) -> None:
68 | self.isshow = False
69 | if self.system is not None and self.system.focus == self:
70 | self.system.focus = None
71 | self.focusout()
72 |
73 | def update_rect(self):
74 | if self.image is not None:
75 | self.rect = self.image.get_rect()
76 | self.rect.x = self.position.x
77 | self.rect.y = self.position.y
78 |
79 | def mousepress(self, evt):
80 | if self.image is not None:
81 | if self.rect.x <= evt.pos[0] <= self.rect.x + self.rect.width and self.rect.y <= evt.pos[1] <= self.rect.y\
82 | + self.rect.height:
83 | return True
84 |
--------------------------------------------------------------------------------
/pyengine/Widgets/__init__.py:
--------------------------------------------------------------------------------
1 | from pyengine.Widgets.AnimatedImage import AnimatedImage
2 | from pyengine.Widgets.Button import Button
3 | from pyengine.Widgets.Checkbox import Checkbox
4 | from pyengine.Widgets.Console import Console
5 | from pyengine.Widgets.Entry import Entry
6 | from pyengine.Widgets.Image import Image
7 | from pyengine.Widgets.Label import Label
8 | from pyengine.Widgets.MultilineLabel import MultilineLabel
9 | from pyengine.Widgets.ProgressBar import ProgressBar
10 | from pyengine.Widgets.Selector import Selector
11 |
--------------------------------------------------------------------------------
/pyengine/Window.py:
--------------------------------------------------------------------------------
1 | import pygame
2 | pygame.init()
3 |
4 | from pyengine.World import World
5 | from pyengine.Utils.Color import Colors, Color
6 | from pyengine.Utils.Font import Font
7 | from pyengine.Utils.Logger import loggers
8 |
9 |
10 | import os
11 | import logging
12 | from pygame import locals as const
13 | from typing import Union, Any
14 | from enum import Enum
15 |
16 | __all__ = ["Window", "WindowCallbacks"]
17 |
18 |
19 | class WindowCallbacks(Enum):
20 | OUTOFWINDOW = 1
21 | STOPWINDOW = 2
22 | CHANGEWORLD = 3
23 | RUNWINDOW = 4
24 |
25 |
26 | class Window:
27 | def __init__(self, width: int, height: int, color: Color = Colors.BLACK.value,
28 | title: str = "PyEngine", icon: Union[None, str] = None, limit_fps: Union[None, int] = None,
29 | update_rate: int = 60, debug: bool = False):
30 | if icon is not None:
31 | pygame.display.set_icon(pygame.image.load(icon))
32 |
33 | os.environ['SDL_VIDEO_CENTERED'] = '1'
34 | pygame.display.set_caption(title)
35 |
36 | self.screen = pygame.display.set_mode((width, height))
37 | pygame.scrap.init()
38 | pygame.time.set_timer(const.USEREVENT, round(1000/update_rate))
39 |
40 | self.clock = pygame.time.Clock()
41 | self.width = width
42 | self.update_rate = update_rate
43 | self.height = height
44 | self.__world = World(self)
45 | self.is_running = False
46 | self.debug = debug
47 | self.color = color
48 | self.debugfont = Font("arial", 15, color=Colors.ORANGE.value)
49 | self.fps_label = self.debugfont.render("FPS : "+str(round(self.clock.get_fps())))
50 | self.fps_timer = 30
51 | self.limit_fps = limit_fps
52 |
53 | self.callbacks = {
54 | WindowCallbacks.OUTOFWINDOW: None,
55 | WindowCallbacks.STOPWINDOW: None,
56 | WindowCallbacks.CHANGEWORLD: None,
57 | WindowCallbacks.RUNWINDOW: None
58 | }
59 |
60 | @property
61 | def title(self):
62 | return pygame.display.get_caption()[0]
63 |
64 | @title.setter
65 | def title(self, title):
66 | pygame.display.set_caption(title)
67 |
68 | @property
69 | def color(self):
70 | return self.__color
71 |
72 | @color.setter
73 | def color(self, color):
74 | if not isinstance(color, Color):
75 | raise TypeError("Color have not a Color type")
76 | self.__color = color
77 |
78 | @property
79 | def size(self):
80 | return self.width, self.height
81 |
82 | @size.setter
83 | def size(self, size):
84 | self.width, self.height = size
85 | pygame.display.set_mode(size)
86 |
87 | @property
88 | def debug(self):
89 | return self.__debug
90 |
91 | @debug.setter
92 | def debug(self, debug):
93 | self.__debug = debug
94 |
95 | if debug:
96 | os.environ['SDL_DEBUG'] = '1'
97 | [l.setLevel(logging.DEBUG) for n, l in loggers.get_all()]
98 | else:
99 | try:
100 | del os.environ['SDL_DEBUG']
101 | except KeyError:
102 | pass
103 | [l.setLevel(logging.INFO) for n, l in loggers.get_all()]
104 |
105 | @property
106 | def world(self):
107 | return self.__world
108 |
109 | @world.setter
110 | def world(self, world):
111 | self.__world.stop_world()
112 | self.call(WindowCallbacks.CHANGEWORLD, self.__world, world)
113 | self.__world = world
114 | self.__world.start_world()
115 |
116 | def __process_event(self, evt):
117 | if evt.type == const.QUIT:
118 | self.stop()
119 | elif evt.type == const.KEYDOWN:
120 | self.world.keypress(evt)
121 | elif evt.type == const.MOUSEBUTTONDOWN:
122 | self.world.mousepress(evt)
123 | elif evt.type == const.KEYUP:
124 | self.world.keyup(evt)
125 | elif evt.type == const.MOUSEMOTION:
126 | self.world.mousemotion(evt)
127 | else:
128 | self.world.event(evt)
129 |
130 | def set_callback(self, callback: WindowCallbacks, function: Any) -> None:
131 | if type(callback) == WindowCallbacks:
132 | self.callbacks[callback] = function
133 | else:
134 | raise TypeError("Callback must be a WindowCallback (from WindowCallback Enum)")
135 |
136 | def call(self, callback: WindowCallbacks, *param) -> None:
137 | if type(callback) == WindowCallbacks:
138 | if self.callbacks[callback] is not None:
139 | self.callbacks[callback](*param) # Call function which is represented by the callback
140 | else:
141 | raise TypeError("Callback must be a WindowCallback (from WindowCallback Enum)")
142 |
143 | def stop(self) -> None:
144 | self.is_running = False
145 | self.call(WindowCallbacks.STOPWINDOW)
146 |
147 | def run(self) -> None:
148 | self.is_running = True
149 | self.call(WindowCallbacks.RUNWINDOW)
150 | while self.is_running:
151 | for event in pygame.event.get():
152 | if event.type == const.USEREVENT:
153 | self.fps_timer -= 1
154 | if self.debug and self.fps_timer <= 0:
155 | self.fps_label = self.debugfont.render("FPS : "+str(round(self.clock.get_fps())))
156 | self.fps_timer = 30
157 | self.world.update()
158 | self.__process_event(event)
159 |
160 | self.screen.fill(self.color.get())
161 |
162 | self.world.show()
163 |
164 | if self.debug:
165 | self.screen.blit(self.fps_label, (10, 10))
166 |
167 | if self.limit_fps is None:
168 | self.clock.tick()
169 | else:
170 | self.clock.tick(self.limit_fps)
171 | pygame.display.update()
172 | pygame.quit()
173 |
--------------------------------------------------------------------------------
/pyengine/World.py:
--------------------------------------------------------------------------------
1 | from typing import Type, Union
2 |
3 | import pymunk
4 | from pymunk import pygame_util
5 |
6 | from pyengine.Components import PhysicsComponent
7 | from pyengine.Exceptions import NoObjectError
8 | from pyengine.Systems import EntitySystem, MusicSystem, UISystem, SoundSystem, CameraSystem
9 | from pyengine.Utils.Logger import loggers
10 |
11 | sunion = Union[EntitySystem, MusicSystem, UISystem, SoundSystem, CameraSystem]
12 | stypes = Union[Type[EntitySystem], Type[MusicSystem], Type[UISystem], Type[SoundSystem], Type[CameraSystem]]
13 |
14 | __all__ = ["World"]
15 |
16 |
17 | class World:
18 | def __init__(self, window, gravity=None):
19 | from pyengine import Window # Define Window only on create world
20 |
21 | if not isinstance(window, Window):
22 | raise TypeError("Window have not Window as type")
23 |
24 | if gravity is None:
25 | gravity = [0, -900]
26 |
27 | self.window = window
28 | self.systems = {
29 | "Entity": EntitySystem(self),
30 | "Music": MusicSystem(),
31 | "UI": UISystem(self),
32 | "Sound": SoundSystem(),
33 | "Camera": CameraSystem(self)
34 | }
35 | self.space = pymunk.Space()
36 | self.gravity = gravity
37 | self.__collision = self.space.add_default_collision_handler()
38 | self.__collision.pre_solve = self.collision
39 |
40 | @property
41 | def gravity(self):
42 | return self.__gravity
43 |
44 | @gravity.setter
45 | def gravity(self, val):
46 | self.space.gravity = val
47 | self.__gravity = val
48 |
49 | def collision(self, arb, space, data):
50 | ret = True
51 | e = []
52 | for i in arb.shapes:
53 | j = [e for e in self.systems["Entity"].entities
54 | if e.has_component(PhysicsComponent) and e.get_component(PhysicsComponent).shape == i][0]
55 | if not j.get_component(PhysicsComponent).solid:
56 | ret = False
57 | e.append(j)
58 | for phys in [i.get_component(PhysicsComponent) for i in e]:
59 | if phys.callback is not None:
60 | temp = e.copy()
61 | temp.remove(phys.entity)
62 | phys.callback(phys.entity, temp, space, data)
63 | return ret
64 |
65 | @property
66 | def window(self):
67 | return self.__window
68 |
69 | @window.setter
70 | def window(self, val):
71 | self.__window = val
72 |
73 | def get_system(self, classe: stypes) -> sunion:
74 | liste = [i for i in self.systems.values() if type(i) == classe]
75 | if len(liste):
76 | return liste[0]
77 | loggers.get_logger("PyEngine").warning("Try to get " + str(classe) + " but World don't have it")
78 |
79 | def update(self):
80 | if self.window is None:
81 | raise NoObjectError("World is attached to any Window.")
82 |
83 | self.space.step(1 / 60)
84 |
85 | self.systems["Entity"].update()
86 | self.systems["UI"].update()
87 |
88 | if self.systems["Camera"].entity_follow is not None:
89 | self.systems["Camera"].update()
90 |
91 | def show(self):
92 | if self.window is None:
93 | raise NoObjectError("World is attached to any Window.")
94 | self.systems["Entity"].show(self.window.screen)
95 | self.systems["UI"].show(self.window.screen)
96 | if self.window.debug:
97 | draw_options = pygame_util.DrawOptions(self.window.screen)
98 |
99 | self.space.debug_draw(draw_options)
100 | self.systems["Entity"].show_debug(self.window.screen)
101 | self.systems["UI"].show_debug(self.window.screen)
102 |
103 | def keypress(self, evt):
104 | self.systems["Entity"].keypress(evt)
105 | self.systems["UI"].keypress(evt)
106 |
107 | def mousepress(self, evt):
108 | self.systems["Entity"].mousepress(evt)
109 | self.systems["UI"].mousepress(evt)
110 |
111 | def keyup(self, evt):
112 | self.systems["Entity"].keyup(evt)
113 | self.systems["UI"].keyup(evt)
114 |
115 | def mousemotion(self, evt):
116 | self.systems["UI"].mousemotion(evt)
117 | self.systems["Entity"].mousemotion(evt)
118 |
119 | def event(self, evt):
120 | if evt.type == self.systems["Music"].ENDSOUND:
121 | self.systems["Music"].next_song()
122 |
123 | def stop_world(self):
124 | self.systems["Entity"].stop_world()
125 |
126 | def start_world(self):
127 | pass
128 |
--------------------------------------------------------------------------------
/pyengine/__init__.py:
--------------------------------------------------------------------------------
1 | try:
2 | from pyengine.Window import Window, WindowCallbacks
3 | from pyengine.World import World
4 | from pyengine.Components.ControlComponent import ControlType, Controls, MouseButton
5 | from pygame import locals as const
6 | except ModuleNotFoundError:
7 | pass
8 |
9 | __version__ = "1.6.1"
10 |
--------------------------------------------------------------------------------
/setup.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | # -*- coding: utf-8 -*-
3 |
4 | from setuptools import setup, find_packages
5 |
6 | import pyengine
7 |
8 | setup(
9 |
10 | name='PyEngine-2D',
11 |
12 | version=pyengine.__version__,
13 |
14 | packages=find_packages(),
15 | author="LavaPower",
16 | author_email="lavapower84@gmail.com",
17 | description="A lib to create 2D games",
18 | long_description_content_type="text/markdown",
19 | long_description=open('README.md').read(),
20 |
21 | include_package_data=True,
22 |
23 | url='http://github.com/LavaPower/PyEngine',
24 |
25 | # https://pypi.python.org/pypi?%3Aaction=list_classifiers.
26 | classifiers=[
27 | "Programming Language :: Python",
28 | "Development Status :: 5 - Production/Stable",
29 | "License :: OSI Approved :: GNU General Public License v3 (GPLv3)",
30 | "Natural Language :: English",
31 | "Operating System :: OS Independent",
32 | "Programming Language :: Python :: 3.7",
33 | "Topic :: Software Development :: Libraries :: pygame",
34 | "Intended Audience :: Developers",
35 | ],
36 | install_requires=['pygame<2.0', 'pymunk', 'numpy', 'pillow']
37 |
38 |
39 | )
--------------------------------------------------------------------------------
/test/game.py:
--------------------------------------------------------------------------------
1 | from pyengine import Window, const, Controls, ControlType, WindowCallbacks
2 | from pyengine.Entities import Entity
3 | from pyengine.Components import PositionComponent, SpriteComponent, PhysicsComponent, MoveComponent, ControlComponent
4 | from pyengine.Systems import EntitySystem
5 | from pyengine.Utils import Colors, Vec2
6 | from random import randint
7 |
8 |
9 | class Jeu:
10 | def __init__(self):
11 | self.window = Window(800, 400, Colors.WHITE.value)
12 | self.window.title = "Pong"
13 |
14 | self.window.set_callback(WindowCallbacks.OUTOFWINDOW, self.outofwindow)
15 |
16 | self.j1 = Entity()
17 | self.j1.add_component(PositionComponent(Vec2(10, 175)))
18 | spritej1 = self.j1.add_component(SpriteComponent("images/sprite0.png"))
19 | spritej1.size = Vec2(20, 50)
20 | controlj1 = self.j1.add_component(ControlComponent(ControlType.UPDOWN, 3))
21 | controlj1.set_control(Controls.UPJUMP, const.K_w)
22 | controlj1.set_control(Controls.DOWN, const.K_s)
23 | self.j1.add_component(PhysicsComponent(False))
24 |
25 | self.j2 = Entity()
26 | self.j2.add_component(PositionComponent(Vec2(770, 175)))
27 | spritej2 = self.j2.add_component(SpriteComponent("images/sprite0.png"))
28 | spritej2.size = Vec2(20, 50)
29 | controlj2 = self.j2.add_component(ControlComponent(ControlType.UPDOWN, 3))
30 | controlj2.set_control(Controls.UPJUMP, const.K_UP)
31 | controlj2.set_control(Controls.DOWN, const.K_DOWN)
32 | self.j2.add_component(PhysicsComponent(False))
33 |
34 | self.ball = Entity()
35 | self.ball.add_component(PositionComponent(Vec2(390, 190)))
36 | spriteballe = self.ball.add_component(SpriteComponent("images/sprite0.png"))
37 | spriteballe.size = Vec2(20, 20)
38 | physball = self.ball.add_component(PhysicsComponent(False))
39 | physball.callback = self.collision
40 | self.ball.add_component(MoveComponent(Vec2(randint(50, 100), randint(50, 100))))
41 |
42 | entitysystem = self.window.world.get_system(EntitySystem)
43 | entitysystem.add_entity(self.j1)
44 | entitysystem.add_entity(self.j2)
45 | entitysystem.add_entity(self.ball)
46 |
47 | self.window.run()
48 |
49 | def collision(self, entity, others, space, data):
50 | move = entity.get_component(MoveComponent)
51 | move.direction = Vec2(-move.direction.x, move.direction.y)
52 |
53 | def outofwindow(self, obj, pos):
54 | if obj == self.j1:
55 | position = self.j1.get_component(PositionComponent)
56 | if pos.y <= obj.rect.height / 2:
57 | position.position = Vec2(10, obj.rect.height / 2)
58 | else:
59 | position.position = Vec2(10, 400 - obj.rect.height / 2)
60 |
61 | elif obj == self.j2:
62 | position = self.j2.get_component(PositionComponent)
63 | if pos.y <= obj.rect.height / 2:
64 | position.position = Vec2(770, obj.rect.height / 2)
65 | else:
66 | position.position = Vec2(770, 400 - obj.rect.height / 2)
67 |
68 | else:
69 | if pos.x < 10 or pos.x > 790:
70 | position = self.ball.get_component(PositionComponent)
71 | position.position = Vec2(390, 190)
72 | self.ball.get_component(MoveComponent).direction = Vec2(randint(50, 100), randint(50, 100))
73 | else:
74 | move = self.ball.get_component(MoveComponent)
75 | move.direction = Vec2(move.direction.x, -move.direction.y)
76 |
77 |
78 | Jeu()
79 |
--------------------------------------------------------------------------------
/test/images/idle.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/pyengine3/PyEngine/61378943657bf8a3b0e59ab422dd040fec2bed2a/test/images/idle.png
--------------------------------------------------------------------------------
/test/images/sprite0.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/pyengine3/PyEngine/61378943657bf8a3b0e59ab422dd040fec2bed2a/test/images/sprite0.png
--------------------------------------------------------------------------------
/test/images/sprite1.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/pyengine3/PyEngine/61378943657bf8a3b0e59ab422dd040fec2bed2a/test/images/sprite1.png
--------------------------------------------------------------------------------
/test/images/test.gif:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/pyengine3/PyEngine/61378943657bf8a3b0e59ab422dd040fec2bed2a/test/images/test.gif
--------------------------------------------------------------------------------
/test/tilemap/TESTMAP.json:
--------------------------------------------------------------------------------
1 | { "height":10,
2 | "infinite":false,
3 | "layers":[
4 | {
5 | "data":[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 2, 2, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 0, 0, 0, 0, 1, 1, 1, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 1, 1, 0, 0, 2, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0],
6 | "height":10,
7 | "id":1,
8 | "name":"Calque de Tile 1",
9 | "opacity":1,
10 | "type":"tilelayer",
11 | "visible":true,
12 | "width":10,
13 | "x":0,
14 | "y":0
15 | }],
16 | "nextlayerid":2,
17 | "nextobjectid":1,
18 | "orientation":"orthogonal",
19 | "renderorder":"right-down",
20 | "tiledversion":"1.2.4",
21 | "tileheight":32,
22 | "tilesets":[
23 | {
24 | "firstgid":1,
25 | "source":"tileset\/Test.tsx"
26 | }],
27 | "tilewidth":32,
28 | "type":"map",
29 | "version":1.2,
30 | "width":10
31 | }
--------------------------------------------------------------------------------
/test/tilemap/tileset/Test.tsx:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
--------------------------------------------------------------------------------
/test/tilemap/tileset/sprite0.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/pyengine3/PyEngine/61378943657bf8a3b0e59ab422dd040fec2bed2a/test/tilemap/tileset/sprite0.png
--------------------------------------------------------------------------------
/test/tilemap/tileset/sprite1.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/pyengine3/PyEngine/61378943657bf8a3b0e59ab422dd040fec2bed2a/test/tilemap/tileset/sprite1.png
--------------------------------------------------------------------------------
/tests/ComponentsTests.py:
--------------------------------------------------------------------------------
1 | import unittest
2 | from pyengine.Components import *
3 | from pyengine import ControlType, Controls, const
4 | from pyengine.Entities import Entity
5 | from pyengine.Utils import Vec2, Color, Font
6 | import pygame
7 |
8 |
9 | class PositionTests(unittest.TestCase):
10 | def setUp(self):
11 | self.entity = Entity()
12 | self.component = self.entity.add_component(PositionComponent(Vec2(10, 10)))
13 |
14 | def test_pos(self):
15 | self.assertEqual(self.component.position, Vec2(10, 10))
16 | self.component.position = Vec2(11, 11)
17 | self.assertEqual(self.component.position, Vec2(11, 11))
18 |
19 | def test_offset(self):
20 | self.assertEqual(self.component.offset, Vec2(0, 0))
21 | self.component.offset = Vec2(11, 11)
22 | self.assertEqual(self.component.offset, Vec2(11, 11))
23 |
24 |
25 | class AnimTests(unittest.TestCase):
26 | def setUp(self):
27 | self.entity = Entity()
28 | self.sprite = self.entity.add_component(SpriteComponent("files/sprite0.png"))
29 | self.component = self.entity.add_component(AnimComponent(5, ["files/sprite0.png", "files/sprite1.png"]))
30 |
31 | def test_flip(self):
32 | self.assertFalse(self.component.flipy)
33 | self.assertFalse(self.component.flipx)
34 | self.component.flipy = True
35 | self.component.flipx = True
36 | self.assertTrue(self.component.flipy)
37 | self.assertTrue(self.component.flipx)
38 |
39 | def test_play(self):
40 | self.assertTrue(self.component.play)
41 | self.component.play = False
42 | self.assertFalse(self.component.play)
43 |
44 | def test_time(self):
45 | self.assertEqual(self.component.time, 5)
46 | self.component.time = 2
47 | self.assertEqual(self.component.time, 2)
48 |
49 | def test_images(self):
50 | self.assertEqual(self.component.images, ["files/sprite0.png", "files/sprite1.png"])
51 | self.component.images = ["files/sprite0.png"]
52 | self.assertEqual(self.component.images, ["files/sprite0.png"])
53 |
54 | def test_update(self):
55 | self.component.time = 1
56 | self.component.update()
57 | self.assertEqual(self.component.current_sprite, 0)
58 | self.assertEqual(self.component.timer, 0)
59 | self.assertEqual(self.sprite.sprite, "files/sprite0.png")
60 | self.component.update()
61 | self.assertEqual(self.component.current_sprite, 1)
62 | self.assertEqual(self.component.timer, 0)
63 | self.assertEqual(self.sprite.sprite, "files/sprite1.png")
64 | self.component.update()
65 | self.assertEqual(self.component.current_sprite, 0)
66 | self.assertEqual(self.component.timer, 0)
67 | self.assertEqual(self.sprite.sprite, "files/sprite0.png")
68 |
69 |
70 | class LifeTests(unittest.TestCase):
71 | def setUp(self):
72 | self.entity = Entity()
73 | self.component = self.entity.add_component(LifeComponent(100, self.die))
74 |
75 | def test_life(self):
76 | self.assertEqual(self.component.life, 100)
77 | self.component.life = 50
78 | self.assertEqual(self.component.life, 50)
79 | self.component.life = 500
80 | self.assertEqual(self.component.life, 100)
81 | self.component.life = -5
82 | self.assertEqual(self.component.life, 0)
83 |
84 | def test_maxlife(self):
85 | self.assertEqual(self.component.maxlife, 100)
86 | self.component.maxlife = 110
87 | self.assertEqual(self.component.maxlife, 110)
88 |
89 | def die(self):
90 | self.assertEqual(self.component.life, 0)
91 |
92 |
93 | class ControlTests(unittest.TestCase):
94 | def setUp(self):
95 | self.entity = Entity()
96 | self.component = ControlComponent(ControlType.FOURDIRECTION)
97 |
98 | def test_speed(self):
99 | self.assertEqual(self.component.speed, 250)
100 | self.component.speed = 4
101 | self.assertEqual(self.component.speed, 4)
102 |
103 | def test_controls(self):
104 | self.assertEqual(self.component.get_control(Controls.LEFT), const.K_LEFT)
105 | self.component.set_control(Controls.UPJUMP, const.K_SPACE)
106 | self.assertEqual(self.component.get_control(Controls.UPJUMP), const.K_SPACE)
107 |
108 |
109 | class MoveTests(unittest.TestCase):
110 | def setUp(self):
111 | self.entity = Entity()
112 | self.p = self.entity.add_component(PositionComponent(Vec2(10, 10)))
113 | self.component = self.entity.add_component(MoveComponent(Vec2(10, 10)))
114 |
115 | def test_direction(self):
116 | self.assertEqual(self.component.direction, Vec2(10, 10))
117 | self.component.direction = Vec2(5, 5)
118 | self.assertEqual(self.component.direction, Vec2(5, 5))
119 |
120 | def test_move(self):
121 | self.assertEqual(self.p.position, Vec2(10, 10))
122 | self.component.update()
123 | self.assertEqual(self.p.position, Vec2(20, 20))
124 |
125 |
126 | class FakeEntitySystem:
127 | def __init__(self):
128 | self.entities = pygame.sprite.Group()
129 |
130 |
131 | class PhysicsTests(unittest.TestCase):
132 | def setUp(self):
133 | self.entity = Entity()
134 | self.entity.system = FakeEntitySystem()
135 | self.entity.add_component(SpriteComponent("files/sprite0.png"))
136 | self.component = self.entity.add_component(PhysicsComponent())
137 | self.p = self.entity.add_component(PositionComponent(Vec2(10, 10)))
138 |
139 | def test_callback(self):
140 | self.assertEqual(self.component.callback, None)
141 | self.component.callback = self.callback
142 | self.assertEqual(self.component.callback, self.callback)
143 |
144 | def callback(self, entity, others, space, data):
145 | pass
146 |
147 |
148 | class SpriteTests(unittest.TestCase):
149 | def setUp(self):
150 | self.entity = Entity()
151 | self.component = self.entity.add_component(SpriteComponent("files/sprite0.png"))
152 | self.basesize = [self.entity.image.get_rect().width, self.entity.image.get_rect().height]
153 |
154 | def test_flip(self):
155 | self.assertFalse(self.component.flipy)
156 | self.assertFalse(self.component.flipx)
157 | self.component.flipy = True
158 | self.component.flipx = True
159 | self.assertTrue(self.component.flipy)
160 | self.assertTrue(self.component.flipx)
161 |
162 | def text_size(self):
163 | self.assertEqual(self.component.size, self.basesize)
164 | self.component.size = [1, 1]
165 | self.assertEqual(self.component.size, [1, 1])
166 |
167 | def test_scale(self):
168 | self.assertEqual(self.component.scale, 1)
169 | self.component.scale = 2
170 | self.assertEqual(self.component.scale, 2)
171 | self.assertEqual([x*self.component.scale for x in self.component.size],
172 | [self.basesize[0]*2, self.basesize[1]*2])
173 |
174 | def test_rotation(self):
175 | self.assertEqual(self.component.rotation, 0)
176 | self.component.rotation = 10
177 | self.assertEqual(self.component.rotation, 10)
178 | self.component.rotation = 45
179 | self.assertEqual(self.component.rotation, 45)
180 |
181 | def test_sprite(self):
182 | self.assertEqual(self.component.sprite, "files/sprite0.png")
183 | self.component.sprite = "files/sprite1.png"
184 | self.assertEqual(self.component.sprite, "files/sprite1.png")
185 |
186 |
187 | class TextTests(unittest.TestCase):
188 | def setUp(self):
189 | pygame.init()
190 | self.entity = Entity()
191 | self.component = self.entity.add_component(TextComponent("test"))
192 |
193 | def test_rendered_size(self):
194 | self.assertEqual(self.component.size, (24, 18))
195 | self.component.text = "OUI"
196 | self.assertEqual(self.component.size, (25, 18))
197 |
198 | def test_scale(self):
199 | self.assertEqual(self.component.scale, 1)
200 | rect = self.entity.image.get_rect()
201 | basesize = [rect.width, rect.height]
202 | self.component.scale = 2
203 | self.assertEqual(self.component.scale, 2)
204 | rect = self.entity.image.get_rect()
205 | self.assertEqual([rect.width, rect.height], [basesize[0] * 2, basesize[1] * 2])
206 |
207 | def test_text(self):
208 | self.assertEqual(self.component.text, "test")
209 | self.component.text = "OUI"
210 | self.assertEqual(self.component.text, "OUI")
211 |
212 | def test_color(self):
213 | self.assertEqual(self.component.color, Color())
214 | self.component.color = Color(2, 23, 2)
215 | self.assertEqual(self.component.color, Color(2, 23, 2))
216 |
217 | def test_font(self):
218 | self.assertEqual(self.component.font, Font())
219 | self.component.font = Font("arial", 13)
220 | self.assertEqual(self.component.font, Font("arial", 13))
221 |
222 | def test_background(self):
223 | self.assertEqual(self.component.background, None)
224 | self.component.background = Color()
225 | self.assertEqual(self.component.background, Color())
226 |
--------------------------------------------------------------------------------
/tests/EntitiesTests.py:
--------------------------------------------------------------------------------
1 | from pyengine.Entities import *
2 | from pyengine.Utils import Vec2
3 | from pyengine.Components import *
4 | from pyengine.Exceptions import CompatibilityError
5 | from pyengine import ControlType
6 | import unittest
7 |
8 |
9 | class TilemapTests(unittest.TestCase):
10 | def setUp(self):
11 | self.tilemap = Tilemap(Vec2(), "files/tilemap/TESTMAP.json")
12 |
13 | def test_tilemap(self):
14 | self.assertEqual(self.tilemap.folder, "files/tilemap/")
15 | self.assertEqual(len(self.tilemap.tiles), 21)
16 |
17 | def test_scale(self):
18 | self.assertEqual(self.tilemap.scale, 1)
19 | self.tilemap.scale = 2
20 | self.assertEqual(self.tilemap.scale, 2)
21 |
22 |
23 | class CustomComponent(TextComponent):
24 | def __init__(self):
25 | super(CustomComponent, self).__init__("CUSTOM")
26 |
27 |
28 | class EntityTests(unittest.TestCase):
29 | def setUp(self):
30 | self.e = Entity()
31 | self.components = [
32 | PositionComponent(Vec2(10, 10)),
33 | SpriteComponent("files/sprite0.png"),
34 | PhysicsComponent(),
35 | LifeComponent(100),
36 | MoveComponent(Vec2(1, 1)),
37 | ControlComponent(ControlType.FOURDIRECTION)
38 | ]
39 |
40 | def test_attached_entity(self):
41 | e2 = Entity()
42 | self.e.attach_entity(e2)
43 | self.assertTrue(e2 in self.e.attachedentities)
44 |
45 | def test_custom_components(self):
46 | self.assertFalse(self.e.has_component(TextComponent))
47 | self.assertFalse(self.e.has_component(CustomComponent))
48 | self.e.add_component(CustomComponent())
49 | self.assertTrue(self.e.has_component(TextComponent))
50 | self.assertTrue(self.e.has_component(CustomComponent))
51 |
52 | def test_components(self):
53 | with self.assertRaises(TypeError):
54 | self.e.add_component(1)
55 | for i in self.components:
56 | self.e.add_component(i)
57 | with self.assertRaises(CompatibilityError):
58 | self.e.add_component(TextComponent(""))
59 | for i in self.components:
60 | self.assertTrue(self.e.has_component(type(i)))
61 | self.assertFalse(self.e.has_component(TextComponent))
62 | for i in self.components:
63 | self.assertEqual(self.e.get_component(type(i)), i)
64 | self.e.remove_component(PhysicsComponent)
65 | self.assertFalse(self.e.has_component(PhysicsComponent))
66 |
--------------------------------------------------------------------------------
/tests/NetworkTests.py:
--------------------------------------------------------------------------------
1 | from pyengine.Network import *
2 | import unittest
3 |
4 |
5 | class NetworkTests(unittest.TestCase):
6 | def setUp(self):
7 | self.nw = NetworkManager()
8 | try:
9 | self.nw.create_client("localhost", 22112, self.callback)
10 | except ConnectionRefusedError:
11 | pass
12 |
13 | def test_send(self):
14 | if self.nw.client is None:
15 | self.skipTest("Client doesn't exist (Server musn't be launched)")
16 | else:
17 | self.nw.client.send("TOALL", 0, "Ceci est un test")
18 |
19 | def callback(self, type_, author, message):
20 | if type_ == "TOALL":
21 | self.assertEqual(type_, "TOALL")
22 | self.assertEqual(message, "Ceci est un test")
23 | self.nw.stop_client()
24 | self.nw.stop_server()
25 |
--------------------------------------------------------------------------------
/tests/SystemsTests.py:
--------------------------------------------------------------------------------
1 | import unittest
2 | from pyengine.Systems import *
3 | from pyengine.Utils import Vec2
4 | from pyengine.Entities import Entity
5 | from pyengine.Widgets import Label
6 | from pyengine.Exceptions import NoObjectError
7 | from pyengine.Components import PositionComponent, TextComponent, SpriteComponent
8 |
9 |
10 | class MusicTests(unittest.TestCase):
11 | def setUp(self):
12 | self.system = MusicSystem()
13 |
14 | def test_loop(self):
15 | self.assertEqual(self.system.loop, False)
16 | self.system.loop = True
17 | self.assertEqual(self.system.loop, True)
18 |
19 | def test_volume(self):
20 | self.assertEqual(self.system.volume, 100)
21 | with self.assertRaises(ValueError):
22 | self.system.volume = 102
23 | self.system.volume = 40
24 | self.assertEqual(self.system.volume, 40)
25 |
26 | def test_queue(self):
27 | self.assertEqual(self.system.queue, [])
28 | self.system.add("test")
29 | self.assertEqual(self.system.queue, ["test"])
30 | self.system.clear_queue()
31 | self.assertEqual(self.system.queue, [])
32 |
33 |
34 | class SoundTests(unittest.TestCase):
35 | def setUp(self):
36 | self.system = SoundSystem()
37 |
38 | def test_nb_channel(self):
39 | self.assertEqual(self.system.number_channel, 8)
40 | self.system.number_channel = 10
41 | self.assertEqual(self.system.number_channel, 10)
42 |
43 | def test_volume(self):
44 | self.assertEqual(self.system.volume, 100)
45 | with self.assertRaises(ValueError):
46 | self.system.volume = 102
47 | self.system.volume = 40
48 | self.assertEqual(self.system.volume, 40)
49 |
50 |
51 | class FakeWorld:
52 | def __init__(self):
53 | pass
54 |
55 |
56 | class CameraTests(unittest.TestCase):
57 | def setUp(self):
58 | self.system = CameraSystem(FakeWorld())
59 |
60 | def test_entity_follow(self):
61 | self.assertEqual(self.system.entity_follow, None)
62 |
63 | def test_offset(self):
64 | self.assertEqual(self.system.offset, Vec2())
65 | self.system.offset = Vec2(1, 1)
66 | self.assertEqual(self.system.offset, Vec2(1, 1))
67 |
68 |
69 | class UITests(unittest.TestCase):
70 | def setUp(self):
71 | self.system = UISystem(FakeWorld())
72 | self.w = Label(Vec2(), "")
73 |
74 | def test_management_widget(self):
75 | self.system.add_widget(self.w)
76 | self.assertEqual(self.system.get_widget(0), self.w)
77 | self.assertEqual(self.system.has_widget(self.w), True)
78 | self.system.remove_widget(self.w)
79 | self.assertEqual(self.system.has_widget(self.w), False)
80 |
81 |
82 | class EntityTests(unittest.TestCase):
83 | def setUp(self):
84 | self.system = EntitySystem(FakeWorld())
85 | self.e = Entity()
86 |
87 | def test_management_entity(self):
88 | with self.assertRaises(NoObjectError):
89 | self.system.add_entity(self.e)
90 | self.e.add_component(PositionComponent(Vec2()))
91 | with self.assertRaises(NoObjectError):
92 | self.system.add_entity(self.e)
93 | self.e.add_component(SpriteComponent("files/sprite0.png"))
94 | self.system.add_entity(self.e)
95 | self.assertIn(self.e, self.system.entities.sprites())
96 | self.assertEqual(self.system.get_entity(0), self.e)
97 | self.assertEqual(self.system.has_entity(self.e), True)
98 | self.system.remove_entity(self.e)
99 | self.assertEqual(self.system.has_entity(self.e), False)
100 |
101 | def test_management_text(self):
102 | with self.assertRaises(NoObjectError):
103 | self.system.add_entity(self.e)
104 | self.e.add_component(PositionComponent(Vec2()))
105 | with self.assertRaises(NoObjectError):
106 | self.system.add_entity(self.e)
107 | self.e.add_component(TextComponent(""))
108 | self.system.add_entity(self.e)
109 | self.assertIn(self.e, self.system.entities.sprites())
110 | self.assertEqual(self.system.get_entity(0), self.e)
111 | self.assertEqual(self.system.has_entity(self.e), True)
112 | self.system.remove_entity(self.e)
113 | self.assertEqual(self.system.has_entity(self.e), False)
114 |
--------------------------------------------------------------------------------
/tests/UtilsTests.py:
--------------------------------------------------------------------------------
1 | import unittest
2 | from pyengine.Utils import *
3 | import os
4 |
5 |
6 | class OthersTests(unittest.TestCase):
7 | def test_clamp(self):
8 | self.assertEqual(clamp(1, 0, 2), 1)
9 | self.assertEqual(clamp(3, 0, 2), 2)
10 | self.assertEqual(clamp(-1, 0, 2), 0)
11 | self.assertEqual(clamp(1, 0), 1)
12 | self.assertEqual(clamp(-1, 0), 0)
13 | self.assertEqual(clamp(1, maxi=3), 1)
14 | self.assertEqual(clamp(4, maxi=3), 3)
15 | self.assertEqual(clamp(1), 1)
16 |
17 | def test_wrap_text(self):
18 | self.assertEqual(wrap_text("oui oui", Font(), 0), "")
19 | self.assertEqual(wrap_text("oui oui", Font(), 50), "oui oui")
20 | self.assertEqual(wrap_text("oui oui", Font(), 20), "oui\noui")
21 |
22 |
23 | class ColorTests(unittest.TestCase):
24 | def setUp(self):
25 | self.color = Color()
26 |
27 | def test_color(self):
28 | self.assertEqual(self.color.get(), (255, 255, 255, 255))
29 | self.color = Color(1, 2, 3)
30 | self.assertEqual(self.color.get(), (1, 2, 3, 255))
31 |
32 | def test_to_hex(self):
33 | self.assertEqual(self.color.to_hex(), "#FFFFFFFF")
34 | self.color = Color(21, 66, 19)
35 | self.assertEqual(self.color.to_hex(), "#154213FF")
36 |
37 | def test_from_hex(self):
38 | with self.assertRaises(ValueError):
39 | self.color.from_hex("#13")
40 | self.color.from_hex("#154213")
41 | self.assertEqual(self.color.get(), (21, 66, 19, 255))
42 |
43 | def test_ope_arith(self):
44 | self.assertEqual(self.color.get(), (255, 255, 255, 255))
45 | self.color -= Color(255, 0, 0)
46 | self.assertEqual(self.color.get(), (0, 255, 255, 0))
47 | self.color += Color(125, 0, 0)
48 | self.assertEqual(self.color.get(), (125, 255, 255, 255))
49 | self.color += Color(0, 0, 1)
50 | self.assertEqual(self.color.get(), (125, 255, 255, 255))
51 | self.color -= Color(255, 0, 0)
52 | self.assertEqual(self.color.get(), (0, 255, 255, 0))
53 |
54 | def test_ope_log(self):
55 | self.assertTrue(self.color == Color())
56 | self.assertTrue(self.color != Color(1, 1, 1))
57 |
58 | def test_function(self):
59 | self.color = Color(150, 150, 150)
60 | self.assertEqual(self.color.lighter().get(), (160, 160, 160, 255))
61 | self.assertEqual(self.color.darker().get(), (140, 140, 140, 255))
62 |
63 | def test_enum(self):
64 | self.assertEqual(Colors.BLACK.value.get(), (0, 0, 0, 255))
65 | self.assertEqual(Colors.WHITE.value.get(), (255, 255, 255, 255))
66 | self.assertEqual(Colors.RED.value.get(), (255, 0, 0, 255))
67 | self.assertEqual(Colors.BLUE.value.get(), (0, 0, 255, 255))
68 | self.assertEqual(Colors.GREEN.value.get(), (0, 255, 0, 255))
69 |
70 |
71 | class FontTests(unittest.TestCase):
72 | def setUp(self):
73 | self.font = Font()
74 |
75 | def test_name(self):
76 | self.assertEqual(self.font.name, "arial")
77 | self.font.name = "Lucida"
78 | self.assertEqual(self.font.name, "Lucida")
79 |
80 | def test_size(self):
81 | self.assertEqual(self.font.size, 15)
82 | self.font.size = 20
83 | self.assertEqual(self.font.size, 20)
84 |
85 | def test_bold(self):
86 | self.assertFalse(self.font.bold)
87 | self.font.bold = True
88 | self.assertTrue(self.font.bold)
89 |
90 | def test_italic(self):
91 | self.assertFalse(self.font.italic)
92 | self.font.italic = True
93 | self.assertTrue(self.font.italic)
94 |
95 | def test_ope_log(self):
96 | self.assertTrue(self.font == Font())
97 | self.assertTrue(self.font != Font("Lucida"))
98 |
99 | def test_rendered_size(self):
100 | self.assertEqual(self.font.rendered_size("test"), (24, 18))
101 | self.assertEqual(self.font.rendered_size("OUI"), (25, 18))
102 |
103 |
104 | class Vec2Tests(unittest.TestCase):
105 | def setUp(self):
106 | self.vec = Vec2()
107 |
108 | def test_coords(self):
109 | self.assertEqual(self.vec.coords, (0, 0))
110 | self.vec.coords = [1, 1]
111 | self.assertEqual(self.vec.coords, (1, 1))
112 |
113 | def test_length(self):
114 | self.assertEqual(self.vec.length(), 0)
115 | self.vec.coords = [0, 1]
116 | self.assertEqual(self.vec.length(), 1)
117 |
118 | def test_normalized(self):
119 | with self.assertRaises(ValueError):
120 | self.vec.normalize()
121 | self.vec.coords = [0, 2]
122 | self.assertEqual(self.vec.normalize(), Vec2(0, 1))
123 |
124 | def test_ope_arith(self):
125 | self.assertEqual(self.vec + Vec2(1, 0), Vec2(1, 0))
126 | self.assertEqual(self.vec - Vec2(1, 0), Vec2(-1, 0))
127 | self.assertEqual(Vec2(2, 2) * Vec2(1, 0), 2.0)
128 | self.assertEqual(Vec2(2, 2) * 2, Vec2(4, 4))
129 | self.assertEqual(-Vec2(1, 1), Vec2(-1, -1))
130 | self.assertEqual(Vec2(2, 2) / 2, Vec2(1, 1))
131 |
132 | def test_ope_log(self):
133 | self.assertTrue(self.vec == Vec2())
134 | self.assertTrue(self.vec != Vec2(1, 0))
135 |
136 | def test_repr(self):
137 | self.assertEqual(self.vec.__repr__(), "")
138 |
139 | def test_iter(self):
140 | for i in self.vec:
141 | self.assertEqual(i, 0)
142 |
143 |
144 | class LoggersTests(unittest.TestCase):
145 | def setUp(self):
146 | self.log = loggers.create_logger("Test", "logs/test.log", False)
147 |
148 | def test_loggers(self):
149 | with self.assertRaises(KeyError):
150 | loggers.get_logger("B")
151 | self.assertEqual(self.log, loggers.get_logger("Test"))
152 |
153 | def test_write(self):
154 | self.log.info("TEST")
155 | with open("logs/test.log") as f:
156 | self.assertEqual(f.readlines()[-1].split(" ")[-1], "TEST\n")
157 | loggers.get_logger("PyEngine").info("TEST")
158 | with open("logs/pyengine.log") as f:
159 | self.assertEqual(f.readlines()[-1].split(" ")[-1], "TEST\n")
160 |
161 |
162 | class LangTests(unittest.TestCase):
163 | def setUp(self):
164 | self.lang = Lang("files/fr.lang")
165 |
166 | def test_lang(self):
167 | self.assertEqual(self.lang.get_translate("accueil", "OUI"), "Bonjour")
168 | self.assertEqual(self.lang.get_translate("wut", "OUI"), "OUI")
169 | self.lang.file = "files/en.lang"
170 | self.assertEqual(self.lang.get_translate("accueil", "OUI"), "Hello")
171 | self.assertEqual(self.lang.get_translate("wut", "OUI"), "OUI")
172 |
173 |
174 | class ConfigTests(unittest.TestCase):
175 | def setUp(self):
176 | self.config = Config("config.conf")
177 |
178 | def test_create(self):
179 | self.config.create({"rep": "oui"})
180 | self.assertEqual(self.config.get("rep"), "oui")
181 | self.assertIsNone(self.config.get("wut"))
182 | self.config.set("rep", "non")
183 | self.assertEqual(self.config.get("rep"), "non")
184 | self.config.save()
185 | self.config.file = "config.conf"
186 | self.assertEqual(self.config.get("rep"), "non")
187 | self.assertIsNone(self.config.get("wut"))
188 | os.remove("config.conf")
189 |
190 |
--------------------------------------------------------------------------------
/tests/WidgetsTests.py:
--------------------------------------------------------------------------------
1 | import unittest
2 | from pyengine.Widgets import *
3 | from pyengine.Utils import Vec2, Color, Font, Colors
4 | from pyengine.Systems import UISystem
5 |
6 | import pygame
7 |
8 | # UTILITIES CLASS FOR TESTS #
9 |
10 |
11 | class FakeWorld:
12 | def __init__(self):
13 | pass
14 |
15 |
16 | # TESTS #
17 |
18 |
19 | class WidgetTests(unittest.TestCase):
20 | def setUp(self):
21 | pygame.init()
22 | self.widget = None
23 |
24 | def test_pos(self):
25 | if self.widget is not None:
26 | self.assertEqual(self.widget.position, Vec2(10, 10))
27 | self.widget.position = Vec2(11, 11)
28 | self.assertEqual(self.widget.position, Vec2(11, 11))
29 |
30 |
31 | class LabelTests(WidgetTests):
32 | def setUp(self):
33 | super(LabelTests, self).setUp()
34 | self.widget = Label(Vec2(10, 10), "test")
35 |
36 | def test_text(self):
37 | self.assertEqual(self.widget.text, "test")
38 | self.widget.text = "OUI"
39 | self.assertEqual(self.widget.text, "OUI")
40 |
41 | def test_color(self):
42 | self.assertEqual(self.widget.color, Color())
43 | self.widget.color = Color(2, 23, 2)
44 | self.assertEqual(self.widget.color, Color(2, 23, 2))
45 |
46 | def test_font(self):
47 | self.assertEqual(self.widget.font, Font())
48 | self.widget.font = Font("arial", 13)
49 | self.assertEqual(self.widget.font, Font("arial", 13))
50 |
51 | def test_background(self):
52 | self.assertEqual(self.widget.background, None)
53 | self.widget.background = Color()
54 | self.assertEqual(self.widget.background, Color())
55 |
56 |
57 | class MultilineLabelTests(WidgetTests):
58 | def setUp(self):
59 | super(MultilineLabelTests, self).setUp()
60 | self.system = UISystem(FakeWorld())
61 | self.widget = MultilineLabel(Vec2(10, 10), "test")
62 | self.system.add_widget(self.widget)
63 |
64 | def test_text(self):
65 | self.assertEqual(self.widget.text, "test")
66 | self.assertEqual(len(self.widget.labels), 1)
67 | self.assertEqual(self.widget.labels[0].text, "test")
68 | self.widget.text = "OUI\ntest"
69 | self.assertEqual(self.widget.text, "OUI\ntest")
70 | self.assertEqual(len(self.widget.labels), 2)
71 | self.assertEqual(self.widget.labels[0].text, "OUI")
72 | self.assertEqual(self.widget.labels[1].text, "test")
73 |
74 | def test_color(self):
75 | self.assertEqual(self.widget.color, Color())
76 | self.widget.color = Color(2, 23, 2)
77 | self.assertEqual(self.widget.color, Color(2, 23, 2))
78 |
79 | def test_font(self):
80 | self.assertEqual(self.widget.font, Font())
81 | self.widget.font = Font("arial", 13)
82 | self.assertEqual(self.widget.font, Font("arial", 13))
83 |
84 | def test_background(self):
85 | self.assertEqual(self.widget.background, None)
86 | self.widget.background = Color()
87 | self.assertEqual(self.widget.background, Color())
88 |
89 |
90 | class ImageTests(WidgetTests):
91 | def setUp(self):
92 | super(ImageTests, self).setUp()
93 | self.widget = Image(Vec2(10, 10), "files/sprite0.png")
94 |
95 | def test_sprite(self):
96 | self.assertEqual(self.widget.sprite, "files/sprite0.png")
97 | self.widget.sprite = "files/sprite1.png"
98 | self.assertEqual(self.widget.sprite, "files/sprite1.png")
99 |
100 | def test_size(self):
101 | self.assertEqual(self.widget.size,
102 | Vec2(self.widget.image.get_rect().width, self.widget.image.get_rect().height))
103 | self.widget.size = Vec2(10, 10)
104 | self.assertEqual(Vec2(self.widget.image.get_rect().width, self.widget.image.get_rect().height), Vec2(10, 10))
105 |
106 |
107 | class AnimatedImageTests(WidgetTests):
108 | def setUp(self):
109 | super(AnimatedImageTests, self).setUp()
110 | self.widget = AnimatedImage(Vec2(10, 10), ["files/sprite0.png", "files/sprite1.png"], 1)
111 |
112 | def test_sprites(self):
113 | self.assertEqual(self.widget.sprites, ["files/sprite0.png", "files/sprite1.png"])
114 | self.widget.sprites = ["files/sprite0.png"]
115 | self.assertEqual(self.widget.sprites, ["files/sprite0.png"])
116 |
117 | def test_size(self):
118 | self.assertEqual(self.widget.size,
119 | Vec2(self.widget.image.get_rect().width, self.widget.image.get_rect().height))
120 | self.widget.size = Vec2(10, 10)
121 | self.assertEqual(Vec2(self.widget.image.get_rect().width, self.widget.image.get_rect().height), Vec2(10, 10))
122 |
123 | def test_animation(self):
124 | self.assertEqual(self.widget.sprite, "files/sprite0.png")
125 | self.widget.update()
126 | self.assertEqual(self.widget.sprite, "files/sprite1.png")
127 | self.widget.update()
128 | self.assertEqual(self.widget.sprite, "files/sprite0.png")
129 | self.widget.update()
130 | self.assertEqual(self.widget.sprite, "files/sprite1.png")
131 |
132 |
133 | class CheckboxTests(WidgetTests):
134 | def setUp(self):
135 | super(CheckboxTests, self).setUp()
136 | self.widget = Checkbox(Vec2(10, 10), "test")
137 |
138 | def test_text(self):
139 | self.assertEqual(self.widget.label.text, "test")
140 | self.widget.label.text = "OUI"
141 | self.assertEqual(self.widget.label.text, "OUI")
142 |
143 | def test_scale(self):
144 | self.assertEqual(self.widget.scale, 1)
145 | self.widget.scale = 2
146 | self.assertEqual(self.widget.scale, 2)
147 |
148 | def test_checked(self):
149 | self.assertFalse(self.widget.checked)
150 | self.widget.checked = True
151 | self.assertTrue(self.widget.checked)
152 |
153 |
154 | class ProgressBarTests(WidgetTests):
155 | def setUp(self):
156 | super(ProgressBarTests, self).setUp()
157 | self.widget = ProgressBar(Vec2(10, 10))
158 |
159 | def test_value(self):
160 | self.assertEqual(self.widget.value, 0)
161 | self.widget.value = 2
162 | self.assertEqual(self.widget.value, 2)
163 |
164 | def test_size(self):
165 | self.assertEqual(self.widget.size, Vec2(150, 10))
166 | self.widget.size = Vec2(300, 20)
167 | self.assertEqual(self.widget.size, Vec2(300, 20))
168 |
169 | def test_sprites(self):
170 | self.assertIsNone(self.widget.sprites)
171 | self.widget.sprites = ["files/sprite0.png", "files/sprite1.png"]
172 | self.assertEqual(self.widget.sprites, ["files/sprite0.png", "files/sprite1.png"])
173 |
174 |
175 | class ButtonTests(WidgetTests):
176 | def setUp(self):
177 | super(ButtonTests, self).setUp()
178 | self.widget = Button(Vec2(10, 10), "test")
179 |
180 | def test_text(self):
181 | self.assertEqual(self.widget.label.text, "test")
182 | self.widget.label.text = "OUI"
183 | self.assertEqual(self.widget.label.text, "OUI")
184 |
185 | def test_sprite(self):
186 | self.assertEqual(self.widget.sprite, None)
187 | self.widget.sprite = "files/sprite1.png"
188 | self.assertEqual(self.widget.sprite, "files/sprite1.png")
189 |
190 | def test_size(self):
191 | self.assertEqual(self.widget.size, Vec2(100, 40))
192 | self.widget.size = Vec2(100, 50)
193 | self.assertEqual(self.widget.size, Vec2(100, 50))
194 |
195 | def test_command(self):
196 | self.assertEqual(self.widget.command, None)
197 | self.widget.command = self.command
198 | self.assertEqual(self.widget.command, self.command)
199 |
200 | def command(self):
201 | pass
202 |
203 |
204 | class SelectorTests(WidgetTests):
205 | def setUp(self):
206 | super(SelectorTests, self).setUp()
207 | self.widget = Selector(Vec2(10, 10), ["Michel", "Mamadou"])
208 |
209 | def test_get(self):
210 | self.assertEqual(self.widget.get(), "Michel")
211 | self.widget.next()
212 | self.assertEqual(self.widget.get(), "Mamadou")
213 | self.widget.next()
214 | self.assertEqual(self.widget.get(), "Michel")
215 | self.widget.precedent()
216 | self.assertEqual(self.widget.get(), "Mamadou")
217 | self.widget.precedent()
218 | self.assertEqual(self.widget.get(), "Michel")
219 |
220 | def test_strings(self):
221 | self.assertEqual(self.widget.strings, ["Michel", "Mamadou"])
222 | self.assertEqual(self.widget.get(), "Michel")
223 | self.widget.strings = ["Ou", "Pas"]
224 | self.assertEqual(self.widget.strings, ["Ou", "Pas"])
225 | self.assertEqual(self.widget.get(), "Ou")
226 | with self.assertRaises(ValueError):
227 | self.widget.strings = []
228 |
229 |
230 | class EntryTests(WidgetTests):
231 | def setUp(self):
232 | super(EntryTests, self).setUp()
233 | self.widget = Entry(Vec2(10, 10))
234 |
235 | def test_text(self):
236 | self.assertEqual(self.widget.text, "")
237 | self.widget.text = "test"
238 | self.assertEqual(self.widget.text, "test")
239 |
240 | def test_width(self):
241 | self.assertEqual(self.widget.width, 200)
242 | self.widget.width = 400
243 | self.assertEqual(self.widget.width, 400)
244 |
245 | def test_color(self):
246 | self.assertEqual(self.widget.color, Colors.BLACK.value)
247 | self.widget.color = Colors.GREEN.value
248 | self.assertEqual(self.widget.color, Colors.GREEN.value)
249 |
250 |
251 | class ConsoleTests(WidgetTests):
252 | def setUp(self):
253 | super(ConsoleTests, self).setUp()
254 | self.widget = Console(None, Vec2(10, -10)) # Console add +20 to her y pos for the response label
255 |
256 | def test_commands(self):
257 | from pyengine.Widgets.Console import print_command
258 | self.assertEqual(self.widget.commands["print"], print_command)
259 | self.widget.add_command("test", self.setUp)
260 | self.assertEqual(self.widget.commands["test"], self.setUp)
261 | self.widget.delete_command("test")
262 | with self.assertRaises(KeyError):
263 | print(self.widget.commands["test"])
264 | with self.assertRaises(ValueError):
265 | self.widget.delete_command("test")
266 |
267 | def test_reply(self):
268 | self.assertEqual(self.widget.retour.text, ">")
269 | self.widget.reply()
270 | self.assertEqual(self.widget.retour.text, "> ")
271 | self.widget.reply("OUI")
272 | self.assertEqual(self.widget.retour.text, "> OUI")
273 |
--------------------------------------------------------------------------------
/tests/WindowTests.py:
--------------------------------------------------------------------------------
1 | import unittest
2 | from pyengine import Window, WindowCallbacks
3 | from pyengine.Utils import Color
4 |
5 |
6 | class WindowTests(unittest.TestCase):
7 | def setUp(self):
8 | self.window = Window(100, 100)
9 |
10 | def test_update_rate(self):
11 | self.assertEqual(self.window.update_rate, 60)
12 |
13 | def test_title(self):
14 | self.assertEqual(self.window.title, "PyEngine")
15 | self.window.title = "OUI"
16 | self.assertEqual(self.window.title, "OUI")
17 |
18 | def test_is_running(self):
19 | self.assertFalse(self.window.is_running)
20 | self.window.run()
21 | self.assertFalse(self.window.is_running) # Code blocked while window run.
22 |
23 | def test_color(self):
24 | self.assertEqual(self.window.color, Color(0, 0, 0))
25 | self.window.color = Color(2, 4, 5)
26 | self.assertEqual(self.window.color, Color(2, 4, 5))
27 |
28 | def test_size(self):
29 | self.assertEqual(self.window.size, (100, 100))
30 | self.window.size = (110, 110)
31 | self.assertEqual(self.window.size, (110, 110))
32 |
33 | def test_debug(self):
34 | self.assertFalse(self.window.debug)
35 | self.window.debug = True
36 | self.assertTrue(self.window.debug)
37 |
38 | def test_callbacks(self):
39 | self.window.set_callback(WindowCallbacks.STOPWINDOW, self.cstop)
40 | self.window.set_callback(WindowCallbacks.CHANGEWORLD, self.cworld)
41 | self.window.set_callback(WindowCallbacks.OUTOFWINDOW, self.cout)
42 | self.window.call(WindowCallbacks.OUTOFWINDOW, None, None)
43 | self.window.call(WindowCallbacks.CHANGEWORLD)
44 | self.window.run()
45 |
46 | def cstop(self):
47 | self.assertFalse(self.window.is_running)
48 |
49 | def cworld(self):
50 | pass
51 |
52 | def cout(self, entity, pos):
53 | self.assertIsNone(entity)
54 | self.assertIsNone(pos)
55 |
--------------------------------------------------------------------------------
/tests/WorldTests.py:
--------------------------------------------------------------------------------
1 | import unittest
2 | from pyengine import World, Window
3 | from pyengine.Systems import *
4 |
5 |
6 | class WorldTests(unittest.TestCase):
7 | def setUp(self):
8 | self.w = Window(2, 2)
9 | self.world = World(self.w)
10 |
11 | def test_create(self):
12 | with self.assertRaises(TypeError):
13 | w = World(1)
14 |
15 | def test_window(self):
16 | self.assertEqual(self.world.window, self.w)
17 |
18 | def test_systems(self):
19 | self.assertEqual(self.world.get_system(EntitySystem), self.world.systems["Entity"])
20 | self.assertEqual(self.world.get_system(MusicSystem), self.world.systems["Music"])
21 | self.assertEqual(self.world.get_system(UISystem), self.world.systems["UI"])
22 | self.assertEqual(self.world.get_system(SoundSystem), self.world.systems["Sound"])
23 | self.assertEqual(self.world.get_system(CameraSystem), self.world.systems["Camera"])
24 |
25 | def test_phys(self):
26 | self.assertEqual(self.world.space.gravity, [0, -900])
27 | self.world.space.gravity = [0, 900]
28 | self.assertEqual(self.world.space.gravity, [0, 900])
29 |
30 |
31 |
--------------------------------------------------------------------------------
/tests/files/en.lang:
--------------------------------------------------------------------------------
1 | accueil: Hello
--------------------------------------------------------------------------------
/tests/files/fr.lang:
--------------------------------------------------------------------------------
1 | accueil: Bonjour
--------------------------------------------------------------------------------
/tests/files/sprite0.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/pyengine3/PyEngine/61378943657bf8a3b0e59ab422dd040fec2bed2a/tests/files/sprite0.png
--------------------------------------------------------------------------------
/tests/files/sprite1.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/pyengine3/PyEngine/61378943657bf8a3b0e59ab422dd040fec2bed2a/tests/files/sprite1.png
--------------------------------------------------------------------------------
/tests/files/tilemap/TESTMAP.json:
--------------------------------------------------------------------------------
1 | { "height":10,
2 | "infinite":false,
3 | "layers":[
4 | {
5 | "data":[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 2, 2, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 0, 0, 0, 0, 1, 1, 1, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 1, 1, 0, 0, 2, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0],
6 | "height":10,
7 | "id":1,
8 | "name":"Calque de Tile 1",
9 | "opacity":1,
10 | "type":"tilelayer",
11 | "visible":true,
12 | "width":10,
13 | "x":0,
14 | "y":0
15 | }],
16 | "nextlayerid":2,
17 | "nextobjectid":1,
18 | "orientation":"orthogonal",
19 | "renderorder":"right-down",
20 | "tiledversion":"1.2.4",
21 | "tileheight":32,
22 | "tilesets":[
23 | {
24 | "firstgid":1,
25 | "source":"Test.tsx"
26 | }],
27 | "tilewidth":32,
28 | "type":"map",
29 | "version":1.2,
30 | "width":10
31 | }
--------------------------------------------------------------------------------
/tests/files/tilemap/Test.tsx:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
--------------------------------------------------------------------------------
/tests/files/tilemap/sprite0.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/pyengine3/PyEngine/61378943657bf8a3b0e59ab422dd040fec2bed2a/tests/files/tilemap/sprite0.png
--------------------------------------------------------------------------------
/tests/files/tilemap/sprite1.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/pyengine3/PyEngine/61378943657bf8a3b0e59ab422dd040fec2bed2a/tests/files/tilemap/sprite1.png
--------------------------------------------------------------------------------
/tests/launch_server_for_test.py:
--------------------------------------------------------------------------------
1 | from pyengine.Network import NetworkManager
2 |
3 | nw = NetworkManager()
4 | nw.create_server(22112)
--------------------------------------------------------------------------------
/tests/launch_tests.py:
--------------------------------------------------------------------------------
1 | import os
2 |
3 | text = ""
4 | for i in os.listdir("."):
5 | if i not in ["launch_tests.py", "launch_server_for_test.py"] and i.endswith(".py"):
6 | text += i + " "
7 | os.system("python -m unittest -v "+text[:-1])
8 |
9 |
--------------------------------------------------------------------------------