├── .gitignore ├── CONTRIBUTING.md ├── LICENSE ├── README.md ├── index.html ├── logo.png ├── pygame ├── __init__.js ├── display.js ├── draw.js ├── event.js ├── font.js ├── image.js ├── key.js ├── mouse.js ├── time.js ├── transform.js └── version.js ├── run-example.bat ├── run-example.sh ├── skulpt_dist ├── debugger.js ├── skulpt-stdlib.js └── skulpt.min.js └── test ├── advanced-exmp.py ├── color_test.py ├── display_test.py ├── draw.py ├── drawing-exmp.py ├── events-exmp.py ├── font.py ├── font_test.py ├── get_pressed_test.py ├── image-exmp.py ├── image_test.py ├── key_example.py ├── key_test.py ├── keyup-example.py ├── mouse_test.py ├── primer1.py ├── primer2.py ├── primer3.py ├── primer4.py ├── primer5.py ├── pygame_test.py ├── rect_method_test.py ├── rect_property_test.py ├── simple_game.py ├── snake.py ├── spaceship.png ├── spaceship.py ├── spirograph.py ├── surface_test.py ├── tick_clock.py ├── transform_test.py ├── transform_test2.py └── version_test.py /.gitignore: -------------------------------------------------------------------------------- 1 | .vscode/ 2 | .idea/ 3 | venv/ 4 | .venv/ 5 | .DS_Store 6 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # Contributing 2 | 3 | If you want to contribute, take a look at the [issues](https://github.com/Petlja/pygame4skulpt/issues). 4 | Contribution workflow is a standard [fork and pull](https://help.github.com/articles/creating-a-pull-request-from-a-fork/). 5 | General Skulpt contribution tutorial can be found [here](https://github.com/skulpt/skulpt/blob/master/HACKING.md), and the 6 | coding style guide [here](https://github.com/skulpt/skulpt/blob/master/CONTRIBUTING.md#coding-style-and-conventions). 7 | 8 | In addition to your functionality, make sure to add a unit test into the [test](https://github.com/Petlja/pygame4skulpt/tree/master/test) directory. 9 | If adding a functionality that is to be tested by running an example, you can add a Pygame program that exposes it. 10 | A good example is [test/tick_clock.py](https://github.com/Petlja/pygame4skulpt/blob/master/test/tick_clock.py). 11 | Otherwise, you can make use of the ```unittest``` library as in [test/version_test.py](https://github.com/Petlja/pygame4skulpt/blob/master/test/version_test.py). 12 | You might find useful to run the test using the index page. All you have to do is to run it with a query string representing 13 | the filename of your test. 14 | ~~~ 15 | http://localhost:8888/index.html?tick_clock.py 16 | ~~~ -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU LESSER GENERAL PUBLIC LICENSE 2 | Version 2.1, February 1999 3 | 4 | Copyright (C) 1991, 1999 Free Software Foundation, Inc. 5 | 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA 6 | Everyone is permitted to copy and distribute verbatim copies 7 | of this license document, but changing it is not allowed. 8 | 9 | [This is the first released version of the Lesser GPL. It also counts 10 | as the successor of the GNU Library Public License, version 2, hence 11 | the version number 2.1.] 12 | 13 | Preamble 14 | 15 | The licenses for most software are designed to take away your 16 | freedom to share and change it. By contrast, the GNU General Public 17 | Licenses are intended to guarantee your freedom to share and change 18 | free software--to make sure the software is free for all its users. 19 | 20 | This license, the Lesser General Public License, applies to some 21 | specially designated software packages--typically libraries--of the 22 | Free Software Foundation and other authors who decide to use it. You 23 | can use it too, but we suggest you first think carefully about whether 24 | this license or the ordinary General Public License is the better 25 | strategy to use in any particular case, based on the explanations below. 26 | 27 | When we speak of free software, we are referring to freedom of use, 28 | not price. Our General Public Licenses are designed to make sure that 29 | you have the freedom to distribute copies of free software (and charge 30 | for this service if you wish); that you receive source code or can get 31 | it if you want it; that you can change the software and use pieces of 32 | it in new free programs; and that you are informed that you can do 33 | these things. 34 | 35 | To protect your rights, we need to make restrictions that forbid 36 | distributors to deny you these rights or to ask you to surrender these 37 | rights. These restrictions translate to certain responsibilities for 38 | you if you distribute copies of the library or if you modify it. 39 | 40 | For example, if you distribute copies of the library, whether gratis 41 | or for a fee, you must give the recipients all the rights that we gave 42 | you. You must make sure that they, too, receive or can get the source 43 | code. If you link other code with the library, you must provide 44 | complete object files to the recipients, so that they can relink them 45 | with the library after making changes to the library and recompiling 46 | it. And you must show them these terms so they know their rights. 47 | 48 | We protect your rights with a two-step method: (1) we copyright the 49 | library, and (2) we offer you this license, which gives you legal 50 | permission to copy, distribute and/or modify the library. 51 | 52 | To protect each distributor, we want to make it very clear that 53 | there is no warranty for the free library. Also, if the library is 54 | modified by someone else and passed on, the recipients should know 55 | that what they have is not the original version, so that the original 56 | author's reputation will not be affected by problems that might be 57 | introduced by others. 58 | 59 | Finally, software patents pose a constant threat to the existence of 60 | any free program. We wish to make sure that a company cannot 61 | effectively restrict the users of a free program by obtaining a 62 | restrictive license from a patent holder. Therefore, we insist that 63 | any patent license obtained for a version of the library must be 64 | consistent with the full freedom of use specified in this license. 65 | 66 | Most GNU software, including some libraries, is covered by the 67 | ordinary GNU General Public License. This license, the GNU Lesser 68 | General Public License, applies to certain designated libraries, and 69 | is quite different from the ordinary General Public License. We use 70 | this license for certain libraries in order to permit linking those 71 | libraries into non-free programs. 72 | 73 | When a program is linked with a library, whether statically or using 74 | a shared library, the combination of the two is legally speaking a 75 | combined work, a derivative of the original library. The ordinary 76 | General Public License therefore permits such linking only if the 77 | entire combination fits its criteria of freedom. The Lesser General 78 | Public License permits more lax criteria for linking other code with 79 | the library. 80 | 81 | We call this license the "Lesser" General Public License because it 82 | does Less to protect the user's freedom than the ordinary General 83 | Public License. It also provides other free software developers Less 84 | of an advantage over competing non-free programs. These disadvantages 85 | are the reason we use the ordinary General Public License for many 86 | libraries. However, the Lesser license provides advantages in certain 87 | special circumstances. 88 | 89 | For example, on rare occasions, there may be a special need to 90 | encourage the widest possible use of a certain library, so that it becomes 91 | a de-facto standard. To achieve this, non-free programs must be 92 | allowed to use the library. A more frequent case is that a free 93 | library does the same job as widely used non-free libraries. In this 94 | case, there is little to gain by limiting the free library to free 95 | software only, so we use the Lesser General Public License. 96 | 97 | In other cases, permission to use a particular library in non-free 98 | programs enables a greater number of people to use a large body of 99 | free software. For example, permission to use the GNU C Library in 100 | non-free programs enables many more people to use the whole GNU 101 | operating system, as well as its variant, the GNU/Linux operating 102 | system. 103 | 104 | Although the Lesser General Public License is Less protective of the 105 | users' freedom, it does ensure that the user of a program that is 106 | linked with the Library has the freedom and the wherewithal to run 107 | that program using a modified version of the Library. 108 | 109 | The precise terms and conditions for copying, distribution and 110 | modification follow. Pay close attention to the difference between a 111 | "work based on the library" and a "work that uses the library". The 112 | former contains code derived from the library, whereas the latter must 113 | be combined with the library in order to run. 114 | 115 | GNU LESSER GENERAL PUBLIC LICENSE 116 | TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 117 | 118 | 0. This License Agreement applies to any software library or other 119 | program which contains a notice placed by the copyright holder or 120 | other authorized party saying it may be distributed under the terms of 121 | this Lesser General Public License (also called "this License"). 122 | Each licensee is addressed as "you". 123 | 124 | A "library" means a collection of software functions and/or data 125 | prepared so as to be conveniently linked with application programs 126 | (which use some of those functions and data) to form executables. 127 | 128 | The "Library", below, refers to any such software library or work 129 | which has been distributed under these terms. A "work based on the 130 | Library" means either the Library or any derivative work under 131 | copyright law: that is to say, a work containing the Library or a 132 | portion of it, either verbatim or with modifications and/or translated 133 | straightforwardly into another language. (Hereinafter, translation is 134 | included without limitation in the term "modification".) 135 | 136 | "Source code" for a work means the preferred form of the work for 137 | making modifications to it. For a library, complete source code means 138 | all the source code for all modules it contains, plus any associated 139 | interface definition files, plus the scripts used to control compilation 140 | and installation of the library. 141 | 142 | Activities other than copying, distribution and modification are not 143 | covered by this License; they are outside its scope. The act of 144 | running a program using the Library is not restricted, and output from 145 | such a program is covered only if its contents constitute a work based 146 | on the Library (independent of the use of the Library in a tool for 147 | writing it). Whether that is true depends on what the Library does 148 | and what the program that uses the Library does. 149 | 150 | 1. You may copy and distribute verbatim copies of the Library's 151 | complete source code as you receive it, in any medium, provided that 152 | you conspicuously and appropriately publish on each copy an 153 | appropriate copyright notice and disclaimer of warranty; keep intact 154 | all the notices that refer to this License and to the absence of any 155 | warranty; and distribute a copy of this License along with the 156 | Library. 157 | 158 | You may charge a fee for the physical act of transferring a copy, 159 | and you may at your option offer warranty protection in exchange for a 160 | fee. 161 | 162 | 2. You may modify your copy or copies of the Library or any portion 163 | of it, thus forming a work based on the Library, and copy and 164 | distribute such modifications or work under the terms of Section 1 165 | above, provided that you also meet all of these conditions: 166 | 167 | a) The modified work must itself be a software library. 168 | 169 | b) You must cause the files modified to carry prominent notices 170 | stating that you changed the files and the date of any change. 171 | 172 | c) You must cause the whole of the work to be licensed at no 173 | charge to all third parties under the terms of this License. 174 | 175 | d) If a facility in the modified Library refers to a function or a 176 | table of data to be supplied by an application program that uses 177 | the facility, other than as an argument passed when the facility 178 | is invoked, then you must make a good faith effort to ensure that, 179 | in the event an application does not supply such function or 180 | table, the facility still operates, and performs whatever part of 181 | its purpose remains meaningful. 182 | 183 | (For example, a function in a library to compute square roots has 184 | a purpose that is entirely well-defined independent of the 185 | application. Therefore, Subsection 2d requires that any 186 | application-supplied function or table used by this function must 187 | be optional: if the application does not supply it, the square 188 | root function must still compute square roots.) 189 | 190 | These requirements apply to the modified work as a whole. If 191 | identifiable sections of that work are not derived from the Library, 192 | and can be reasonably considered independent and separate works in 193 | themselves, then this License, and its terms, do not apply to those 194 | sections when you distribute them as separate works. But when you 195 | distribute the same sections as part of a whole which is a work based 196 | on the Library, the distribution of the whole must be on the terms of 197 | this License, whose permissions for other licensees extend to the 198 | entire whole, and thus to each and every part regardless of who wrote 199 | it. 200 | 201 | Thus, it is not the intent of this section to claim rights or contest 202 | your rights to work written entirely by you; rather, the intent is to 203 | exercise the right to control the distribution of derivative or 204 | collective works based on the Library. 205 | 206 | In addition, mere aggregation of another work not based on the Library 207 | with the Library (or with a work based on the Library) on a volume of 208 | a storage or distribution medium does not bring the other work under 209 | the scope of this License. 210 | 211 | 3. You may opt to apply the terms of the ordinary GNU General Public 212 | License instead of this License to a given copy of the Library. To do 213 | this, you must alter all the notices that refer to this License, so 214 | that they refer to the ordinary GNU General Public License, version 2, 215 | instead of to this License. (If a newer version than version 2 of the 216 | ordinary GNU General Public License has appeared, then you can specify 217 | that version instead if you wish.) Do not make any other change in 218 | these notices. 219 | 220 | Once this change is made in a given copy, it is irreversible for 221 | that copy, so the ordinary GNU General Public License applies to all 222 | subsequent copies and derivative works made from that copy. 223 | 224 | This option is useful when you wish to copy part of the code of 225 | the Library into a program that is not a library. 226 | 227 | 4. You may copy and distribute the Library (or a portion or 228 | derivative of it, under Section 2) in object code or executable form 229 | under the terms of Sections 1 and 2 above provided that you accompany 230 | it with the complete corresponding machine-readable source code, which 231 | must be distributed under the terms of Sections 1 and 2 above on a 232 | medium customarily used for software interchange. 233 | 234 | If distribution of object code is made by offering access to copy 235 | from a designated place, then offering equivalent access to copy the 236 | source code from the same place satisfies the requirement to 237 | distribute the source code, even though third parties are not 238 | compelled to copy the source along with the object code. 239 | 240 | 5. A program that contains no derivative of any portion of the 241 | Library, but is designed to work with the Library by being compiled or 242 | linked with it, is called a "work that uses the Library". Such a 243 | work, in isolation, is not a derivative work of the Library, and 244 | therefore falls outside the scope of this License. 245 | 246 | However, linking a "work that uses the Library" with the Library 247 | creates an executable that is a derivative of the Library (because it 248 | contains portions of the Library), rather than a "work that uses the 249 | library". The executable is therefore covered by this License. 250 | Section 6 states terms for distribution of such executables. 251 | 252 | When a "work that uses the Library" uses material from a header file 253 | that is part of the Library, the object code for the work may be a 254 | derivative work of the Library even though the source code is not. 255 | Whether this is true is especially significant if the work can be 256 | linked without the Library, or if the work is itself a library. The 257 | threshold for this to be true is not precisely defined by law. 258 | 259 | If such an object file uses only numerical parameters, data 260 | structure layouts and accessors, and small macros and small inline 261 | functions (ten lines or less in length), then the use of the object 262 | file is unrestricted, regardless of whether it is legally a derivative 263 | work. (Executables containing this object code plus portions of the 264 | Library will still fall under Section 6.) 265 | 266 | Otherwise, if the work is a derivative of the Library, you may 267 | distribute the object code for the work under the terms of Section 6. 268 | Any executables containing that work also fall under Section 6, 269 | whether or not they are linked directly with the Library itself. 270 | 271 | 6. As an exception to the Sections above, you may also combine or 272 | link a "work that uses the Library" with the Library to produce a 273 | work containing portions of the Library, and distribute that work 274 | under terms of your choice, provided that the terms permit 275 | modification of the work for the customer's own use and reverse 276 | engineering for debugging such modifications. 277 | 278 | You must give prominent notice with each copy of the work that the 279 | Library is used in it and that the Library and its use are covered by 280 | this License. You must supply a copy of this License. If the work 281 | during execution displays copyright notices, you must include the 282 | copyright notice for the Library among them, as well as a reference 283 | directing the user to the copy of this License. Also, you must do one 284 | of these things: 285 | 286 | a) Accompany the work with the complete corresponding 287 | machine-readable source code for the Library including whatever 288 | changes were used in the work (which must be distributed under 289 | Sections 1 and 2 above); and, if the work is an executable linked 290 | with the Library, with the complete machine-readable "work that 291 | uses the Library", as object code and/or source code, so that the 292 | user can modify the Library and then relink to produce a modified 293 | executable containing the modified Library. (It is understood 294 | that the user who changes the contents of definitions files in the 295 | Library will not necessarily be able to recompile the application 296 | to use the modified definitions.) 297 | 298 | b) Use a suitable shared library mechanism for linking with the 299 | Library. A suitable mechanism is one that (1) uses at run time a 300 | copy of the library already present on the user's computer system, 301 | rather than copying library functions into the executable, and (2) 302 | will operate properly with a modified version of the library, if 303 | the user installs one, as long as the modified version is 304 | interface-compatible with the version that the work was made with. 305 | 306 | c) Accompany the work with a written offer, valid for at 307 | least three years, to give the same user the materials 308 | specified in Subsection 6a, above, for a charge no more 309 | than the cost of performing this distribution. 310 | 311 | d) If distribution of the work is made by offering access to copy 312 | from a designated place, offer equivalent access to copy the above 313 | specified materials from the same place. 314 | 315 | e) Verify that the user has already received a copy of these 316 | materials or that you have already sent this user a copy. 317 | 318 | For an executable, the required form of the "work that uses the 319 | Library" must include any data and utility programs needed for 320 | reproducing the executable from it. However, as a special exception, 321 | the materials to be distributed need not include anything that is 322 | normally distributed (in either source or binary form) with the major 323 | components (compiler, kernel, and so on) of the operating system on 324 | which the executable runs, unless that component itself accompanies 325 | the executable. 326 | 327 | It may happen that this requirement contradicts the license 328 | restrictions of other proprietary libraries that do not normally 329 | accompany the operating system. Such a contradiction means you cannot 330 | use both them and the Library together in an executable that you 331 | distribute. 332 | 333 | 7. You may place library facilities that are a work based on the 334 | Library side-by-side in a single library together with other library 335 | facilities not covered by this License, and distribute such a combined 336 | library, provided that the separate distribution of the work based on 337 | the Library and of the other library facilities is otherwise 338 | permitted, and provided that you do these two things: 339 | 340 | a) Accompany the combined library with a copy of the same work 341 | based on the Library, uncombined with any other library 342 | facilities. This must be distributed under the terms of the 343 | Sections above. 344 | 345 | b) Give prominent notice with the combined library of the fact 346 | that part of it is a work based on the Library, and explaining 347 | where to find the accompanying uncombined form of the same work. 348 | 349 | 8. You may not copy, modify, sublicense, link with, or distribute 350 | the Library except as expressly provided under this License. Any 351 | attempt otherwise to copy, modify, sublicense, link with, or 352 | distribute the Library is void, and will automatically terminate your 353 | rights under this License. However, parties who have received copies, 354 | or rights, from you under this License will not have their licenses 355 | terminated so long as such parties remain in full compliance. 356 | 357 | 9. You are not required to accept this License, since you have not 358 | signed it. However, nothing else grants you permission to modify or 359 | distribute the Library or its derivative works. These actions are 360 | prohibited by law if you do not accept this License. Therefore, by 361 | modifying or distributing the Library (or any work based on the 362 | Library), you indicate your acceptance of this License to do so, and 363 | all its terms and conditions for copying, distributing or modifying 364 | the Library or works based on it. 365 | 366 | 10. Each time you redistribute the Library (or any work based on the 367 | Library), the recipient automatically receives a license from the 368 | original licensor to copy, distribute, link with or modify the Library 369 | subject to these terms and conditions. You may not impose any further 370 | restrictions on the recipients' exercise of the rights granted herein. 371 | You are not responsible for enforcing compliance by third parties with 372 | this License. 373 | 374 | 11. If, as a consequence of a court judgment or allegation of patent 375 | infringement or for any other reason (not limited to patent issues), 376 | conditions are imposed on you (whether by court order, agreement or 377 | otherwise) that contradict the conditions of this License, they do not 378 | excuse you from the conditions of this License. If you cannot 379 | distribute so as to satisfy simultaneously your obligations under this 380 | License and any other pertinent obligations, then as a consequence you 381 | may not distribute the Library at all. For example, if a patent 382 | license would not permit royalty-free redistribution of the Library by 383 | all those who receive copies directly or indirectly through you, then 384 | the only way you could satisfy both it and this License would be to 385 | refrain entirely from distribution of the Library. 386 | 387 | If any portion of this section is held invalid or unenforceable under any 388 | particular circumstance, the balance of the section is intended to apply, 389 | and the section as a whole is intended to apply in other circumstances. 390 | 391 | It is not the purpose of this section to induce you to infringe any 392 | patents or other property right claims or to contest validity of any 393 | such claims; this section has the sole purpose of protecting the 394 | integrity of the free software distribution system which is 395 | implemented by public license practices. Many people have made 396 | generous contributions to the wide range of software distributed 397 | through that system in reliance on consistent application of that 398 | system; it is up to the author/donor to decide if he or she is willing 399 | to distribute software through any other system and a licensee cannot 400 | impose that choice. 401 | 402 | This section is intended to make thoroughly clear what is believed to 403 | be a consequence of the rest of this License. 404 | 405 | 12. If the distribution and/or use of the Library is restricted in 406 | certain countries either by patents or by copyrighted interfaces, the 407 | original copyright holder who places the Library under this License may add 408 | an explicit geographical distribution limitation excluding those countries, 409 | so that distribution is permitted only in or among countries not thus 410 | excluded. In such case, this License incorporates the limitation as if 411 | written in the body of this License. 412 | 413 | 13. The Free Software Foundation may publish revised and/or new 414 | versions of the Lesser General Public License from time to time. 415 | Such new versions will be similar in spirit to the present version, 416 | but may differ in detail to address new problems or concerns. 417 | 418 | Each version is given a distinguishing version number. If the Library 419 | specifies a version number of this License which applies to it and 420 | "any later version", you have the option of following the terms and 421 | conditions either of that version or of any later version published by 422 | the Free Software Foundation. If the Library does not specify a 423 | license version number, you may choose any version ever published by 424 | the Free Software Foundation. 425 | 426 | 14. If you wish to incorporate parts of the Library into other free 427 | programs whose distribution conditions are incompatible with these, 428 | write to the author to ask for permission. For software which is 429 | copyrighted by the Free Software Foundation, write to the Free 430 | Software Foundation; we sometimes make exceptions for this. Our 431 | decision will be guided by the two goals of preserving the free status 432 | of all derivatives of our free software and of promoting the sharing 433 | and reuse of software generally. 434 | 435 | NO WARRANTY 436 | 437 | 15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO 438 | WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW. 439 | EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR 440 | OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY 441 | KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE 442 | IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 443 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE 444 | LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME 445 | THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 446 | 447 | 16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN 448 | WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY 449 | AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU 450 | FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR 451 | CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE 452 | LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING 453 | RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A 454 | FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF 455 | SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH 456 | DAMAGES. 457 | 458 | END OF TERMS AND CONDITIONS 459 | 460 | How to Apply These Terms to Your New Libraries 461 | 462 | If you develop a new library, and you want it to be of the greatest 463 | possible use to the public, we recommend making it free software that 464 | everyone can redistribute and change. You can do so by permitting 465 | redistribution under these terms (or, alternatively, under the terms of the 466 | ordinary General Public License). 467 | 468 | To apply these terms, attach the following notices to the library. It is 469 | safest to attach them to the start of each source file to most effectively 470 | convey the exclusion of warranty; and each file should have at least the 471 | "copyright" line and a pointer to where the full notice is found. 472 | 473 | 474 | Copyright (C) 475 | 476 | This library is free software; you can redistribute it and/or 477 | modify it under the terms of the GNU Lesser General Public 478 | License as published by the Free Software Foundation; either 479 | version 2.1 of the License, or (at your option) any later version. 480 | 481 | This library is distributed in the hope that it will be useful, 482 | but WITHOUT ANY WARRANTY; without even the implied warranty of 483 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 484 | Lesser General Public License for more details. 485 | 486 | You should have received a copy of the GNU Lesser General Public 487 | License along with this library; if not, write to the Free Software 488 | Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 489 | USA 490 | 491 | Also add information on how to contact you by electronic and paper mail. 492 | 493 | You should also get your employer (if you work as a programmer) or your 494 | school, if any, to sign a "copyright disclaimer" for the library, if 495 | necessary. Here is a sample; alter the names: 496 | 497 | Yoyodyne, Inc., hereby disclaims all copyright interest in the 498 | library `Frob' (a library for tweaking knobs) written by James Random 499 | Hacker. 500 | 501 | , 1 April 1990 502 | Ty Coon, President of Vice 503 | 504 | That's all there is to it! 505 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Pygame module for Skulpt 2 | An example of the module can be found on [http://petlja.github.io/pygame4skulpt](http://petlja.github.io/pygame4skulpt). 3 | ## How to use 4 | In order to use the module, you will probably want to have files served by a http server as in [run-example.sh](https://github.com/Petlja/pygame4skulpt/blob/master/run-example.sh) and [run-example.bat](https://github.com/Petlja/pygame4skulpt/blob/master/run-example.bat). 5 | Our Pygame module can be imported as follows: 6 | ~~~ 7 | var basePath = 'pygame/'; 8 | Sk.externalLibraries = { 9 | 'pygame': { 10 | path: basePath + '__init__.js', 11 | }, 12 | 'pygame.display': { 13 | path: basePath + 'display.js', 14 | }, 15 | 'pygame.draw': { 16 | path: basePath + 'draw.js', 17 | }, 18 | 'pygame.event': { 19 | path: basePath + 'event.js', 20 | }, 21 | 'pygame.font': { 22 | path: basePath + 'font.js', 23 | }, 24 | 'pygame.image': { 25 | path: basePath + 'image.js', 26 | }, 27 | 'pygame.key': { 28 | path: basePath + 'key.js', 29 | }, 30 | 'pygame.mouse': { 31 | path: basePath + 'mouse.js', 32 | }, 33 | 'pygame.time': { 34 | path: basePath + 'time.js', 35 | }, 36 | 'pygame.transform': { 37 | path: basePath + 'transform.js', 38 | }, 39 | 'pygame.version': { 40 | path: basePath + 'version.js', 41 | }, 42 | }; 43 | ~~~ 44 | Base path should correspond to the location where you put the Pygame module. A CDN version can be found at 45 | [https://cdn.rawgit.com/Petlja/pygame4skulpt/3435847b/pygame/__init__.js](https://cdn.rawgit.com/Petlja/pygame4skulpt/3435847b/pygame/__init__.js). 46 | 47 | ### API 48 | #### Sk.main_canvas 49 | Since the Pygame module relies heavily on the graphics and event handling, we provide several functionalities for 50 | communicating with the module. First and the most important one is registering your canvas. Basically, Pygame module 51 | needs to have a reference to the canvas to be used for rendering graphics. In order to register your canvas, use the following: 52 | ~~~ 53 | Sk.main_canvas = document.createElement("canvas"); 54 | ~~~ 55 | or 56 | ~~~ 57 | Sk.main_canvas = document.getElementById("myCanvas"); 58 | ~~~ 59 | 60 | #### Sk.insertEvent 61 | Pygame module has mouse and keyboard event listeners added to canvas and window. If you want to have an additional way of 62 | inserting the events (eg. you want to add the arrows that create keydown events) you can use Sk.insertEvent function as follows: 63 | ~~~ 64 | Sk.insertEvent("left"); 65 | ~~~ 66 | Currently, the only supported events are: 67 | - "up" corresponding to ```KEYDOWN``` event with ```K_UP``` key. 68 | - "down" corresponding to ```KEYDOWN``` event with ```K_DOWN``` key. 69 | - "right" corresponding to ```KEYDOWN``` event with ```K_RIGHT``` key. 70 | - "left" corresponding to ```KEYDOWN``` event with ```K_LEFT``` key. 71 | - "quit" corresponding to ```QUIT``` event with ```K_ESCAPE``` key. 72 | 73 | #### Sk.title_container 74 | If you want to have an element where the title is going to be shown, make use of the following: 75 | ~~~ 76 | Sk.title_container = ... 77 | ~~~ 78 | 79 | #### Sk.quitHandler 80 | After running the Pygame code, you want to make sure that everything got cleaned up. For that reason, there exists 81 | ```Sk.quitHandler``` which gets called by pygame.quit() method. An possible example is: 82 | ~~~ 83 | Sk.quitHandler = function () { 84 | $('.modal').modal('hide'); 85 | }; 86 | ~~~ 87 | ## Implemented parts 88 | ###### Most useful stuff: 89 | - [x] Color 90 | - [x] pygame.Color.r — Gets or sets the red value of the Color. 91 | - [x] pygame.Color.g — Gets or sets the green value of the Color. 92 | - [x] pygame.Color.b — Gets or sets the blue value of the Color. 93 | - [x] pygame.Color.a — Gets or sets the alpha value of the Color. 94 | - [x] pygame.Color.cmy — Gets or sets the CMY representation of the Color. 95 | - [x] pygame.Color.hsva — Gets or sets the HSVA representation of the Color. 96 | - [x] pygame.Color.hsla — Gets or sets the HSLA representation of the Color. 97 | - [x] pygame.Color.i1i2i3 — Gets or sets the I1I2I3 representation of the Color. 98 | - [x] pygame.Color.normalize — Returns the normalized RGBA values of the Color. 99 | - [x] pygame.Color.correct_gamma — Applies a certain gamma value to the Color. 100 | - [x] pygame.Color.set_length — Set the number of elements in the Color to 1,2,3, or 4. 101 | - [x] display 102 | - [x] pygame.display.init — Initialize the display module 103 | - [x] pygame.display.quit — Uninitialize the display module 104 | - [x] pygame.display.get_init — Returns True if the display module has been initialized 105 | - [x] pygame.display.set_mode — Initialize a window or screen for display 106 | - [x] pygame.display.get_surface — Get a reference to the currently set display surface 107 | - [x] pygame.display.flip — Update the full display Surface to the screen 108 | - [x] pygame.display.update — Update portions of the screen for software displays 109 | - [ ] pygame.display.get_driver — Get the name of the pygame display backend 110 | - [ ] pygame.display.Info — Create a video display information object 111 | - [ ] pygame.display.get_wm_info — Get information about the current windowing system 112 | - [ ] pygame.display.list_modes — Get list of available fullscreen modes 113 | - [ ] pygame.display.mode_ok — Pick the best color depth for a display mode 114 | - [ ] pygame.display.gl_get_attribute — Get the value for an OpenGL flag for the current display 115 | - [ ] pygame.display.gl_set_attribute — Request an OpenGL display attribute for the display mode 116 | - [x] pygame.display.get_active — Returns True when the display is active on the display 117 | - [ ] pygame.display.iconify — Iconify the display surface 118 | - [ ] pygame.display.toggle_fullscreen — Switch between fullscreen and windowed displays 119 | - [ ] pygame.display.set_gamma — Change the hardware gamma ramps 120 | - [ ] pygame.display.set_gamma_ramp — Change the hardware gamma ramps with a custom lookup 121 | - [ ] pygame.display.set_icon — Change the system image for the display window 122 | - [x] pygame.display.set_caption — Set the current window caption 123 | - [x] pygame.display.get_caption — Get the current window caption 124 | - [ ] pygame.display.set_palette — Set the display color palette for indexed displays 125 | - [x] draw 126 | - [x] pygame.draw.rect — draw a rectangle shape 127 | - [x] pygame.draw.polygon — draw a shape with any number of sides 128 | - [x] pygame.draw.circle — draw a circle around a point 129 | - [x] pygame.draw.ellipse — draw a round shape inside a rectangle 130 | - [x] pygame.draw.arc — draw a partial section of an ellipse 131 | - [x] pygame.draw.line — draw a straight line segment 132 | - [x] pygame.draw.lines — draw multiple contiguous line segments 133 | - [x] pygame.draw.aaline — draw fine antialiased lines 134 | - [x] pygame.draw.aalines — draw a connected sequence of antialiased lines 135 | - [x] event 136 | - [ ] pygame.event.pump — internally process pygame event handlers 137 | - [x] pygame.event.get — get events from the queue 138 | - [ ] pygame.event.poll — get a single event from the queue 139 | - [x] pygame.event.wait — wait for a single event from the queue 140 | - [ ] pygame.event.peek — test if event types are waiting on the queue 141 | - [ ] pygame.event.clear — remove all events from the queue 142 | - [ ] pygame.event.event_name — get the string name from and event id 143 | - [ ] pygame.event.set_blocked — control which events are allowed on the queue 144 | - [ ] pygame.event.set_allowed — control which events are allowed on the queue 145 | - [ ] pygame.event.get_blocked — test if a type of event is blocked from the queue 146 | - [ ] pygame.event.set_grab — control the sharing of input devices with other applications 147 | - [ ] pygame.event.get_grab — test if the program is sharing input devices 148 | - [ ] pygame.event.post — place a new event on the queue 149 | - [x] pygame.event.Event — create a new event object 150 | - [x] pygame.event.EventType — pygame object for representing SDL events 151 | - [x] font 152 | - [x] pygame.font.init — initialize the font module 153 | - [x] pygame.font.quit — uninitialize the font module 154 | - [x] pygame.font.get_init — true if the font module is initialized 155 | - [x] pygame.font.get_default_font — get the filename of the default font 156 | - [x] pygame.font.get_fonts — get all available fonts 157 | - [x] pygame.font.match_font — find a specific font on the system 158 | - [x] pygame.font.SysFont — create a Font object from the system fonts 159 | - [x] pygame.font.Font — create a new Font object from a file 160 | - [x] image 161 | - [x] pygame.image.load — load new image from a file 162 | - [x] pygame.image.save — save an image to disk 163 | - [x] pygame.image.get_extended — test if extended image formats can be loaded 164 | - [ ] pygame.image.tostring — transfer image to string buffer 165 | - [ ] pygame.image.fromstring — create new Surface from a string buffer 166 | - [ ] pygame.image.frombuffer — create a new Surface that shares data inside a string buffer 167 | - [x] key 168 | - [x] pygame.key.get_focused — true if the display is receiving keyboard input from the system 169 | - [x] pygame.key.get_pressed — get the state of all keyboard buttons 170 | - [x] pygame.key.get_mods — determine which modifier keys are being held 171 | - [x] pygame.key.set_mods — temporarily set which modifier keys are pressed 172 | - [x] pygame.key.set_repeat — control how held keys are repeated 173 | - [x] pygame.key.get_repeat — see how held keys are repeated 174 | - [x] pygame.key.name — get the name of a key identifier 175 | - [ ] locals 176 | - [ ] mixer 177 | - [x] mouse 178 | - [x] pygame.mouse.get_pressed — get the state of the mouse buttons 179 | - [x] pygame.mouse.get_pos — get the mouse cursor position 180 | - [x] pygame.mouse.get_rel — get the amount of mouse movement 181 | - [x] pygame.mouse.set_pos — set the mouse cursor position 182 | - [x] pygame.mouse.set_visible — hide or show the mouse cursor 183 | - [x] pygame.mouse.get_focused — check if the display is receiving mouse input 184 | - [x] pygame.mouse.set_cursor — set the image for the system mouse cursor 185 | - [x] pygame.mouse.get_cursor — get the image for the system mouse cursor 186 | - [x] Rect 187 | - [x] pygame.Rect.copy — copy the rectangle 188 | - [x] pygame.Rect.move — moves the rectangle 189 | - [x] pygame.Rect.move_ip — moves the rectangle, in place 190 | - [x] pygame.Rect.inflate — grow or shrink the rectangle size 191 | - [x] pygame.Rect.inflate_ip — grow or shrink the rectangle size, in place 192 | - [x] pygame.Rect.clamp — moves the rectangle inside another 193 | - [x] pygame.Rect.clamp_ip — moves the rectangle inside another, in place 194 | - [x] pygame.Rect.clip — crops a rectangle inside another 195 | - [x] pygame.Rect.union — joins two rectangles into one 196 | - [x] pygame.Rect.union_ip — joins two rectangles into one, in place 197 | - [x] pygame.Rect.unionall — the union of many rectangles 198 | - [x] pygame.Rect.unionall_ip — the union of many rectangles, in place 199 | - [x] pygame.Rect.fit — resize and move a rectangle with aspect ratio 200 | - [x] pygame.Rect.normalize — correct negative sizes 201 | - [x] pygame.Rect.contains — test if one rectangle is inside another 202 | - [x] pygame.Rect.collidepoint — test if a point is inside a rectangle 203 | - [x] pygame.Rect.colliderect — test if two rectangles overlap 204 | - [x] pygame.Rect.collidelist — test if one rectangle in a list intersects 205 | - [x] pygame.Rect.collidelistall — test if all rectangles in a list intersect 206 | - [ ] pygame.Rect.collidedict — test if one rectangle in a dictionary intersects 207 | - [ ] pygame.Rect.collidedictall — test if all rectangles in a dictionary intersect 208 | - [x] Surface 209 | - [x] pygame.Surface.blit — draw one image onto another 210 | - [ ] pygame.Surface.blits — draw many images onto another 211 | - [x] pygame.Surface.convert — change the pixel format of an image 212 | - [x] pygame.Surface.convert_alpha — change the pixel format of an image including per pixel alphas 213 | - [x] pygame.Surface.copy — create a new copy of a Surface 214 | - [ ] pygame.Surface.fill — fill Surface with a solid color 215 | - [x] pygame.Surface.scroll — Shift the surface image in place 216 | - [ ] pygame.Surface.set_colorkey — Set the transparent colorkey 217 | - [ ] pygame.Surface.get_colorkey — Get the current transparent colorkey 218 | - [ ] pygame.Surface.set_alpha — set the alpha value for the full Surface image 219 | - [ ] pygame.Surface.get_alpha — get the current Surface transparency value 220 | - [ ] pygame.Surface.lock — lock the Surface memory for pixel access 221 | - [ ] pygame.Surface.unlock — unlock the Surface memory from pixel access 222 | - [ ] pygame.Surface.mustlock — test if the Surface requires locking 223 | - [ ] pygame.Surface.get_locked — test if the Surface is current locked 224 | - [ ] pygame.Surface.get_locks — Gets the locks for the Surface 225 | - [x] pygame.Surface.get_at — get the color value at a single pixel 226 | - [x] pygame.Surface.set_at — set the color value for a single pixel 227 | - [ ] pygame.Surface.get_at_mapped — get the mapped color value at a single pixel 228 | - [ ] pygame.Surface.get_palette — get the color index palette for an 8-bit Surface 229 | - [ ] pygame.Surface.get_palette_at — get the color for a single entry in a palette 230 | - [ ] pygame.Surface.set_palette — set the color palette for an 8-bit Surface 231 | - [ ] pygame.Surface.set_palette_at — set the color for a single index in an 8-bit Surface palette 232 | - [ ] pygame.Surface.map_rgb — convert a color into a mapped color value 233 | - [ ] pygame.Surface.unmap_rgb — convert a mapped integer color value into a Color 234 | - [ ] pygame.Surface.set_clip — set the current clipping area of the Surface 235 | - [ ] pygame.Surface.get_clip — get the current clipping area of the Surface 236 | - [ ] pygame.Surface.subsurface — create a new surface that references its parent 237 | - [ ] pygame.Surface.get_parent — find the parent of a subsurface 238 | - [ ] pygame.Surface.get_abs_parent — find the top level parent of a subsurface 239 | - [ ] pygame.Surface.get_offset — find the position of a child subsurface inside a parent 240 | - [ ] pygame.Surface.get_abs_offset — find the absolute position of a child subsurface inside its top level parent 241 | - [x] pygame.Surface.get_size — get the dimensions of the Surface 242 | - [x] pygame.Surface.get_width — get the width of the Surface 243 | - [x] pygame.Surface.get_height — get the height of the Surface 244 | - [x] pygame.Surface.get_rect — get the rectangular area of the Surface 245 | - [ ] pygame.Surface.get_bitsize — get the bit depth of the Surface pixel format 246 | - [ ] pygame.Surface.get_bytesize — get the bytes used per Surface pixel 247 | - [x] pygame.Surface.get_flags — get the additional flags used for the Surface 248 | - [ ] pygame.Surface.get_pitch — get the number of bytes used per Surface row 249 | - [ ] pygame.Surface.get_masks — the bitmasks needed to convert between a color and a mapped integer 250 | - [ ] pygame.Surface.set_masks — set the bitmasks needed to convert between a color and a mapped integer 251 | - [ ] pygame.Surface.get_shifts — the bit shifts needed to convert between a color and a mapped integer 252 | - [ ] pygame.Surface.set_shifts — sets the bit shifts needed to convert between a color and a mapped integer 253 | - [ ] pygame.Surface.get_losses — the significant bits used to convert between a color and a mapped integer 254 | - [x] pygame.Surface.get_bounding_rect — find the smallest rect containing data 255 | - [ ] pygame.Surface.get_view — return a buffer view of the Surface's pixels. 256 | - [ ] pygame.Surface.get_buffer — acquires a buffer object for the pixels of the Surface. 257 | - [ ] pygame.Surface._pixels_address — pixel buffer address 258 | - [x] time 259 | - [x] pygame.time.get_ticks — get the time in milliseconds 260 | - [x] pygame.time.wait — pause the program for an amount of time 261 | - [x] pygame.time.delay — pause the program for an amount of time 262 | - [x] pygame.time.set_timer — repeatedly create an event on the event queue 263 | - [x] pygame.time.Clock — create an object to help track time 264 | - [ ] music 265 | - [x] pygame 266 | - [x] pygame.init — initialize all imported pygame modules 267 | - [x] pygame.quit — uninitialize all pygame modules 268 | - [x] pygame.error — standard pygame exception 269 | - [ ] pygame.get_error — get the current error message 270 | - [ ] pygame.set_error — set the current error message 271 | - [x] pygame.get_sdl_version — get the version number of SDL 272 | - [x] pygame.get_sdl_byteorder — get the byte order of SDL 273 | - [ ] pygame.register_quit — register a function to be called when pygame quits 274 | - [ ] pygame.encode_string — Encode a Unicode or bytes object 275 | - [ ] pygame.encode_file_path — Encode a Unicode or bytes object as a file system path 276 | 277 | ###### Advanced stuff: 278 | - [ ] cursors 279 | - [ ] joystick 280 | - [ ] mask 281 | - [ ] sprite 282 | - [x] transform 283 | - [x] pygame.transform.flip — flip vertically and horizontally 284 | - [x] pygame.transform.scale — resize to new resolution 285 | - [x] pygame.transform.rotate — rotate an image 286 | - [x] pygame.transform.rotozoom — filtered scale and rotation 287 | - [x] pygame.transform.scale2x — specialized image doubler 288 | - [x] pygame.transform.smoothscale — scale a surface to an arbitrary size smoothly 289 | - [ ] pygame.transform.get_smoothscale_backend — return smoothscale filter version in use: 'GENERIC', 'MMX', or 'SSE' 290 | - [ ] pygame.transform.set_smoothscale_backend — set smoothscale filter version to one of: 'GENERIC', 'MMX', or 'SSE' 291 | - [x] pygame.transform.chop — gets a copy of an image with an interior area removed 292 | - [ ] pygame.transform.laplacian — find edges in a surface 293 | - [ ] pygame.transform.average_surfaces — find the average surface from many surfaces. 294 | - [ ] pygame.transform.average_color — finds the average color of a surface 295 | - [ ] pygame.transform.threshold — finds which, and how many pixels in a surface are within a threshold of a 'search_color' or a 'search_surf'. 296 | - [ ] BufferProxy 297 | - [ ] freetype 298 | - [ ] gfxdraw 299 | - [ ] midi 300 | - [ ] Overlay 301 | - [ ] PixelArray 302 | - [ ] pixelcopy 303 | - [ ] sndarray 304 | - [ ] surfarray 305 | - [ ] math 306 | 307 | ###### Other: 308 | - [ ] camera 309 | - [ ] cdrom 310 | - [ ] examples 311 | - [ ] scrap 312 | - [ ] tests 313 | - [x] version 314 | - [x] pygame.version.ver — version number as a string 315 | - [x] pygame.version.vernum — tupled integers of the version 316 | - [x] pygame.version.rev — repository revision of the build 317 | -------------------------------------------------------------------------------- /index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | Fork me on GitHub 16 |
17 |
18 |
19 | logo 20 |
21 |
22 | 23 |
24 |
25 |
26 |
27 |
28 |
29 |
30 |
31 |
32 |

 33 |         
