├── .gitignore
├── Installing-ImageMagick.md
├── LICENSE
├── README.md
├── docs
├── index.md
└── reference.md
├── help
├── help.py
└── index.html
├── logo.png
├── mkdocs.yml
├── setup.py
└── slither
├── __init__.py
├── examples
├── assets
│ ├── boom.wav
│ ├── doge.png
│ └── grass.png
├── dogeinvasion.py
├── helloworld.py
├── mover.py
├── pressforsound.py
├── runsnakey.py
└── turnAndMove.py
├── slither.py
├── snakey.png
└── tests
├── assets
├── SOS.png
├── SVG Logo.svg
├── SoExcited.png
├── arrow.png
├── bg2.png
├── boom.wav
├── circle.png
└── snakey.png
├── basicTest.py
├── bgTest.py
├── captionTest.py
├── fullScreenTest.py
├── imageBounceTest.py
├── isTouchingTest.py
├── keysDownTest.py
├── mouseTest.py
├── moveStepsTest.py
├── soundtest.py
├── svgTest.py
├── textTest.py
└── zindextest.py
/.gitignore:
--------------------------------------------------------------------------------
1 | *.pyc
2 | __pycache__
3 | dist/
4 | build/
5 | slither.egg-info/
6 | *.db
7 | nppBackup
8 | install.bat
9 | Thumbs.db
10 | site/
11 | .DS_Store
12 |
--------------------------------------------------------------------------------
/Installing-ImageMagick.md:
--------------------------------------------------------------------------------
1 | # Installing ImageMagick
2 | In order for Slither to have support for SVG files, you need to have ImageMagick installed. Here are some installation instructions for common platforms.
3 |
4 | ## On Windows
5 | Download and install the correct binary from [ImageMagick's binaries page](http://www.imagemagick.org/script/binary-releases.php#windows).
6 |
7 | ## On OSX/MacOS
8 | If you have homebrew installed, the easiest way is to run `brew install imagemagick` in your terminal.
9 |
10 | If you have MacPorts installed, you can run `sudo port install ImageMagick` to install ImageMagick.
11 |
12 | Otherwise, follow the instructions at [ImageMagick's binaries page](http://www.imagemagick.org/script/binary-releases.php#macosx)
13 |
14 | ## On GNU/Linux
15 |
16 | ### Debian
17 | Run `sudo aptitude update && aptitude install imagemagick`.
18 |
19 | ### Ubuntu
20 | Run `sudo apt-get install imagemagick`.
21 |
22 | ### Other systems
23 | Use your package manager to install ImageMagick, if has it.
24 |
25 | Otherwise, try [ImageMagick's binaries page](http://www.imagemagick.org/script/binary-releases.php#unix).
26 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | The MIT License (MIT)
2 |
3 | Copyright (c) 2016 Tymewalk
4 |
5 | Permission is hereby granted, free of charge, to any person obtaining a copy
6 | of this software and associated documentation files (the "Software"), to deal
7 | in the Software without restriction, including without limitation the rights
8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9 | copies of the Software, and to permit persons to whom the Software is
10 | furnished to do so, subject to the following conditions:
11 |
12 | The above copyright notice and this permission notice shall be included in all
13 | copies or substantial portions of the Software.
14 |
15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21 | SOFTWARE.
22 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | 
2 |
3 | [](https://www.codacy.com/app/stanleybookowl/Slither)
4 |
5 | ## What is Slither?
6 | Slither is a Python module that uses PyGame to bring Scratch-like features to Python.
7 | [Scratch](scratch.mit.edu) is a programming language developed by MIT that uses block-based scripts to introduce kids to programming.
8 |
9 | ## How do I run Slither?
10 | ### Through `pip`
11 | Run `pip install slither`.
12 |
13 | *Note*: Linux/Unix users without the proper permissions may need to run it as `sudo pip install slither`.
14 |
15 | *Note*: Python 3 uses `pip3`.
16 |
17 | ### Manually
18 | Run `python setup.py build` and then `python setup.py install`.
19 | If that doesn't work, run `python setup.py bdist_wheel`, and then run `pip install path`, where path is the final path of the .whl file (which should be in dist/). If this fails, install wheel with `pip install wheel` then retry.
20 | If it still fails, make sure you have `setuptools` fully updated and properly installed.
21 | Remember to add `import slither` in your script.
22 |
23 | Note that you must have PyGame installed in order to use Slither. Also, in order to have SVG support, you need to [install ImageMagick](Installing-ImageMagick.md).
24 |
25 | ## Why use Slither?
26 | Those just getting started with Python after using Scratch may want to go straight from one GUI to another. Slither allows those people to quickly make simple projects in a matter of minutes, while also learning Python.
27 |
28 | ## How can I help with Slither?
29 | Check the issues to see what problems need fixing. Then make a pull request detailing what you've changed and how it should help. After testing, someone will merge it into the main project.
30 | If you help enough times, Tymewalk will add you as a collaborator.
31 | **WARNING: Abuse of collaborator permissions WILL result in you being removed as a collaborator.**
32 | So just be careful with what you do and you'll be fine.
33 |
34 | ## I'm making a change! What should I do?
35 | ### As a pull request
36 | Nothing. I'll look it over and fix what needs to be fixed.
37 |
38 | ### As a collaborator
39 | If it's a small change, go ahead and commit it to master.
40 | Examples of small changes include "Fix spelling error", "Properly indent code", etc.
41 |
42 | If it's a big change, make a new branch and then a pull request for it.
43 | Examples of big changes include adding new functions, re-writing a lot of code, etc.
44 |
45 | ## Uh-oh! There's a problem!
46 | First, check to make sure you've properly installed all of Slither's requirements and Slither.
47 | Next, check your Python program over. Do you have correct syntax and spelling?
48 | Finally, check to see if you have the newest version of Slither.
49 |
50 | If you've done all three of those things and it still doesn't work, file an issue.
51 |
52 | # Contributors
53 | A list of all contributors who have helped or are helping.
54 |
55 | ### Tymewalk
56 | Started Slither, and added several groundwork features.
57 |
58 | ### BookOwl
59 | Helped majorly rewrite Slither so it's easier to code in. Additionally helped suggest and add changes that helped Slither get many important features.
60 |
61 | ### Omegabyte
62 | Began and currently works on documentation, also added sound support.
63 |
64 | ### Ethanhs
65 | Currently working on adding SVG support to slither.
66 |
67 | ### Icelys
68 | Helped with a small costume changing fix.
69 |
70 | # Code of Conduct
71 | Rules to follow when contributing. Follow these and you should be fine.
72 |
73 | - Never push directly to master. Always make branches and pull requests. This is to make sure Slither stays as bug-free as possible.
74 | - Additionally, wait to merge until you're sure your code is bug-free and/or someone has reviewed it.
75 | - The only exception is minor changes or important bugfixes that can't wait for someone to review it.
76 | - Always ask for feedback before merging a pull request.
77 | - Only Tymewalk should merge pull requests that add big features or change large portions of Slither.
78 | - Make a new issue if you want to propose a new release. Don't make releases without getting approval from other contributors.
79 | - Most importantly, have fun!
80 |
81 | # Minor Rules
82 | You won't get removed if you don't follow these, but it's recommended that you do.
83 |
84 | - Add comments to your code if it doesn't seem straightforward.
85 | - Credit sources such as StackOverflow.
86 |
87 | # Credits
88 | Scratch is property of The Lifelong Kindergarten Group. The Slither devs are not affiliated with the LLK, nor do they own Scratch.
89 |
--------------------------------------------------------------------------------
/docs/index.md:
--------------------------------------------------------------------------------
1 | 
2 |
3 | [](https://www.codacy.com/app/stanleybookowl/Slither)
4 |
5 | # What is Slither?
6 | Slither is a Python module that uses PyGame to bring Scratch-like features to Python.
7 | [Scratch](https://scratch.mit.edu) is a programming language developed by MIT that uses block-based scripts to introduce kids to programming.
8 |
9 | # Why use Slither?
10 | Those just getting started with Python after using Scratch may want to go straight from one GUI to another. Slither allows those people to quickly make simple projects in a matter of minutes, while also learning Python.
11 |
12 | # How do I install Slither?
13 | ## Through pip
14 | Run `pip install slither`.
15 |
16 | ## Manually
17 | Run `python setup.py build` and then `python setup.py install`.
18 | If that doesn't work, run `python setup.py bdist_wheel`, and then run `pip install path`, where path is the final path of the .whl file (which should be in dist/). If this fails, install wheel with `pip install wheel` then retry.
19 | If it still fails, make sure you have `setuptools` fully updated and properly installed.
20 | Remember to add `import slither` in your script.
21 |
22 | Slither supports both Python 2 and Python 3. Also, note that you must have [PyGame](http://pygame.org/hifi.html) installed in order to use Slither.
23 |
24 |
25 | # Uh-oh! There's a problem!
26 | First, check to make sure you've properly installed all of Slither's requirements and Slither.
27 | Next, check your Python program over. Do you have correct syntax and spelling?
28 | Finally, check to see if you have the newest version of Slither.
29 |
30 | If you've done all three of those things and it still doesn't work, [file an issue](https://github.com/PySlither/Slither/issues/new).
31 |
32 | # How can I help with Slither?
33 | Check [the issues](https://github.com/PySlither/Slither/issues) to see what problems need fixing. Then [make a pull request](https://github.com/PySlither/Slither/compare) detailing what you've changed and how it should help. After testing, someone will merge it into the main project.
34 | If you help enough times, Tymewalk will add you as a collaborator.
35 | **WARNING: Abuse of collaborator permissions WILL result in you being removed as a collaborator.**
36 | So just be careful with what you do and you'll be fine.
37 |
38 | # Credits
39 | Scratch is property of The Lifelong Kindergarten Group. The Slither devs are not affiliated with the LLK, nor do they own Scratch. Slither is in no way associated with, and is not a product of, the LLK.
40 |
--------------------------------------------------------------------------------
/docs/reference.md:
--------------------------------------------------------------------------------
1 | # Reference
2 |
3 | ## function `keysDown()`
4 | Returns a list of the currently held down keys
5 |
6 | ## class `Mouse`
7 | A class for getting and setting mouse properties
8 | This is a static class, all methods should be called directly through the class
9 |
10 | ### function `Mouse.buttonsPressed()`
11 | Returns a three-tuple of bools that give the state of the left, middle, and right buttons
12 |
13 | ### function `Mouse.isFocused()`
14 | Returns `True` if the mouse is focused on the slither window
15 |
16 | ### function `Mouse.isVisible()`
17 | Returns `True` if the mouse is visable
18 |
19 | ### function `Mouse.leftPressed()`
20 | Returns `True` if the left mouse button is pressed
21 |
22 | ### function `Mouse.middlePressed()`
23 | Returns `True` if the middle mouse button is pressed
24 |
25 | ### function `Mouse.pos()`
26 | Returns the position of the mouse as an `(x, y)` tuple
27 |
28 | ### function `Mouse.relativeMovement()`
29 | Returns the reletive movement of the mouse since the last call to this function as a `(x, y)` tuple
30 |
31 | ### function `Mouse.rightPressed()`
32 | Returns `True` if the right mouse button is pressed
33 |
34 | ### function `Mouse.setPos(x, y)`
35 | Sets the position of the mouse pointer to `(x, y)`
36 |
37 | ### function `Mouse.setVisible(visable)`
38 | Sets the visibility of the mouse
39 |
40 | ### function `Mouse.setXPos(x)`
41 | Sets the x position of the mouse
42 |
43 | ### function `Mouse.setYPos()y`
44 | Sets the y position of the mouse
45 |
46 | ### function `Mouse.xPos()`
47 | Gets the x position of the mouse
48 |
49 | ### function `Mouse.yPos()`
50 | Gets the x position of the mouse
51 |
52 |
53 | ## class `Stage`
54 | The stage class is the base class of all the sprites. It has one concrete instance, `slitherStage`
55 |
56 | ### data `costumes`
57 | A `collections.OrderedDict` of costumes
58 |
59 | ### data `bgColor`
60 | A `(red, green, blue)` tuple used as the background color of the stage
61 |
62 | ### function `addCostume(costumePath, costumeName)`
63 | Loads a costume from the path `costumePath` and gives it the name `costumeName`
64 |
65 | ### function `deleteCostumeByName(name)`
66 | Deletes the costume with the name `name`
67 |
68 | ### function `deleteCostumeByNumber(n)`
69 | Deletes the costume numbered `n`
70 |
71 | ### property `costumeNumber`
72 | The costume number of the current costume. Assigning `n` to this switches to costume `n % len(self.costumes)`
73 | ### property `costumeName`
74 | The name of the current costume. Assigning to this switches to the costume with that name
75 |
76 | ## slitherStage
77 | An instance of Stage. Manipulate this to change the stage used in slither programs
78 |
79 |
80 |
--------------------------------------------------------------------------------
/help/help.py:
--------------------------------------------------------------------------------
1 | url = 'http://localhost:8000'
2 | try: # It will check if using python 2
3 | import SimpleHTTPServer
4 | import SocketServer
5 | import webbrowser
6 | PORT = 8000
7 | HANDLER = SimpleHTTPServer.SimpleHTTPRequestHandler
8 | httpd = SocketServer.TCPServer(("",PORT), HANDLER)
9 | print "Closed the page and want to come back? Enter localhost:8000 in your browser."
10 | webbrowser.open(url, new=0, autoraise=True)
11 | httpd.serve_forever()
12 | except ImportError: # If using python 3 this is run.
13 | import http.server
14 | import webbrowser
15 | from http.server import HTTPServer
16 | server_class = HTTPServer
17 | server_address = ("", 8000)
18 | httpd = server_class(server_adress, handler_class)
19 | print("Closed the page and want to come back? Enter localhost:8000 in your browser.")
20 | webbrowser.open(url,new=0,autoraise=True)
21 | httpd.serve_forever()
22 |
--------------------------------------------------------------------------------
/help/index.html:
--------------------------------------------------------------------------------
1 |
2 |
3 | Slither - Help Page
4 |
5 |
6 |
7 |
8 |
Slither Help
9 |
10 |
11 |
Slither is a Python module designed for bridging the gap between Scratch and Python. It adds Scratch-like features to Python using Pygame.
12 |
If you are new to Slither, make a simple Slither program with this:
After you run this you'll get a green window.So how does this work? It uses a number of things that I'll explain step by step.
29 |
import slither Allows Slither to be used in your code.
30 |
slither.slitherStage.setColor() Changes the background color, you enter values in the form of "number, number, number", where number represents a RGB value.
31 |
slither.setup() Sets up Slither, similar to "pygame.init()".
32 |
def loop(): This function is usually called 60 times a second (depending on your FPS). Your program's main loop should be in here.
33 |
pass For this example there is no main loop, so pass skips the main loop.
34 |
slither.runMainLoop(loop) This important fuction runs your main loop, you need this for your code to run.
35 |
36 |
37 |
38 |
Stage Functions
Brief description
39 |
__init__()
Initilizes the stage and sprite costumes. You shouldn't call this manually.
40 |
setColor()
Sets the stage's background color (Stage Only).
41 |
addCostume()
Add a costume based on a given path and name.
42 |
deleteCostumeByName()
Delete a costume by name.
43 |
deleteCostumeByNumber()
Delete a costume by number.
44 |
setCostumeByName()
Set a costume by it's name.
45 |
setCostumeByNumber()
Set a costume by it's number.
46 |
getCostumeNumber()
Get the costume number of a sprite.
47 |
getCostumeName()
Get the costume name of a sprite.
48 |
Sprite Functions
Brief description
49 |
__init__()
Initilizes a sprite.
50 |
goto(x, y)
Tells the sprite to go to (x, y).
51 |
moveSteps(setps)
Move (steps) steps forward, based on direction.
52 |
isVisible()
Check if the object is visible, not just showing.
53 |
delete()
Remove the sprite from the global sprites list, causing it not to be drawn.
54 |
Sprite Variables
Brief description
55 |
Sprite.currentCostume
The costume the sprite is set to (in the form of a Pygame rect).
56 |
Sprite.xpos
The X position of the sprite.
57 |
Sprite.ypos
The Y position of the sprite.
58 |
Sprite.direction
Which direction the sprite is pointing in. Sprites point to 0 by default.
59 |
Sprite.show
Set to "True" to show the sprite, set to "False" to hide it. Replaces "show()" and "hide()" from v0.2.2 on.
60 |
Sprite.scale
How big the sprite is. Set to 1 by default.
61 |
Sprite.zindex
Default is 0. Determines how high up the sprite is. For example, a sprite with a z-index of 1 will be drawn above a sprite with a z-index of 0.
62 |
Other Functions
Brief description
63 |
setup()
Sets up PyGame and returns a screen object that can be used with blit().
64 |
blit()
Draw all graphic changes on the screen. This must be called to display graphics.
65 |
setFPS()
Set the FPS of the project. Default is 60, and Scratch runs at 30.
66 |
registerCallback()
Register the function func to handle the event eventname
67 |
runQuitCallback()
Quit eventname handling.
68 |
runMainLoop()
Run the main game loop.
69 |
70 |
71 |
72 |
73 |
--------------------------------------------------------------------------------
/logo.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/PySlither/Slither/affda7ac36188c2c3af1a8a0b7ecbe7bd228007c/logo.png
--------------------------------------------------------------------------------
/mkdocs.yml:
--------------------------------------------------------------------------------
1 | site_name: Slither
2 | theme: flatly
3 | pages:
4 | - Home: index.md
5 | - Reference: reference.md
6 |
--------------------------------------------------------------------------------
/setup.py:
--------------------------------------------------------------------------------
1 | """A Python module that uses PyGame to bring Scratch-like features to Python.
2 | https://github.com/PySlither/Slither
3 | """
4 |
5 | # Always prefer setuptools over distutils
6 | from setuptools import setup#, find_packages
7 | # To use a consistent encoding
8 | #from codecs import open
9 | from os import path
10 | import glob
11 |
12 | here = path.abspath(path.dirname(__file__))
13 |
14 | # Get the long description from the README file
15 | #with open(path.join(here, 'README.md'), encoding='utf-8') as f:
16 | # long_description = f.read()
17 |
18 | setup(
19 | name='slither',
20 |
21 | # Versions should comply with PEP440. For a discussion on single-sourcing
22 | # the version across setup.py and the project code, see
23 | # https://packaging.python.org/en/latest/single_source_version.html
24 | version='0.3.0',
25 |
26 | description='A Python module that uses PyGame to bring Scratch-like features to Python',
27 | long_description='A Python module that uses PyGame to bring Scratch-like features to Python. PyGame IS required for this module to work.',
28 |
29 | # The project's main homepage.
30 | url='https://github.com/PySlither/Slither',
31 |
32 | # Author details
33 | author='The PySlither Devs',
34 | author_email='none',
35 |
36 | # Choose your license
37 | license='MIT',
38 |
39 | # See https://pypi.python.org/pypi?%3Aaction=list_classifiers
40 | classifiers=[
41 | # How mature is this project? Common values are
42 | # 3 - Alpha
43 | # 4 - Beta
44 | # 5 - Production/Stable
45 | 'Development Status :: 3 - Alpha',
46 |
47 | # Indicate who your project is intended for
48 | 'Intended Audience :: Other Audience',
49 | 'Topic :: Games/Entertainment',
50 |
51 | # Pick your license as you wish (should match "license" above)
52 | 'License :: OSI Approved :: MIT License',
53 |
54 | # Specify the Python versions you support here. In particular, ensure
55 | # that you indicate whether you support Python 2, Python 3 or both.
56 | 'Programming Language :: Python :: 2',
57 | 'Programming Language :: Python :: 2.6',
58 | 'Programming Language :: Python :: 2.7',
59 | 'Programming Language :: Python :: 3',
60 | 'Programming Language :: Python :: 3.2',
61 | 'Programming Language :: Python :: 3.3',
62 | 'Programming Language :: Python :: 3.4',
63 | 'Programming Language :: Python :: 3.5',
64 | ],
65 |
66 | # What does your project relate to?
67 | keywords='scratch pygame',
68 |
69 | # You can just specify the packages manually here if your project is
70 | # simple. Or you can use find_packages().
71 | packages=["slither", "slither.examples"],
72 |
73 | # Alternatively, if you want to distribute just a my_module.py, uncomment
74 | # this:
75 | # py_modules=["my_module"],
76 |
77 | # List run-time dependencies here. These will be installed by pip when
78 | # your project is installed. For an analysis of "install_requires" vs pip's
79 | # requirements files see:
80 | # https://packaging.python.org/en/latest/requirements.html
81 | install_requires=[
82 | ],
83 |
84 | # List additional groups of dependencies here (e.g. development
85 | # dependencies). You can install these using the following syntax,
86 | # for example:
87 | # $ pip install -e .[dev,test]
88 | extras_require={
89 | },
90 |
91 | # If there are data files included in your packages that need to be
92 | # installed, specify them here. If using Python 2.6 or less, then these
93 | # have to be included in MANIFEST.in as well.
94 | package_data={
95 | 'slither': ['snakey.png'],
96 | 'slither.examples': list(map(path.basename, glob.glob("slither/examples/*.png") + glob.glob("slither/examples/*.wav")))
97 | },
98 |
99 | # Although 'package_data' is the preferred approach, in some case you may
100 | # need to place data files outside of your packages. See:
101 | # http://docs.python.org/3.4/distutils/setupscript.html#installing-additional-files # noqa
102 | # In this case, 'data_file' will be installed into '/my_data'
103 | data_files=[],
104 |
105 | )
106 |
--------------------------------------------------------------------------------
/slither/__init__.py:
--------------------------------------------------------------------------------
1 | from .slither import *
2 |
3 | __all__ = ['slither','Mouse','Stage','Sprite','Sound']
4 |
--------------------------------------------------------------------------------
/slither/examples/assets/boom.wav:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/PySlither/Slither/affda7ac36188c2c3af1a8a0b7ecbe7bd228007c/slither/examples/assets/boom.wav
--------------------------------------------------------------------------------
/slither/examples/assets/doge.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/PySlither/Slither/affda7ac36188c2c3af1a8a0b7ecbe7bd228007c/slither/examples/assets/doge.png
--------------------------------------------------------------------------------
/slither/examples/assets/grass.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/PySlither/Slither/affda7ac36188c2c3af1a8a0b7ecbe7bd228007c/slither/examples/assets/grass.png
--------------------------------------------------------------------------------
/slither/examples/dogeinvasion.py:
--------------------------------------------------------------------------------
1 | import slither, random # Get functions from slither and random
2 |
3 | doge = [None]* 30 # Initialize array 'doge'
4 | dogecount = 1 # Initialize iterator 'dogecount'
5 |
6 | while dogecount != 30: # Produce 30 doges
7 | doge[dogecount] = slither.Sprite() # Make each doge a sprite
8 | doge[dogecount].addCostume('./assets/doge.png', 'doge') # Give them the costume 'doge'
9 | doge[dogecount].costumeName = 'doge' # Set the doges costume to 'doge'
10 | doge[dogecount].ypos = random.randint(0, 400) # Make the doges go to a random y position
11 | doge[dogecount].xpos = random.randint(0, 400) # Make the doges go to a random x position
12 | dogecount += 1 # Increase the iterator for reiteration
13 |
14 | slither.setup('Doge invasion!', 400, 400) # Setup slither, set caption to 'Doge invasion!' and set resolution to 400px by 400px
15 |
16 | def loop(): # Define main game loop called 'loop'
17 | pass # Do nothing...
18 |
19 | slither.runMainLoop(loop) # Run main game loop
20 |
--------------------------------------------------------------------------------
/slither/examples/helloworld.py:
--------------------------------------------------------------------------------
1 | import slither # Get slither functions
2 |
3 | snakey = slither.Sprite() # Make a sprite called snakey
4 | snakey.costumeName = "costume0" # Set snakey's costume to costume0
5 |
6 | snakey.goto(200, 200) # Make snakey go to x 200 and y 200
7 |
8 | slither.setup('Hello World!', 400, 400) # Setup slither with caption 'Hello World!' and resolution 400px by 400px
9 |
10 | def run_a_frame(): # Define main game loop
11 | pass # Do nothing. This is only a simple project
12 |
13 | slither.runMainLoop(run_a_frame) # Start main game loop
14 |
--------------------------------------------------------------------------------
/slither/examples/mover.py:
--------------------------------------------------------------------------------
1 | # mover.py
2 | import pygame # We need pygame for the event constants and the key functions
3 | import slither
4 | from pygame.locals import *
5 |
6 | sprite = slither.Sprite()
7 | sprite.goto(slither.WIDTH // 2, slither.HEIGHT // 2) # Goto the middle of the screen
8 | sprite.addCostume("../tests/assets/arrow.png", "arrow") # Load the arrow costume
9 | sprite.costumeName = "arrow" # Set the costume.
10 |
11 | # This dict holds the data for how fast the arrow moves and what direction it is pointing
12 | controls = {"turn":0, "speed":0}
13 |
14 | @slither.registerCallback(pygame.MOUSEBUTTONDOWN)
15 | def handle_mousedown(event): # When the mouse button is pressed...
16 | print(controls) # ...print out the controls dict
17 |
18 | def run_a_frame():
19 | keys = pygame.key.get_pressed()
20 | # Because this example relies on having keys pressed down,
21 | # we can't use the event handlers, and have to check the key states ourself
22 | if keys[K_LEFT]:
23 | controls["turn"] -= 4
24 | elif keys[K_RIGHT]:
25 | controls["turn"] += 4
26 | if keys[K_SPACE]:
27 | controls["speed"] = min(controls["speed"] + 2, 10)
28 | else:
29 | controls["speed"] = max(controls["speed"] - 0.2, 0)
30 | # Set the sprites direction...
31 | sprite.direction = controls["turn"]
32 | # ... and move it speed steps
33 | sprite.moveSteps(controls["speed"])
34 | # Add wraparound checks.
35 | if sprite.xpos > slither.WIDTH:
36 | sprite.xpos = 0
37 | elif sprite.xpos < 0:
38 | sprite.xpos = slither.WIDTH
39 | if sprite.ypos > slither.HEIGHT:
40 | sprite.ypos = 0
41 | elif sprite.ypos < 0:
42 | sprite.ypos = slither.HEIGHT
43 |
44 | # Print instructions
45 | print("Use the left and right arrows to turn.\nUse the space key to go forward")
46 | # Setup slither...
47 | slither.setup("Move!")
48 | # and start it running!
49 | slither.runMainLoop(run_a_frame)
50 |
--------------------------------------------------------------------------------
/slither/examples/pressforsound.py:
--------------------------------------------------------------------------------
1 | import slither, time # Get slither and time functions
2 |
3 | slither.setup('Press S for sound', 400, 400) # Setup slither with the caption 'Press S for sound' and resolution 400px by 400px
4 |
5 | def loop(): # Define main loop
6 | try: # Error handling wrapper
7 | if slither.keysDown()[0] == 's': # Run if key s is pressed...
8 | sound = slither.slitherSound.loadSound('./assets/boom.wav') # Load the sound 'boom.wav'
9 | sound.play() # Play the sound
10 | time.sleep(2) # Wait 2 seconds
11 | except: # Run code if there's an error
12 | pass # Do nothing
13 |
14 | slither.runMainLoop(loop) # Run main loop
15 |
--------------------------------------------------------------------------------
/slither/examples/runsnakey.py:
--------------------------------------------------------------------------------
1 | import slither # Get slither functions
2 |
3 | background = slither.slitherStage # Make 'background' the stage
4 | background.addCostume('./assets/grass.png', 'grass') # Add costume 'grass' to background
5 | background.costumeName = 'grass' # Set the costume to grass
6 |
7 | snakey = slither.Sprite() # Make a sprite named snakey (default)
8 | snakey.goto(700, 200) # Make snakey go to xpos 700 and ypos 200
9 |
10 | slither.setup('Run Snakey!', 800, 400) # Setup slither, set the caption to 'Run Snakey!' and set the resolution to 800px by 400px
11 |
12 | def myloop(): # Make a main loop named 'myloop'
13 | slither.blitText('Run snakey, Run!', 300, 20, 32) # Add the text 'Run snakey, Run!' to the screen on xpos 300, ypos 20 with font size 32
14 | snakey.xpos -= 10 # Make snakey run forward
15 | if snakey.xpos == 100: # Trigger code if snakey is about to exit screen
16 | snakey.goto(700, 200) # Make snakey restart
17 |
18 | slither.runMainLoop(myloop) # Run the main game loop
19 |
--------------------------------------------------------------------------------
/slither/examples/turnAndMove.py:
--------------------------------------------------------------------------------
1 | import slither
2 | import pygame
3 |
4 | snakey = slither.Sprite()
5 | snakey.costumeName = "costume0"
6 |
7 | snakey.goto(0, 0)
8 |
9 | slither.setup() # Begin slither
10 |
11 | def handlequit():
12 | print("Quitting...")
13 | return True
14 | slither.registerCallback(pygame.QUIT, handlequit) # This uses the direct call form
15 |
16 | @slither.registerCallback(pygame.MOUSEBUTTONUP) # This uses the decorator form
17 | def handlemouseup(event):
18 | print("Mouseup:", event.pos, event.button)
19 |
20 | def run_a_frame():
21 | snakey.xpos += 1
22 | snakey.ypos += 1
23 | snakey.direction += 1
24 |
25 | slither.runMainLoop(run_a_frame)
26 |
--------------------------------------------------------------------------------
/slither/slither.py:
--------------------------------------------------------------------------------
1 | # SLITHER FOR PYTHON 2 AND 3
2 | # Hi there, code divers!
3 | # There's a lot of cool stuff here that has comments so you can understand what's going on.
4 | # You can even mess around with it yourself :)
5 | # If you think your messing around might help, go to:
6 | # https://github.com/PySlither/Slither
7 | # and make a pull request!
8 |
9 | import pygame
10 | import sys, os, collections, warnings, math
11 | import tempfile, shutil, atexit, subprocess
12 | try:
13 | from shlex import quote
14 | except ImportError:
15 | from pipes import quote
16 |
17 | _DEVNULL = open(os.devnull, "wb")
18 |
19 | # Check for ImageMagick
20 | if subprocess.call("identify -version", shell=True, stdout=_DEVNULL) != 0:
21 | svgSupport = False
22 | warnings.warn("Could not find ImageMagick, so there is no SVG support\n"
23 | "See https://github.com/PySlither/Slither/blob/master/Installing-ImageMagick.md "
24 | "for instructions on installing ImageMagick")
25 | else:
26 | svgSupport = True
27 |
28 | tempdir = tempfile.mkdtemp(prefix="PySlither-")
29 | @atexit.register
30 | def _clean_temp_dir():
31 | "Cleans the temp dir when the program quits"
32 | shutil.rmtree(tempdir)
33 |
34 | class NoSVGSupportError(Exception):
35 | pass
36 |
37 | WIDTH, HEIGHT = (800, 600)
38 | SCREEN_SIZE = (WIDTH, HEIGHT)
39 |
40 | fullScreen = False
41 |
42 | sprites = [] # List of all sprites
43 | clock = pygame.time.Clock() # Used to control framerate
44 | eventnames = ['QUIT', 'ACTIVEEVENT', 'KEYDOWN', 'KEYUP', 'MOUSEMOTION', 'MOUSEBUTTONUP', 'MOUSEBUTTONDOWN',
45 | 'JOYAXISMOTION', 'JOYBALLMOTION', 'JOYHATMOTION', 'JOYBUTTONUP', 'JOYBUTTONDOWN',
46 | 'VIDEORESIZE', 'VIDEOEXPOSE', 'USEREVENT']
47 | eventCallbacks = {
48 | getattr(pygame, name): lambda e=None: True
49 | for name in eventnames
50 | } # Create a dict of callbacks that do nothing
51 | globalscreen = None
52 |
53 | keysPressed = []
54 |
55 | try:
56 | scriptdir = os.path.dirname(os.path.realpath(__import__("__main__").__file__))
57 | except AttributeError:
58 | warnings.warn("Couldn't find scripts dir, some functions may not work.")
59 | scriptdir = os.path.realpath(".")
60 |
61 |
62 | def keysDown():
63 | "returns the keys that are currently pressed"
64 | return keysPressed[:]
65 |
66 | # Convienience functions
67 | # Taken from http://stackoverflow.com/questions/4183208/how-do-i-rotate-an-image-around-its-center-using-pygame
68 | def rotateCenter(image, angle):
69 | '''rotate a Surface, maintaining position.'''
70 | rot_sprite = pygame.transform.rotate(image, angle)
71 | return rot_sprite
72 |
73 | class Mouse:
74 | """A class for getting and setting mouse properties
75 | This is a static class, all functions should be called directly through the class"""
76 | _v = True
77 |
78 | @staticmethod
79 | def buttonsPressed():
80 | """Returns a three-tuple of bools that gives the state
81 | of the left, middle, and right buttons"""
82 | return tuple(bool(state) for state in pygame.mouse.get_pressed())
83 |
84 | @staticmethod
85 | def leftPressed():
86 | return Mouse.buttonsPressed()[0]
87 |
88 | @staticmethod
89 | def middlePressed():
90 | return Mouse.buttonsPressed()[1]
91 |
92 | @staticmethod
93 | def rightPressed():
94 | return Mouse.buttonsPressed()[2]
95 |
96 | @staticmethod
97 | def pos():
98 | return pygame.mouse.get_pos()
99 |
100 | @staticmethod
101 | def xPos():
102 | return Mouse.pos()[0]
103 |
104 | @staticmethod
105 | def yPos():
106 | return Mouse.pos()[1]
107 |
108 | @staticmethod
109 | def relativeMovement():
110 | "Returns how much the mouse has moved since the last call to this function"
111 | return pygame.mouse.get_rel()
112 |
113 | @staticmethod
114 | def setPos(x, y):
115 | pygame.mouse.set_pos(x, y)
116 |
117 | @staticmethod
118 | def setXPos(x):
119 | pygame.mouse.set_pos(x, Mouse.yPos())
120 |
121 | @staticmethod
122 | def setYPos(y):
123 | pygame.mouse.set_pos(Mouse.xPos(), y)
124 |
125 | @staticmethod
126 | def isVisible():
127 | return Mouse._v
128 |
129 | @staticmethod
130 | def setVisible(status):
131 | Mouse._v = pygame.mouse.set_visible(status)
132 |
133 | @staticmethod
134 | def isFocused():
135 | return bool(pygame.mouse.get_focused())
136 |
137 | #Costume classes
138 | class SVGCostume:
139 | "A class that handles resizing the SVG correctly"
140 | def __init__(self, costumePath, scale):
141 | if not svgSupport:
142 | raise NoSVGSupportError("You do not have ImageMagick installed correctly")
143 | self.costumePath = costumePath
144 | self.scale = scale
145 | command = 'convert {} -format "%w %h" info:'.format(
146 | '"' + quote(os.path.join(scriptdir, self.costumePath))[1:-1] + '"')
147 | #print(command)
148 | d = subprocess.check_output(command,
149 | shell=True)
150 | self.width, self.height = map(int, d.split())
151 | #print(self.width, self.height, sep=", ")
152 | self.createImage()
153 |
154 | def createImage(self):
155 | name = os.path.splitext(os.path.basename(self.costumePath))[0] + ".png"
156 | in_ = os.path.join(scriptdir, self.costumePath)
157 | path = os.path.join(tempdir, name)
158 | subprocess.check_output("convert -density {den} -resize {w}x{h} {in_} {out}".format(
159 | den=72*self.scale+5,
160 | w=self.scale*self.width,
161 | h=self.scale*self.height,
162 | in_='"'+quote(in_)[1:-1]+'"',
163 | out='"'+quote(path)[1:-1]+'"'),
164 | shell=True)
165 | self.img = pygame.image.load(path)
166 |
167 | def resize(self, scale):
168 | self.scale = scale
169 | self.createImage()
170 |
171 | class PNGCostume:
172 | "Dummy class to make SVG and PNG costumes the same"
173 | def __init__(self, img):
174 | self.img = img
175 | def resize(self, scale):
176 | pass
177 |
178 |
179 |
180 | # Stage class
181 | class Stage(object):
182 | def __init__(self):
183 | self.snakey = PNGCostume(pygame.image.load(os.path.join(os.path.dirname(__file__), "snakey.png")))
184 | self.costumes = collections.OrderedDict({"costume0" : self.snakey})
185 | self._costumeNumber = 0
186 | self._costumeName = "costume0"
187 | self.currentCostume = None
188 | self.bgColor = (255, 255, 255)
189 |
190 | # Functions shared by sprites
191 | def addCostume(self, costumePath, costumeName):
192 | '''Add a costume based on a given path and name.'''
193 | if os.path.splitext(costumePath)[1] in (".svg", ".svgx"):
194 | costume = SVGCostume(costumePath, self.scale if hasattr(self, "scale") else 1)
195 | else:
196 | path = os.path.join(scriptdir, costumePath)
197 | costume = PNGCostume(pygame.image.load(path))
198 | self.costumes[costumeName] = costume
199 | self._costumeName = costumeName # Switch to the new costume
200 |
201 | def deleteCostumeByName(self, name):
202 | '''Delete a costume by name.'''
203 | self.costumes.pop(name, None)
204 | self.recalculateNumberFromName(self.costumeName) # Make sure we recalculate the costume data!
205 |
206 | def deleteCostumeByNumber(self, number):
207 | '''Delete a costume by number.'''
208 | if number < len(self.costumes):
209 | costumeName = self.costumes.keys()[number]
210 | self.deleteCostumeByName(costumeName) # TODO: Fix this stupid "get name from number" thing
211 |
212 | @property
213 | def costumeNumber(self):
214 | '''The number of the costume the sprite is showing'''
215 | return self._costumeNumber
216 |
217 | @costumeNumber.setter
218 | def costumeNumber(self, val):
219 | val = val % len(self.costumes)
220 | self._costumeName = list(self.costumes.keys())[val]
221 | self.currentCostume = self.costumes[self.costumeName]
222 | self._costumeNumber = val
223 |
224 | @property
225 | def costumeName(self):
226 | '''The name of the costume the sprite is showing'''
227 | return self._costumeName
228 |
229 | @costumeName.setter
230 | def costumeName(self, val):
231 | if val in self.costumes:
232 | self._costumeName = val
233 | self.currentCostume = self.costumes[self.costumeName]
234 |
235 |
236 | slitherStage = Stage()
237 |
238 | # The Sprite inherits things such as the costumes from the stage so everything can be kept in one place.
239 | class Sprite(Stage):
240 | def __init__(self):
241 | Stage.__init__(self) # Get all the stuff from the stage, too
242 | self.currentCostume = self.snakey # By default we should be set to Snakey
243 | self.xpos = 0 # X Position
244 | self.ypos = 0 # Y Position
245 | self.direction = 0 # Direction is how much to change the direction, hence why it starts at 0 and not 90
246 | self.show = True
247 | self.showBoundingBox = False
248 | self._scale = 1 # How much to multiply it by in the scale
249 | self._zindex = 0 # How high up are we in the "z" axis?
250 | sprites.append(self) # Add this sprite to the global list of sprites
251 |
252 | @property
253 | def zindex(self):
254 | '''The location of the sprite in the z-axis. Those with higher z-indexes are displayed above those with lower ones.'''
255 | return self._zindex
256 |
257 | @zindex.setter
258 | def zindex(self, val):
259 | #if val < 0 or int(val) != val:
260 | # raise ValueError("zindex must be a non-negative integer")
261 | self._zindex = val
262 | reorderSprites()
263 |
264 | @property
265 | def scale(self):
266 | return self._scale
267 |
268 | @scale.setter
269 | def scale(self, val):
270 | self._scale = val
271 | self.currentCostume.resize(self._scale)
272 |
273 | def goto(self, xpos, ypos):
274 | '''Go to xpos, ypos.'''
275 | self.xpos = xpos
276 | self.ypos = ypos
277 |
278 | def moveSteps(self, numSteps):
279 | """Move numSteps steps in the current direction"""
280 | self.goto(self.xpos + math.cos(math.radians(self.direction)) * numSteps,
281 | self.ypos + math.sin(math.radians(self.direction)) * numSteps)
282 |
283 | def isVisible(self):
284 | '''Check if the object is visible, not just showing.
285 | This is better than Sprite.show because it also checks the scale.'''
286 | return self.show and self.scale > 0
287 |
288 | def delete(self):
289 | '''Remove the sprite from the global sprites list, causing it not to be drawn.'''
290 | sprites.remove(self)
291 |
292 | def isTouching(self, collideSprite):
293 | '''Detects if one sprite is touching another.'''
294 | ourRect = self.currentCostume.img.get_rect()
295 | theirRect = collideSprite.currentCostume.img.get_rect()
296 | ourRect.center = (self.xpos, self.ypos)
297 | theirRect.center = (collideSprite.xpos, collideSprite.ypos)
298 | return ourRect.colliderect(theirRect)
299 |
300 | pygame.mixer.init(44100, -16, 2, 2048)
301 |
302 | class Sound():
303 | # Based on pygame examples, http://stackoverflow.com/questions/8690301/pygame-memoryerror
304 | def loadSound(self, name):
305 | '''Load a sound. Set this function to a variable then call variable.play()'''
306 | try:
307 | pygame.mixer.get_init()
308 | except:
309 | pass
310 | class NoneSound:
311 | def play(self): pass
312 | if not pygame.mixer:
313 | return NoneSound()
314 | fullname = os.path.join(scriptdir, name)
315 | try:
316 | sound = pygame.mixer.Sound(fullname)
317 | except pygame.error as e:
318 | print ('Cannot load sound: %s' % fullname)
319 | raise e
320 | return sound
321 |
322 | slitherSound = Sound()
323 |
324 | # Convienience function to blit text
325 | def blitText(text, x=0, y=0, size=12, font=False, fontPath=False, antialias=0, color=(0,0,0)):
326 | global globalscreen
327 | if font:
328 | textFont = pygame.font.SysFont(font, size)
329 | elif fontPath:
330 | textFont = pygame.font.Font(fontPath, size)
331 | else:
332 | textFont = pygame.font.SysFont("Helvetica", size) # Users should always have Helvetica installed
333 |
334 | textImage = textFont.render(text, antialias, color)
335 |
336 | globalscreen.blit(textImage, (x, y))
337 |
338 | #pygame.display.flip()
339 |
340 | def setup(caption=sys.argv[0], width=800, height=600):
341 | '''Sets up PyGame and returns a screen object that can be used with blit().'''
342 | global globalscreen, WIDTH, HEIGHT, SCREEN_SIZE
343 | WIDTH = width
344 | HEIGHT = height
345 | SCREEN_SIZE = (WIDTH, HEIGHT)
346 | pygame.init()
347 | pygame.font.init()
348 | screen = pygame.display.set_mode(SCREEN_SIZE)
349 | caption = pygame.display.set_caption(caption)
350 | globalscreen = screen
351 | return screen
352 |
353 | def toggleFullScreen():
354 | "Toggles fullscreen"
355 | global fullScreen
356 | fullScreen = not fullScreen
357 | setFullScreen(fullScreen)
358 |
359 | def setFullScreen(mode):
360 | "If mode is True, turns on full screen, otherwise, turns it off"
361 | global screen
362 | if mode:
363 | screen = pygame.display.set_mode((0, 0), pygame.FULLSCREEN|pygame.HWSURFACE|pygame.DOUBLEBUF)
364 | else:
365 | screen = pygame.display.set_mode(SCREEN_SIZE)
366 |
367 | projectFPS = 60 # 60 is the default
368 | def setFPS(fps):
369 | '''Set the FPS of the project. Default is 60, and Scratch runs at 30.'''
370 | global projectFPS
371 | projectFPS = fps # projectFPS is the FPS that the main loop uses
372 |
373 | def setCaption(caption):
374 | "Sets the screen's caption to caption"
375 | pygame.display.set_caption(caption)
376 |
377 | def reorderSprites():
378 | global sprites
379 | sprites = sorted(sprites, key=(lambda s: s.zindex))
380 |
381 | def blit(screen):
382 | '''Takes a screen as an argument and draws objects to the screen. THIS MUST BE CALLED FOR SLITHER TO DISPAY OBJECTS.'''
383 | if screen:
384 | screen.fill(slitherStage.bgColor)
385 |
386 | if slitherStage.currentCostume:
387 | screen.blit(pygame.transform.scale(slitherStage.currentCostume.img, SCREEN_SIZE), (0, 0))
388 |
389 | for obj in sprites:
390 | if obj.isVisible(): # Check if the object is showing before we do anything
391 | image = obj.currentCostume.img # So we can modify it and blit the modified version easily
392 | # These next few blocks of code check if the object has the defaults before doing anything.
393 | if not obj.scale == 1 and not isinstance(obj.currentCostume, SVGCostume):
394 | imageSize = image.get_size()
395 | image = pygame.transform.scale(image, (int(imageSize[0] * obj.scale), int(imageSize[1] * obj.scale)))
396 | if not obj.direction == 0:
397 | image = rotateCenter(image, -obj.direction)
398 | new_rect = image.get_rect()
399 | new_rect.center = (obj.xpos, obj.ypos)
400 | screen.blit(image, new_rect)
401 | if obj.showBoundingBox:
402 | pygame.draw.rect(screen, (0,0,0), new_rect, 5)
403 |
404 | #pygame.display.flip()
405 |
406 | def registerCallback(eventname, func=None):
407 | '''Register the function func to handle the event eventname'''
408 | if func:
409 | # Direct call (registerCallback(pygame.QUIT, func))
410 | eventCallbacks[eventname] = func
411 | else:
412 | # Decorator call (@registerCallback(pygame.QUIT)
413 | # def f(): pass
414 | def f(func):
415 | eventCallbacks[eventname] = func
416 | return f
417 |
418 | def runQuitCallback():
419 | return eventCallbacks[pygame.QUIT]()
420 |
421 | def runMainLoop(frameFunc):
422 | while True:
423 | blit(globalscreen)
424 | frameFunc()
425 | for event in pygame.event.get():
426 | if event.type == pygame.QUIT:
427 | if runQuitCallback():
428 | # runQuitCallback would run the function
429 | # given to setQuitCallback, and return its result
430 | pygame.quit()
431 | sys.exit()
432 | else:
433 | if event.type == pygame.KEYDOWN:
434 | keysPressed.append(pygame.key.name(event.key))
435 | elif event.type == pygame.KEYUP:
436 | keysPressed.remove(pygame.key.name(event.key))
437 | eventCallbacks[event.type](event)
438 | # eventCallbacks would be a dictionary mapping
439 | # event types to handler functions.
440 | pygame.display.flip() # Always flip at the end
441 | clock.tick(projectFPS) # Run at however many FPS the user specifies
442 |
--------------------------------------------------------------------------------
/slither/snakey.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/PySlither/Slither/affda7ac36188c2c3af1a8a0b7ecbe7bd228007c/slither/snakey.png
--------------------------------------------------------------------------------
/slither/tests/assets/SOS.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/PySlither/Slither/affda7ac36188c2c3af1a8a0b7ecbe7bd228007c/slither/tests/assets/SOS.png
--------------------------------------------------------------------------------
/slither/tests/assets/SVG Logo.svg:
--------------------------------------------------------------------------------
1 |
260 |
--------------------------------------------------------------------------------
/slither/tests/assets/SoExcited.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/PySlither/Slither/affda7ac36188c2c3af1a8a0b7ecbe7bd228007c/slither/tests/assets/SoExcited.png
--------------------------------------------------------------------------------
/slither/tests/assets/arrow.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/PySlither/Slither/affda7ac36188c2c3af1a8a0b7ecbe7bd228007c/slither/tests/assets/arrow.png
--------------------------------------------------------------------------------
/slither/tests/assets/bg2.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/PySlither/Slither/affda7ac36188c2c3af1a8a0b7ecbe7bd228007c/slither/tests/assets/bg2.png
--------------------------------------------------------------------------------
/slither/tests/assets/boom.wav:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/PySlither/Slither/affda7ac36188c2c3af1a8a0b7ecbe7bd228007c/slither/tests/assets/boom.wav
--------------------------------------------------------------------------------
/slither/tests/assets/circle.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/PySlither/Slither/affda7ac36188c2c3af1a8a0b7ecbe7bd228007c/slither/tests/assets/circle.png
--------------------------------------------------------------------------------
/slither/tests/assets/snakey.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/PySlither/Slither/affda7ac36188c2c3af1a8a0b7ecbe7bd228007c/slither/tests/assets/snakey.png
--------------------------------------------------------------------------------
/slither/tests/basicTest.py:
--------------------------------------------------------------------------------
1 | #! usr/bin/env python3
2 | # basicTest.py
3 | import slither
4 |
5 | snakey = slither.Sprite()
6 | snakey.costumeName = "costume0" # You can set the default costume (costume0) by name...
7 | snakey.ypos = 100
8 |
9 | SoExcited = slither.Sprite()
10 | SoExcited.addCostume("assets/SoExcited.png", "avatar")
11 | SoExcited.costumeNumber = 1 # ...or you can use a number.
12 |
13 | SoExcited.goto(300, 300)
14 | SoExcited.scale = 0.33 # May look grainy when used on too low a scale.
15 |
16 | slither.slitherStage.bgColor = (40, 222, 40)
17 |
18 | slither.setup() # Begin slither
19 |
20 | def run_a_frame():
21 | snakey.xpos += 1
22 | SoExcited.direction += 1
23 |
24 | slither.runMainLoop(run_a_frame)
25 |
--------------------------------------------------------------------------------
/slither/tests/bgTest.py:
--------------------------------------------------------------------------------
1 | #! usr/bin/env python3
2 | # bgTest.py
3 | import math
4 | import slither
5 |
6 | snakey = slither.Sprite()
7 | snakey.ypos = 460
8 |
9 | slither.slitherStage.bgColor = (40, 222, 40)
10 | slither.slitherStage.addCostume("assets/bg2.png", "bg")
11 | slither.slitherStage.costumeName = "bg"
12 |
13 | slither.setup() # Begin slither'
14 |
15 | i = 0
16 | def run_a_frame():
17 | global i
18 | snakey.xpos = ((math.sin(i) * 200) + 300)
19 | i += 0.05
20 |
21 | slither.runMainLoop(run_a_frame)
22 |
--------------------------------------------------------------------------------
/slither/tests/captionTest.py:
--------------------------------------------------------------------------------
1 | import slither
2 |
3 | i = 0
4 |
5 | def run_a_frame():
6 | global i
7 | slither.setCaption("-"*(i+1))
8 | i = (i + 1) % 60
9 |
10 | slither.setup("")
11 |
12 | slither.runMainLoop(run_a_frame)
13 |
--------------------------------------------------------------------------------
/slither/tests/fullScreenTest.py:
--------------------------------------------------------------------------------
1 | #! usr/bin/env python3
2 | # fullScreenTest.py
3 |
4 | import slither, pygame
5 |
6 | snakey = slither.Sprite()
7 | snakey.costumeName = "costume0" # You can set the default costume (costume0) by name...
8 | snakey.goto(400, 300)
9 |
10 | slither.slitherStage.bgColor = (40, 222, 40)
11 |
12 | slither.setup() # Begin slither
13 |
14 | def run_a_frame():
15 | snakey.direction += 1
16 |
17 | @slither.registerCallback(pygame.MOUSEBUTTONUP)
18 | def handle_mousedown(event):
19 | slither.toggleFullScreen()
20 |
21 | slither.runMainLoop(run_a_frame)
22 |
--------------------------------------------------------------------------------
/slither/tests/imageBounceTest.py:
--------------------------------------------------------------------------------
1 | #! usr/bin/env python3
2 | # imageBounceTest.py
3 | import slither
4 |
5 | def create_circle():
6 | circle = slither.Sprite()
7 | circle.addCostume("assets/circle.png", "circle")
8 | circle.costumeName = "circle"
9 | circle.goto(0,0)
10 | return circle
11 | circle1, circle2, circle3 = create_circle(), create_circle(), create_circle()
12 | circle4 = create_circle()
13 | circle4.goto(400,300)
14 | slither.slitherStage.bgcolor = (255, 255, 255)
15 |
16 | def run_a_frame():
17 | circle1.xpos += 0.5
18 | circle1.ypos += 0.5
19 | circle1.direction += 1
20 |
21 | circle2.xpos += 0.5
22 | circle2.direction += 1
23 |
24 | circle3.ypos += 0.5
25 | circle3.direction += 1
26 |
27 | circle4.direction += 1
28 |
29 | slither.setup()
30 | slither.runMainLoop(run_a_frame)
31 |
--------------------------------------------------------------------------------
/slither/tests/isTouchingTest.py:
--------------------------------------------------------------------------------
1 | #! usr/bin/env python3
2 | # isTouchingTest.py
3 | import slither
4 |
5 | toucher = slither.Sprite()
6 | toucher.addCostume("assets/arrow.png", "arrow")
7 | toucher.costumeName = "arrow"
8 | toucher.goto(0, 100)
9 |
10 | snakey = slither.Sprite()
11 | snakey.goto(slither.WIDTH // 2, 100)
12 |
13 | def run_a_frame():
14 | toucher.moveSteps(3)
15 | if toucher.isTouching(snakey):
16 | print("Touching!")
17 | else:
18 | print("Not touching.")
19 |
20 | slither.setup()
21 | slither.runMainLoop(run_a_frame)
22 |
--------------------------------------------------------------------------------
/slither/tests/keysDownTest.py:
--------------------------------------------------------------------------------
1 | # usr/bin/env python3
2 | # keysDownTest.py - Test slither.keysDown()
3 |
4 | import slither
5 |
6 | def run_a_frame():
7 | print(slither.keysDown())
8 |
9 | slither.setup()
10 | slither.runMainLoop(run_a_frame)
11 |
--------------------------------------------------------------------------------
/slither/tests/mouseTest.py:
--------------------------------------------------------------------------------
1 | # usr/bin/env python3
2 | # mouseTest.py
3 |
4 | import slither
5 | from slither import Mouse
6 |
7 | def run_a_frame():
8 | print(Mouse.buttonsPressed())
9 | print(Mouse.pos())
10 | print(Mouse.isFocused())
11 | print()
12 |
13 | slither.setup()
14 | slither.runMainLoop(run_a_frame)
15 |
--------------------------------------------------------------------------------
/slither/tests/moveStepsTest.py:
--------------------------------------------------------------------------------
1 | #! usr/bin/env python3
2 | # moveStepsTest.py
3 | import slither
4 |
5 | sprite = slither.Sprite()
6 | sprite.addCostume("assets/arrow.png", "arrow")
7 | sprite.costumeName = "arrow"
8 | sprite.goto(slither.WIDTH // 2, 75)
9 |
10 | def run_a_frame():
11 | sprite.direction += 5
12 | sprite.moveSteps(20)
13 |
14 | slither.setup()
15 | slither.setFPS(30) # Slow slither down
16 | slither.runMainLoop(run_a_frame)
17 |
--------------------------------------------------------------------------------
/slither/tests/soundtest.py:
--------------------------------------------------------------------------------
1 | #! usr/bin/env python3
2 | # soundtest.py
3 | # Sound works, make sure your volume is up.
4 | import slither
5 | import time
6 |
7 | sound = slither.slitherSound.loadSound('assets/boom.wav')
8 | sound.play()
9 | time.sleep(2)
10 |
--------------------------------------------------------------------------------
/slither/tests/svgTest.py:
--------------------------------------------------------------------------------
1 | # usr/bin/env python3
2 | # svgTest.py - Test Slither's SVG support
3 |
4 | import slither
5 |
6 | if slither.svgSupport:
7 | print("We have SVG support!")
8 | else:
9 | print("No SVGs today :(")
10 |
11 | svg = slither.Sprite()
12 | svg.addCostume("assets/SVG Logo.svg", "svg")
13 | svg.costumeNumber = 1
14 | svg.scale = 1
15 | svg.showBoundingBox = False
16 | svg.goto(100, 300)
17 |
18 | svg2 = slither.Sprite()
19 | svg2.addCostume("assets/SVG Logo.svg", "svg")
20 | svg2.costumeNumber = 1
21 | svg2.scale = 5
22 | svg2.showBoundingBox = False
23 | svg2.goto(500, 300)
24 |
25 | slither.setup() # Begin slither
26 |
27 | def run_a_frame():
28 | pass
29 |
30 | slither.runMainLoop(run_a_frame)
31 |
--------------------------------------------------------------------------------
/slither/tests/textTest.py:
--------------------------------------------------------------------------------
1 | #! usr/bin/env python3
2 | # textTest.py
3 | import slither
4 |
5 | slither.slitherStage.bgColor = (40, 222, 40)
6 |
7 | slither.setup() # Begin slither
8 |
9 | slither.blitText("Hello, world!")
10 |
11 | def run_a_frame():
12 | slither.blitText("Hello, world!", size=40)
13 |
14 | slither.runMainLoop(run_a_frame)
15 |
--------------------------------------------------------------------------------
/slither/tests/zindextest.py:
--------------------------------------------------------------------------------
1 | #! usr/bin/env python3
2 | # zindextest.py
3 | import slither
4 |
5 | # Normally, since Snakey was made before SoExcited, SoExcited would be rendered after Snakey and be put on top.
6 | snakey = slither.Sprite()
7 |
8 | SoExcited = slither.Sprite()
9 | SoExcited.addCostume("assets/SoExcited.png", "avatar")
10 | SoExcited.costumeNumber = 1
11 |
12 | SoExcited.zindex = -1 # But when SoExcited's z-index is set to below that of Snakey's, SoExcited gets rendered before (and thus below) Snakey.
13 |
14 | SoExcited.goto(300, 300)
15 | SoExcited.scale = 0.33
16 |
17 | slither.slitherStage.bgColor = (40, 40, 222)
18 |
19 | slither.setup()
20 |
21 | def run_a_frame():
22 | snakey.xpos += 1
23 | snakey.ypos += 1
24 | SoExcited.direction += 1
25 |
26 | slither.runMainLoop(run_a_frame)
27 |
--------------------------------------------------------------------------------