├── .gitignore
├── LICENSE
├── MANIFEST.in
├── README.md
├── docs
└── DOCS.md
├── examples
├── lil_t.py
├── lil_t_endless.py
├── scrap_bench.py
└── scrap_test.py
├── pics
├── example1.jpg
├── example1.kra
└── example1.kra~
├── pyproject.toml
├── src
└── scrap_engine
│ ├── __init__.py
│ ├── addable
│ ├── __init__.py
│ ├── addable.py
│ ├── misc
│ │ ├── __init__.py
│ │ ├── box.py
│ │ ├── circle.py
│ │ ├── frame.py
│ │ ├── line.py
│ │ ├── square.py
│ │ └── text.py
│ ├── object.py
│ ├── object_group.py
│ └── state.py
│ ├── consts.py
│ ├── error.py
│ └── map
│ ├── __init__.py
│ ├── map.py
│ └── submap.py
└── tests
├── __init__.py
├── add_text_test.py
├── circle.py
├── circler.py
└── stack_test.py
/.gitignore:
--------------------------------------------------------------------------------
1 | *.out
2 | **/__pycache__
3 | build
4 | dist
5 | scrap_engine.egg-info
6 | submit.sh
7 | .eggs
8 | .idea/*
9 |
--------------------------------------------------------------------------------
/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 | .
675 |
--------------------------------------------------------------------------------
/MANIFEST.in:
--------------------------------------------------------------------------------
1 | prune tests/
2 | prune examples/
3 | prune pics/
4 | prune docs/
5 | prune .gitignore
6 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # Scrap_engine
2 | By lxgr
3 |
4 | ## Installation
5 | Manually:
6 | ```shell
7 | # python setup.py install
8 | ```
9 |
10 | Via pip (This will just install the latest stable release):
11 | ```shell
12 | # python -m pip install scrap_engine
13 | ```
14 |
15 | From the AUR (When using Arch Linux):
16 | ```shell
17 | $ buildaur -S python-scrap_engine-git # You can use what ever AUR-helper you want
18 | ```
19 |
20 | To run the examples install python and the pynput module via pip.
21 |
22 | See the project on [pypi](https://pypi.org/project/scrap-engine/)
23 |
24 | ## Usage
25 | See [examples](examples) and [Documentation](docs/DOCS.md). For further documentation see ```pydoc scrap_engine.py```
26 |
27 | ## Examples and tests
28 | The examples in [examples](examples) are made to show how scrap_engine works in a simple and commented way by, in case of scrap_test, building a little game. For more examples you can look at [tests](tests) which also contain explanatory programs.
29 |
30 | They can be ran by either installing scrap_engine like in the installation section or by moving the ```scrap_engine.py``` file in their directories, and then just executing them.
31 |
32 | Another source to understand the functionality of scrap_engine is the small snake implementation [scrape](https://github.com/lxgr-linux/scrape), that was firstly designed to be a tutorial but was later split out due to it's size. This may also help to implement a proper game using scrap_engine.
33 |
34 | ## Notes
35 | The examples and tests where all tested on Arch Linux x86 and Windows 10.
36 |
--------------------------------------------------------------------------------
/docs/DOCS.md:
--------------------------------------------------------------------------------
1 | # Scrap_engine documentation
2 |
3 | ## Table of contents
4 | 1. [Concept](#concept)
5 | 2. [Classes](#classes)
6 | 1. [scrap_engine.Map](#scrap_enginemap)
7 | 2. [scrap_engine.Object](#scrap_engineobject)
8 | 3. [scrap_engine.ObjectGroup](#scrap_engineobjectgroup)
9 | 4. [scrap_engine.Text](#scrap_enginetext)
10 | 5. [scrap_engine.Square](#scrap_enginesquare)
11 | 6. [scrap_engine.Frame](#scrap_engineframe)
12 | 7. [scrap_engine.Box](#scrap_enginebox)
13 | 8. [scrap_engine.Circle](#scrap_enginecircle)
14 | 9. [scrap_engine.Submap](#scrap_enginesubmap)
15 | 3. [Errors](#errors)
16 | 1. [CoordinateError](#coordinateerror)
17 | 4. [Examples](#examples)
18 | ## Concept
19 | The basic concept of scrap_engine evolves around having a ```map``` that is basically a coordinate system that represents the column and rows in the console/terminal.
20 | On this maps ```objects``` can be added, moved, and removed according to given rules.
21 | 
22 |
23 | ## Classes
24 | Note: The most constructor/method arguments of class directly translate to their attributes and, with some exceptions (state, dynfps, type...), should not be manipulated directly.
25 |
26 | There may be some method descriptions missing for some classes, that's because those methods are described in their mother classes description.
27 |
28 | ### scrap_engine.Map
29 | The basic map class to add scrap_engine.objects on.
30 |
31 | #### Method ```scrap_engine.Map.__init__(self, height=height-1, width=width, background="#", dynfps=True)```
32 | Constructor.
33 | - height:```int``` Height of the map
34 | - width:```int``` Width of the map
35 | - background:```String``` Default char, that will be used as the maps background
36 | - dynfps:```boolean``` If changes of the map will be checked a ```scrap_engine.Map.show()```
37 |
38 | #### Method ```scrap_engine.Map.show(self, init=False)```
39 | Shows a frame.
40 | - init:```boolean``` Forces printing
41 |
42 | #### Method ```scrap_engine.Map.resize(self, height, width, background="#")```
43 | Resizes the map.
44 | - height:```int``` New height of the map
45 | - width:```int``` New width of the map
46 | - background:```String``` Default char, that will be used as the maps background
47 |
48 | #### Method ```scrap_engine.Map.blur_in(self, blurmap, esccode="\033[37m")```
49 | Blurs another map as the background into the map
50 | - blurmap:```scrap_engine.Map``` The map to use as the background
51 | - esccode:```String``` Escape code used to blur the blurmap
52 |
53 | ---
54 |
55 | ### scrap_engine.Object
56 | An object that can be added and moved on a ```scrap_engine.Map```.
57 |
58 | #### Method ```scrap_engine.Object.__init__(self, char, state="solid", arg_proto={})```
59 | Constructor.
60 | - char:```String``` A string that represents to object on the map
61 | - state:```String``` State ```"solid"``` or ```"float"```, that indices the behaviour of the Object. ```"solid"``` means that not other objects can be put over the object, ```"float"``` means that it is possible.
62 | - arg_proto:```dictionary``` A custom dictionary that can be passed to custom objects in, for example ```scrap_engine.Text```
63 |
64 | #### Method ```scrap_engine.Object.add(self, map, x, y)```
65 | Adds the object to a given map at a given coordinate.
66 | - map:```scrap_engine.Map``` The map the object should be added to
67 | - x:```int``` The x coordinate the object will be set to
68 | - y:```int``` The y coordinate the object will be set to
69 |
70 | #### Method ```scrap_engine.Object.set(self, x, y)```
71 | Sets the object to a given coordinate on the map.
72 | If this fails, the method will return 1.
73 | - x:```int``` The new x coordinate the object will be set to
74 | - y:```int``` The new y coordinate the object will be set to
75 |
76 | #### Method ```scrap_engine.Object.remove(self)```
77 | Removes the object from the map.
78 |
79 | #### Method ```scrap_engine.Object.redraw(self)```
80 | Redraws the object on the map.
81 |
82 | #### Method ```scrap_engine.Object.rechar(self, char)```
83 | Changes the char of the Object, that represents the object on the map.
84 | - char:```String``` The new string that represents to object on the map
85 |
86 | #### Method ```scrap_engine.Object.action(self, ob)```
87 | Method that is executed, when another object is laid over it self. This just works, if ```self.state = "float"```. This function returns nothing and does nothing, it can be used in custom daughter classes of ```scrap_engine.Object```.
88 | - ob:```scrap_engine.Object``` The object, that is laid over self.
89 |
90 | #### Method ```scrap_engine.Object.bump(self, ob, x, y)```
91 | Method that's executed, when it's tried to lay this object over another object with ```self.state = "solid"```. This function returns nothing and does nothing, it can be used in custom daughter classes of ```scrap_engine.Object```.
92 | - ob:```scrap_engine.Object``` The object, that self tried to be laid over
93 | - x:```int``` X coordinate of the object, that self tried to be laid over
94 | - y:```int``` Y coordinate of the object, that self tried to be laid over
95 |
96 | #### Method ```scrap_engine.Object.bump_left(self)```
97 | This method is executed when trying to set self over the left boarders of the map. This function returns nothing and does nothing, it can be used in custom daughter classes of ```scrap_engine.Object```.
98 |
99 | #### Method ```scrap_engine.Object.bump_right(self)```
100 | This method is executed when trying to set self over the right boarders of the map. This function returns nothing and does nothing, it can be used in custom daughter classes of ```scrap_engine.Object```.
101 |
102 | #### Method ```scrap_engine.Object.bump_top(self)```
103 | This method is executed when trying to set self over the top boarders of the map. This function returns nothing and does nothing, it can be used in custom daughter classes of ```scrap_engine.Object```.
104 |
105 | #### Method ```scrap_engine.Object.bump_bottom(self)```
106 | This method is executed when trying to set self over the bottom boarders of the map. This function returns nothing and does nothing, it can be used in custom daughter classes of ```scrap_engine.Object```.
107 |
108 | #### Method ```scrap_engine.Object.pull_ob(self)```
109 | This method is executed when trying to move self from a place out of the boarders of the map to a place inside the boarders. This function returns nothing and does nothing, it can be used in custom daughter classes of ```scrap_engine.Object```.
110 |
111 | #### Method ```scrap_engine.Object.set_state(self, state)```
112 | Sets the state of the Object.
113 | - state:```String``` The new state ("float" or "solid")
114 |
115 | ---
116 |
117 | ### scrap_engine.ObjectGroup
118 | More a meta class to organize ```scrap_engine.Object```s and daughter objects to do certain actions with a group of those at once.
119 |
120 | #### Method ```scrap_engine.ObjectGroup.__init__(self, obs)```
121 | Constructor.
122 | - obs:```list``` The initial list of ```scrap_engine.Object```s.
123 |
124 | #### Method ```scrap_engine.ObjectGroup.add_ob(self, ob)```
125 | Adds an ```scrap_engine.Object``` to the group.
126 | - ob:```scrap_engine.Object``` A single ```scrap_engine.Object```, that's added to the list of ```scrap_engine.Object```s.
127 |
128 | #### Method ```scrap_engine.ObjectGroup.add_obs(self, obs)```
129 | Adds a list of ```scrap_engine.Object```s to the group.
130 | - obs:```list``` A list of ```scrap_engine.Object```s, that's added to the group.
131 |
132 | #### Method ```scrap_engine.ObjectGroup.rem_ob(self, ob)```
133 | Removes an ```scrap_engine.Object``` from the group.
134 | - ob:```scrap_engine.Object``` The ```scrap_engine.Object``` that's going to be removed.
135 |
136 | #### Method ```scrap_engine.ObjectGroup.move(self, x=0, y=0)```
137 | Moves all objects of the group with a given vector.
138 | - x:```int``` X component of the vector
139 | - y:```int``` Y component of the vector
140 |
141 | #### Method ```scrap_engine.ObjectGroup.remove(self)```
142 | Removes all ```scrap_engine.Object```s in the group from the map.
143 |
144 | #### Method ```scrap_engine.ObjectGroup.set(self, x, y)```
145 | Moves the group to a given coordinate. THIS JUST WORKS WITH DAUGHTER CLASSES, BECAUSE ```scrap_engine.ObjectGroup``` HAS NO COORDINATE BY IT SELF.
146 | - x:```int``` The new x coordinate the group will be set to
147 | - y:```int``` The new y coordinate the group will be set to
148 |
149 | #### Method ```scrap_engine.ObjectGroup.set_state(self, state)```
150 | Sets the state of the Object.
151 | - state:```String``` The new state ("float" or "solid")
152 |
153 | ---
154 |
155 | ### scrap_engine.Text
156 | An easy way to generate text labels. This is a daughter class of ```scrap_engine.ObjectGroup``` and shares all its methods. Texts can be added together.
157 |
158 | #### Method ```scrap_engine.Text.__init__(self, text, state="solid", esccode="", ob_class=Object, ob_args={}, ignore="")```
159 | Constructor.
160 | - text:```String``` The text of the label.
161 | - state:```String``` State ```"solid"``` or ```"float"```, that indices the behaviour of the Obeject. ```"solid"``` means that not other objects can be put over the object, ```"float"``` means that it is possible.
162 | - esccode:```String``` The ansii escape code that can be used to colour the text or make it bold/italic...
163 | - ob_class:```class``` The class of the objects in the label, that should be used.
164 | - ob_args:```dictionary``` This dictionary is passed as ```arg_proto``` to the objects.
165 | - ignore:```String``` Character of objects that should be ignored not be added to the map.
166 |
167 | #### Method ```scrap_engine.Text.add(self, map, x, y)```
168 | Adds the text to a map.
169 | - map:```scrap_engine.Map``` The map the text should be added to
170 | - x:```int``` The x coordinate the text will be set to
171 | - y:```int``` The y coordinate the text will be set to
172 |
173 | #### Method ```scrap_engine.Text.remove(self)```
174 | Removes the text from the map.
175 |
176 | #### Method ```scrap_engine.Text.rechar(self, text, esccode="")```
177 | Changes the text of the text.
178 | - text:```String``` The text of the label.
179 | - esccode:```String``` The ansii escape code that can be used to colour the text or make it bold/italic...
180 |
181 | ---
182 |
183 | ### scrap_engine.Square
184 | An easy way to generate rectangles. This is a daughter class of ```scrap_engine.ObjectGroup``` and shares all its methods.
185 |
186 | #### Method ```scrap_engine.Square.__init__(self, char, width, height, state="solid", ob_class=Object, ob_args={}, threads=False)```
187 | Constructor.
188 | - char:```String``` The character that's used in the rectangle
189 | - width:```int``` Width of the rectangle
190 | - height:```int``` Height of the rectangle
191 | - state:```String``` State ```"solid"``` or ```"float"```, that indices the behaviour of the Object. ```"solid"``` means that not other objects can be put over the object, ```"float"``` means that it is possible.
192 | - esccode:```String``` The ansii escape code that can be used to color the text or make it bold/italic...
193 | - ob_class:```class``` The class of the objects in the label, that should be used
194 | - ob_args:```dictionary``` This dictionary is passed as ```arg_proto``` to the objects
195 | - threads:```boolean``` If or if not threading should be used for generating the rectangle (useful for big rectangles)
196 |
197 | #### Method ```scrap_engine.Square.add(self, map, x, y)```
198 | Adds the rectangle to a map.
199 | - map:```scrap_engine.Map``` The map the rectangle should be added to
200 | - x:```int``` The x coordinate the rectangle will be set to
201 | - y:```int``` The y coordinate the rectangle will be set to
202 |
203 | #### Method ```scrap_engine.Square.rechar(self, char)```
204 | Changes char for the character of the rectangle.
205 | - char:```String``` The new character of the rectangle
206 |
207 | #### Method ```scrap_engine.Square.resize(self, width, height)```
208 | Changes the size of the rectangle.
209 | - width:```int``` Width of the rectangle
210 | - height:```int``` Height of the rectangle
211 |
212 | ---
213 |
214 | ### scrap_engine.Frame
215 | An easy way to generate frames. This is a daughter class of ```scrap_engine.ObjectGroup``` and shares all its methods.
216 |
217 | #### Method ```scrap_engine.Frame.__init__(self, height, width, corner_chars=["+", "+", "+", "+"], horizontal_chars=["-", "-"], vertical_chars=["|", "|"], state="solid", ob_class=Object, ob_args={})```
218 | Constructor.
219 | - height:```int``` Height of the frame
220 | - width:```int``` Width of the frame
221 | - corner_chars:```list``` Chars used for frame corners, [lefttop, righttop, leftbottom, rightbottom]
222 | - horizontal_chars:```list``` Chars used for horizontals, [top, bottom]
223 | - vertical_chars:```list``` Chars used for verticals, [left, right]
224 | - state:```String``` State ```"solid"``` or ```"float"```, that indices the behaviour of the Object. ```"solid"``` means that not other objects can be put over the object, ```"float"``` means that it is possible.
225 | - ob_class:```class``` The class of the objects in the label, that should be used
226 | - ob_args:```dictionary``` This dictionary is passed as ```arg_proto``` to the objects
227 |
228 | #### Method ```scrap_engine.Frame.add(self, map, x, y)```
229 | Adds the frame to a map.
230 | - map:```scrap_engine.Map``` The map the frame should be added to
231 | - x:```int``` The x coordinate the frame will be set to
232 | - y:```int``` The y coordinate the frame will be set to
233 |
234 | #### Method ```scrap_engine.Frame.set(self, x, y)```
235 | Moves the frame to a given coordinate.
236 | - x:```int``` The new x coordinate the frame will be set to
237 | - y:```int``` The new y coordinate the frame will be set to
238 |
239 | #### Method ```scrap_engine.Frame.rechar(self, corner_chars=["+", "+", "+", "+"], horizontal_char="-", vertical_char="|")```
240 | Changes char for the character of the rectangle.
241 | - corner_chars:```list``` Chars used for frame corners, [lefttop, righttop, leftbottom, rightbottom]
242 | - horizontal_chars:```list``` Chars used for horizontals, [top, bottom]
243 | - vertical_chars:```list``` Chars used for verticals, [left, right]
244 |
245 | #### Method ```scrap_engine.Frame.remove(self)```
246 | Removes the frame from the map.
247 |
248 | #### Method ```scrap_engine.Frame.resize(self, height, width)```
249 | Resizes the frame.
250 | - height:```int``` Height of the frame
251 | - width:```int``` Width of the frame
252 |
253 | ---
254 |
255 | ### scrap_engine.Box
256 | A box to pack objects/groups/frames etc. into relative to a coordinate. This is a daughter class of ```scrap_engine.ObjectGroup``` and shares all its methods.
257 |
258 | #### Method ```scrap_engine.Box.__init__(self, height, width)```
259 | Constructor.
260 | - height:```int``` Height of the box
261 | - width:```int``` Width of the box
262 |
263 | #### Method ```scrap_engine.Box.add(self, map, x, y)```
264 | Adds the box to a map.
265 | - map:```scrap_engine.Map``` The map the box should be added to
266 | - x:```int``` The x coordinate the box will be set to
267 | - y:```int``` The y coordinate the box will be set to
268 |
269 | #### Method ```scrap_engine.Box.add_ob(self, ob, rx, ry)```
270 | Adds an object/group etc. to the box.
271 | - ob:```scrap_engine.Object```/```scrap_engine.ObjectGroup``` etc. The object/group that's added to the box
272 | - rx:```int``` The x coordinate the object will be set to in the box
273 | - ry:```int``` The y coordinate the object will be set to in the box
274 |
275 | #### Method ```scrap_engine.Box.set_ob(self, ob, rx, ry)```
276 | Sets an object to another coordinate in the box.
277 | - ob:```scrap_engine.Object```/```scrap_engine.ObjectGroup``` etc. The object/group that's is
278 | - rx:```int``` The new x coordinate the object will be set to in the box
279 | - ry:```int``` The new y coordinate the object will be set to in the box
280 |
281 | #### Method ```scrap_engine.Box.remove(self)```
282 | Removes the box from the map.
283 |
284 | #### Method ```scrap_engine.Box.resize(self, height, width)```
285 | Resizes the box.
286 | - height:```int``` Height of the box
287 | - width:```int``` Width of the box
288 |
289 | ---
290 |
291 | ### scrap_engine.Circle
292 | An easy way to create a circle with a given radius, that's more like an ellipse. This is a daughter class of ```scrap_engine.Box``` and shares all its methods.
293 |
294 | #### Method ```scrap_engine.Circle.__init__(self, char, radius, state="solid", ob_class=Object, ob_args={})```
295 | Constructor.
296 | - char:```String``` Character used for the circle
297 | - radius:```float``` Radius of the circle
298 | - state:```String``` State ```"solid"``` or ```"float"```, that indices the behaviour of the Object. ```"solid"``` means that not other objects can be put over the object, ```"float"``` means that it is possible.
299 | - ob_class:```class``` The class of the objects in the label, that should be used
300 | - ob_args:```dictionary``` This dictionary is passed as ```arg_proto``` to the objects
301 |
302 | #### Method ```scrap_engine.Circle.rechar(self, char)```
303 | Changes char for the character of the circle.
304 | - char:```String``` The new character of the circle
305 |
306 | #### Method ```scrap_engine.Circle.resize(self, radius)```
307 | Changes the radius of the circle
308 | - radius:```float``` Radius of the circle
309 |
310 | ---
311 |
312 | ### scrap_engine.Line
313 | A line that can be drawn on the map, that's described by a vector. This is a daughter class of ```scrap_engine.Box``` and shares all its methods. The unrounded coordinates of the single points Objects of the line are passed in arg_proto to the Objects.
314 |
315 | #### Method ```scrap_engine.Line.__init__(self, char, cx, cy, l_type="straight", state="solid", ob_class=Object, ob_args={})```
316 | Constructor.
317 | - char:```String``` Character used for the circle
318 | - cx: ```float``` X component of the vector
319 | - cy: ```float``` Y component of the vector
320 | - state:```String``` State ```"solid"``` or ```"float"```, that indices the behaviour of the Object. ```"solid"``` means that not other objects can be put over the object, ```"float"``` means that it is possible.
321 | - l_type:```String``` The type the line should have `straight` or `crippled`
322 | - ob_class:```class``` The class of the objects in the label, that should be used
323 | - ob_args:```dictionary``` This dictionary is passed as ```arg_proto``` to the objects
324 |
325 | #### Method ```scrap_engine.Line.rechar(self, char)```
326 | Changes char for the character of the line.
327 | - char:```String``` The new character of the circle
328 |
329 | #### Method ```scrap_engine.Line.resize(self, cx, cy)```
330 | Changes the vector of the line.
331 | - cx: ```float``` X component of the vector
332 | - cy: ```float``` Y component of the vector
333 |
334 | ---
335 |
336 | ### scrap_engine.Submap
337 | A map that's background is a cut-out of another map. This is a daughter class of ```scrap_engine.Map``` and shares all its methods.
338 |
339 | #### Method ```scrap_engine.Submap.__init__(self, bmap, x, y, height=height-1, width=width, dynfps=True)```
340 | Constructor.
341 | - bmap:```scrap_engine.Map``` The map that's the background
342 | - x:```int``` The x coordinate the map will be set to
343 | - y:```int``` The y coordinate the map will be set to
344 | - height:```int``` Height of the map
345 | - width:```int``` Width of the map
346 | - dynfps:```boolean``` If changes of the map will be checked a ```scrap_engine.Map.show()```
347 |
348 | #### Method ```scrap_engine.Submap.remap(self)```
349 | Updates the background.
350 |
351 | #### Method ```scrap_engine.Submap.set(self, x, y)```
352 | Moves the map to a given coordinate.
353 | - x:```int``` The new x coordinate the map will be set to
354 | - y:```int``` The new y coordinate the map will be set to
355 |
356 | #### Method ```scrap_engine.Submap.full_show(self, init=False)```
357 | A wrapper for ```scrap_engine.Submap.show()``` and ```scrap_engine.Submap.remap(self)```
358 | - init:```boolean``` Forces printing
359 |
360 | ## Errors
361 | ### CoordinateError
362 | The CoordinateError is raised, when an Object is tried to add to an impossible coordinate.
363 | Its' attributes are:
364 | - obj:`scrap_engine.Object` The Object that's tried to add
365 | - map_:`scrap_engine.Map` The Map the Object is tried to add to
366 | - x:`int` The x coordinate the Object is tried to add to
367 | - y:`int` The y coordinate the Object is tried to add to
368 |
369 | ## Examples
370 | This is just a simple example program that adds a an "a" to the coordinate (10|5) in the terminal.
371 | ```python
372 | import scrap_engine as se # imports scrap_engine
373 |
374 | mymap = se.Map(background=" ") # defines mymap as a map as big as the terminal window with the background " "
375 | myob = se.Object("a") # defines myob as an object with "a" as character
376 |
377 | myob.add(mymap, 10, 5) # adds myob to mymap at (10|5)
378 | mymap.show() # shows mymap
379 | ```
380 |
381 | Another small example that moves the a in a line over the screen.
382 | ```python
383 | import scrap_engine as se # imports scrap_engine
384 | import time
385 |
386 | mymap = se.Map(background=" ") # defines mymap as a map as big as the terminal window with the background " "
387 | myob = se.Object("a") # defines myob as an object with "a" as character
388 |
389 | myob.add(mymap, 10, 5) # adds myob to mymap at (10|5)
390 | mymap.show() # shows mymap
391 |
392 | for i in range(5):
393 | time.sleep(0.3) # waiting 0.3 seconds
394 | myob.set(myob.x+1, 5) # sets myob to its own x coordinate +1 and y coordinate 5
395 | mymap.show() # shows mymap
396 | ```
397 |
398 | An example of the Text, Square and Frame class.
399 | ```python
400 | import scrap_engine as se # imports scrap_engine
401 |
402 | mymap = se.Map(background=" ") # defines mymap as a map as big as the terminal window with the background " "
403 | mytext = se.Text("Hello world") # defines a text as "Hello world"
404 | myrectangle = se.Square(height=5, width=6, char="#") # defines a rectangle width height 5, width 6 and the character "#"
405 | myframe = se.Frame(height=7, width=8, corner_chars=["┌", "┐", "└", "┘"], horizontal_chars=["─", "─"], vertical_chars=["│", "│"]) # defines a frame see scrap_engine.Frame
406 |
407 | mytext.add(mymap, 0, 0) # adds mytext to (0|0)
408 | myrectangle.add(mymap, 2, 2) # adds myrectangle to (2|2)
409 | myframe.add(mymap, 1, 1) # adds myframe to (1|1)
410 |
411 | mymap.show() # now a frame with a rectangle and a text above it should be shown
412 | ```
413 |
414 | An example of a line across the screen with a moving "#" in it.
415 | ```python
416 | import scrap_engine as se
417 | import time
418 |
419 | map = se.Map(background=" ")
420 | line = se.Line("a", 10, 5, type="straight") # makes a straight line described by the vector (10 5) with "a" as its char
421 |
422 | line.add(map, 0, 0) # addes line to (0|0)
423 |
424 | map.show()
425 |
426 | for i in range(len(line.obs)): # list.obs is the list of all Objects that are part of the line
427 | line.obs[i].rechar("#") # rechars the Object to "#"
428 | if i != 0:
429 | line.obs[i-1].rechar(line.char) # line.char is the default char of the line
430 | time.sleep(0.4)
431 | map.show()
432 | ```
433 |
434 | Example for a clock like line rotation.
435 | ```python
436 | import scrap_engine as se
437 | import time, math
438 |
439 | map = se.Map(background=" ")
440 | line = se.Line("#", 0, 10) # downwards facing line of the vector (0 10)
441 | line.add(map, 10, 10)
442 | map.show()
443 |
444 | # loops i until 360 and resizes the line with the vector (sin(i)*10 cos(i)*10)
445 | for i in range(360):
446 | line.resize(math.sin(math.radians(i))*10, math.cos(math.radians(i))*10)
447 | time.sleep(0.05)
448 | map.show()
449 |
450 | ```
451 |
452 | An example that shows how Texts are added.
453 | ```python
454 | import scrap_engine as se
455 |
456 | map = se.Map(background=" ")
457 | text1 = se.Text("Hey")
458 | text2 = se.Text(" You!")
459 |
460 | text1 += text2
461 | text1.add(map, 0, 0) # Those two steps can even be switched
462 |
463 | #>>> Hey You!
464 |
465 | ```
466 |
--------------------------------------------------------------------------------
/examples/lil_t.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python3
2 | import scrap_engine as se
3 | import time, os, threading, sys
4 |
5 | os.system("")
6 | width, height = os.get_terminal_size()
7 | t=ev=v=0
8 | g=0.015
9 |
10 | map=se.Map(height-1, 1000, " ")
11 | smap=se.Submap(map, 0, 0)
12 |
13 | block=se.Object("#")
14 | panel=se.Square("#", 10, 1)
15 | ground=se.Square("#", map.width, 5)
16 | player=se.Object("t")
17 | h=se.Text("00 00")
18 |
19 | block.add(map, 200, map.height-6)
20 | panel.add(map, 100, map.height-10)
21 | ground.add(map, 0, map.height-5)
22 | player.add(map, round(smap.width/2), round(map.height/2))
23 | h.add(smap, 0, 0)
24 |
25 | def on_press(key):
26 | global ev
27 | ev=str(key)
28 |
29 | if sys.platform == "linux": # Use another (not on xserver relying) way to read keyboard input, to make this shit work in tty or via ssh, where no xserver is available
30 | def recogniser():
31 | global ev
32 | while True:
33 | a=os.popen('./reader.sh').read()
34 | if a == "\n":
35 | ev="Key.enter"
36 | else:
37 | ev="'"+a.rstrip()+"'"
38 | else:
39 | from pynput.keyboard import Key, Listener
40 | def recogniser():
41 | global ev
42 | while True:
43 | with Listener(on_press=on_press) as listener:
44 | listener.join()
45 |
46 | recognising=threading.Thread(target=recogniser)
47 | recognising.daemon=True
48 | recognising.start()
49 |
50 | smap.remap()
51 | smap.show(init=True)
52 | time.sleep(0.5)
53 | while True:
54 | for ob in map.obs:
55 | if player.y+1 == ob.y and player.x == ob.x:
56 | t=0
57 | v=0
58 | if ev == "Key.enter":
59 | v=-0.25
60 | ev=0
61 | player.set(player.x+1, player.y)
62 | if player.set(player.x, round(player.y-(v*(v/g)-1/2*g*(v/g)**2)-v*t+1/2*g*t**2)) != 0 and t != 0:
63 | player.set(player.x, player.y+1)
64 | t+=1
65 | exec("point_%s=se.Object('*', 'float')"%t)
66 | exec("point_%s.add(map, player.x, player.y-1)"%t)
67 | if player.x < smap.x-1:
68 | exit()
69 | h.rechar((2-len(str(player.y)))*" "+str(player.y)+" "+str(map.height))
70 | time.sleep(0.05)
71 | smap.remap()
72 | smap.show()
73 | smap.set(smap.x+1, smap.y)
74 |
--------------------------------------------------------------------------------
/examples/lil_t_endless.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python3
2 | import scrap_engine as se
3 | import time, os, threading, sys, random
4 |
5 |
6 | class PanelItem(se.Object):
7 | def bump_left(self):
8 | global moving
9 | del moving[moving.index(self)]
10 | self.remove()
11 |
12 | def bump(self, ob, x, y):
13 | ob.set(ob.x-1, ob.y)
14 | self.set(self.x-1, self.y)
15 |
16 |
17 | class Panel(se.Square):
18 | def init(self):
19 | for ob in self.obs:
20 | moving.append(ob)
21 |
22 | def genpanel():
23 | global panelindex, test
24 | exec("panel_%s=Panel('#', 10, 1, ob_class=PanelItem)"%panelindex)
25 | exec("panel_%s.add(map, map.width-11, map.height-%i)"%(panelindex, random.randint(8,20)))
26 | exec("panel_%s.init()"%panelindex)
27 | panelindex+=1
28 |
29 | def on_press(key):
30 | global ev
31 | ev=str(key)
32 |
33 | if sys.platform == "linux": # Use another (not on xserver relying) way to read keyboard input, to make this shit work in tty or via ssh, where no xserver is available
34 | def recogniser():
35 | import tty, sys, termios
36 | global ev, old_settings, termios, fd, do_exit
37 |
38 | do_exit=False
39 | fd=sys.stdin.fileno()
40 | old_settings = termios.tcgetattr(fd)
41 | tty.setraw(fd)
42 | while True:
43 | char=sys.stdin.read(1)
44 | if ord(char) == 13:
45 | ev="Key.enter"
46 | elif ord(char) == 32:
47 | ev="Key.space"
48 | else:
49 | ev="'"+char.rstrip()+"'"
50 | if ord(char) == 3 or do_exit:
51 | termios.tcsetattr(fd, termios.TCSADRAIN, old_settings)
52 | ev="exit"
53 | else:
54 | from pynput.keyboard import Key, Listener
55 | def recogniser():
56 | global ev
57 | while True:
58 | with Listener(on_press=on_press) as listener:
59 | listener.join()
60 |
61 |
62 | def main():
63 | global v, t, ev, g, framenum, genframe
64 | while True:
65 | nexty=lambda v,g,t : round(player.y-(v*(v/g)-1/2*g*(v/g)**2)-v*t+1/2*g*t**2)
66 | for ob in map.obs[1:]:
67 | if player.y+1 == ob.y and player.x == ob.x:
68 | t=0
69 | v=0
70 | for ob in map.obs[1:]:
71 | if player.y < ob.y < nexty(v,g,t) and ob.x == player.x+1:
72 | player.set(player.x, ob.y-1)
73 | t=0
74 | v=0
75 | break
76 | elif player.y > ob.y > nexty(v,g,t) and ob.x == player.x+1:
77 | player.set(player.x, ob.y+1)
78 | t=0
79 | v=0
80 | break
81 | if ev == "Key.space":
82 | v=-0.25
83 | ev=0
84 | elif ev == "exit":
85 | ev=0
86 | raise KeyboardInterrupt
87 | if player.set(player.x, nexty(v,g,t))!= 0 and t != 0:
88 | for ob in map.obs[1:]:
89 | if ob.x == player.x and ob.y == nexty(v,g,t):
90 | v=0
91 | player.set(player.x, player.y+1)
92 | t+=1
93 | # exec("point_%s=PanelItem('*', 'float')"%panelindex)
94 | # exec("point_%s.add(map, player.x-1, player.y)"%panelindex)
95 | # exec("moving.append(point_%s)"%panelindex)
96 | # panelindex+=1
97 | for mov in moving:
98 | mov.set(mov.x-1, mov.y)
99 | if player.x < smap.x-1:
100 | exit()
101 | h.rechar((2-len(str(player.y)))*" "+str(player.y)+" "+str(map.height)+" "+str(player.y)+" "+str(nexty(v,g,t))+" "+str(player.y-nexty(v,g,t)))
102 | if genframe+15 == framenum:
103 | genpanel()
104 | genframe+=15
105 | time.sleep(0.05)
106 | smap.remap()
107 | smap.show()
108 | framenum+=1
109 |
110 |
111 | os.system("")
112 | width, height = os.get_terminal_size()
113 | t=ev=v=0
114 | g=0.015
115 | panelindex=0
116 | framenum=0
117 | genframe=0
118 |
119 | map=se.Map(height-1, width+12, " ")
120 | smap=se.Submap(map, 0, 0)
121 |
122 | player=se.Object("t")
123 | block=PanelItem("#")
124 | panel=Panel("#", 10, 1, ob_class=PanelItem)
125 | ground=se.Square("#", map.width, 5)
126 | h=se.Text("00 00")
127 |
128 | player.add(map, round(smap.width/2), round(map.height/2))
129 | block.add(map, map.width-11, map.height-6)
130 | panel.add(map, map.width-11, map.height-10)
131 | ground.add(map, 0, map.height-5)
132 | h.add(smap, 0, 0)
133 | moving=[ob for ob in panel.obs]+[block]
134 |
135 | recognising=threading.Thread(target=recogniser)
136 | recognising.daemon=True
137 | recognising.start()
138 |
139 | smap.remap()
140 | smap.show(init=True)
141 | main()
142 |
--------------------------------------------------------------------------------
/examples/scrap_bench.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python3
2 |
3 | import scrap_engine as se
4 | import time, random, os
5 |
6 | def main():
7 | global avr, tcount
8 |
9 | os.system("")
10 | b_map = se.Map(background=" ")
11 | text = se.Text("0")
12 | avr = se.Text("0")
13 | rectangle = se.Square('\033[34ma\033[0m', 50, 10)
14 | text.add(b_map, round((b_map.width-len(text.text))/2-10),
15 | round(b_map.height/2)-1)
16 | avr.add(b_map, round((b_map.width-len(text.text))/2-10),
17 | round(b_map.height/2))
18 | rectangle.add(b_map, 0, 0)
19 |
20 | tcount = 0
21 | times = 0
22 | time2 = 0
23 |
24 | b_map.show()
25 | while True:
26 | time0 = time.time()
27 | times += time2
28 | for ob in rectangle.obs:
29 | ob.set(random.choice([ob.x, ob.x+1, ob.x-1]), random.choice([ob.y, ob.y+1, ob.y-1]))
30 | text.rechar(str(time2))
31 | avr.rechar(str(times/tcount if tcount != 0 else 1))
32 | b_map.show()
33 | tcount += 1
34 | time2 = time.time()-time0
35 |
36 | if __name__ == "__main__":
37 | try:
38 | main()
39 | except KeyboardInterrupt:
40 | print(f"""KeyboardInterrupt
41 |
42 | Screen size: {se.screen_width}x{se.screen_height}
43 | Average frame time: {avr.text}s
44 | Frames drawn: {tcount}""")
45 |
--------------------------------------------------------------------------------
/examples/scrap_test.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/python3
2 | # This software is licensed under the PGL v3 and comes with no warranty and so on....
3 | # This software a proof of concept thingie for all features of the scrap_engine python module.
4 | # It is also kind of an explaination for those, see the comments.
5 | # Have fun!
6 |
7 | import scrap_engine as se
8 | from pynput.keyboard import Key, Listener
9 | import threading, time, os
10 |
11 | # Because of some wierd windows shit this is required to let colors work
12 | os.system("")
13 |
14 | # Some vars
15 | luisframe=0
16 | luisview="r"
17 | framenum=0
18 | bullet_num=0
19 | bullets=[]
20 | ev=ev2=0
21 | obcount=0
22 |
23 | # Adding Maps
24 | map=se.Map(width=200, background=" ") # Maps are kind of the "playground" which you can add Objects and Groups to
25 | smap=se.Submap(map, 0,0) # This one is just a small part of the real (map) Map
26 | menumap=se.Map(background=" ")
27 | howtomap=se.Map(background=" ")
28 |
29 | # Defining the "action" function for the Pad class wich is a modified Object class, which is triggert, when another Object is in the same spot as the Object it self
30 | class Pad(se.Object):
31 | def action(self, ob):
32 | ob.remove()
33 |
34 | # Same as above, but the player is set to the middle of the map when he bumps into an solid Object
35 | class Player(se.Object):
36 | def bump(self, ob, x, y):
37 | self.set(round(self.map.width/2), round(self.map.height/2))
38 | if self.char == "T":
39 | self.rechar("t")
40 | elif self.char == "t":
41 | self.rechar("T")
42 | elif self.char == "F":
43 | self.rechar("f")
44 | elif self.char == "f":
45 | self.rechar("F")
46 |
47 | class Bullet(se.Object):
48 | def bump_action(self):
49 | for i in range(len(bullets)):
50 | if bullets[i] == self:
51 | del bullets[i]
52 | break
53 | self.remove()
54 |
55 | def bump(self, ob, x, y):
56 | ob.remove()
57 | self.bump_action()
58 |
59 | def bump_right(self):
60 | self.bump_action()
61 |
62 | def bump_left(self):
63 | self.bump_action()
64 |
65 | def bump_top(self):
66 | self.bump_action()
67 |
68 | def bump_bottom(self):
69 | self.bump_action()
70 |
71 | def shoot(ob):
72 | exec("bullet"+str(bullet_num)+"=Bullet('*', state='float')")
73 | exec("bullet"+str(bullet_num)+".direction=ob.direction")
74 | if ob.direction == "t":
75 | exec("bullet"+str(bullet_num)+".add(map, ob.x, ob.y-1)")
76 | elif ob.direction == "l":
77 | exec("bullet"+str(bullet_num)+".add(map, ob.x-1, ob.y)")
78 | elif ob.direction == "b":
79 | exec("bullet"+str(bullet_num)+".add(map, ob.x, ob.y+1)")
80 | elif ob.direction == "r":
81 | exec("bullet"+str(bullet_num)+".add(map, ob.x+1, ob.y)")
82 | exec("bullets.append(bullet"+str(bullet_num)+")")
83 |
84 | # Creating Objects
85 | lui=se.Object(char="L") # Objects are just objects that can be added to a map
86 | rock=se.Object(char="A")
87 | menuind=se.Object("*")
88 | player=Player(char="T")
89 | player0=Player(char="F")
90 | pad=Pad(char="i", state="float") # The state="float" means that other Objects can be placed over it, default is "solid"
91 | testob=se.Object(char="t")
92 | testob2=se.Object(char="t")
93 | testtext=se.Text("Hey!")
94 | box=se.Box(10, 10)
95 | box.add_ob(testob, 5, 5)
96 | box.add_ob(testob2, 6, 6)
97 | box.add_ob(testtext, 7, 7)
98 | box.add(map, 100, 10)
99 |
100 | # Creating Groups
101 | menutext1=se.Text("Resume", float) # The Text class creates a Group with the text in it
102 | menutext2=se.Text("How to play", float)
103 | menutext3=se.Text("Exit", float)
104 | howtotext=se.Text("How to play this game ou ask?\nIf you haven't already understood,\nyou can move your character with w, a, s and d.\nTo open the menu press m", float)
105 | text=se.Text("hello", float, esccode="\033[1m")
106 | text2=se.Text("this\nis\nmultiline text!", float)
107 | square1=se.Square("#", 2, 3, float)
108 | square2=se.Square("#", 10, 5) # The Square class creates a square of a specific character
109 |
110 | # Adding Objects and Groups to their Maps
111 | player.add(map, 0, 0)
112 | player0.add(map, 0, 1)
113 | lui.add(map, 20, 10)
114 | rock.add(map, 10, 10)
115 | howtotext.add(howtomap, int(round(howtomap.width-47)/2), int(round(howtomap.height/2)-2))
116 | menutext1.add(menumap, int(round(menumap.width/2)-2), int(round(menumap.height/2)-4))
117 | menutext3.add(menumap, int(round(menumap.width/2)-2), int(round(menumap.height/2)+4))
118 | menutext2.add(menumap, int(round(menumap.width/2)-2), int(round(menumap.height/2)))
119 | menuind.add(menumap, int(round(menumap.width/2)-4), menutext1.y)
120 | text.add(map, 11, 3)
121 | text2.add(map, 11, 4)
122 | square2.add(map, 60, 10)
123 | square1.add(map, 20, 20)
124 | pad.add(map, 10, 20)
125 | player.direction="r"
126 | player0.direction="r"
127 |
128 | # Menu function
129 | def menu():
130 | global ev
131 | ev=0
132 | menuind.index=1
133 | menumap.blur_in(smap) # Blurs in the map Map into the background of the menumap Map
134 | menumap.show(init=True)
135 | while True:
136 | if ev == "'m'":
137 | ev=0
138 | break
139 | elif ev == "'w'":
140 | if menuind.index != 1:
141 | menuind.index-=1
142 | exec("menuind.set(menuind.x, menutext"+str(menuind.index)+".y)")
143 | ev=0
144 | elif ev == "'s'":
145 | if menuind.index != 3:
146 | menuind.index+=1
147 | exec("menuind.set(menuind.x, menutext"+str(menuind.index)+".y)")
148 | ev=0
149 | elif ev == "Key.enter":
150 | if menuind.y == menutext1.y:
151 | return
152 | elif menuind.y == menutext2.y:
153 | howtoplay()
154 | menumap.show(init=True)
155 | elif menuind.y == menutext3.y:
156 | exit()
157 | ev=0
158 | else:
159 | time.sleep(0.05)
160 | menumap.show() # Showing menumap
161 |
162 | # How to play menuentry function
163 | def howtoplay():
164 | global ev
165 | ev=0
166 | #howtomap.blur_in(menumap) # Blurs in the menumap Map into the background of the howtomap Map
167 | howtomap.show(init=True)
168 | while True:
169 | if ev == "'m'":
170 | ev=0
171 | break
172 | else:
173 | time.sleep(0.05)
174 | howtomap.show() # Showing howtomap
175 |
176 | # Adding functions for capturing the keyboard and controling the game, you may recicle this in your applications
177 | def on_press(key):
178 | global ev, ev2
179 | if str(key) in ["'w'", "'a'", "'s'", "'d'", "'e'", "'q'", "Key.space"]:
180 | ev=str(key)
181 | elif str(key) in ["Key.up", "Key.left", "Key.down", "Key.right", "'#'"]:
182 | ev2=str(key)
183 |
184 | def recogniser():
185 | global ev, ev2
186 | while True:
187 | with Listener(on_press=on_press) as listener:
188 | listener.join()
189 |
190 | # Starting those in another thread
191 | recognising=threading.Thread(target=recogniser)
192 | recognising.daemon=True
193 | recognising.start()
194 |
195 | smap.remap()
196 | smap.show() # showing smap Map
197 | while True:
198 | if ev == "'w'":
199 | player.direction="t"
200 | player.set(player.x, player.y-1) # Doing something on keypress w
201 | ev=0
202 | elif ev == "'a'":
203 | player.direction="l"
204 | player.set(player.x-1, player.y) # Doing something different on keypress a
205 | ev=0
206 | elif ev == "'s'":
207 | player.direction="b"
208 | player.set(player.x, player.y+1) # Doing something more different on keypress s
209 | ev=0
210 | elif ev == "'d'":
211 | player.direction="r"
212 | player.set(player.x+1, player.y) # Doing yet another different thing on keypress d
213 | ev=0
214 | elif ev2 == "Key.up":
215 | player0.direction="t"
216 | player0.set(player0.x, player0.y-1) # Doing something on keypress w
217 | ev2=0
218 | elif ev2 == "Key.left":
219 | player0.direction="l"
220 | player0.set(player0.x-1, player0.y) # Doing something different on keypress a
221 | ev2=0
222 | elif ev2 == "Key.down":
223 | player0.direction="b"
224 | player0.set(player0.x, player0.y+1) # Doing something more different on keypress s
225 | ev2=0
226 | elif ev2 == "Key.right":
227 | player0.direction="r"
228 | player0.set(player0.x+1, player0.y) # Doing yet another different thing on keypress d
229 | ev2=0
230 | elif ev == "'e'":
231 | text2.rechar("thus\nus\nmultiline mext!")
232 | square2.rechar("A") # Doing some weird shit on keypress e
233 | ev=0
234 | elif ev == "'q'":
235 | # Creating and adding some Object on keypress q
236 | exec("ob_"+str(obcount)+"=se.Object('A', state='solid')")
237 | exec("ob_"+str(obcount)+".add(map, player.x+1, player.y)")
238 | obcount+=1
239 | ev=0
240 | elif ev == "'m'":
241 | menu() # Running the menu function on keypress q to open the menu
242 | smap.show(init=True) # The init=True option ensures, the map Map is drawn after closing the menu, even if no changes accured in the map
243 | smap.remap()
244 | ev=0
245 | elif ev == "Key.space":
246 | shoot(player)
247 | ev=0
248 | elif ev2 == "'#'":
249 | shoot(player0)
250 | ev2=0
251 | else:
252 | time.sleep(0.05) # Else just wait 0.05 seconds
253 | # Let lui run
254 | if luisframe+20 == framenum:
255 | if lui.x == 20 and luisview == "l":
256 | lui.set(19, 10)
257 | luisview="r"
258 | elif lui.x == 20 and luisview == "r":
259 | lui.set(21, 10)
260 | luisview="l"
261 | elif lui.x == 19 or lui.x == 21:
262 | lui.set(20, 10)
263 | luisframe+=20
264 | for ob in [player, player0]:
265 | if ob.x+5 > smap.x+smap.width:
266 | smap.set(smap.x+1 ,smap.y)
267 | if ob.x < smap.x+5:
268 | smap.set(smap.x-1 ,smap.y)
269 | for ob in bullets:
270 | if ob.direction == "t":
271 | ob.set(ob.x, ob.y-1)
272 | elif ob.direction == "l":
273 | ob.set(ob.x-1, ob.y)
274 | elif ob.direction == "b":
275 | ob.set(ob.x, ob.y+1)
276 | elif ob.direction == "r":
277 | ob.set(ob.x+1, ob.y)
278 | smap.remap()
279 | smap.show() # Draw the frame
280 | framenum+=1
281 |
--------------------------------------------------------------------------------
/pics/example1.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/lxgr-linux/scrap_engine/8cad24563ef6806a0f536c439a9afbbcf5a99954/pics/example1.jpg
--------------------------------------------------------------------------------
/pics/example1.kra:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/lxgr-linux/scrap_engine/8cad24563ef6806a0f536c439a9afbbcf5a99954/pics/example1.kra
--------------------------------------------------------------------------------
/pics/example1.kra~:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/lxgr-linux/scrap_engine/8cad24563ef6806a0f536c439a9afbbcf5a99954/pics/example1.kra~
--------------------------------------------------------------------------------
/pyproject.toml:
--------------------------------------------------------------------------------
1 | [build-system]
2 | requires = ["setuptools", "setuptools-scm"]
3 | build-backend = "setuptools.build_meta"
4 |
5 | [project]
6 | name = "scrap_engine"
7 | authors = [{ name = "lxgr", email = "lxgr@protonmail.com" }]
8 | description = "A 2D ascii game engine for the terminal"
9 | keywords = ["game", "Ascii"]
10 | version = "1.4.3"
11 | license = { text = "GPL-3.0-only" }
12 | readme = "README.md"
13 | requires-python = ">=3.11"
14 | classifiers = [
15 | "Programming Language :: Python :: 3",
16 | "Operating System :: OS Independent",
17 | ]
18 |
19 | [project.urls]
20 | Homepage = "https://github.com/lxgr-linux/scrap_engine"
21 | Issues = "https://github.com/lxgr-linux/scrap_engine/issue"
22 | Repository = "https://github.com/lxgr-linux/scrap_engine.git"
23 |
--------------------------------------------------------------------------------
/src/scrap_engine/__init__.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python3
2 | """
3 | Ascii game engine for the terminal.
4 |
5 | The main data structures are Map and Object.
6 | Maps are objects, Object objects can be added to and then can be shown on
7 | the screen.
8 |
9 | ObjectGroup and their daughters can be used to automate generating, adding,
10 | removing etc. for a list of objects in their defined manner.
11 |
12 | States:
13 | Possible states an object can have are 'solid' and 'float'.
14 | If an objects state is 'solid' no other object can be set over it,
15 | so the other objects .set() method will return 1.
16 | If an objects state is 'float' other objects can be set over them,
17 | so their .set() methods will return 0.
18 |
19 | arg_proto:
20 | arg_proto is an dictionary that is given to an object by
21 | the programmer or an object_group(circle, frame, etc.) via the ob_args
22 | argument.
23 | This can be used to store various extra values and is especially useful
24 | when using daughter classes of Object that needs extra values.
25 |
26 | This software is licensed under the GPL3
27 | You should have gotten an copy of the GPL3 license alongside this software
28 | Feel free to contribute what ever you want to this engine
29 | You can contribute here: https://github.com/lxgr-linux/scrap_engine
30 | """
31 |
32 | __author__ = "lxgr "
33 | __version__ = "1.4.2"
34 |
35 | from .error import CoordinateError
36 | from .consts import *
37 | from .addable import *
38 | from .map import *
39 |
--------------------------------------------------------------------------------
/src/scrap_engine/addable/__init__.py:
--------------------------------------------------------------------------------
1 | from .addable import Addable
2 | from .object import Object
3 | from .object_group import ObjectGroup
4 | from .state import State, DEFAULT_STATE
5 | from .misc import *
6 |
--------------------------------------------------------------------------------
/src/scrap_engine/addable/addable.py:
--------------------------------------------------------------------------------
1 | from abc import ABC, abstractmethod
2 | from typing import Optional
3 |
4 | from scrap_engine.addable.state import DEFAULT_STATE, State
5 | from scrap_engine.map.map import Map
6 |
7 | class Addable(ABC):
8 | """
9 | The parent class of any object that can be added to a Map.
10 | """
11 |
12 | def __init__(self, state:State=DEFAULT_STATE):
13 | self.x:int = -1
14 | self.y:int = -1
15 | # Those are the relativ coordinated used, when grouped
16 | self.rx = None
17 | self.ry = None
18 | self.added:bool = False
19 | self.group = None
20 | self.state: State = state
21 | self.map: Optional[Map] = None
22 |
23 | def set_state(self, state: State):
24 | self.state = state
25 |
26 | @abstractmethod
27 | def add(self, _map:Map, x:int, y:int):
28 | ...
29 |
30 | @abstractmethod
31 | def remove(self):
32 | ...
33 |
34 | @abstractmethod
35 | def set(self, x:int, y:int):
36 | ...
37 |
--------------------------------------------------------------------------------
/src/scrap_engine/addable/misc/__init__.py:
--------------------------------------------------------------------------------
1 | from .box import Box
2 | from .circle import Circle
3 | from .frame import Frame
4 | from .line import Line
5 | from .square import Square
6 | from .text import Text
7 |
--------------------------------------------------------------------------------
/src/scrap_engine/addable/misc/box.py:
--------------------------------------------------------------------------------
1 | from scrap_engine.addable.state import DEFAULT_STATE
2 | from ..object_group import ObjectGroup
3 |
4 | class Box(ObjectGroup):
5 | """
6 | A datastucture used to group objects(groups) relative to a certain
7 | coordinate, that can be added to a map.
8 | """
9 |
10 | def __init__(self, height:int, width:int):
11 | super().__init__([], DEFAULT_STATE)
12 | self.height:int = height
13 | self.width:int = width
14 |
15 | def add(self, _map, x:int, y:int):
16 | """
17 | Adds the box to a certain coordinate on a certain map.
18 | """
19 | self.x = x
20 | self.y = y
21 | self.map = _map
22 | for obj in self.obs:
23 | obj.add(self.map, obj.rx + self.x, obj.ry + self.y)
24 | self.added = True
25 |
26 | def add_ob(self, obj, x:int, y:int):
27 | """
28 | Adds an object(group) to a certain coordinate relative to the box.
29 | """
30 | self.obs.append(obj)
31 | obj.rx = x
32 | obj.ry = y
33 | obj.group = self
34 | if self.added:
35 | obj.add(self.map, obj.rx + self.x, obj.ry + self.y)
36 |
37 | def set_ob(self, obj, x, y):
38 | """
39 | Sets an object(group) to a certain coordinate relative to the box.
40 | """
41 | obj.rx = x
42 | obj.ry = y
43 | if self.added:
44 | obj.set(obj.rx + self.x, obj.ry + self.y)
45 |
46 | def remove(self):
47 | """
48 | Removes the box from the map.
49 | """
50 | for obj in self.obs:
51 | obj.remove()
52 | self.added = False
53 |
54 | def resize(self, height, width):
55 | """
56 | Resizes the box.
57 | """
58 | self.height = height
59 | self.width = width
60 |
--------------------------------------------------------------------------------
/src/scrap_engine/addable/misc/circle.py:
--------------------------------------------------------------------------------
1 | import math
2 | from typing import Type
3 |
4 | from scrap_engine.addable.state import DEFAULT_STATE, State
5 | from .box import Box
6 | from ..object import Object
7 |
8 |
9 | class Circle(Box):
10 | """
11 | A circle, that can be added to a map.
12 | """
13 |
14 | def __init__(
15 | self, char: str, radius:int, state:State=DEFAULT_STATE,
16 | ob_class:Type[Object]=Object, ob_args=None
17 | ):
18 | super().__init__(0, 0)
19 | if ob_args is None:
20 | ob_args = {}
21 | self.char = char
22 | self.ob_class = ob_class
23 | self.ob_args = ob_args
24 | self.state = state
25 | self.__gen(radius)
26 |
27 | def __gen(self, radius):
28 | self.radius = radius
29 | for i in range(-(int(radius) + 1), int(radius + 1) + 1):
30 | for j in range(-(int(radius) + 1), int(radius + 1) + 1):
31 | if math.sqrt(i ** 2 + j ** 2) <= radius:
32 | self.add_ob(self.ob_class(self.char, state=self.state,
33 | arg_proto=self.ob_args), i, j)
34 |
35 | def rechar(self, char):
36 | """
37 | Changes the chars the circle is filled with.
38 | """
39 | self.char = char
40 | for obj in self.obs:
41 | obj.rechar(char)
42 |
43 | def resize(self, radius):
44 | """
45 | Resizes the circle.
46 | """
47 | if added := self.added:
48 | self.remove()
49 | self.obs = []
50 | self.__gen(radius)
51 | if added:
52 | self.add(self.map, self.x, self.y)
53 |
--------------------------------------------------------------------------------
/src/scrap_engine/addable/misc/frame.py:
--------------------------------------------------------------------------------
1 | from typing import Optional, Type
2 | from scrap_engine.addable.state import DEFAULT_STATE, State
3 | from .box import Box
4 | from .square import Square
5 | from ..object import Object
6 |
7 |
8 | class Frame(Box):
9 | """
10 | A Frame made of ascii charactes:
11 |
12 | +----+
13 | | |
14 | | |
15 | +----+
16 |
17 | That can be added to map.
18 | """
19 |
20 | def __init__(
21 | self, height:int, width:int, corner_chars:Optional[list[str]]=None,
22 | horizontal_chars:Optional[list[str]]=None, vertical_chars:Optional[list[str]]=None,
23 | state:State=DEFAULT_STATE, ob_class:Type[Object]=Object, ob_args=None
24 | ):
25 | super().__init__(height, width)
26 | if ob_args is None:
27 | ob_args = {}
28 | if vertical_chars is None:
29 | vertical_chars = ["|", "|"]
30 | if horizontal_chars is None:
31 | horizontal_chars = ["-", "-"]
32 | if corner_chars is None:
33 | corner_chars = ["+", "+", "+", "+"]
34 | self.state = state
35 | self.ob_class = ob_class
36 | self.ob_args = ob_args
37 | self.corner_chars = corner_chars
38 | self.horizontal_chars = horizontal_chars
39 | self.vertical_chars = vertical_chars
40 | self.__gen_obs()
41 |
42 | def __gen_obs(self):
43 | # Corners
44 | self.corners = [
45 | self.ob_class(
46 | i, arg_proto=self.ob_args, state=self.state
47 | )
48 | for i, j in zip(self.corner_chars, range(4))
49 | ]
50 | for obj, rx, ry in zip(
51 | self.corners, [0, self.width - 1, 0, self.width - 1],
52 | [0, 0, self.height - 1, self.height - 1]
53 | ):
54 | self.add_ob(obj, rx, ry)
55 | # Horizontals
56 | self.horizontals = [
57 | Square(
58 | char=i, width=self.width - 2, height=1,
59 | state=self.state, ob_class=Object, ob_args=self.ob_args
60 | )
61 | for i, j in zip(self.horizontal_chars, range(2))
62 | ]
63 | for obj, rx, ry in zip(self.horizontals, [1, 1], [0, self.height - 1]):
64 | self.add_ob(obj, rx, ry)
65 | # Verticals
66 | self.verticals = [
67 | Square(
68 | char=i, width=1, height=self.height - 2,
69 | state=self.state, ob_class=Object, ob_args=self.ob_args
70 | )
71 | for i, j in zip(self.vertical_chars, range(2))
72 | ]
73 | for obj, rx, ry in zip(self.verticals, [0, self.width - 1], [1, 1]):
74 | self.add_ob(obj, rx, ry)
75 |
76 | def rechar(self, corner_chars=None, horizontal_chars=None,
77 | vertical_chars=None):
78 | """
79 | Rechars the frame.
80 | """
81 | if corner_chars is not None:
82 | self.corner_chars = corner_chars
83 | if horizontal_chars is not None:
84 | self.horizontal_chars = horizontal_chars
85 | if vertical_chars is not None:
86 | self.vertical_chars = vertical_chars
87 |
88 | for obj, _c in zip(self.corners, self.corner_chars):
89 | obj.rechar(_c)
90 | for obj, _c in zip(self.horizontals, self.horizontal_chars):
91 | obj.rechar(_c)
92 | for obj, _c in zip(self.verticals, self.vertical_chars):
93 | obj.rechar(_c)
94 |
95 | def resize(self, height, width):
96 | """
97 | Changes the frames size.
98 | """
99 | super().resize(height, width)
100 | if added := self.added:
101 | self.remove()
102 | self.obs = []
103 | self.__gen_obs()
104 | if added:
105 | self.add(self.map, self.x, self.y)
106 |
--------------------------------------------------------------------------------
/src/scrap_engine/addable/misc/line.py:
--------------------------------------------------------------------------------
1 | import math
2 | from typing import Literal, Type
3 |
4 | from scrap_engine.addable.state import DEFAULT_STATE, State
5 |
6 | from .box import Box
7 | from ..object import Object
8 |
9 | LineType = Literal["straight", "crippled"]
10 |
11 | class Line(Box):
12 | """
13 | A line described by a vector, that cam be added to map.
14 | """
15 |
16 | def __init__(
17 | self, char:str, cx:int, cy:int, l_type:LineType="straight",
18 | state:State=DEFAULT_STATE,
19 | ob_class:Type[Object]=Object, ob_args=None
20 | ):
21 | super().__init__(0, 0)
22 | if ob_args is None:
23 | ob_args = {}
24 | self.char = char
25 | self.ob_class = ob_class
26 | self.ob_args = ob_args
27 | self.state = state
28 | self.type:LineType = l_type
29 | self.__gen(cx, cy)
30 |
31 | def __gen(self, cx:int, cy:int):
32 | self.cx = cx
33 | self.cy = cy
34 | if cx ** 2 >= cy ** 2:
35 | for i in range(int(math.sqrt(cx ** 2))):
36 | i = int(cx / math.sqrt(cx ** 2) * i)
37 | j = {"straight": int, "crippled": round}[self.type](cy * i / cx)
38 | self.add_ob(self.ob_class(self.char, state=self.state,
39 | arg_proto={**self.ob_args, **{"x": i, "y": cy * i / cx}}),
40 | i, j)
41 | else:
42 | for j in range(int(math.sqrt(cy ** 2))):
43 | j = int(cy / math.sqrt(cy ** 2) * j)
44 | i = {"straight": int, "crippled": round}[self.type](cx * j / cy)
45 | self.add_ob(self.ob_class(self.char, state=self.state,
46 | arg_proto={**self.ob_args, **{"x": cx * j / cy, "y": j}}),
47 | i, j)
48 |
49 | def rechar(self, char):
50 | """
51 | Changes the chars the line is made from.
52 | """
53 | self.char = char
54 | for obj in self.obs:
55 | obj.rechar(char)
56 |
57 | def resize(self, cx:int, cy:int):
58 | """
59 | Resizes the line.
60 | """
61 | if added := self.added:
62 | self.remove()
63 | self.obs = []
64 | self.__gen(cx, cy)
65 | if added:
66 | self.add(self.map, self.x, self.y)
67 |
--------------------------------------------------------------------------------
/src/scrap_engine/addable/misc/square.py:
--------------------------------------------------------------------------------
1 | from typing import Type
2 | from scrap_engine.addable.state import DEFAULT_STATE, State
3 | from .box import Box
4 | from ..object import Object
5 |
6 |
7 | class Square(Box):
8 | """
9 | A rectangle, that can be added to a map.
10 | """
11 |
12 | def __init__(
13 | self, char, width, height, state:State=DEFAULT_STATE,
14 | ob_class:Type[Object]=Object, ob_args=None
15 | ):
16 | super().__init__(height, width)
17 | if ob_args is None:
18 | ob_args = {}
19 | if state is not None:
20 | self.state = state
21 | self.ob_class = ob_class
22 | self.char = char
23 | self.ob_args = ob_args
24 | self.__create()
25 |
26 | def __create(self):
27 | for ry in range(self.height):
28 | for rx in range(self.width):
29 | self.add_ob(
30 | self.ob_class(
31 | self.char, self.state, arg_proto=self.ob_args
32 | ),
33 | rx, ry
34 | )
35 |
36 | def rechar(self, char):
37 | """
38 | Changes the chars the Square is filled with.
39 | """
40 | self.char = char
41 | for obj in self.obs:
42 | obj.rechar(char)
43 |
44 | def resize(self, width, height):
45 | """
46 | Resizes the rectangle to a certain size.
47 | """
48 | super().resize(height, width)
49 | if added := self.added:
50 | self.remove()
51 | self.obs = []
52 | self.__create()
53 | if added:
54 | self.add(self.map, self.x, self.y)
55 |
--------------------------------------------------------------------------------
/src/scrap_engine/addable/misc/text.py:
--------------------------------------------------------------------------------
1 | from typing import Type
2 | from scrap_engine.addable.state import DEFAULT_STATE, State
3 | from ..object_group import ObjectGroup
4 | from ..object import Object
5 |
6 |
7 | class Text(ObjectGroup):
8 | """
9 | A datatype containing a string, that can be added to a map.
10 | Different Texts can be added together with the '+' operator.
11 | """
12 |
13 | def __init__(
14 | self, text, state:State=DEFAULT_STATE, esccode="",
15 | ob_class:Type[Object]=Object, ob_args=None, ignore=""
16 | ):
17 | super().__init__([], state)
18 | if ob_args is None:
19 | ob_args = {}
20 | self.ob_class = ob_class
21 | self.text = text
22 | self.esccode = esccode
23 | self.ignore = ignore
24 | self.ob_args = ob_args
25 | self.__texter(text)
26 |
27 | @property
28 | def width(self):
29 | """
30 | The Texts peak width
31 | """
32 | return sorted(len(i) for i in self.text.split("\n"))[-1]
33 |
34 | @property
35 | def height(self):
36 | """
37 | The Texts height
38 | """
39 | return len(self.text.split("\n"))
40 |
41 | def __add__(self, other):
42 | self.text += other.text
43 | self.obs += other.obs
44 | for obj in self.obs:
45 | obj.group = self
46 | if self.added:
47 | self.remove()
48 | self.add(self.map, self.x, self.y)
49 | return self
50 |
51 | def __texter(self, text):
52 | for txt in text.split("\n"):
53 | for char in txt:
54 | if self.esccode != "":
55 | char = self.esccode + char + "\033[0m"
56 | obj = self.ob_class(
57 | char, self.state, arg_proto=self.ob_args
58 | )
59 | obj.group = self
60 | self.obs.append(obj)
61 | for obj in self.obs:
62 | obj.group = self
63 |
64 | def add(self, _map, x, y):
65 | """
66 | Adds the text to a certain coordinate on a certain map.
67 | """
68 | self.added = True
69 | self.map = _map
70 | self.x = x
71 | self.y = y
72 | count = 0
73 | for l, text in enumerate(self.text.split("\n")):
74 | for i, obj in enumerate(self.obs[count:count + len(text)]):
75 | if obj.char != self.ignore:
76 | obj.add(self.map, x + i, y + l)
77 | count += len(text)
78 |
79 | def remove(self):
80 | """
81 | Removes the text from the map.
82 | """
83 | self.added = False
84 | for obj in self.obs:
85 | obj.remove()
86 |
87 | def rem_ob(self, obj):
88 | """
89 | Removes an object from the group.
90 | """
91 | if obj in self.obs:
92 | obj.group = None
93 | index = self.obs.index(obj)
94 | idx = 0
95 | while idx < len(self.text):
96 | if self.text[idx:idx+2] == "\n":
97 | idx += 2
98 | continue
99 | if idx == index:
100 | self.text = self.text[:idx] + self.text[idx + 1:]
101 | break
102 | idx += 1
103 | self.obs.pop(index)
104 | return 0
105 | return 1
106 |
107 | def rechar(self, text, esccode=""):
108 | """
109 | Changes the string contained in the text.
110 | """
111 | self.esccode = esccode
112 | if self.added:
113 | for obj in self.obs:
114 | obj.remove()
115 | self.obs = []
116 | self.__texter(text)
117 | self.text = text
118 | if self.added:
119 | self.add(self.map, self.x, self.y)
120 |
--------------------------------------------------------------------------------
/src/scrap_engine/addable/object.py:
--------------------------------------------------------------------------------
1 | from scrap_engine.addable.state import DEFAULT_STATE, State
2 | from scrap_engine.map.map import Map
3 | from .addable import Addable
4 | from ..error import CoordinateError
5 |
6 | class Object(Addable):
7 | """
8 | An object, containing a character, that can be added to a map.
9 | """
10 |
11 | def __init__(self, char: str, state:State=DEFAULT_STATE, arg_proto=None):
12 | if arg_proto is None:
13 | arg_proto = {}
14 | super().__init__(state)
15 | self.char: str = char
16 | self.arg_proto = arg_proto
17 | self.backup = None
18 |
19 | def add(self, _map:Map, x:int, y:int):
20 | """
21 | Adds the object to a certain coordinate on a certain map.
22 | """
23 | if not 0 <= x < _map.width or not 0 <= y < _map.height:
24 | raise CoordinateError(self, _map, x, y)
25 | if len(lis := _map.obmap[y][x]) != 0 and lis[-1].state == "solid":
26 | return 1
27 | self.backup = _map.map[y][x]
28 | self.x = x
29 | self.y = y
30 | _map.map[y][x] = self.char
31 | _map.obmap[y][x].append(self)
32 | _map.obs.append(self)
33 | self.map = _map
34 | self.added = True
35 | return 0
36 |
37 | def set(self, x:int, y:int):
38 | """
39 | Sets the object to a certain coordinate.
40 | """
41 | if not self.added:
42 | return 1
43 | elif not (0 <= x < self.map.width and 0 <= y < self.map.height):
44 | self.bump(None, x - self.x, y - self.y, side=True)
45 | return 1
46 | elif self.x > self.map.width - 1 or self.y > self.map.height - 1:
47 | self.pull_ob()
48 | return 1
49 | for obj in self.map.obmap[y][x]:
50 | if obj.state == "solid":
51 | self.bump(obj, x - self.x, y - self.y)
52 | return 1
53 | self.__backup_setter()
54 | self.map.obmap[y][x].append(self)
55 | self.backup = self.map.map[y][x]
56 | self.x = x
57 | self.y = y
58 | self.map.map[y][x] = self.char
59 | for obj in self.map.obmap[y][x]:
60 | if obj.state == "float":
61 | obj.action(self)
62 | return 0
63 |
64 | def redraw(self):
65 | """
66 | Redraws the object on the map.
67 | """
68 | if not self.added:
69 | return 1
70 | self.backup = self.map.map[self.y][self.x]
71 | self.map.map[self.y][self.x] = self.char
72 | return 0
73 |
74 | def __backup_setter(self):
75 | if (len(self.map.obmap[self.y][self.x])
76 | > self.map.obmap[self.y][self.x].index(self) + 1):
77 | self.map.obmap[self.y][self.x][self.map.obmap[self.y][self.x].index(self) + 1].backup = self.backup
78 | else:
79 | self.map.map[self.y][self.x] = self.backup
80 | del self.map.obmap[self.y][self.x][self.map.obmap[self.y][self.x].index(self)]
81 |
82 | def action(self, ob):
83 | """
84 | This is triggered when another object is set over this one.
85 | """
86 | return
87 |
88 | def bump(self, ob, x, y, side=False):
89 | """
90 | This is triggered, when this object is tried to be set onto another
91 | solid object. Or it hits the side of the map, in which case `side == True`.
92 | `x` and `ỳ` are the vectore self should have been set to.
93 | """
94 | return
95 |
96 | def pull_ob(self):
97 | """
98 | This is triggered, when trying to set an object from a non existing
99 | spot on the map to an existing one.
100 | This is just usefull when resizing maps with objects out of the
101 | new size.
102 | """
103 | return
104 |
105 | def rechar(self, char):
106 | """
107 | Changes the objects character.
108 | """
109 | self.char = char
110 | if not self.added:
111 | return 1
112 | self.map.map[self.y][self.x] = self.backup
113 | self.redraw()
114 | return 0
115 |
116 | def remove(self):
117 | """
118 | Removes the object from the map.
119 | """
120 | if not self.added:
121 | return 1
122 | self.added = False
123 | self.__backup_setter()
124 | del self.map.obs[self.map.obs.index(self)]
125 | return 0
126 |
--------------------------------------------------------------------------------
/src/scrap_engine/addable/object_group.py:
--------------------------------------------------------------------------------
1 | from scrap_engine.addable.state import DEFAULT_STATE, State
2 | from .addable import Addable
3 |
4 |
5 | class ObjectGroup(Addable):
6 | """
7 | A datatype used to group objects together and do things with them
8 | simultaniuously.
9 | """
10 |
11 | def __init__(self, obs, state:State=DEFAULT_STATE):
12 | super().__init__(state)
13 | self.obs = obs
14 | for obj in obs:
15 | obj.group = self
16 |
17 | def add_ob(self, obj):
18 | """
19 | Adds and object to the group.
20 | """
21 | self.obs.append(obj)
22 | obj.group = self
23 |
24 | def add_obs(self, obs):
25 | """
26 | Adds a list of objects to th group.
27 | """
28 | for obj in obs:
29 | self.add_ob(obj)
30 |
31 | def rem_ob(self, obj):
32 | """
33 | Removes an object from the group.
34 | """
35 | if obj in self.obs:
36 | obj.group = None
37 | self.obs.pop(self.obs.index(obj))
38 | return 0
39 | return 1
40 |
41 | def move(self, x=0, y=0):
42 | """
43 | Moves all objects in the group by a certain vector.
44 | """
45 | for obj in self.obs:
46 | obj.remove()
47 | for obj in self.obs:
48 | obj.add(self.map, obj.x + x, obj.y + y)
49 |
50 | def remove(self):
51 | """
52 | Removes all objects from their maps.
53 | """
54 | for obj in self.obs:
55 | obj.remove()
56 |
57 | def set(self, x:int, y:int):
58 | """
59 | Sets the group to a certain coordinate.
60 | !!! Just use this with inherited classes !!!
61 | """
62 | self.move(x - self.x, y - self.y)
63 | self.x = x
64 | self.y = y
65 |
66 | def set_state(self, state:State):
67 | """
68 | Sets all objects states to a certain state.
69 | """
70 | super().set_state(state)
71 | for obj in self.obs:
72 | obj.set_state(state)
73 |
--------------------------------------------------------------------------------
/src/scrap_engine/addable/state.py:
--------------------------------------------------------------------------------
1 | from typing import Literal
2 |
3 |
4 | State = Literal["float", "solid"]
5 |
6 | DEFAULT_STATE:State = "solid"
7 |
--------------------------------------------------------------------------------
/src/scrap_engine/consts.py:
--------------------------------------------------------------------------------
1 | import os
2 |
3 |
4 | MAXCACHE_LINE = 512
5 | MAXCACHE_FRAME = 64
6 |
7 |
8 | try:
9 | screen_width, screen_height = os.get_terminal_size()
10 | except OSError:
11 | screen_width, screen_height = 100, 100
12 |
--------------------------------------------------------------------------------
/src/scrap_engine/error.py:
--------------------------------------------------------------------------------
1 | class CoordinateError(Exception):
2 | """
3 | An Error that is thrown, when an object is added to a non-existing
4 | part of a map.
5 | """
6 |
7 | def __init__(self, obj, _map, x, y):
8 | self.ob = obj
9 | self.x = x
10 | self.y = y
11 | self.map = _map
12 | super().__init__(
13 | f"The {obj}s coordinate ({x}|{y}) is "
14 | f"not in {self.map.width - 1}x{self.map.height - 1}"
15 | )
16 |
--------------------------------------------------------------------------------
/src/scrap_engine/map/__init__.py:
--------------------------------------------------------------------------------
1 | from .map import Map
2 | from .submap import Submap
3 |
--------------------------------------------------------------------------------
/src/scrap_engine/map/map.py:
--------------------------------------------------------------------------------
1 | import functools
2 |
3 | from ..consts import screen_height, screen_width, MAXCACHE_FRAME, MAXCACHE_LINE
4 |
5 | class Map:
6 | """
7 | The map, objects can be added to.
8 | """
9 |
10 | def __init__(self, height=screen_height - 1, width=screen_width,
11 | background="#", dynfps=True):
12 | self.height = height
13 | self.width = width
14 | self.dynfps = dynfps
15 | self.background = background
16 | self.map = [[self.background for _ in range(width)]
17 | for _ in range(height)]
18 | self.obmap = [[[] for _ in range(width)] for _ in range(height)]
19 | self.obs = []
20 | self.out_old = ""
21 |
22 | def blur_in(self, blurmap, esccode="\033[37m"):
23 | """
24 | Sets another maps content as its background.
25 | """
26 | for h in range(self.height):
27 | for w in range(self.width):
28 | if blurmap.map[h][w] != " ":
29 | self.map[h][w] = (esccode +
30 | blurmap.map[h][w].replace("\033[0m", "")[-1] +
31 | "\033[0m")
32 | else:
33 | self.map[h][w] = " "
34 | for obj in self.obs:
35 | obj.redraw()
36 |
37 | def show(self, init=False):
38 | """
39 | Prints the maps content.
40 | """
41 | _map = (tuple(arr) for arr in self.map)
42 | out = self.__show_map(self.__show_line, _map)
43 | if self.out_old != out or not self.dynfps or init:
44 | print(out + "\n\033[0E\033[2K", end="")
45 | self.out_old = out
46 |
47 | @staticmethod
48 | @functools.lru_cache(MAXCACHE_FRAME)
49 | def __show_map(show_line, _map):
50 | out = "\033[H"
51 | for arr in _map:
52 | out += show_line(arr)
53 | return out
54 |
55 | @staticmethod
56 | @functools.lru_cache(MAXCACHE_LINE)
57 | def __show_line(arr):
58 | out_line = ""
59 | for char in arr:
60 | out_line += char
61 | return out_line
62 |
63 | def resize(self, height, width, background="#"):
64 | """
65 | Resizes the map to a certain size.
66 | """
67 | self.background = background
68 | self.map = [[self.background for _ in range(width)]
69 | for _ in range(height)]
70 | self.obmap = [[[] for _ in range(width
71 | if width > self.width else self.width)]
72 | for _ in range(height
73 | if height > self.height else self.height)]
74 | self.width = width
75 | self.height = height
76 | for obj in self.obs:
77 | if obj.y < height and obj.x < width:
78 | self.obmap[obj.y][obj.x].append(obj)
79 | obj.redraw()
80 |
--------------------------------------------------------------------------------
/src/scrap_engine/map/submap.py:
--------------------------------------------------------------------------------
1 | import functools
2 |
3 | from .map import Map
4 | from ..consts import screen_height, screen_width
5 |
6 | class Submap(Map):
7 | """
8 | Behaves just like a map, but it self contains a part of another map.
9 | """
10 |
11 | def __init__(self, bmap, x, y, height=screen_height - 1,
12 | width=screen_width, dynfps=True):
13 | super().__init__(height, width, dynfps=dynfps)
14 | del self.background
15 | self.y = y
16 | self.x = x
17 | self.bmap = bmap
18 | self.remap()
19 |
20 | def remap(self):
21 | """
22 | Updates the map (rereads the map, the submap contains a part from)
23 | """
24 | self.map = self.__full_bg(self.bmap.background, self.width, self.height)
25 | self.map = self.__map_to_parent(self.height, self.width, self.y, self.x,
26 | (tuple(line) for line in self.map),
27 | (tuple(line) for line in self.bmap.map))
28 | for obj in self.obs:
29 | obj.redraw()
30 |
31 | @staticmethod
32 | @functools.lru_cache()
33 | def __map_to_parent(height, width, _y, _x, parent, child):
34 | parent = [list(line) for line in parent]
35 | child = [list(line) for line in child]
36 | for sy, y in zip(range(0, height),
37 | range(_y, _y + height)):
38 | for sx, x in zip(range(0, width),
39 | range(_x, _x + width)):
40 | try:
41 | parent[sy][sx] = child[y][x]
42 | except IndexError:
43 | continue
44 | return parent
45 |
46 | @staticmethod
47 | @functools.lru_cache(1)
48 | def __full_bg(background, width, height):
49 | return [[background for _ in range(width)]
50 | for _ in range(height)]
51 |
52 | def set(self, x, y):
53 | """
54 | Changes the coordinates on the map, the submap is at.
55 | """
56 | if x < 0 or y < 0:
57 | return 1
58 | self.x = x
59 | self.y = y
60 | self.remap()
61 | return 0
62 |
63 | def full_show(self, init=False):
64 | """
65 | Combines remap() and show().
66 | """
67 | self.remap()
68 | self.show(init)
69 |
--------------------------------------------------------------------------------
/tests/__init__.py:
--------------------------------------------------------------------------------
1 | from .add_text_test import TextTest
2 | from .circle import CircleTest
3 | from .circler import CirclerTest
4 | from .stack_test import StackTest
5 |
--------------------------------------------------------------------------------
/tests/add_text_test.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/python3
2 |
3 | import unittest
4 | import scrap_engine as se
5 |
6 | class TextTest(unittest.TestCase):
7 | def test_text(self):
8 | map = se.Map(background=" ")
9 |
10 | t = se.Text("Hello")
11 | t.add(map, 0, 0)
12 |
13 | k = se.Text(" You", esccode="\033[31m")
14 | t+=k
15 |
16 | map.show()
17 |
--------------------------------------------------------------------------------
/tests/circle.py:
--------------------------------------------------------------------------------
1 | import scrap_engine as se
2 | import math
3 | import unittest
4 |
5 | class CircleTest(unittest.TestCase):
6 | def test_circle(self):
7 | class Circle(se.Box):
8 | def __init__(self, char, radius):
9 | super().__init__(0, 0)
10 | self.char = char
11 | self.radius = radius
12 | for i in range(-(int(radius)+1), int(radius+1)+1):
13 | for j in range(-(int(radius)+1), int(radius+1)+1):
14 | if math.sqrt((i)**2+(j)**2) <= radius:
15 | self.add_ob(se.Object(char), i, j)
16 |
17 | map = se.Map(background=" ")
18 |
19 | circle = Circle("#", 4.3)
20 | circle.add(map, 6, 6)
21 | circle.set(20, 10)
22 |
23 | map.show()
24 |
--------------------------------------------------------------------------------
/tests/circler.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python3
2 |
3 | import unittest
4 | import scrap_engine as se
5 | import math, time
6 |
7 |
8 | class CirclerTest(unittest.TestCase):
9 | def test_circler(self):
10 | map = se.Map(background=" ")
11 |
12 | def circle(x, y, radius):
13 | for i in range(map.height)[(y-radius if y-radius in range(map.height) else 0):][:(y+radius if y+radius in range(map.height) else map.height)]:
14 | for j in range(map.width)[x-radius:][:x+radius]:
15 | if math.sqrt((i-y)**2+(j-x)**2) <= radius:
16 | try:
17 | se.Object("a").add(map, j, i)
18 | except:
19 | continue
20 |
21 | map.show(init=True)
22 | for i in range(int(map.width/2)):
23 | time.sleep(0.1)
24 | circle(int(map.width/2), int(map.height/2), i)
25 | map.show()
26 | while len(map.obs) > 0:
27 | map.obs[0].remove()
28 |
--------------------------------------------------------------------------------
/tests/stack_test.py:
--------------------------------------------------------------------------------
1 | import unittest
2 | import scrap_engine as se
3 |
4 |
5 | class StackTest(unittest.TestCase):
6 | def test_stack(self):
7 | map = se.Map(background=" ")
8 |
9 | a = se.Object("a", state="float")
10 | b = se.Object("b", state="float")
11 | c = se.Object("c", state="float")
12 |
13 | a.add(map, 1, 1)
14 | b.add(map, 1, 1)
15 | c.add(map, 1, 1)
16 |
17 | b.set(0, 0)
18 | c.set(0, 0)
19 |
20 | map.show()
21 |
--------------------------------------------------------------------------------