34 |
35 |
36 | Run code 38 |
39 |
40 | 41 |
42 | 46 | 52 |
53 |
54 |
55 |
56 | 57 |
58 |
59 | 60 | 65 | 66 | 67 | 73 | 319 | 320 | 321 | 322 | -------------------------------------------------------------------------------- /logo.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Petlja/pygame4skulpt/a87cbe8dfb20e97d4e0b98c5692eaa33cc7c4da2/logo.png -------------------------------------------------------------------------------- /pygame/display.js: -------------------------------------------------------------------------------- 1 | var $builtinmodule = function (name) { 2 | var mod = {}; 3 | mod.init = new Sk.builtin.func(function () { 4 | mod.__is_initialized = true; 5 | return Sk.builtin.none.none$; 6 | }); 7 | mod.quit = new Sk.builtin.func(function () { 8 | mod.__is_initialized = false; 9 | return Sk.builtin.none.none$; 10 | }); 11 | mod.get_init = new Sk.builtin.func(function () { 12 | if (mod.__is_initialized) { 13 | return Sk.ffi.remapToPy(true); 14 | } 15 | return Sk.ffi.remapToPy(false); 16 | }); 17 | mod.set_mode = new Sk.builtin.func(function (size, flags) { 18 | var f = 0; 19 | if (flags !== undefined) { 20 | f = Sk.ffi.remapToJs(flags); 21 | } 22 | if (f & PygameLib.constants.FULLSCREEN) { 23 | mod.surface = Sk.misceval.callsim(PygameLib.SurfaceType, size, true, true); 24 | } else { 25 | mod.surface = Sk.misceval.callsim(PygameLib.SurfaceType, size, false, true); 26 | } 27 | 28 | PygameLib.surface = mod.surface; 29 | return mod.surface; 30 | }); 31 | mod.get_surface = new Sk.builtin.func(function () { 32 | return PygameLib.surface; 33 | }); 34 | mod.update = new Sk.builtin.func(function () { 35 | Sk.misceval.callsim(mod.surface.update, mod.surface); 36 | }); 37 | mod.flip = new Sk.builtin.func(function () { 38 | Sk.misceval.callsim(mod.surface.update, mod.surface); 39 | }); 40 | mod.set_caption = new Sk.builtin.func(function (caption) { 41 | PygameLib.caption = Sk.ffi.remapToJs(caption); 42 | if (Sk.title_container) { 43 | Sk.title_container.innerText = PygameLib.caption; 44 | } 45 | }); 46 | mod.get_caption = new Sk.builtin.func(function () { 47 | return Sk.ffi.remapToPy(PygameLib.caption); 48 | }); 49 | mod.get_active = new Sk.builtin.func(function () { 50 | return Sk.ffi.remapToPy(document.hasFocus()); 51 | }); 52 | return mod; 53 | }; 54 | -------------------------------------------------------------------------------- /pygame/draw.js: -------------------------------------------------------------------------------- 1 | var $builtinmodule = function (name) { 2 | mod = {}; 3 | mod.rect = new Sk.builtin.func(draw_rect); 4 | mod.polygon = new Sk.builtin.func(draw_polygon); 5 | mod.circle = new Sk.builtin.func(draw_circle); 6 | mod.ellipse = new Sk.builtin.func(draw_ellipse); 7 | mod.arc = new Sk.builtin.func(draw_arc); 8 | mod.line = new Sk.builtin.func(draw_line); 9 | mod.lines = new Sk.builtin.func(draw_lines); 10 | mod.aaline = new Sk.builtin.func(draw_aaline); 11 | mod.aalines = new Sk.builtin.func(draw_aalines); 12 | return mod; 13 | }; 14 | 15 | //returns Rect object used as bounding box for drawing functions 16 | var bbox = function (min_h, max_h, min_w, max_w) { 17 | var width = max_w - min_w; 18 | var height = max_h - min_h; 19 | var top = min_h; 20 | var left = min_w; 21 | t = Sk.builtin.tuple([left, top]); 22 | return Sk.misceval.callsim(PygameLib.RectType, Sk.builtin.tuple([left, top]), Sk.builtin.tuple([width, height])); 23 | }; 24 | 25 | //pygame.draw.rect() 26 | //rect(Surface, color, Rect, width=0) -> Rect 27 | var draw_rect = function (surface, color, rect, width = 0) { 28 | var ctx = surface.context2d; 29 | var color_js = PygameLib.extract_color(color); 30 | var width_js = Sk.ffi.remapToJs(width); 31 | var rect_js = PygameLib.extract_rect(rect); 32 | 33 | var left = rect_js[0]; 34 | var top = rect_js[1]; 35 | var width = rect_js[2]; 36 | var height = rect_js[3]; 37 | 38 | if (width_js) { 39 | ctx.lineWidth = width_js; 40 | ctx.strokeStyle = 'rgba(' + color_js[0] + ', ' + color_js[1] + ', ' + color_js[2] + ', ' + color_js[3] + ')'; 41 | ctx.strokeRect(left, top, width, height); 42 | } else { 43 | ctx.fillStyle = 'rgba(' + color_js[0] + ', ' + color_js[1] + ', ' + color_js[2] + ', ' + color_js[3] + ')'; 44 | ctx.fillRect(left, top, width, height); 45 | } 46 | 47 | return Sk.misceval.callsim(PygameLib.RectType, Sk.builtin.tuple([left, top]), Sk.builtin.tuple([width, height])); 48 | }; 49 | 50 | //pygame.draw.polygon() 51 | //polygon(Surface, color, pointlist, width=0) -> Rect 52 | var draw_polygon = function (surface, color, pointlist, width = 0) { 53 | return draw_lines(surface, color, true, pointlist, width); 54 | }; 55 | 56 | //pygame.draw.circle() 57 | //circle(Surface, color, pos, radius, width=0) -> Rect 58 | var draw_circle = function (surface, color, pos, radius, width = 0) { 59 | var ctx = surface.context2d; 60 | var width_js = Sk.ffi.remapToJs(width); 61 | var center = Sk.ffi.remapToJs(pos); 62 | var rad = Sk.ffi.remapToJs(radius); 63 | var color_js = PygameLib.extract_color(color); 64 | ctx.beginPath(); 65 | ctx.arc(center[0], center[1], rad, 0, 2 * Math.PI); 66 | if (width_js) { 67 | ctx.lineWidth = width_js; 68 | ctx.strokeStyle = 'rgba(' + color_js[0] + ', ' + color_js[1] + ', ' + color_js[2] + ', ' + color_js[3] + ')'; 69 | ctx.stroke(); 70 | } else { 71 | ctx.fillStyle = 'rgba(' + color_js[0] + ', ' + color_js[1] + ', ' + color_js[2] + ', ' + color_js[3] + ')'; 72 | ctx.fill(); 73 | } 74 | 75 | return bbox(center[1] - rad, center[1] + rad, center[0] - rad, center[0] + rad); 76 | }; 77 | 78 | //pygame.draw.arc() 79 | //arc(Surface, color, Rect, start_angle, stop_angle, width=1) -> Rect 80 | var draw_arc = function (surface, color, rect, start_angle, stop_angle, width = 0) { 81 | return draw_oval(surface, color, rect, start_angle, stop_angle, width, false); 82 | }; 83 | 84 | //pygame.draw.arg() 85 | //ellipse(Surface, color, Rect, width=0) -> Rect 86 | var draw_ellipse = function (surface, color, rect, width = 0) { 87 | return draw_oval(surface, color, rect, 0, 2 * Math.PI, width, true); 88 | }; 89 | 90 | //help function 91 | var draw_oval = function (surface, color, rect, start_angle, stop_angle, width, ellipse = false) { 92 | var ctx = surface.context2d; 93 | var width_js = Sk.ffi.remapToJs(width); 94 | var color_js = PygameLib.extract_color(color); 95 | var rect_js = PygameLib.extract_rect(rect); 96 | var angles = [0, 0]; 97 | angles[0] = Sk.ffi.remapToJs(start_angle); 98 | angles[1] = Sk.ffi.remapToJs(stop_angle); 99 | var center = [0, 0]; 100 | center[0] = rect_js[0] + rect_js[2] / 2; 101 | center[1] = rect_js[1] + rect_js[3] / 2; 102 | 103 | ctx.beginPath(); 104 | 105 | ctx.ellipse(center[0], center[1], rect_js[2] / 2, rect_js[3] / 2, 0, -angles[0], -angles[1], true); 106 | 107 | if (width_js) { 108 | ctx.lineWidth = width_js; 109 | ctx.strokeStyle = 'rgba(' + color_js[0] + ', ' + color_js[1] + ', ' + color_js[2] + ', ' + color_js[3] + ')'; 110 | ctx.stroke(); 111 | } else if (ellipse) { 112 | ctx.fillStyle = 'rgba(' + color_js[0] + ', ' + color_js[1] + ', ' + color_js[2] + ', ' + color_js[3] + ')'; 113 | ctx.fill(); 114 | } 115 | 116 | return Sk.misceval.callsim(PygameLib.RectType, Sk.builtin.tuple([rect_js[0], rect_js[1]]), Sk.builtin.tuple([rect_js[2], rect_js[3]])); 117 | }; 118 | 119 | //pygame.draw.line() 120 | //line(Surface, color, start_pos, end_pos, width=1) -> Rect 121 | var draw_line = function (surface, color, start_pos, end_pos, width = 1) { 122 | var width_js = Sk.ffi.remapToJs(width); 123 | var start_pos_js = Sk.ffi.remapToJs(start_pos); 124 | var end_pos_js = Sk.ffi.remapToJs(end_pos); 125 | var color_js = PygameLib.extract_color(color); 126 | var ctx = surface.context2d; 127 | var ax = start_pos_js[0]; 128 | var ay = start_pos_js[1]; 129 | var bx = end_pos_js[0]; 130 | var by = end_pos_js[1]; 131 | var points; 132 | if (Math.abs(ax - bx) <= Math.abs(ay - by)) { 133 | points = [Sk.builtin.tuple([ax - width_js / 2, ay]), Sk.builtin.tuple([ax + width_js / 2, ay]), 134 | Sk.builtin.tuple([bx + width_js / 2, by]), Sk.builtin.tuple([bx - width_js / 2, by])]; 135 | points = Sk.builtin.list(points); 136 | } 137 | else { 138 | points = [Sk.builtin.tuple([ax, ay - width_js / 2]), Sk.builtin.tuple([ax, ay + width_js / 2]), 139 | Sk.builtin.tuple([bx, by + width_js / 2]), Sk.builtin.tuple([bx, by - width_js / 2])]; 140 | points = Sk.builtin.list(points); 141 | } 142 | draw_polygon(surface, color, points); 143 | var left = Math.min(start_pos_js[0], end_pos_js[0]); 144 | var right = Math.max(start_pos_js[0], end_pos_js[0]); 145 | var top = Math.min(start_pos_js[1], end_pos_js[1]); 146 | var bot = Math.max(start_pos_js[1], end_pos_js[1]); 147 | return bbox(top, bot, left, right); 148 | }; 149 | 150 | //pygame.draw.lines() 151 | //lines(Surface, color, closed, pointlist, width=1) -> Rect 152 | var draw_lines = function (surface, color, closed, pointlist, width = 1) { 153 | var width_js = Sk.ffi.remapToJs(width); 154 | var closed_js = Sk.ffi.remapToJs(closed); 155 | var pointlist_js = Sk.ffi.remapToJs(pointlist); 156 | var color_js = PygameLib.extract_color(color); 157 | var ctx = surface.context2d; 158 | if (!width_js) { 159 | ctx.beginPath(); 160 | ctx.lineWidth = width_js; 161 | var first_point = pointlist_js[0]; 162 | var max_h = first_point[1], max_w = first_point[0]; 163 | var min_h = first_point[1], min_w = first_point[0]; 164 | ctx.moveTo(first_point[0], first_point[1]); 165 | for (var i = 0; i < pointlist_js.length; i++) { 166 | ctx.lineTo(pointlist_js[i][0], pointlist_js[i][1]); 167 | max_w = Math.max(max_w, pointlist_js[i][0]); 168 | min_w = Math.min(min_w, pointlist_js[i][0]); 169 | max_h = Math.max(max_h, pointlist_js[i][1]); 170 | min_h = Math.min(min_h, pointlist_js[i][1]); 171 | } 172 | if (closed_js) { 173 | ctx.closePath(); 174 | } 175 | } 176 | else { 177 | for (var i = 0; i < pointlist_js.length - 1; i++) { 178 | draw_line(surface, color, Sk.builtin.tuple([pointlist_js[i][0], pointlist_js[i][1]]), Sk.builtin.tuple([pointlist_js[i + 1][0], pointlist_js[i + 1][1]]), width); 179 | } 180 | return bbox(0, 0, 0, 0); 181 | } 182 | 183 | if (width_js) { 184 | ctx.strokeStyle = 'rgba(' + color_js[0] + ', ' + color_js[1] + ', ' + color_js[2] + ', ' + color_js[3] + ')'; 185 | ctx.stroke(); 186 | } else { 187 | ctx.fillStyle = 'rgba(' + color_js[0] + ', ' + color_js[1] + ', ' + color_js[2] + ', ' + color_js[3] + ')'; 188 | ctx.fill(); 189 | } 190 | return bbox(min_h, max_h, min_w, max_w); 191 | }; 192 | 193 | //pygame.draw.aaline() 194 | //aaline(Surface, color, startpos, endpos, blend=1) -> Rect 195 | var draw_aaline = function (surface, color, startpos, endpos, blend = 1) { 196 | return draw_line(surface, color, startpos, endpos); 197 | }; 198 | 199 | //pygame.draw.aalines() 200 | //aalines(Surface, color, closed, pointlist, blend=1) -> Rect 201 | var draw_aalines = function (surface, color, closed, pointlist, blend = 1) { 202 | return draw_lines(surface, color, closed, pointlist); 203 | }; 204 | -------------------------------------------------------------------------------- /pygame/event.js: -------------------------------------------------------------------------------- 1 | var $builtinmodule = function (name) { 2 | var mod = {}; 3 | mod.get = new Sk.builtin.func(get_event); 4 | mod.EventType = Sk.misceval.buildClass(mod, event_EventType_f, "EventType", []); 5 | PygameLib.EventType = mod.EventType; 6 | mod.Event = new Sk.builtin.func(function (type, dict) { 7 | return Sk.misceval.callsim(mod.EventType, type, dict) 8 | }); 9 | 10 | mod.wait = new Sk.builtin.func(function () { 11 | return new Sk.misceval.promiseToSuspension(new Promise(function (resolve) { 12 | var f = function () { 13 | if (PygameLib.eventQueue.length) { 14 | var event = PygameLib.eventQueue.splice(0, 1)[0]; 15 | var type = Sk.ffi.remapToPy(event[0]); 16 | var dictjs = event[1]; 17 | kvs = []; 18 | for (k in dictjs) { 19 | kvs.push(Sk.ffi.remapToPy(k)); 20 | kvs.push(Sk.ffi.remapToPy(dictjs[k])); 21 | } 22 | var dict = new Sk.builtin.dict(kvs); 23 | var e = Sk.misceval.callsim(PygameLib.EventType, type, dict); 24 | resolve(e); 25 | } 26 | else 27 | Sk.setTimeout(f, 10); 28 | }; 29 | 30 | Sk.setTimeout(f, 10); 31 | })); 32 | }); 33 | return mod; 34 | }; 35 | 36 | //pygame.event module 37 | //pygame.event.get() 38 | //get() -> Eventlist 39 | //get(type) -> Eventlist 40 | //get(typelist) -> Eventlist 41 | var get_event = function (types) { 42 | Sk.builtin.pyCheckArgs('get_event', arguments, 0, 1, false, false); 43 | var list = []; 44 | var t, d; 45 | var types_js = types ? Sk.ffi.remapToJs(types) : []; 46 | var queue = types ? (Sk.abstr.typeName(types) == "list" ? PygameLib.eventQueue.filter(e => types_js.includes(e[0])) : PygameLib.eventQueue.filter(e => e[0] == types_js)) 47 | : PygameLib.eventQueue; 48 | 49 | for (var i = 0; i < queue.length; i++) { 50 | var event = queue[i]; 51 | var type = Sk.ffi.remapToPy(event[0]); 52 | var dictjs = event[1]; 53 | kvs = []; 54 | for (k in dictjs) { 55 | kvs.push(Sk.ffi.remapToPy(k)); 56 | kvs.push(Sk.ffi.remapToPy(dictjs[k])); 57 | } 58 | var dict = new Sk.builtin.dict(kvs); 59 | var e = Sk.misceval.callsim(PygameLib.EventType, type, dict); 60 | list.push(e); 61 | } 62 | queue.splice(0); 63 | 64 | return new Sk.builtin.list(list); 65 | } 66 | 67 | function event_EventType_f($gbl, $loc) { 68 | $loc.__init__ = new Sk.builtin.func(function (self, type, dict) { 69 | Sk.builtin.pyCheckArgs('__init__', arguments, 2, 3, false, false); 70 | dict = dict || new Sk.builtin.dict(); 71 | Sk.abstr.sattr(self, 'dict', dict, false); 72 | Sk.abstr.sattr(self, 'type', type, false); 73 | dictjs = Sk.ffi.remapToJs(dict); 74 | for (k in dictjs) { 75 | Sk.abstr.sattr(self, k, Sk.ffi.remapToPy(dictjs[k]), false); 76 | } 77 | return Sk.builtin.none.none$; 78 | }); 79 | $loc.__init__.co_name = new Sk.builtins['str']('__init__'); 80 | $loc.__init__.co_varnames = ['self', 'type', 'dict']; 81 | 82 | $loc.__repr__ = new Sk.builtin.func(function (self) { 83 | var dict = Sk.ffi.remapToJs(Sk.abstr.gattr(self, 'dict', false)); 84 | var type = Sk.ffi.remapToJs(Sk.abstr.gattr(self, 'type', false)); 85 | return Sk.ffi.remapToPy(''); 86 | }); 87 | $loc.__repr__.co_name = new Sk.builtins['str']('__repr__'); 88 | $loc.__repr__.co_varnames = ['self']; 89 | 90 | } 91 | -------------------------------------------------------------------------------- /pygame/font.js: -------------------------------------------------------------------------------- 1 | $builtinmodule = function (name) { 2 | mod = {}; 3 | mod.__is_initialized = false; 4 | mod.Font = Sk.misceval.buildClass(mod, font_Font, "FontType", []); 5 | PygameLib.FontType = mod.Font; 6 | mod.SysFont = new Sk.builtin.func(function (name, size, bold, italic) { 7 | var font = Sk.misceval.callsim(PygameLib.FontType, size); 8 | Sk.abstr.sattr(font, 'name', name, false); 9 | Sk.abstr.sattr(font, 'sz', size, false); 10 | if (bold === undefined) { 11 | Sk.abstr.sattr(font, 'bold', Sk.ffi.remapToPy(false), false); 12 | } else { 13 | Sk.abstr.sattr(font, 'bold', bold, false); 14 | } 15 | if (italic === undefined) { 16 | Sk.abstr.sattr(font, 'italic', Sk.ffi.remapToPy(false), false); 17 | } else { 18 | Sk.abstr.sattr(font, 'italic', italic, false); 19 | } 20 | Sk.abstr.sattr(font, 'underline', Sk.ffi.remapToPy(false), false); 21 | return font; 22 | }); 23 | mod.init = new Sk.builtin.func(function () { 24 | mod.__is_initialized = true; 25 | }); 26 | mod.quit = new Sk.builtin.func(function () { 27 | mod.__is_initialized = false; 28 | }); 29 | mod.get_init = new Sk.builtin.func(function () { 30 | if (mod.__is_initialized) { 31 | return Sk.ffi.remapToPy(true); 32 | } 33 | return Sk.ffi.remapToPy(false); 34 | }); 35 | mod.get_default_font = new Sk.builtin.func(function () { 36 | return Sk.ffi.remapToPy('arial'); 37 | }); 38 | mod.get_fonts = new Sk.builtin.func(function () { 39 | return Sk.ffi.remapToPy(fonts_osx); 40 | }); 41 | mod.match_font = new Sk.builtin.func(function () { 42 | return Sk.builtin.none.none$; 43 | }); 44 | return mod; 45 | }; 46 | 47 | function font_Font($gbl, $loc) { 48 | $loc.__init__ = new Sk.builtin.func(function (self, filename, size) { 49 | Sk.abstr.sattr(self, 'name', name, false); 50 | Sk.abstr.sattr(self, 'sz', size, false); 51 | Sk.abstr.sattr(self, 'bold', Sk.ffi.remapToPy(false), false); 52 | Sk.abstr.sattr(self, 'italic', Sk.ffi.remapToPy(false), false); 53 | Sk.abstr.sattr(self, 'underline', Sk.ffi.remapToPy(false), false); 54 | return Sk.builtin.none.none$; 55 | }); 56 | $loc.render = new Sk.builtin.func(renderFont, $gbl); 57 | $loc.render.co_name = new Sk.builtins['str']('render'); 58 | $loc.render.co_varnames = ['self', 'text', 'antialias', 'color', 'background']; 59 | $loc.render.$defaults = [Sk.builtin.none.none$]; 60 | 61 | $loc.size = new Sk.builtin.func(fontSize, $gbl); 62 | $loc.size.co_name = new Sk.builtins['str']('size'); 63 | 64 | $loc.set_underline = new Sk.builtin.func(function (self, bool) { 65 | Sk.abstr.sattr(self, 'underline', bool, false); 66 | }, $gbl); 67 | $loc.get_underline = new Sk.builtin.func(function (self) { 68 | return Sk.abstr.gattr(self, 'underline', false); 69 | }, $gbl); 70 | 71 | $loc.set_italic = new Sk.builtin.func(function (self, bool) { 72 | Sk.abstr.sattr(self, 'italic', bool, false); 73 | }, $gbl); 74 | $loc.get_italic = new Sk.builtin.func(function (self) { 75 | return Sk.abstr.gattr(self, 'italic', false); 76 | }, $gbl); 77 | 78 | $loc.set_bold = new Sk.builtin.func(function (self, bool) { 79 | Sk.abstr.sattr(self, 'bold', bool, false); 80 | }, $gbl); 81 | $loc.get_bold = new Sk.builtin.func(function (self) { 82 | return Sk.abstr.gattr(self, 'bold', false); 83 | }, $gbl); 84 | } 85 | 86 | function fontSize(self, text) { 87 | var msg = Sk.ffi.remapToJs(text); 88 | var h = 1.01 * Sk.ffi.remapToJs(Sk.abstr.gattr(self, 'sz', false)); 89 | var fontName = Sk.ffi.remapToJs(Sk.abstr.gattr(self, 'name', false)); 90 | fontName = "" + h + "px " + fontName; 91 | var bold = Sk.ffi.remapToJs(Sk.abstr.gattr(self, 'bold', false)); 92 | if (bold) { 93 | fontName = 'bold ' + fontName; 94 | } 95 | var italic = Sk.ffi.remapToJs(Sk.abstr.gattr(self, 'italic', false)); 96 | if (italic) { 97 | fontName = 'italic ' + fontName; 98 | } 99 | var w = 300; 100 | 101 | // Create a dummy canvas in order to exploit its measureText() method 102 | var t = Sk.builtin.tuple([w, h]); 103 | var s = Sk.misceval.callsim(PygameLib.SurfaceType, t, false); 104 | var ctx = s.offscreen_canvas.getContext("2d"); 105 | ctx.font = fontName; 106 | return new Sk.builtin.tuple([ctx.measureText(msg).width, h]); 107 | } 108 | 109 | function renderFont(self, text, antialias, color, background) { 110 | var msg = Sk.ffi.remapToJs(text); 111 | var STRETCH_CONST = 1.1; 112 | var h = STRETCH_CONST * Sk.ffi.remapToJs(Sk.abstr.gattr(self, 'sz', false)); 113 | var fontName = Sk.ffi.remapToJs(Sk.abstr.gattr(self, 'name', false)); 114 | fontName = "" + h + "px " + fontName; 115 | var bold = Sk.ffi.remapToJs(Sk.abstr.gattr(self, 'bold', false)); 116 | if (bold) { 117 | fontName = 'bold ' + fontName; 118 | } 119 | var italic = Sk.ffi.remapToJs(Sk.abstr.gattr(self, 'italic', false)); 120 | if (italic) { 121 | fontName = 'italic ' + fontName; 122 | } 123 | var underline = Sk.ffi.remapToJs(Sk.abstr.gattr(self, 'underline', false)); 124 | 125 | var w = 300; 126 | 127 | // Create a dummy canvas in order to exploit its measureText() method 128 | var t = Sk.builtin.tuple([w, h]); 129 | var s = Sk.misceval.callsim(PygameLib.SurfaceType, t, false); 130 | var ctx = s.offscreen_canvas.getContext("2d"); 131 | ctx.font = fontName; 132 | w = ctx.measureText(msg).width; 133 | 134 | t = Sk.builtin.tuple([w, h]); 135 | s = Sk.misceval.callsim(PygameLib.SurfaceType, t, false); 136 | ctx = s.offscreen_canvas.getContext("2d"); 137 | if (background !== undefined) { 138 | var background_js = PygameLib.extract_color(background); 139 | ctx.fillStyle = 'rgba(' + background_js[0] + ', ' + background_js[1] + ', ' + background_js[2] + ', ' 140 | + background_js[3] + ')'; 141 | ctx.fillRect(0, 0, s.offscreen_canvas.width, s.offscreen_canvas.height); 142 | } 143 | ctx.font = fontName; 144 | var color_js = PygameLib.extract_color(color); 145 | ctx.fillStyle = 'rgba(' + color_js[0] + ', ' + color_js[1] + ', ' + color_js[2] + ', ' + color_js[3] + ')'; 146 | ctx.fillText(msg, 0, 1 / STRETCH_CONST * h); 147 | if (underline) { 148 | ctx.strokeStyle = 'rgba(' + color_js[0] + ', ' + color_js[1] + ', ' + color_js[2] + ', ' + color_js[3] + ')'; 149 | ctx.lineWidth = 1; 150 | ctx.beginPath(); 151 | ctx.moveTo(0, h - 1); 152 | ctx.lineTo(w, h - 1); 153 | ctx.stroke(); 154 | } 155 | return s; 156 | } 157 | 158 | var fonts_osx = ['applecoloremojiui', 'cochin', 'raanana', 'franklingothicmedium', 'signpainter', 'iowanoldstyle', 'corbel', 'avenir', 'birchstd', 'bitstreamverasansmono', 'sfcompacttext', 'albayan', 'applesdgothicneo', 'damascus', 'malayalammn', 'kohinoortelugu', 'minionpro', 'estrangelomidyat', 'lucidagrandeui', 'hiraginokakugothicpro', 'diwankufi', 'calibri', 'arialnarrow', 'applesdgothicneoi', 'gillsans', 'stixsizefoursym', 'adobehebrew', 'farisi', 'ptsanscaption', 'hiraginomarugothicpron', 'avenirnextcondensed', 'couriernew', 'myriadhebrew', 'hiraginominchopron', 'laomn', 'estrangeloantioch', 'damascuspua', 'hiraginosans', 'avenirnext', 'gohatibebzemen', 'altarikhpua', 'arial', 'itfdevanagari', 'hiraginokakugothicstd', 'adobegaramondpro', 'oratorstd', 'kozukagothicpro', 'skia', 'chaparralpro', 'sfnsdisplaycondensed', 'geezapro', 'lithospro', 'heitisc', 'gujaratimt', 'corsivahebrew', 'hoeflertext', 'athelas', 'lucidagrande', 'timesnewroman', 'decotypenaskhpua', 'webdings', 'inaimathi', 'myriadarabic', 'lettergothicstd', 'kozukagothicpr6n', 'lucidasansunicode', 'geezaprointerface', 'kozukaminchopr6n', 'luminari', 'helveticaneue', 'kailasa', 'helvetica', 'systemfont', 'shreedevanagari714', 'gillsansmt', 'applebraille', 'adobedevanagari', 'krungthep', 'stixgeneral', 'verdana', 'sfcompactdisplay', 'baskerville', 'sertomalankara', 'rockwell', 'newpeninimmt', 'malayalamsangammn', 'palatinolinotype', 'mspmincho', 'euphemiaucas', 'gurmukhisangammn', 'ptsansnarrow', 'trattatello', 'consolas', 'mishafigold', 'arialhebrewscholar', 'pingfangtc', 'symbol', 'ptserif', 'ayuthaya', 'notonastaliqurduui', 'stixintegralsd', 'kohinoordevanagari', 'sertomardin', 'notonastaliqurdu', 'stixnonunicode', 'adobekaitistd', 'pingfangsc', 'pingfanghk', 'stencilstd', 'trebuchetms', 'heititc', 'times', 'kohinoorbangla', 'marlett', 'seravek', 'tamilmn', 'andalemono', 'kufistandardgkpua', 'estrangelotalada', 'meiryo', 'banglasangammn', 'adobeheitistd', 'alnilepua', 'cambria', 'sukhumvitset', 'msmincho', 'marion', 'cooperstd', 'brushscriptmt', 'charter', 'comicsansms', 'sinhalasangammn', 'mingliuhkscs', 'palatino', 'arialroundedmtbold', 'estrangeloquenneshrin', 'ptsans', 'kefa', 'chalkboard', 'arabicuidisplay', 'laosangammn', 'impact', 'luxisans', 'menlo', 'bigcaslon', 'simhei', 'helveticaneuedeskinterface', 'myriadpro', 'snellroundhand', 'stixintegralsup', 'bitstreamverasans', 'arialhebrewdeskinterface', 'adobesongstd', 'stixsizeonesym', 'adobefanheitistd', 'superclarendon', 'sfcompactrounded', 'chalkboardse', 'muna', 'perpetua', 'hiraginokakugothicinterface', 'dinalternate', 'adobenaskh', 'stixintegralssm', 'tahoma', 'luxiserif', 'sertojerusalemoutline', 'telugusangammn', 'arabicuitext', 'sfnstextcondensed', 'adobemingstd', 'twcenmt', 'ptserifcaption', 'kannadasangammn', 'candara', 'americantypewriter', 'msreferencesansserif', 'papyrus', 'hiraginokakugothicpron', 'mishafi', 'futura', 'estrangeloedessa', 'sinhalamn', 'kozukaminchopro', 'albayanpua', 'adobecaslonpro', 'gujaratisangammn', 'trajanpro', 'constantia', 'myanmarsangammn', 'copperplate', 'teamviewer12', 'lucidaconsole', 'chalkduster', 'microsoftyibaiti', 'khmersangammn', 'songtitc', 'microsofttaile', 'bodoni72smallcaps', 'itfdevanagarimarathi', 'hiraginokakugothicstdn', 'oriyamn', 'georgia', 'pmingliuextb', 'nadeempua', 'tektonpro', 'applesymbols', 'markerfelt', 'nuevastd', 'songtisc', 'herculanum', 'optima', 'kufistandardgk', 'ptmono', 'bodoni72', 'adobearabic', 'giddyupstd', 'luximono', 'applechancery', 'khmermn', 'arialunicodems', 'bitstreamveraserif', 'eastsyriacadiabene', 'mspgothic', 'mingliu', 'bodoni72oldstyle', 'devanagarimt', 'sertobatnan', 'aquakana', 'hiraginosansgbinterface', 'mshtakan', 'msgothic', 'blackoakstd', 'bradleyhand', 'estrangelonisibin', 'prestigeelitestd', 'wingdings3', 'wingdings2', 'myanmarmn', 'sertokharput', 'stixsizefivesym', 'gurmukhimn', 'kannadamn', 'munapua', 'devanagarisangammn', 'wingdings', 'dincondensed', 'nadeem', 'sanapua', 'thonburi', 'applemyungjo', 'arialhebrew', 'beirutpua', 'baghdadpua', 'gurmukhimt', 'savoyeletcc', 'geezapropua', 'zapfino', 'telugumn', 'banglamn', 'waseem', 'arialblack', 'sertourhoy', 'charlemagnestd', 'microsoftsansserif', 'gulim', 'savoyelet', 'decotypenaskh', 'batang', 'stsong', 'ocrastd', 'franklingothicbook', 'didot', 'applegothic', 'altarikh', 'adobefangsongstd', 'stixvariants', 'zapfdingbats', 'hiraginosansgb', 'farah', 'baghdad', 'gb18030bitmap', 'kokonor', 'sertojerusalem', 'silom', 'estrangeloturabdin', 'bookshelfsymbol7', 'noteworthy', 'stixsizetwosym', 'oriyasangammn', 'tamilsangammn', 'alnile', 'phosphate', 'cambriamath', 'sana', 'stixintegralsupd', 'simsun', 'sathu', 'estrangelonisibinoutline', 'mingliuextb', 'simsunextb', 'beirut', 'farahpua', 'brushscriptstd', 'eastsyriacctesiphon', 'diwankufipua', 'rosewoodstd', 'mongolianbaiti', 'diwanthuluth', 'stixintegralsupsm', 'gabriola', 'mingliuhkscsextb', 'adobemyungjostd', 'msreferencespecialty', 'keyboard', 'microsofthimalaya', 'mesquitestd', 'poplarstd', 'hiraginomarugothicpro', 'hiraginominchopro', 'hobostd', 'stixsizethreesym', 'bodoniornaments', 'lastresort', 'pmingliu', 'applecoloremoji', 'plantagenetcherokee', 'adobegothicstd']; 159 | -------------------------------------------------------------------------------- /pygame/image.js: -------------------------------------------------------------------------------- 1 | var $builtinmodule = function (name) { 2 | mod = {}; 3 | mod.load = new Sk.builtin.func(function (filename) { 4 | function imageExists(imageUrl) { 5 | var http = new XMLHttpRequest(); 6 | http.open('HEAD', imageUrl, false); 7 | http.send(); 8 | return http.status == 200; 9 | } 10 | 11 | if (imageExists(Sk.imgPath + Sk.ffi.remapToJs(filename))) { 12 | return Sk.misceval.promiseToSuspension(new Promise(function (resolve) { 13 | var img = new Image(); 14 | img.src = Sk.imgPath + Sk.ffi.remapToJs(filename); 15 | img.onload = function () { 16 | var t = Sk.builtin.tuple([img.width, img.height]); 17 | var s = Sk.misceval.callsim(PygameLib.SurfaceType, t); 18 | var ctx = s.offscreen_canvas.getContext("2d"); 19 | ctx.drawImage(img, 0, 0); 20 | resolve(s); 21 | }; 22 | })); 23 | } 24 | else 25 | throw new Sk.builtin.RuntimeError("Image does not exist."); 26 | }); 27 | mod.get_extended = new Sk.builtin.func(function () { 28 | return Sk.ffi.remapToPy(false); 29 | }); 30 | mod.save = new Sk.builtin.func(function (surf, filename) { 31 | var fname = 'surface'; 32 | if (filename !== undefined) { 33 | fname = Sk.ffi.remapToJs(filename); 34 | } 35 | // https://stackoverflow.com/a/34707543 36 | saveAsPNG(surf.offscreen_canvas, fname); 37 | 38 | function saveAsPNG(image, filename) { // No IE <11 support. Chrome URL bug for large images may crash 39 | var anchorElement, event, blob; 40 | 41 | function image2Canvas(image) { // converts an image to canvas 42 | function createCanvas(width, height) { // creates a canvas of width height 43 | var can = document.createElement("canvas"); 44 | can.width = width; 45 | can.height = height; 46 | return can; 47 | }; 48 | var newImage = canvas(img.width, img.height); // create new image 49 | newImage.ctx = newImage.getContext("2d"); // get image context 50 | newImage.ctx.drawImage(image, 0, 0); // draw the image onto the canvas 51 | return newImage; // return the new image 52 | } 53 | 54 | if (image.toDataURL === undefined) { // does the image have the toDataURL function 55 | image = image2Canvas(image); // No then convert to canvas 56 | } 57 | // if msToBlob and msSaveBlob then use them to save. IE >= 10 58 | // As suggested by Kaiido 59 | if (image.msToBlob !== undefined && navigator.msSaveBlob !== undefined) { 60 | blob = image.msToBlob(); 61 | navigator.msSaveBlob(blob, filename + ".png"); 62 | return; 63 | } 64 | anchorElement = document.createElement('a'); // Create a download link 65 | anchorElement.href = image.toDataURL(); // attach the image data URL 66 | // check for download attribute 67 | if (anchorElement.download !== undefined) { 68 | anchorElement.download = filename + ".png"; // set the download filename 69 | if (typeof MouseEvent === "function") { // does the browser support the object MouseEvent 70 | event = new MouseEvent( // yes create a new mouse click event 71 | "click", { 72 | view: window, 73 | bubbles: true, 74 | cancelable: true, 75 | ctrlKey: false, 76 | altKey: false, 77 | shiftKey: false, 78 | metaKey: false, 79 | button: 0, 80 | buttons: 1, 81 | } 82 | ); 83 | anchorElement.dispatchEvent(event); // simulate a click on the download link. 84 | } else if (anchorElement.fireEvent) { // if no MouseEvent object try fireEvent 85 | anchorElement.fireEvent("onclick"); 86 | } 87 | } 88 | } 89 | }); 90 | return mod; 91 | }; 92 | -------------------------------------------------------------------------------- /pygame/key.js: -------------------------------------------------------------------------------- 1 | var $builtinmodule = function (name) { 2 | mod = {}; 3 | mod.set_repeat = new Sk.builtin.func(function (delay, interval) { 4 | if (delay !== undefined) { 5 | PygameLib.repeatKeys = true; 6 | } else { 7 | PygameLib.repeatKeys = false; 8 | } 9 | }); 10 | mod.get_repeat = new Sk.builtin.func(function () { 11 | if (PygameLib.repeatKeys) { 12 | return Sk.builtin.tuple([1, 1]); 13 | } else { 14 | return Sk.builtin.tuple([0, 0]); 15 | } 16 | }); 17 | mod.get_focused = new Sk.builtin.func(function () { 18 | return Sk.ffi.remapToPy(document.hasFocus()); 19 | }); 20 | mod.get_pressed = new Sk.builtin.func(function () { 21 | var pressed = new Array(PygameLib.constants.K_LAST+1).fill(false); 22 | for(var key = 0; key< pressed.length; key ++) { 23 | if(PygameLib.pressedKeys[key]) 24 | pressed[key] = true 25 | } 26 | return Sk.ffi.remapToPy(pressed); 27 | }); 28 | mod.get_mods = new Sk.builtin.func(function () { 29 | var mask = 0; 30 | for (var i = 0; i < PygameLib.eventQueue.length; i++) { 31 | for (var j = 0; j < keyboardModifierKeys.length; j++) { 32 | if (PygameLib.eventQueue[i][1].key === keyboardModifierKeys[j]) { 33 | mask &= 1 << j; 34 | } 35 | } 36 | } 37 | return Sk.ffi.remapToPy(mask); 38 | }); 39 | mod.set_mods = new Sk.builtin.func(function (m) { 40 | var mask = Sk.ffi.remapToJs(m); 41 | for (var i = 0; i < keyboardModifierKeys.length; i++) { 42 | if (mask & (1 << i)) { 43 | PygameLib.eventQueue.unshift([PygameLib.constants.KEYDOWN, {key: keyboardModifierKeys[i]}]); 44 | } 45 | } 46 | 47 | }); 48 | mod.name = new Sk.builtin.func(function (idx) { 49 | var i = Sk.ffi.remapToJs(idx); 50 | if (i < 0 || i >= 323) { 51 | return Sk.ffi.remapToPy("unknown key"); 52 | } 53 | return Sk.ffi.remapToPy(keyToName[i]); 54 | }); 55 | return mod; 56 | }; 57 | 58 | keyToName = ['unknown key', 'unknown key', 'unknown key', 'unknown key', 'unknown key', 'unknown key', 59 | 'unknown key', 'unknown key', 'backspace', 'tab', 'unknown key', 'unknown key', 'clear', 'return', 'unknown key', 60 | 'unknown key', 'unknown key', 'unknown key', 'unknown key', 'pause', 'unknown key', 'unknown key', 'unknown key', 61 | 'unknown key', 'unknown key', 'unknown key', 'unknown key', 'escape', 'unknown key', 'unknown key', 'unknown key', 62 | 'unknown key', 'space', '!', '"', '#', '$', 'unknown key', '&', "'", '(', ')', '*', '+', ',', '-', '.', '/', '0', 63 | '1', '2', '3', '4', '5', '6', '7', '8', '9', ':', ';', '<', '=', '>', '?', '@', 'unknown key', 'unknown key', 64 | 'unknown key', 'unknown key', 'unknown key', 'unknown key', 'unknown key', 'unknown key', 'unknown key', 65 | 'unknown key', 'unknown key', 'unknown key', 'unknown key', 'unknown key', 'unknown key', 'unknown key', 66 | 'unknown key', 'unknown key', 'unknown key', 'unknown key', 'unknown key', 'unknown key', 'unknown key', 67 | 'unknown key', 'unknown key', 'unknown key', '[', '\\', ']', '^', '_', '`', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 68 | 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'unknown key', 69 | 'unknown key', 'unknown key', 'unknown key', 'delete', 'unknown key', 'unknown key', 'unknown key', 'unknown key', 70 | 'unknown key', 'unknown key', 'unknown key', 'unknown key', 'unknown key', 'unknown key', 'unknown key', 71 | 'unknown key', 'unknown key', 'unknown key', 'unknown key', 'unknown key', 'unknown key', 'unknown key', 72 | 'unknown key', 'unknown key', 'unknown key', 'unknown key', 'unknown key', 'unknown key', 'unknown key', 73 | 'unknown key', 'unknown key', 'unknown key', 'unknown key', 'unknown key', 'unknown key', 'unknown key', 74 | 'world 0', 'world 1', 'world 2', 'world 3', 'world 4', 'world 5', 'world 6', 'world 7', 'world 8', 'world 9', 75 | 'world 10', 'world 11', 'world 12', 'world 13', 'world 14', 'world 15', 'world 16', 'world 17', 'world 18', 76 | 'world 19', 'world 20', 'world 21', 'world 22', 'world 23', 'world 24', 'world 25', 'world 26', 'world 27', 77 | 'world 28', 'world 29', 'world 30', 'world 31', 'world 32', 'world 33', 'world 34', 'world 35', 'world 36', 78 | 'world 37', 'world 38', 'world 39', 'world 40', 'world 41', 'world 42', 'world 43', 'world 44', 'world 45', 79 | 'world 46', 'world 47', 'world 48', 'world 49', 'world 50', 'world 51', 'world 52', 'world 53', 'world 54', 80 | 'world 55', 'world 56', 'world 57', 'world 58', 'world 59', 'world 60', 'world 61', 'world 62', 'world 63', 81 | 'world 64', 'world 65', 'world 66', 'world 67', 'world 68', 'world 69', 'world 70', 'world 71', 'world 72', 82 | 'world 73', 'world 74', 'world 75', 'world 76', 'world 77', 'world 78', 'world 79', 'world 80', 'world 81', 83 | 'world 82', 'world 83', 'world 84', 'world 85', 'world 86', 'world 87', 'world 88', 'world 89', 'world 90', 84 | 'world 91', 'world 92', 'world 93', 'world 94', 'world 95', '[0]', '[1]', '[2]', '[3]', '[4]', '[5]', '[6]', 85 | '[7]', '[8]', '[9]', '[.]', '[/]', '[*]', '[-]', '[+]', 'enter', 'equals', 'up', 'down', 'right', 'left', 'insert', 86 | 'home', 'end', 'page up', 'page down', 'f1', 'f2', 'f3', 'f4', 'f5', 'f6', 'f7', 'f8', 'f9', 'f10', 'f11', 'f12', 87 | 'f13', 'f14', 'f15', 'unknown key', 'unknown key', 'unknown key', 'numlock', 'caps lock', 'scroll lock', 88 | 'right shift', 'left shift', 'right ctrl', 'left ctrl', 'right alt', 'left alt', 'right meta', 'left meta', 89 | 'left super', 'right super', 'alt gr', 'compose', 'help', 'print screen', 'sys req', 'break', 'menu', 'power', 90 | 'euro', 'undo', 'unknown key']; 91 | var keyboardModifierKeys = [PygameLib.constants.K_LSHIFT, PygameLib.constants.K_RSHIFT, 0, 0, 0, 0, 92 | PygameLib.constants.K_LCTRL, PygameLib.constants.K_RCTRL, PygameLib.constants.K_LALT, PygameLib.constants.K_RALT, 93 | PygameLib.constants.K_LMETA, PygameLib.constants.K_RMETA, 0, PygameLib.constants.K_CAPSLOCK, 94 | PygameLib.constants.K_NUMLOCK, PygameLib.constants.K_MODE]; 95 | -------------------------------------------------------------------------------- /pygame/mouse.js: -------------------------------------------------------------------------------- 1 | var $builtinmodule = function (name) { 2 | mod = {}; 3 | mod.get_pressed = new Sk.builtin.func(function () { 4 | return Sk.ffi.remapToPy(PygameLib.mouseData["button"]); 5 | }); 6 | mod.get_pos = new Sk.builtin.func(function () { 7 | return Sk.ffi.remapToPy(PygameLib.mouseData["pos"]); 8 | }); 9 | mod.get_rel = new Sk.builtin.func(function () { 10 | return Sk.ffi.remapToPy(PygameLib.mouseData["rel"]); 11 | }); 12 | mod.set_pos = new Sk.builtin.func(function (x, y) { 13 | if (Sk.abstr.typeName(x) === "tuple" && y === undefined) { 14 | var xy = Sk.ffi.remapToJs(x); 15 | x = xy[0]; 16 | y = xy[1]; 17 | } else if (Sk.abstr.typeName(x) === "int" && Sk.abstr.typeName(y) === "int") { 18 | x = Sk.ffi.remapToJs(x); 19 | y = Sk.ffi.remapToJs(y); 20 | } else { 21 | throw new Sk.builtin.TypeError("invalid position argument for set_pos"); 22 | } 23 | PygameLib.mouseData["pos"] = [x, y]; 24 | }); 25 | mod.set_visible = new Sk.builtin.func(function (b) { 26 | if (Sk.ffi.remapToJs(b)) { 27 | document.body.style.cursor = ''; 28 | } else { 29 | document.body.style.cursor = 'none'; 30 | } 31 | }); 32 | mod.get_focused = new Sk.builtin.func(function () { 33 | return Sk.ffi.remapToPy(document.hasFocus()); 34 | }); 35 | mod.set_cursor = new Sk.builtin.func(function () { 36 | throw new Sk.builtin.NotImplementedError("Not yet implemented"); 37 | }); 38 | mod.get_cursor = new Sk.builtin.func(function () { 39 | throw new Sk.builtin.NotImplementedError("Not yet implemented"); 40 | }); 41 | return mod; 42 | }; 43 | -------------------------------------------------------------------------------- /pygame/time.js: -------------------------------------------------------------------------------- 1 | var $builtinmodule = function (name) { 2 | mod = {}; 3 | mod.wait = new Sk.builtin.func(function (amount) { 4 | var t_m = Sk.importModule("time", false, true); 5 | var sec = Sk.ffi.remapToJs(amount) / 1000; 6 | return Sk.misceval.callsimOrSuspend(t_m.$d['sleep'], Sk.ffi.remapToPy(sec)); 7 | }); 8 | 9 | mod.get_ticks = new Sk.builtin.func(function () { 10 | return Sk.ffi.remapToPy(new Date() - PygameLib.initial_time); 11 | }); 12 | mod.delay = new Sk.builtin.func(function (amount) { 13 | var t_m = Sk.importModule("time", false, false); 14 | var sec = Sk.ffi.remapToJs(amount) / 1000; 15 | return Sk.misceval.callsimOrSuspend(t_m.$d['sleep'], Sk.ffi.remapToPy(sec)); 16 | }); 17 | mod.set_timer = new Sk.builtin.func(function (eventid, milliseconds) { 18 | var event = Sk.ffi.remapToJs(eventid); 19 | var ms = Sk.ffi.remapToJs(milliseconds); 20 | if (PygameLib.eventTimer[event]) { 21 | clearInterval(PygameLib.eventTimer[event].timer); 22 | } 23 | else { 24 | PygameLib.eventTimer[event] = {}; 25 | PygameLib.eventTimer[event].f = function () { 26 | var e = [event, {}]; 27 | PygameLib.eventQueue.unshift(e); 28 | } 29 | } 30 | if (ms) { 31 | PygameLib.eventTimer[event].timer = setInterval(PygameLib.eventTimer[event].f, ms); 32 | } 33 | return mod; 34 | }); 35 | 36 | mod.Clock = Sk.misceval.buildClass(mod, time_Clock, 'Clock', []); 37 | PygameLib.ClockType = mod.Clock; 38 | return mod; 39 | }; 40 | 41 | function time_Clock($gbl, $loc) { 42 | $loc.__init__ = new Sk.builtin.func(function (self) { 43 | Sk.abstr.sattr(self, 'prevTime', Sk.builtin.none.none$, false); 44 | Sk.abstr.sattr(self, 'getTime', Sk.builtin.none.none$, false); 45 | Sk.abstr.sattr(self, 'rawTime', Sk.ffi.remapToPy(0), false); 46 | Sk.abstr.sattr(self, 'fpsArray', Sk.ffi.remapToPy([]), false); 47 | Sk.abstr.sattr(self, 'fpsIdx', Sk.ffi.remapToPy(0)); 48 | return Sk.builtin.none.none$; 49 | }, $gbl); 50 | $loc.__init__.co_name = new Sk.builtins['str']('__init__'); 51 | 52 | $loc.tick = new Sk.builtin.func(function (self, framerate) { 53 | 54 | var currTime = Date.now(); 55 | var mills = 0; 56 | if (Sk.ffi.remapToJs(Sk.abstr.gattr(self, 'prevTime', false)) !== null) { 57 | var prevTime = Sk.ffi.remapToJs(Sk.abstr.gattr(self, 'prevTime', false)); 58 | mills = (currTime - prevTime); 59 | } 60 | Sk.abstr.sattr(self, 'prevTime', Sk.ffi.remapToPy(currTime), false); 61 | Sk.abstr.sattr(self, 'getTime', Sk.ffi.remapToPy(mills), false); 62 | var arr = Sk.ffi.remapToJs(Sk.abstr.gattr(self, 'fpsArray', false)); 63 | var idx = Sk.ffi.remapToJs(Sk.abstr.gattr(self, 'fpsIdx', false)); 64 | if (arr.length < 10) { 65 | arr.push(mills); 66 | } else { 67 | arr[idx] = mills; 68 | } 69 | idx = (idx + 1) % 10; 70 | Sk.abstr.sattr(self, 'fpsArray', Sk.ffi.remapToPy(arr), false); 71 | Sk.abstr.sattr(self, 'fpsIdx', Sk.ffi.remapToPy(idx), false); 72 | if (framerate !== undefined) { 73 | var timeout = 1000 / Sk.ffi.remapToJs(framerate); 74 | return new Sk.misceval.promiseToSuspension( 75 | new Promise(function (resolve) { 76 | var f = function () { 77 | Sk.abstr.sattr(self, 'rawTime', Sk.ffi.remapToPy(Date.now() - currTime), false); 78 | resolve(mills); 79 | }; 80 | 81 | if (PygameLib.running) { 82 | Sk.setTimeout(f, timeout); 83 | } 84 | })); 85 | } 86 | Sk.abstr.sattr(self, 'rawTime', Sk.ffi.remapToPy(Date.now() - currTime), false); 87 | return Sk.ffi.remapToPy(mills); 88 | }, $gbl); 89 | $loc.tick.co_name = new Sk.builtins['str']('tick'); 90 | $loc.tick.co_varnames = ['framerate']; 91 | $loc.tick.$defaults = [Sk.ffi.remapToPy(0)]; 92 | 93 | $loc.tick_busy_loop = new Sk.builtin.func(function (self, framerate) { 94 | var currTime = Date.now(); 95 | var mills = 0; 96 | if (Sk.ffi.remapToJs(Sk.abstr.gattr(self, 'prevTime', false)) !== null) { 97 | var prevTime = Sk.ffi.remapToJs(Sk.abstr.gattr(self, 'prevTime', false)); 98 | mills = (currTime - prevTime); 99 | } 100 | Sk.abstr.sattr(self, 'prevTime', Sk.ffi.remapToPy(currTime), false); 101 | Sk.abstr.sattr(self, 'getTime', Sk.ffi.remapToPy(mills), false); 102 | 103 | if (framerate !== undefined) { 104 | var timeout = 1000 / Sk.ffi.remapToJs(framerate); 105 | return new Sk.misceval.promiseToSuspension( 106 | new Promise(function (resolve) { 107 | var f = function () { 108 | Sk.abstr.sattr(self, 'rawTime', Sk.ffi.remapToPy(Date.now() - currTime), false); 109 | resolve(mills); 110 | }; 111 | if (PygameLib.running) { 112 | Sk.setTimeout(f, timeout); 113 | } 114 | })); 115 | } 116 | Sk.abstr.sattr(self, 'rawTime', Sk.ffi.remapToPy(Date.now() - currTime), false); 117 | return Sk.ffi.remapToPy(mills); 118 | }, $gbl); 119 | $loc.tick_busy_loop.co_name = new Sk.builtins['str']('tick_busy_loop'); 120 | $loc.tick_busy_loop.co_varnames = ['framerate']; 121 | $loc.tick_busy_loop.$defaults = [Sk.ffi.remapToPy(0)]; 122 | 123 | $loc.get_time = new Sk.builtin.func(function (self) { 124 | return Sk.abstr.gattr(self, 'getTime', false); 125 | }); 126 | $loc.get_time.co_name = new Sk.builtins['str']('get_time'); 127 | 128 | $loc.get_rawtime = new Sk.builtin.func(function (self) { 129 | return Sk.abstr.gattr(self, 'rawTime', false); 130 | }); 131 | $loc.get_rawtime.co_name = new Sk.builtins['str']('get_rawtime'); 132 | 133 | $loc.get_fps = new Sk.builtin.func(function (self) { 134 | var arr = Sk.ffi.remapToJs(Sk.abstr.gattr(self, 'fpsArray', false)); 135 | if (arr.length < 10 || arr[0] === 0) { 136 | return Sk.ffi.remapToPy(0); 137 | } 138 | var sum = 0; 139 | for (var i = 0; i < 10; i++) { 140 | sum += arr[i]; 141 | } 142 | return Sk.ffi.remapToPy(sum / 10); 143 | }); 144 | } 145 | 146 | time_Clock.co_name = new Sk.builtins['str']('Clock'); 147 | -------------------------------------------------------------------------------- /pygame/transform.js: -------------------------------------------------------------------------------- 1 | var $builtinmodule = function (name) { 2 | mod = {}; 3 | mod.flip = new Sk.builtin.func(function (surf, xbool, ybool) { 4 | if (Sk.abstr.typeName(surf) !== "Surface") { 5 | throw new Sk.builtin.TypeError("Wrong arguments"); 6 | } 7 | if (Sk.abstr.typeName(xbool) !== "bool" || Sk.abstr.typeName(ybool) !== "bool") { 8 | throw new Sk.builtin.TypeError("Wrong arguments"); 9 | } 10 | var t = Sk.builtin.tuple([surf.width, surf.height]); 11 | var ret = Sk.misceval.callsim(PygameLib.SurfaceType, t); 12 | ret.context2d.save(); 13 | var xb = Sk.ffi.remapToJs(xbool); 14 | var xflip = xb ? -1 : 1; 15 | var yb = Sk.ffi.remapToJs(ybool); 16 | var yflip = yb ? -1 : 1; 17 | ret.context2d.scale(xflip, yflip); 18 | ret.context2d.drawImage(surf.offscreen_canvas, -surf.width, 0, surf.width, surf.height); 19 | ret.context2d.restore(); 20 | return ret; 21 | }); 22 | 23 | function scale(surf, size, dest) { 24 | if (Sk.abstr.typeName(surf) !== "Surface") { 25 | throw new Sk.builtin.TypeError("Wrong arguments"); 26 | } 27 | if (Sk.abstr.typeName(size) !== "tuple") { 28 | throw new Sk.builtin.TypeError("Wrong arguments"); 29 | } 30 | var sz = Sk.ffi.remapToJs(size); 31 | var w = Math.round(sz[0]); 32 | var h = Math.round(sz[1]); 33 | if (w === 0 || h === 0) { 34 | if (dest !== undefined && dest !== Sk.builtins.none.none$) { 35 | dest.context2d.drawImage(surf.offscreen_canvas, 0, 0); 36 | } 37 | return surf; 38 | } 39 | var t = Sk.builtin.tuple([w, h]); 40 | var xs = w / surf.width; 41 | var ys = h / surf.height; 42 | var ret = Sk.misceval.callsim(PygameLib.SurfaceType, t); 43 | ret.context2d.save(); 44 | ret.context2d.scale(xs, ys); 45 | ret.context2d.drawImage(surf.offscreen_canvas, 0, 0); 46 | ret.context2d.restore(); 47 | if (dest !== undefined && dest !== Sk.builtins.none.none$) { 48 | dest.context2d.drawImage(ret.offscreen_canvas, 0, 0); 49 | } 50 | return ret; 51 | } 52 | 53 | mod.scale = new Sk.builtin.func(scale); 54 | mod.smoothscale = new Sk.builtin.func(scale); 55 | mod.rotate = new Sk.builtin.func(function (surf, angle) { 56 | if (Sk.abstr.typeName(surf) !== "Surface") { 57 | throw new Sk.builtin.TypeError("Wrong arguments"); 58 | } 59 | var a = Sk.ffi.remapToJs(angle); 60 | var w = surf.width; 61 | var h = surf.height; 62 | var t = Sk.builtin.tuple([1.5 * w, 1.5 * h]); 63 | var ret = Sk.misceval.callsim(PygameLib.SurfaceType, t); 64 | ret.context2d.save(); 65 | ret.context2d.translate(w / 2, h / 2); 66 | ret.context2d.rotate(-a * Math.PI / 180); 67 | ret.context2d.translate(-w / 2, -h / 2); 68 | ret.context2d.drawImage(surf.offscreen_canvas, 0, 0); 69 | ret.context2d.restore(); 70 | return ret; 71 | }); 72 | mod.rotozoom = new Sk.builtin.func(function (surf, angle, sc) { 73 | if (Sk.abstr.typeName(surf) !== "Surface") { 74 | throw new Sk.builtin.TypeError("Wrong arguments"); 75 | } 76 | var scale = Sk.ffi.remapToJs(sc); 77 | var a = Sk.ffi.remapToJs(angle); 78 | var w = surf.width; 79 | var h = surf.height; 80 | var t = Sk.builtin.tuple([2 * scale * w, 2 * scale * h]); 81 | var ret = Sk.misceval.callsim(PygameLib.SurfaceType, t); 82 | ret.context2d.save(); 83 | ret.context2d.scale(scale, scale); 84 | w *= scale; 85 | h *= scale; 86 | ret.context2d.translate(w / 2, h / 2); 87 | ret.context2d.rotate(-a * Math.PI / 180); 88 | ret.context2d.translate(-w / 2, -h / 2); 89 | ret.context2d.drawImage(surf.offscreen_canvas, 0, 0); 90 | ret.context2d.restore(); 91 | return ret; 92 | }); 93 | mod.scale2x = new Sk.builtin.func(function (surf, dest) { 94 | if (Sk.abstr.typeName(surf) !== "Surface") { 95 | throw new Sk.builtin.TypeError("Wrong arguments"); 96 | } 97 | var w = surf.width; 98 | var h = surf.height; 99 | var t = Sk.builtin.tuple([2 * w, 2 * h]); 100 | var ret = Sk.misceval.callsim(PygameLib.SurfaceType, t); 101 | ret.context2d.save(); 102 | ret.context2d.scale(2, 2); 103 | ret.context2d.drawImage(surf.offscreen_canvas, 0, 0); 104 | ret.context2d.restore(); 105 | if (dest !== undefined && dest !== Sk.builtins.none.none$) { 106 | dest.context2d.drawImage(ret.offscreen_canvas, 0, 0); 107 | } 108 | return ret; 109 | }); 110 | mod.chop = new Sk.builtin.func(function (surf, rect) { 111 | if (Sk.abstr.typeName(surf) !== "Surface") { 112 | throw new Sk.builtin.TypeError("Wrong arguments"); 113 | } 114 | if (Sk.abstr.typeName(rect) !== "Rect") { 115 | throw new Sk.builtin.TypeError("Wrong arguments"); 116 | } 117 | var rr = PygameLib.extract_rect(rect); 118 | var x1 = rr[0]; 119 | var y1 = rr[1]; 120 | var x2 = rr[0] + rr[2]; 121 | var y2 = rr[1] + rr[3]; 122 | var w = surf.width; 123 | var h = surf.height; 124 | var rw = w - x2; 125 | var rh = h - y2; 126 | var t = Sk.builtin.tuple([w, h]); 127 | var ret = Sk.misceval.callsim(PygameLib.SurfaceType, t); 128 | ret.context2d.drawImage(surf.offscreen_canvas, 0, 0, x1, y1, 0, 0, x1, y1); 129 | ret.context2d.drawImage(surf.offscreen_canvas, 0, y2, x1, rh, 0, y1, x1, rh); 130 | ret.context2d.drawImage(surf.offscreen_canvas, x2, 0, rw, y1, x1, 0, rw, y1); 131 | ret.context2d.drawImage(surf.offscreen_canvas, x2, y2, rw, rh, x1, y1, rw, rh); 132 | return ret; 133 | }); 134 | return mod; 135 | }; 136 | -------------------------------------------------------------------------------- /pygame/version.js: -------------------------------------------------------------------------------- 1 | var $builtinmodule = function (name) { 2 | mod = {}; 3 | mod.ver = Sk.ffi.remapToPy("1.9.3"); 4 | mod.vernum = Sk.builtin.tuple([Sk.ffi.remapToPy(1), Sk.ffi.remapToPy(9), Sk.ffi.remapToPy(3)]); 5 | mod.rev = Sk.builtin.str(""); 6 | return mod; 7 | }; 8 | -------------------------------------------------------------------------------- /run-example.bat: -------------------------------------------------------------------------------- 1 | start python -m http.server 5000 --bind 127.0.0.1 2 | start http://127.0.0.1:5000/example/index.html 3 | -------------------------------------------------------------------------------- /run-example.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | ./venv/bin/python -m http.server 8888 --bind 127.0.0.1 4 | -------------------------------------------------------------------------------- /skulpt_dist/debugger.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Debugger support for skulpt module 3 | */ 4 | 5 | var Sk = Sk || {}; //jshint ignore:line 6 | 7 | function hasOwnProperty(obj, prop) { 8 | var proto = obj.constructor.prototype; 9 | return (prop in obj) && 10 | (!(prop in proto) || proto[prop] !== obj[prop]); 11 | } 12 | 13 | Sk.Breakpoint = function(filename, lineno, colno) { 14 | this.filename = filename; 15 | this.lineno = lineno; 16 | this.colno = colno; 17 | this.enabled = true; 18 | this.ignore_count = 0; 19 | }; 20 | 21 | Sk.Debugger = function(filename, output_callback) { 22 | this.dbg_breakpoints = {}; 23 | this.tmp_breakpoints = {}; 24 | this.suspension_stack = []; 25 | this.current_suspension = -1; 26 | this.eval_callback = null; 27 | this.suspension = null; 28 | this.output_callback = output_callback; 29 | this.step_mode = false; 30 | this.filename = filename; 31 | }; 32 | 33 | Sk.Debugger.prototype.print = function(txt) { 34 | if (this.output_callback != null) { 35 | this.output_callback.print(txt); 36 | } 37 | }; 38 | 39 | Sk.Debugger.prototype.get_source_line = function(lineno) { 40 | if (this.output_callback != null) { 41 | return this.output_callback.get_source_line(lineno); 42 | } 43 | 44 | return ""; 45 | }; 46 | 47 | Sk.Debugger.prototype.move_up_the_stack = function() { 48 | this.current_suspension = Math.min(this.current_suspension + 1, this.suspension_stack.length - 1); 49 | }; 50 | 51 | Sk.Debugger.prototype.move_down_the_stack = function() { 52 | this.current_suspension = Math.max(this.current_suspension - 1, 0); 53 | }; 54 | 55 | Sk.Debugger.prototype.enable_step_mode = function() { 56 | this.step_mode = true; 57 | }; 58 | 59 | Sk.Debugger.prototype.disable_step_mode = function() { 60 | this.step_mode = false; 61 | }; 62 | 63 | Sk.Debugger.prototype.get_suspension_stack = function() { 64 | return this.suspension_stack; 65 | }; 66 | 67 | Sk.Debugger.prototype.get_active_suspension = function() { 68 | if (this.suspension_stack.length === 0) { 69 | return null; 70 | } 71 | 72 | return this.suspension_stack[this.current_suspension]; 73 | }; 74 | 75 | Sk.Debugger.prototype.generate_breakpoint_key = function(filename, lineno, colno) { 76 | var key = filename + "-" + lineno; 77 | return key; 78 | }; 79 | 80 | Sk.Debugger.prototype.check_breakpoints = function(filename, lineno, colno, globals, locals) { 81 | // If Step mode is enabled then ignore breakpoints since we will just break 82 | // at every line. 83 | if (this.step_mode === true) { 84 | return true; 85 | } 86 | 87 | var key = this.generate_breakpoint_key(filename, lineno, colno); 88 | if (hasOwnProperty(this.dbg_breakpoints, key) && 89 | this.dbg_breakpoints[key].enabled === true) { 90 | var bp = null; 91 | if (hasOwnProperty(this.tmp_breakpoints, key)) { 92 | delete this.dbg_breakpoints[key]; 93 | delete this.tmp_breakpoints[key]; 94 | return true; 95 | } 96 | 97 | this.dbg_breakpoints[key].ignore_count -= 1; 98 | this.dbg_breakpoints[key].ignore_count = Math.max(0, this.dbg_breakpoints[key].ignore_count); 99 | 100 | bp = this.dbg_breakpoints[key]; 101 | if (bp.ignore_count === 0) { 102 | return true; 103 | } else { 104 | return false; 105 | } 106 | } 107 | return false; 108 | }; 109 | 110 | Sk.Debugger.prototype.get_breakpoints_list = function() { 111 | return this.dbg_breakpoints; 112 | }; 113 | 114 | Sk.Debugger.prototype.disable_breakpoint = function(filename, lineno, colno) { 115 | var key = this.generate_breakpoint_key(filename, lineno, colno); 116 | 117 | if (hasOwnProperty(this.dbg_breakpoints, key)) { 118 | this.dbg_breakpoints[key].enabled = false; 119 | } 120 | }; 121 | 122 | Sk.Debugger.prototype.enable_breakpoint = function(filename, lineno, colno) { 123 | var key = this.generate_breakpoint_key(filename, lineno, colno); 124 | 125 | if (hasOwnProperty(this.dbg_breakpoints, key)) { 126 | this.dbg_breakpoints[key].enabled = true; 127 | } 128 | }; 129 | 130 | Sk.Debugger.prototype.clear_breakpoint = function(filename, lineno, colno) { 131 | var key = this.generate_breakpoint_key(filename, lineno, colno); 132 | if (hasOwnProperty(this.dbg_breakpoints, key)) { 133 | delete this.dbg_breakpoints[key]; 134 | return null; 135 | } else { 136 | return "Invalid breakpoint specified: " + filename + " line: " + lineno; 137 | } 138 | }; 139 | 140 | Sk.Debugger.prototype.clear_all_breakpoints = function() { 141 | this.dbg_breakpoints = {}; 142 | this.tmp_breakpoints = {}; 143 | }; 144 | 145 | Sk.Debugger.prototype.set_ignore_count = function(filename, lineno, colno, count) { 146 | var key = this.generate_breakpoint_key(filename, lineno, colno); 147 | if (hasOwnProperty(this.dbg_breakpoints, key)) { 148 | var bp = this.dbg_breakpoints[key]; 149 | bp.ignore_count = count; 150 | } 151 | }; 152 | 153 | Sk.Debugger.prototype.set_condition = function(filename, lineno, colno, lhs, cond, rhs) { 154 | var key = this.generate_breakpoint_key(filename, lineno, colno); 155 | var bp; 156 | if (hasOwnProperty(this.dbg_breakpoints, key)) { 157 | // Set a new condition 158 | bp = this.dbg_breakpoints[key]; 159 | } else { 160 | bp = new Sk.Breakpoint(filename, lineno, colno); 161 | } 162 | 163 | bp.condition = new Sk.Condition(lhs, cond, rhs); 164 | this.dbg_breakpoints[key] = bp; 165 | }; 166 | 167 | Sk.Debugger.prototype.print_suspension_info = function(suspension) { 168 | var filename = suspension.filename; 169 | var lineno = suspension.lineno; 170 | var colno = suspension.colno; 171 | this.print("Hit Breakpoint at <" + filename + "> at line: " + lineno + " column: " + colno + "\n"); 172 | this.print("----------------------------------------------------------------------------------\n"); 173 | this.print(" ==> " + this.get_source_line(lineno - 1) + "\n"); 174 | this.print("----------------------------------------------------------------------------------\n"); 175 | }; 176 | 177 | Sk.Debugger.prototype.set_suspension = function(suspension) { 178 | var parent = null; 179 | if (!hasOwnProperty(suspension, "filename") && suspension.child instanceof Sk.misceval.Suspension) { 180 | suspension = suspension.child; 181 | } 182 | 183 | // Pop the last suspension of the stack if there is more than 0 184 | if (this.suspension_stack.length > 0) { 185 | this.suspension_stack.pop(); 186 | this.current_suspension -= 1; 187 | } 188 | 189 | // Unroll the stack to get each suspension. 190 | while (suspension instanceof Sk.misceval.Suspension) { 191 | parent = suspension; 192 | this.suspension_stack.push(parent); 193 | this.current_suspension += 1; 194 | suspension = suspension.child; 195 | } 196 | 197 | suspension = parent; 198 | 199 | this.print_suspension_info(suspension); 200 | }; 201 | 202 | Sk.Debugger.prototype.add_breakpoint = function(filename, lineno, colno, temporary) { 203 | var key = this.generate_breakpoint_key(filename, lineno, colno); 204 | this.dbg_breakpoints[key] = new Sk.Breakpoint(filename, lineno, colno); 205 | if (temporary) { 206 | this.tmp_breakpoints[key] = true; 207 | } 208 | }; 209 | 210 | Sk.Debugger.prototype.suspension_handler = function(susp) { 211 | return new Promise(function(resolve, reject) { 212 | try { 213 | resolve(susp.resume()); 214 | } catch(e) { 215 | reject(e); 216 | } 217 | }); 218 | }; 219 | 220 | Sk.Debugger.prototype.resume = function() { 221 | // Reset the suspension stack to the topmost 222 | this.current_suspension = this.suspension_stack.length - 1; 223 | 224 | if (this.suspension_stack.length === 0) { 225 | this.print("No running program"); 226 | } else { 227 | var promise = this.suspension_handler(this.get_active_suspension()); 228 | promise.then(this.success.bind(this), this.error.bind(this)); 229 | } 230 | }; 231 | 232 | Sk.Debugger.prototype.pop_suspension_stack = function() { 233 | this.suspension_stack.pop(); 234 | this.current_suspension -= 1; 235 | }; 236 | 237 | Sk.Debugger.prototype.success = function(r) { 238 | if (r instanceof Sk.misceval.Suspension) { 239 | this.set_suspension(r); 240 | } else { 241 | if (this.suspension_stack.length > 0) { 242 | // Current suspension needs to be popped of the stack 243 | this.pop_suspension_stack(); 244 | 245 | if (this.suspension_stack.length === 0) { 246 | this.print("Program execution complete"); 247 | return; 248 | } 249 | 250 | var parent_suspension = this.get_active_suspension(); 251 | // The child has completed the execution. So override the child's resume 252 | // so we can continue the execution. 253 | parent_suspension.child.resume = function() {}; 254 | this.resume(); 255 | } else { 256 | this.print("Program execution complete"); 257 | } 258 | } 259 | }; 260 | 261 | Sk.Debugger.prototype.error = function(e) { 262 | this.print("Traceback (most recent call last):"); 263 | for (var idx = 0; idx < e.traceback.length; ++idx) { 264 | this.print(" File \"" + e.traceback[idx].filename + "\", line " + e.traceback[idx].lineno + ", in "); 265 | var code = this.get_source_line(e.traceback[idx].lineno - 1); 266 | code = code.trim(); 267 | code = " " + code; 268 | this.print(code); 269 | } 270 | 271 | var err_ty = e.constructor.tp$name; 272 | for (idx = 0; idx < e.args.v.length; ++idx) { 273 | this.print(err_ty + ": " + e.args.v[idx].v); 274 | } 275 | }; 276 | 277 | Sk.Debugger.prototype.asyncToPromise = function(suspendablefn, suspHandlers, debugger_obj) { 278 | return new Promise(function(resolve, reject) { 279 | try { 280 | var r = suspendablefn(); 281 | 282 | (function handleResponse (r) { 283 | try { 284 | while (r instanceof Sk.misceval.Suspension) { 285 | debugger_obj.set_suspension(r); 286 | return; 287 | } 288 | 289 | resolve(r); 290 | } catch(e) { 291 | reject(e); 292 | } 293 | })(r); 294 | 295 | } catch (e) { 296 | reject(e); 297 | } 298 | }); 299 | }; 300 | 301 | Sk.Debugger.prototype.execute = function(suspendablefn, suspHandlers) { 302 | var r = suspendablefn(); 303 | 304 | if (r instanceof Sk.misceval.Suspension) { 305 | this.suspensions.concat(r); 306 | this.eval_callback(r); 307 | } 308 | }; 309 | 310 | goog.exportSymbol("Sk.Debugger", Sk.Debugger); -------------------------------------------------------------------------------- /test/advanced-exmp.py: -------------------------------------------------------------------------------- 1 | import pygame as pg 2 | 3 | prozor_sirina, prozor_visina = 400, 300 4 | vx, vy = 40, 20 # piksela u sekundi 5 | stranica = 50 6 | boja = pg.Color('yellow') 7 | pozadina = pg.Color('black') 8 | 9 | pg.init() 10 | prozor = pg.display.set_mode([prozor_sirina, prozor_visina]) 11 | while not pg.event.get(pg.QUIT): 12 | t = pg.time.get_ticks() / 1000 # sekundi od inicijalizacije 13 | x = (t * vx) % (prozor_sirina - stranica) 14 | y = (t * vy) % (prozor_visina - stranica) 15 | prozor.fill(pozadina) 16 | pg.draw.rect(prozor, boja, pg.Rect(x, y, stranica, stranica)) 17 | pg.display.update() 18 | pg.time.wait(50) 19 | pg.quit() -------------------------------------------------------------------------------- /test/color_test.py: -------------------------------------------------------------------------------- 1 | import pygame as pg 2 | 3 | ccc = pg.Color("pink") 4 | print("ccc", len(ccc)) 5 | print(ccc.hsla) 6 | ccc.hsla = (120.0, 100.0, 50.0, 0.0) 7 | print("before", ccc.r) 8 | ccc.r += 3 9 | print("after", ccc.r) 10 | print(ccc.g) 11 | print(ccc.b) 12 | print(ccc.a) 13 | h, s, v, a = ccc.hsva 14 | 15 | ccc = pg.Color("red") 16 | print(ccc.i1i2i3) 17 | ddd = pg.Color("blue") 18 | ddd.i1i2i3 = (0.3333333333333333, 0.5, -0.25) 19 | print(ddd.r) 20 | print(ddd.g) 21 | print(ddd.b) 22 | print(ccc.normalize()) 23 | ccc.a = 100 24 | print(ccc.correct_gamma(0.5)) 25 | ccc.set_length(2) 26 | print(len(ccc)) 27 | print(ccc.correct_gamma(0.5)) 28 | 29 | -------------------------------------------------------------------------------- /test/display_test.py: -------------------------------------------------------------------------------- 1 | import pygame as pg 2 | 3 | pg.init() 4 | print(pg.display.get_init()) 5 | pg.display.init() 6 | print(pg.display.get_init()) 7 | pg.display.set_mode((400, 400)) 8 | pg.display.set_caption("cap cap") 9 | print(pg.display.get_caption()) 10 | pg.quit() -------------------------------------------------------------------------------- /test/draw.py: -------------------------------------------------------------------------------- 1 | import math, random 2 | import pygame as pg 3 | 4 | pg.init() 5 | 6 | pg.display.set_caption("krugovi na dijagonali") 7 | (sirina, visina) = (400, 500) 8 | prozor = pg.display.set_mode((sirina, visina)) 9 | 10 | 11 | def nasumicna_boja(): 12 | return random.randint(0, 255), random.randint(0, 255), random.randint(0, 255) 13 | 14 | 15 | def crtaj(): 16 | r = d / (2 * n) 17 | kx = sirina / (2 * n) 18 | ky = visina / (2 * n) 19 | prozor.fill(pg.Color("white")) 20 | for i in range(n): 21 | (cx, cy) = ((2 * i + 1) * kx, visina - (2 * i + 1) * ky) 22 | pg.draw.circle(prozor, nasumicna_boja(), (round(cx), round(cy)), round(r), 2) 23 | pg.display.update() 24 | 25 | 26 | d = math.sqrt(sirina ** 2 + visina ** 2) 27 | 28 | n = 5 29 | crtaj() 30 | 31 | kraj = False 32 | while not kraj: 33 | dogadjaj = pg.event.wait() 34 | if dogadjaj.type == pg.QUIT: 35 | kraj = True 36 | elif dogadjaj.type == pg.MOUSEBUTTONDOWN: 37 | if dogadjaj.button == 1: 38 | n += 1 39 | crtaj() 40 | elif dogadjaj.button == 3 and n > 1: 41 | n -= 1 42 | crtaj() 43 | if dogadjaj.type == pg.KEYDOWN: 44 | if dogadjaj.key == pg.K_UP: 45 | n += 1 46 | crtaj() 47 | elif dogadjaj.key == pg.K_DOWN and n > 1: 48 | n -= 1 49 | crtaj() 50 | 51 | pg.quit() 52 | -------------------------------------------------------------------------------- /test/drawing-exmp.py: -------------------------------------------------------------------------------- 1 | import pygame 2 | import math 3 | import time 4 | pygame.init() 5 | 6 | s = pygame.Surface([300, 300]) 7 | print("sirina ", s.get_width()) 8 | print("visina ", s.get_height()) 9 | print("proba") 10 | print(s) 11 | screen = pygame.display.set_mode([400, 400]) 12 | print(screen) 13 | print(screen.get_width()) 14 | 15 | c = pygame.Color(1, 2, 3, 4) 16 | c.r = 5 17 | print(c) 18 | 19 | r = pygame.Rect((10, 300), (80, 20)) 20 | print(r) 21 | r.top = 19 22 | print(r) 23 | r = pygame.draw.rect(screen, pygame.Color('brown'), r) 24 | print(r) 25 | 26 | r = pygame.draw.line(screen, (255, 0, 0, 255) , [10, 10], [550, 50], 3) 27 | print(r) 28 | c = pygame.Color('blue') 29 | print(c) 30 | pygame.draw.line(screen, c, [150, 10], [550, 50]) 31 | 32 | pygame.draw.lines(screen, (0, 0, 255, 1), True, [[0, 80], [50, 90], [200, 80], [220, 30]]) 33 | 34 | r = pygame.draw.lines(screen, pygame.Color('navyblue'), True, [[300, 300], [310, 350], [350, 350]], 0) 35 | print(r) 36 | 37 | r = pygame.draw.polygon(screen, pygame.Color('lightsalmon2'), [[100, 300], [150, 320], [180, 300], [140, 250]]) 38 | print("poligon r: ", r) 39 | 40 | r = pygame.draw.circle(screen, pygame.Color('red'), [200, 200], 50) 41 | print("krug r:", r) 42 | 43 | r.width = 200 44 | r = pygame.draw.arc(screen, pygame.Color('green'), r, 0, math.pi / 3, 10) 45 | print("arc r: ", r) 46 | 47 | r = pygame.draw.ellipse(screen, pygame.Color('blue'), r, 2) 48 | print("elipe r: ", r) 49 | 50 | pygame.draw.aaline(screen, c, [150, 200], [350, 200]) 51 | 52 | e = pygame.event.Event(5,{"key":22}) 53 | print(e) 54 | print(e.key) 55 | 56 | done = False 57 | is_blue = True 58 | x = 30 59 | y = 30 60 | 61 | while not done: 62 | for event in pygame.event.get(): 63 | if event.type == pygame.QUIT: 64 | print("gotova petlja") 65 | done = True 66 | if event.type == pygame.KEYDOWN: 67 | print("otkucano: "+ str(event.key)) 68 | time.sleep(1) 69 | -------------------------------------------------------------------------------- /test/events-exmp.py: -------------------------------------------------------------------------------- 1 | import pygame as pg 2 | 3 | pg.init() 4 | sirina, visina = 400, 400 5 | prozor = pg.display.set_mode([sirina, visina]) 6 | 7 | x, y = 200, 200 8 | r = 50 9 | 10 | kraj= False 11 | prikaz_treba_osveziti = True 12 | pg.time.set_timer(pg.USEREVENT, 20) 13 | while not kraj: 14 | if prikaz_treba_osveziti: 15 | prozor.fill(pg.Color("white")) 16 | pg.draw.circle(prozor, pg.Color("green"), [x, y], r) 17 | pg.display.update() 18 | prikaz_treba_osveziti = False 19 | 20 | dogadjaj = pg.event.wait() 21 | 22 | if dogadjaj.type == pg.QUIT: 23 | kraj = True 24 | elif dogadjaj.type == pg.MOUSEBUTTONDOWN: 25 | x, y = dogadjaj.pos 26 | prikaz_treba_osveziti = True 27 | elif dogadjaj.type == pg.KEYDOWN: 28 | if dogadjaj.key == pg.K_LEFT: 29 | x = (x - 50) % sirina 30 | elif dogadjaj.key == pg.K_RIGHT: 31 | x = (x + 50) % sirina 32 | elif dogadjaj.key == pg.K_UP: 33 | y = (y - 50) % visina 34 | elif dogadjaj.key == pg.K_DOWN: 35 | y = (y + 50) % visina 36 | elif dogadjaj.type == pg.USEREVENT: 37 | r = (r - 50 + 1) % 100 + 50 38 | prikaz_treba_osveziti = True 39 | 40 | pg.quit() 41 | 42 | -------------------------------------------------------------------------------- /test/font.py: -------------------------------------------------------------------------------- 1 | import pygame as pg 2 | 3 | pg.init() 4 | 5 | (sirina, visina) = (600, 600) 6 | prozor = pg.display.set_mode((sirina, visina)) 7 | 8 | prozor.fill(pg.Color("white")) 9 | 10 | font = pg.font.SysFont("consolas", 40) 11 | font.set_underline(True) 12 | 13 | poruka = "Zdravo svete!" 14 | tekst = font.render(poruka, True, pg.Color("yellow")) 15 | 16 | # određujemo veličinu tog teksta (da bismo mogli da ga centriramo) 17 | (sirina_teksta, visina_teksta) = (tekst.get_width(), tekst.get_height()) 18 | # položaj određujemo tako da tekst bude centriran 19 | (x, y) = ((sirina - sirina_teksta) / 2, (visina - visina_teksta) / 2) 20 | # prikazujemo sličicu na odgovarajućem mestu na ekranu 21 | prozor.blit(tekst, (x, y)) 22 | 23 | # -*- acsection: after-main -*- 24 | # ažuriramo prikaz sadržaja ekrana 25 | pg.display.update() 26 | 27 | # čekamo da korisnik isključi prozor 28 | while pg.event.wait().type != pg.QUIT: 29 | pass 30 | 31 | # isključivanje rada biblioteke PyGame 32 | pg.quit() 33 | 34 | -------------------------------------------------------------------------------- /test/font_test.py: -------------------------------------------------------------------------------- 1 | import pygame as pg 2 | pg.init() 3 | 4 | print(pg.font.get_fonts()) 5 | print(pg.font.get_default_font()) 6 | print(pg.font.match_font('arial')) 7 | print(pg.font.match_font('nonexistentrandomfont')) 8 | 9 | # pg.font.Font("asdf", 10) 10 | fnt = pg.font.SysFont("asdf", 10) 11 | fnt.render("check the font size", True, pg.Color("black")) 12 | fnt.set_bold(True) 13 | fnt.set_underline(True) 14 | fnt.set_italic(True) 15 | print(fnt.get_bold()) 16 | print(fnt.get_underline()) 17 | print(fnt.get_italic()) 18 | print(fnt.size("ASD")) 19 | # print(fnt.metrics("asdf")) 20 | -------------------------------------------------------------------------------- /test/get_pressed_test.py: -------------------------------------------------------------------------------- 1 | import pygame as pg 2 | 3 | pg.init() 4 | sirina, visina = 400, 400 5 | prozor = pg.display.set_mode([sirina, visina]) 6 | 7 | kraj = False 8 | while not kraj: 9 | 10 | dogadjaj = pg.event.wait() 11 | 12 | if dogadjaj.type == pg.QUIT: 13 | kraj = True 14 | pg.key.get_pressed() 15 | pg.key.get_mods() 16 | pg.key.set_mods(123) 17 | pg.quit() -------------------------------------------------------------------------------- /test/image-exmp.py: -------------------------------------------------------------------------------- 1 | # -*- acsection: general-init -*- 2 | import pygame as pg, random 3 | 4 | # uključujemo rad biblioteke PyGame 5 | pg.init() 6 | 7 | # podešavamo događaje tastaturom - prvi događaj se generiše nakon 8 | # 50ms, a svaki naredni nakon 25ms 9 | pg.key.set_repeat(50, 25) 10 | 11 | # postavljamo naslov prozora 12 | pg.display.set_caption("Setanje broda tastaturom") 13 | 14 | # otvaramo prozor dimenzije 400x400 piksela 15 | (sirina, visina) = (400, 400) 16 | prozor = pg.display.set_mode((sirina, visina)) 17 | 18 | # -*- acsection: main -*- 19 | # učitavamo sliku svemirskog broda 20 | brod = pg.image.load('spaceship.png') 21 | # očitavamo dimenzije slike 22 | brod_sirina = brod.get_width() 23 | brod_visina = brod.get_height() 24 | 25 | # koordinate centra prozora 26 | (x, y) = (sirina / 2, visina / 2) 27 | # pomeraji po x i y koordinati 28 | (dx, dy) = (10, 10) 29 | 30 | pomeraj = {pg.K_LEFT: (-dx, 0), 31 | pg.K_RIGHT: (dx, 0), 32 | pg.K_DOWN: (0, dy), 33 | pg.K_UP: (0, -dy)} 34 | 35 | # u prvom koraku je potrebno nacrtati lopticu 36 | treba_crtati = True 37 | kraj = False 38 | while not kraj: 39 | # ako je potrebno аžurirati sliku 40 | if treba_crtati: 41 | # bojimo prozor u belo 42 | prozor.fill(pg.Color("black")) 43 | # crtamo svemirski brod 44 | prozor.blit(brod, (x - brod_sirina / 2, y - brod_visina / 2)) 45 | # ažuriramo prikaz sadržaja prozora 46 | pg.display.update() 47 | treba_crtati = False 48 | 49 | # obrađujemo prvi događaj koji se desi 50 | dogadjaj = pg.event.wait() 51 | # isključivanje prozora 52 | if dogadjaj.type == pg.QUIT: 53 | kraj = True 54 | # pritisak tastera na tastaturi 55 | if dogadjaj.type == pg.KEYDOWN: 56 | if dogadjaj.key in pomeraj: 57 | # pomeramo centar broda za odgovarajući pomeraj 58 | (DX, DY) = pomeraj[dogadjaj.key] 59 | x += DX 60 | y += DY 61 | # pošto je brod pomeren, ponovo ćemo crtati scenu 62 | treba_crtati = True 63 | 64 | # -*- acsection: after-main -*- 65 | # isključujemo rad biblioteke PyGame 66 | pg.quit() 67 | -------------------------------------------------------------------------------- /test/image_test.py: -------------------------------------------------------------------------------- 1 | import pygame as pg 2 | 3 | pg.init() 4 | 5 | (sirina, visina) = (400, 400) 6 | prozor = pg.display.set_mode((sirina, visina)) 7 | 8 | brod = pg.image.load('spaceship.png') 9 | pg.image.save(brod, 'asdf') 10 | 11 | -------------------------------------------------------------------------------- /test/key_example.py: -------------------------------------------------------------------------------- 1 | import pygame as pg 2 | 3 | pg.init() 4 | prozor = pg.display.set_mode((400, 400)) 5 | while True: 6 | print(pg.key.get_repeat()) 7 | pg.key.set_repeat(20, 50) 8 | print(pg.key.get_repeat()) 9 | pg.quit() 10 | -------------------------------------------------------------------------------- /test/key_test.py: -------------------------------------------------------------------------------- 1 | import pygame as pg 2 | 3 | pg.init() 4 | pg.display.set_mode((800, 600)) 5 | 6 | 7 | print([pg.key.name(i) for i in range(323)]) 8 | pg.key.get_mods() 9 | # pg.key.set_mods() 10 | pg.key.get_focused() 11 | print(pg.key.get_pressed()) 12 | pg.key.get_repeat() 13 | pg.key.set_repeat() 14 | 15 | while True: 16 | dogadjaj = pg.event.wait() 17 | 18 | if dogadjaj.type == pg.QUIT: 19 | break 20 | 21 | pg.quit() -------------------------------------------------------------------------------- /test/keyup-example.py: -------------------------------------------------------------------------------- 1 | import pygame as pg 2 | 3 | pg.init() 4 | sirina, visina = 400, 400 5 | prozor = pg.display.set_mode([sirina, visina]) 6 | 7 | 8 | 9 | kraj = False 10 | prikaz_treba_osveziti = True 11 | crno = True 12 | pg.time.set_timer(pg.USEREVENT, 20) 13 | while not kraj: 14 | if prikaz_treba_osveziti: 15 | if crno: 16 | prozor.fill(pg.Color("black")) 17 | else: 18 | prozor.fill(pg.Color("white")) 19 | pg.display.update() 20 | prikaz_treba_osveziti = False 21 | 22 | dogadjaj = pg.event.wait() 23 | 24 | if dogadjaj.type == pg.QUIT: 25 | kraj = True 26 | elif dogadjaj.type == pg.MOUSEBUTTONUP: 27 | # print("down") 28 | if not crno: 29 | crno = True 30 | prikaz_treba_osveziti = True 31 | elif dogadjaj.type == pg.MOUSEBUTTONDOWN: 32 | # print("UP") 33 | if crno: 34 | crno = False 35 | prikaz_treba_osveziti = True 36 | 37 | pg.quit() 38 | 39 | -------------------------------------------------------------------------------- /test/mouse_test.py: -------------------------------------------------------------------------------- 1 | import pygame as pg 2 | 3 | pg.init() 4 | 5 | print(pg.mouse.get_pressed()) 6 | print(pg.mouse.get_rel()) 7 | print(pg.mouse.get_pos()) 8 | pg.mouse.set_pos(1, 2) 9 | pg.mouse.set_pos((1, 2)) 10 | pg.mouse.set_visible(True) 11 | print(pg.mouse.get_focused()) -------------------------------------------------------------------------------- /test/primer1.py: -------------------------------------------------------------------------------- 1 | import pygame as pg 2 | 3 | pg.init() 4 | dimenzije_prozora = (200, 200) 5 | prozor = pg.display.set_mode(dimenzije_prozora) 6 | pg.draw.rect(prozor, pg.Color("white"), (50, 50, 100, 100)) 7 | pg.display.update() 8 | while pg.event.wait().type != pg.QUIT: pass 9 | pg.quit() 10 | -------------------------------------------------------------------------------- /test/primer2.py: -------------------------------------------------------------------------------- 1 | import pygame as pg 2 | 3 | prozor_sirina, prozor_visina = 400, 300 4 | vx, vy = 40, 20 # piksela u sekundi 5 | stranica = 50 6 | boja = pg.Color('yellow') 7 | pozadina = pg.Color('black') 8 | 9 | pg.init() 10 | prozor = pg.display.set_mode([prozor_sirina, prozor_visina]) 11 | 12 | kraj = False 13 | while not kraj: 14 | #print(pg.time.get_ticks()) 15 | t = pg.time.get_ticks() / 1000 # sekundi od inicijalizacije 16 | #print(t) 17 | x = (t * vx) % (prozor_sirina - stranica) 18 | y = (t * vy) % (prozor_visina - stranica) 19 | prozor.fill(pozadina) 20 | pg.draw.rect(prozor, boja, pg.Rect(x, y, stranica, stranica)) 21 | pg.display.update() 22 | pg.time.wait(50) 23 | pg.quit() 24 | 25 | -------------------------------------------------------------------------------- /test/primer3.py: -------------------------------------------------------------------------------- 1 | import pygame as pg 2 | 3 | pg.init() 4 | prozor = pg.display.set_mode([400, 400]) 5 | 6 | x, y = 200, 200 7 | r = 50 8 | 9 | kraj = False 10 | while not kraj: 11 | prozor.fill(pg.Color("white")) 12 | pg.draw.circle(prozor, pg.Color("green"), [x, y], r) 13 | pg.display.update() 14 | 15 | dogadjaj = pg.event.wait() 16 | if dogadjaj.type == pg.QUIT: 17 | kraj = True 18 | elif dogadjaj.type == pg.MOUSEBUTTONDOWN: 19 | x, y = dogadjaj.pos 20 | 21 | pg.quit() -------------------------------------------------------------------------------- /test/primer4.py: -------------------------------------------------------------------------------- 1 | import pygame as pg 2 | pg.init() 3 | prozor = pg.display.set_mode([400, 400]) 4 | x, y = 50, 50 5 | faza = 0 6 | boje = ["red","green","yellow"] 7 | kraj = False 8 | while not kraj: 9 | for dogadjaj in pg.event.get(): 10 | if dogadjaj.type == pg.QUIT: 11 | kraj = True 12 | elif dogadjaj.type == pg.MOUSEBUTTONDOWN: 13 | faza = (faza + 1) % 3 14 | 15 | prozor.fill(pg.Color("white")) 16 | pg.draw.circle(prozor, pg.Color(boje[faza]), [x, y], 30) 17 | pg.display.update() 18 | pg.time.wait(20) 19 | pg.quit() -------------------------------------------------------------------------------- /test/primer5.py: -------------------------------------------------------------------------------- 1 | import pygame as pg 2 | 3 | pg.init() 4 | prozor = pg.display.set_mode([400, 400]) 5 | 6 | x, y = 200, 200 7 | r = 50 8 | 9 | kraj= False 10 | prikaz_treba_osveziti = True 11 | while not kraj: 12 | if prikaz_treba_osveziti: 13 | prozor.fill(pg.Color("white")) 14 | pg.draw.circle(prozor, pg.Color("green"), [x, y], r) 15 | pg.display.update() 16 | prikaz_treba_osveziti = False 17 | 18 | dogadjaj = pg.event.wait() 19 | if dogadjaj.type == pg.QUIT: 20 | kraj = True 21 | elif dogadjaj.type == pg.MOUSEBUTTONDOWN: 22 | x, y = dogadjaj.pos 23 | prikaz_treba_osveziti = True 24 | 25 | pg.quit() 26 | -------------------------------------------------------------------------------- /test/pygame_test.py: -------------------------------------------------------------------------------- 1 | import pygame as pg 2 | 3 | pg.init() 4 | try: 5 | raise pg.error("ASD") 6 | except RuntimeError: 7 | print("RTE") 8 | 9 | print(pg.get_sdl_version()) 10 | print(pg.get_sdl_byteorder()) 11 | -------------------------------------------------------------------------------- /test/rect_method_test.py: -------------------------------------------------------------------------------- 1 | import pygame as pg 2 | 3 | pg.init() 4 | 5 | r = pg.Rect((1, 1), (2, 2)) 6 | print("", r.move(17, 31)) 7 | print(r) 8 | r.move_ip(17, 31) 9 | print(r) 10 | 11 | r = pg.Rect((0, 0), (4, 4)) 12 | print(r.inflate(3, 3)) 13 | r.inflate_ip(3, 3) 14 | print(r) 15 | 16 | clamper = pg.Rect((0, 0), (200, 200)) 17 | r = pg.Rect((-10, -10), (5, 5)) 18 | 19 | print("0, 0, 5, 5)", r.clamp(clamper)) 20 | r.clamp_ip(clamper) 21 | print(r) 22 | 23 | a = pg.Rect((0, 0), (4, 4)) 24 | b = pg.Rect((10, 10), (12, 12)) 25 | print("0, 0, 22, 22", a.union(b)) 26 | b.union_ip(a) 27 | print(b) 28 | 29 | x = pg.Rect(-10, -10, 1, 1) 30 | l = [pg.Rect((i, i), (1, 1)) for i in range(10)] 31 | print("-10, -10, 20, 20", x.unionall(l)) 32 | x.unionall_ip(l) 33 | print(x) 34 | 35 | a = pg.Rect((1, 2), (3, 4)) 36 | b = pg.Rect((5, 6), (7, 8)) 37 | print("1, 2, 3, 3", b.fit(a)) 38 | upsidedown = pg.Rect((3, 3), (-10, -10)) 39 | print(upsidedown.left) 40 | print(upsidedown.right) 41 | upsidedown.normalize() 42 | print(upsidedown.left) 43 | print(upsidedown.right) 44 | print("true?", upsidedown.contains(pg.Rect((0, 0), (1, 1)))) 45 | rect = pg.Rect((0, 0), (4, 4)) 46 | print("0 1 <->", rect.collidepoint((4, 4)), rect.collidepoint(3, 3)) 47 | try: 48 | print(rect.collidepoint("a random argument")) 49 | except TypeError: 50 | print("type error successfully raised") 51 | 52 | print("True", rect.colliderect(pg.Rect((3, 3), (1, 1)))) 53 | try: 54 | print(rect.colliderect("a random argument")) 55 | except TypeError: 56 | print("error successfully raised") 57 | 58 | print("5 =", rect.collidelist([pg.Rect((i - 5, i - 5), (1, 1)) for i in range(10)])) 59 | try: 60 | rect.collidelist(1237) 61 | except TypeError: 62 | print("ok type error") 63 | 64 | dummylist = ["a"] * 5 65 | try: 66 | rect.collidelist(dummylist) 67 | except TypeError: 68 | print("ok type error") 69 | 70 | print("[5, 6, 7, 8] =", rect.collidelistall([pg.Rect((i - 5, i - 5), (1, 1)) for i in range(10)])) 71 | try: 72 | rect.collidelistall(1237) 73 | except TypeError: 74 | print("ok type error") 75 | 76 | dummylist = ["a"] * 5 77 | try: 78 | rect.collidelistall(dummylist) 79 | except TypeError: 80 | print("ok type error") 81 | 82 | a = pg.Rect((1, 2), (3, 4)) 83 | b = pg.Rect((5, 6), (7, 8)) 84 | print("1200", a.clip(b)) 85 | print("5600", b.clip(a)) 86 | a = pg.Rect((0, 0), (4, 4)) 87 | b = pg.Rect((2, 2), (4, 4)) 88 | print("2222", a.clip(b)) 89 | -------------------------------------------------------------------------------- /test/rect_property_test.py: -------------------------------------------------------------------------------- 1 | import pygame as pg 2 | 3 | pg.init() 4 | 5 | r = pg.Rect((1, 1), (12, 26)) 6 | r.center = (137, 351) 7 | print("2, 2", r.center, r.centerx, r.centery) 8 | r.top = 3 9 | print("top 3", r.top) 10 | r.bottom = 6 11 | print("bottom 6", r.bottom) 12 | r.right = 17 13 | print("right 17", r.right) 14 | r.left = 12 15 | print(r.left) 16 | 17 | r.size = (123, 321) 18 | print("size 123321", r.size) 19 | 20 | r.w = 888 21 | print("888", r.w, r.width) 22 | 23 | r.h = 357 24 | print("357", r.h, r.height) 25 | 26 | r.topleft = (0, 0) 27 | print(r.topleft) 28 | 29 | r.topright = (0, 1) 30 | print(r.topright) 31 | 32 | r.bottomleft = (1, 0) 33 | print(r.bottomleft) 34 | 35 | r.bottomright = (1, 1) 36 | print(r.bottomright) 37 | 38 | # r = pg.Rect((0, 0), (1, 2)) 39 | r.midtop = (1, 0) 40 | print("midtop (1, 0)", r.midtop) 41 | # 42 | r.midbottom = (1, 2) 43 | print("midbottom (1, 2)", r.midbottom) 44 | 45 | r.midleft = (3, 1) 46 | print("midleft (3, 1)", r.midleft) 47 | 48 | r.midright = (4, 1) 49 | print("midrignt (4, 1)", r.midright) 50 | 51 | # print("W=", r.w) 52 | print(r.right) 53 | r.right = 123 54 | print("%d + %d = %d" % (r.left, r.width, r.right)) 55 | print("bottom", r.bottom) 56 | r.bottom = 7 57 | print("top, height", r.top, r.height) 58 | r.x = 12 59 | print(r.x) 60 | r.x = r.x + 4 61 | r.left = 3 62 | print(r.x) 63 | r.top = 333123 64 | print(r.y) 65 | print(r.left) 66 | g = r.copy() 67 | 68 | 69 | print(g.left, g.top, g.width, g.height) 70 | -------------------------------------------------------------------------------- /test/simple_game.py: -------------------------------------------------------------------------------- 1 | import pygame 2 | 3 | pygame.init() 4 | screen = pygame.display.set_mode((400, 300)) 5 | done = False 6 | is_blue = True 7 | x = 30 8 | y = 30 9 | 10 | clock = pygame.time.Clock() 11 | 12 | while not done: 13 | for event in pygame.event.get(): 14 | if event.type == pygame.QUIT: 15 | done = True 16 | if event.type == pygame.KEYDOWN and event.key == pygame.K_SPACE: 17 | is_blue = not is_blue 18 | 19 | pressed = pygame.key.get_pressed() 20 | if pressed[pygame.K_UP]: y -= 3 21 | if pressed[pygame.K_DOWN]: y += 3 22 | if pressed[pygame.K_LEFT]: x -= 3 23 | if pressed[pygame.K_RIGHT]: x += 3 24 | 25 | screen.fill((0, 0, 0)) 26 | if is_blue: 27 | color = (0, 128, 255) 28 | else: 29 | color = (255, 100, 0) 30 | pygame.draw.rect(screen, color, pygame.Rect(x, y, 60, 60)) 31 | 32 | pygame.display.flip() 33 | clock.tick(60) -------------------------------------------------------------------------------- /test/snake.py: -------------------------------------------------------------------------------- 1 | import pygame as pg 2 | from random import randint 3 | 4 | pg.init() 5 | side = 30 6 | w = 17 7 | h = 15 8 | disp = pg.display.set_mode((w * side, h * side)) 9 | 10 | game_running = 0 11 | 12 | dirs = [pg.K_RIGHT, pg.K_DOWN, pg.K_LEFT, pg.K_UP] 13 | dx = [1, 0, -1, 0] 14 | dy = [0, 1, 0, -1] 15 | snake = [(7, 3), (7, 4)] 16 | direction = 0 17 | 18 | 19 | def place_apple(): 20 | a = (randint(0, w - 1), randint(0, h - 1)) 21 | while a in snake: 22 | a = (randint(0, w - 1), randint(0, h - 1)) 23 | return a 24 | 25 | 26 | apple = place_apple() 27 | 28 | 29 | def check_collisions(): 30 | head = snake[-1] 31 | for i in range(len(snake) - 1): 32 | if head == snake[i]: 33 | return 2 34 | if head[0] >= w or head[0] < 0: 35 | return 3 36 | if head[1] >= h or head[1] < 0: 37 | return 3 38 | if head == apple: 39 | return 1 40 | return 0 41 | 42 | 43 | clock = pg.time.Clock() 44 | f = pg.font.SysFont('console', 24, True) 45 | 46 | while True: 47 | clock.tick(8) 48 | for e in pg.event.get(): 49 | if e.type == pg.QUIT: 50 | pg.quit() 51 | break 52 | if e.type == pg.KEYDOWN: 53 | if game_running == 0: 54 | game_runnig = 1 55 | if e.key == pg.K_SPACE: 56 | game_running = 0 57 | snake = [(7, 3), (7, 4)] 58 | direction = 0 59 | apple = place_apple() 60 | for i in range(4): 61 | if e.key == dirs[i] and direction != (i + 2) % 4: 62 | direction = i 63 | if game_running == 2: 64 | disp.fill(pg.Color("black")) 65 | disp.blit(f.render("Game over!", False, pg.Color("blue")), (3 * side, 3 * side)) 66 | pg.display.update() 67 | game_running = 3 68 | if game_running == 3: 69 | continue 70 | snake.append((snake[-1][0] + dx[direction], snake[-1][1] + dy[direction])) 71 | coll = check_collisions() 72 | if coll >= 2: 73 | game_running = 2 74 | pass 75 | elif coll == 1: 76 | apple = place_apple() 77 | pass 78 | elif coll == 0: 79 | snake.pop(0) 80 | disp.fill(pg.Color("black")) 81 | for i in range(len(snake)): 82 | pg.draw.rect(disp, pg.Color("green"), pg.Rect(snake[i][0] * side, snake[i][1] * side, side, side)) 83 | pg.draw.rect(disp, pg.Color("red"), pg.Rect(apple[0] * side, apple[1] * side, side, side)) 84 | pg.display.update() 85 | -------------------------------------------------------------------------------- /test/spaceship.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Petlja/pygame4skulpt/a87cbe8dfb20e97d4e0b98c5692eaa33cc7c4da2/test/spaceship.png -------------------------------------------------------------------------------- /test/spaceship.py: -------------------------------------------------------------------------------- 1 | # -*- acsection: general-init -*- 2 | import pygame as pg, random 3 | 4 | # uključujemo rad biblioteke PyGame 5 | pg.init() 6 | 7 | # podešavamo događaje tastaturom - prvi događaj se generiše nakon 8 | # 50ms, a svaki naredni nakon 25ms 9 | pg.key.set_repeat(50, 25) 10 | 11 | # postavljamo naslov prozora 12 | pg.display.set_caption("setanje broda") 13 | 14 | # otvaramo prozor dimenzije 400x400 piksela 15 | (sirina, visina) = (400, 400) 16 | prozor = pg.display.set_mode((sirina, visina)) 17 | 18 | # -*- acsection: main -*- 19 | # učitavamo sliku svemirskog broda 20 | brod = pg.image.load('./test/spaceship.png') 21 | # očitavamo dimenzije slike 22 | brod_sirina = brod.get_width() 23 | brod_visina = brod.get_height() 24 | 25 | # koordinate centra prozora 26 | (x, y) = (sirina / 2, visina / 2) 27 | # pomeraji po x i y koordinati 28 | (dx, dy) = (10, 10) 29 | 30 | pomeraj = {pg.K_LEFT: (-dx, 0), 31 | pg.K_RIGHT: (dx, 0), 32 | pg.K_DOWN: (0, dy), 33 | pg.K_UP: (0, -dy)} 34 | 35 | # u prvom koraku je potrebno nacrtati lopticu 36 | treba_crtati = True 37 | kraj = False 38 | while not kraj: 39 | # ako je potrebno аžurirati sliku 40 | if treba_crtati: 41 | # bojimo prozor u belo 42 | prozor.fill(pg.Color("black")) 43 | # crtamo svemirski brod 44 | prozor.blit(brod, (x - brod_sirina / 2, y - brod_visina / 2)) 45 | # ažuriramo prikaz sadržaja prozora 46 | pg.display.update() 47 | treba_crtati = False 48 | 49 | # obrađujemo prvi događaj koji se desi 50 | dogadjaj = pg.event.wait() 51 | # isključivanje prozora 52 | if dogadjaj.type == pg.QUIT: 53 | kraj = True 54 | # pritisak tastera na tastaturi 55 | if dogadjaj.type == pg.KEYDOWN: 56 | if dogadjaj.key in pomeraj: 57 | # pomeramo centar broda za odgovarajući pomeraj 58 | (DX, DY) = pomeraj[dogadjaj.key] 59 | x += DX 60 | y += DY 61 | # pošto je brod pomeren, ponovo ćemo crtati scenu 62 | treba_crtati = True 63 | 64 | # -*- acsection: after-main -*- 65 | # isključujemo rad biblioteke PyGame 66 | pg.quit() 67 | -------------------------------------------------------------------------------- /test/spirograph.py: -------------------------------------------------------------------------------- 1 | import math 2 | import pygame as pg 3 | 4 | 5 | pg.init() 6 | 7 | pg.display.set_caption("Spirograph") 8 | (sirina, visina) = (400, 400) 9 | prozor = pg.display.set_mode((sirina, visina)) 10 | 11 | (cx, cy) = (sirina // 2, visina // 2) 12 | R = min(sirina//2, visina//2) 13 | k = 0.67 14 | l = 0.67 15 | r = round(k * R) 16 | alpha = 0 17 | 18 | kriva = pg.Surface((sirina, visina)) 19 | kriva.fill(pg.Color("white")) 20 | 21 | pg.time.set_timer(pg.USEREVENT, 1000 // 50) 22 | 23 | kraj = False 24 | treba_crtati = True 25 | while not kraj: 26 | if treba_crtati: 27 | prozor.fill(pg.Color("white")) 28 | prozor.blit(kriva, (0, 0)) 29 | pg.draw.circle(prozor, pg.Color("black"), (cx, cy), R, 3) 30 | pg.draw.circle(prozor, pg.Color("red"), (round(cx + R * math.cos(alpha)), round(cy - R * math.sin(alpha))), 5) 31 | (mx, my) = (round(cx + (R-r)*math.cos(alpha)), round(cy - (R-r)*math.sin(alpha))) 32 | pg.draw.circle(prozor, pg.Color("blue"), (mx, my), r, 3) 33 | beta = - (R - r)/r*alpha 34 | (Ax, Ay) = (round(mx + l*r*math.cos(beta)), round(my - l*r*math.sin(beta))) 35 | pg.draw.circle(prozor, pg.Color("red"), (Ax, Ay), 5) 36 | 37 | hue = round(((alpha + math.pi) % (2*math.pi)) / (2*math.pi) * 360) 38 | boja = pg.Color("black") 39 | boja.hsva = (hue, 100, 100, 1) 40 | pg.draw.circle(kriva, boja, (Ax, Ay), 2) 41 | 42 | pg.display.update() 43 | treba_crtati = False 44 | dogadjaj = pg.event.wait() 45 | if dogadjaj.type == pg.QUIT: 46 | kraj = True 47 | elif dogadjaj.type == pg.USEREVENT: 48 | alpha += math.pi / 90 49 | treba_crtati = True 50 | elif dogadjaj.type == pg.MOUSEMOTION: 51 | (x, y) = dogadjaj.pos 52 | phi0 = (alpha + math.pi) % (2*math.pi) - math.pi 53 | phi = math.atan2(cy - y, x - cx) 54 | d_phi = phi - phi0 55 | if d_phi > math.pi: 56 | d_phi -= 2*math.pi 57 | if d_phi < -math.pi: 58 | d_phi += 2*math.pi 59 | alpha += d_phi 60 | treba_crtati = True 61 | 62 | pg.quit() 63 | -------------------------------------------------------------------------------- /test/surface_test.py: -------------------------------------------------------------------------------- 1 | import pygame as pg 2 | 3 | pg.init() 4 | 5 | (sirina, visina) = (400, 200) 6 | prozor = pg.display.set_mode((sirina, visina)) 7 | 8 | font = pg.font.SysFont("consolas", 40) 9 | font.set_underline(False) 10 | 11 | 12 | poruka = "Zdravo svete!" 13 | tekst1 = font.render(poruka, True, pg.Color("black")) 14 | tekst2 = font.render(poruka, True, pg.Color("yellow")) 15 | # tekst2.convert_alpha() 16 | tekst3 = tekst2.copy() 17 | tekst1.blit(tekst3, (0, 0)) 18 | tekst1.set_at((1, 1), pg.Color("yellow")) 19 | print(tekst1.get_at((1, 1))) 20 | 21 | print("get_rect(): ", tekst1.get_rect(), tekst1.get_bounding_rect()) 22 | (sirina_teksta, visina_teksta) = (tekst1.get_width(), tekst1.get_height()) 23 | print(sirina_teksta, visina_teksta) 24 | (x, y) = ((sirina - sirina_teksta) / 2, (visina - visina_teksta) / 2) 25 | prozor.blit(tekst1, (x, y)) 26 | 27 | pg.display.update() 28 | 29 | kraj = False 30 | while not kraj: 31 | pg.time.wait(1000) 32 | print(prozor.scroll(10, 0)) 33 | pg.display.update() 34 | dogadjaj = pg.event.wait() 35 | # isključivanje prozora 36 | if dogadjaj.type == pg.QUIT: 37 | kraj = True 38 | 39 | pg.quit() 40 | -------------------------------------------------------------------------------- /test/tick_clock.py: -------------------------------------------------------------------------------- 1 | import pygame as pg 2 | 3 | pg.init() 4 | 5 | cl = pg.time.Clock() 6 | end = False 7 | counter = 0 8 | while not end: 9 | cl.tick(1) 10 | print(cl.get_fps()) 11 | counter += 1 12 | if counter == 100: 13 | break 14 | 15 | pg.quit() 16 | -------------------------------------------------------------------------------- /test/transform_test.py: -------------------------------------------------------------------------------- 1 | import pygame as pg 2 | 3 | pg.init() 4 | 5 | prozor = pg.display.set_mode((400, 400)) 6 | 7 | petit_font = pg.font.SysFont("arial", 10) 8 | tekst = petit_font.render("!", True, pg.Color("yellow")) 9 | w, h = tekst.get_size() 10 | prozor.fill(pg.Color("black")) 11 | prozor.blit(tekst, (0, 0)) 12 | pg.display.update() 13 | for i in range(20): 14 | d = pg.event.wait() 15 | if d.type == pg.KEYDOWN: 16 | tekst = pg.transform.scale2x(tekst) 17 | prozor.fill(pg.Color("black")) 18 | prozor.blit(tekst, (0, 0)) 19 | pg.display.update() 20 | 21 | font = pg.font.SysFont("arial", 100) 22 | 23 | tekst = font.render("rotzoom", True, pg.Color("yellow")) 24 | w, h = tekst.get_size() 25 | prozor.fill(pg.Color("black")) 26 | prozor.blit(tekst, (0, 0)) 27 | pg.display.update() 28 | for i in range(20): 29 | d = pg.event.wait() 30 | if d.type == pg.KEYDOWN: 31 | tekst = pg.transform.rotozoom(tekst, 30, 0.5) 32 | prozor.fill(pg.Color("black")) 33 | prozor.blit(tekst, (0, 0)) 34 | pg.display.update() 35 | 36 | tekst = font.render("123", True, pg.Color("yellow")) 37 | w, h = tekst.get_size() 38 | prozor.fill(pg.Color("black")) 39 | prozor.blit(tekst, (0, 0)) 40 | pg.display.update() 41 | for i in range(20): 42 | d = pg.event.wait() 43 | if d.type == pg.KEYDOWN: 44 | tekst = pg.transform.flip(tekst, True, False) 45 | prozor.fill(pg.Color("black")) 46 | prozor.blit(tekst, (0, 0)) 47 | pg.display.update() 48 | 49 | tekst = font.render("rot", True, pg.Color("yellow")) 50 | w, h = tekst.get_size() 51 | prozor.fill(pg.Color("black")) 52 | prozor.blit(tekst, (0, 0)) 53 | pg.display.update() 54 | for i in range(20): 55 | d = pg.event.wait() 56 | if d.type == pg.KEYDOWN: 57 | tekst = pg.transform.rotate(tekst, -30) 58 | prozor.fill(pg.Color("black")) 59 | prozor.blit(tekst, (0, 0)) 60 | pg.display.update() 61 | 62 | tekst = font.render("scale", True, pg.Color("yellow")) 63 | w, h = tekst.get_size() 64 | prozor.fill(pg.Color("black")) 65 | prozor.blit(tekst, (0, 0)) 66 | pg.display.update() 67 | while True: 68 | d = pg.event.wait() 69 | if d.type == pg.KEYDOWN: 70 | w = int(w * 0.95) 71 | h = int(h * 0.95) 72 | tekst = pg.transform.scale(tekst, (w, h)) 73 | prozor.fill(pg.Color("black")) 74 | prozor.blit(tekst, (0, 0)) 75 | pg.display.update() 76 | -------------------------------------------------------------------------------- /test/transform_test2.py: -------------------------------------------------------------------------------- 1 | import pygame as pg 2 | 3 | pg.init() 4 | 5 | prozor = pg.display.set_mode((400, 400)) 6 | 7 | font = pg.font.SysFont("arial", 100) 8 | 9 | tekst = font.render("1234567", True, pg.Color("yellow")) 10 | w, h = tekst.get_size() 11 | prozor.fill(pg.Color("black")) 12 | prozor.blit(tekst, (0, 0)) 13 | pg.display.update() 14 | cnt = 0 15 | for i in range(10): 16 | d = pg.event.wait() 17 | if d.type == pg.KEYDOWN: 18 | tekst = font.render("1234567", True, pg.Color("yellow")) 19 | w, h = tekst.get_size() 20 | tekst = pg.transform.chop(tekst, pg.Rect(w/2 * (cnt % 2), w / 2 * (cnt % 4 / 2), w/2, h/2)) 21 | cnt += 1 22 | prozor.fill(pg.Color("black")) 23 | prozor.blit(tekst, (0, 0)) 24 | pg.display.update() 25 | 26 | -------------------------------------------------------------------------------- /test/version_test.py: -------------------------------------------------------------------------------- 1 | import pygame as pg 2 | import unittest 3 | 4 | 5 | class TestingPygameVersion(unittest.TestCase): 6 | def test_ver(self): 7 | self.assertIsInstance(pg.version.ver, str) 8 | 9 | def test_vernum(self): 10 | self.assertIsInstance(pg.version.vernum, tuple) 11 | self.assertEqual(len(pg.version.vernum), 3) 12 | for i in range(3): 13 | self.assertIsInstance(pg.version.vernum[i], int) 14 | 15 | def test_rev(self): 16 | self.assertEqual(pg.version.rev, "") 17 | 18 | 19 | if __name__ == '__main__': 20 | pg.init() 21 | unittest.main() 22 | pg.quit() 23 | --------------------------------------------------------------------------------