pytron/README.md
2018-12-13 14:07:02 +01:00

95 lines
2.6 KiB
Markdown

# Python Snake
This program is a simple python game, made for implementing your own AIs.
## Table of contents
- [How to download the game](#how-to-download-the-game)
- [How to play the game](#how-to-play-the-game)
- [How to create your own AI](#how-to-create-your-own-ai)
## How to download the game
The first step is to clone the repository:
``` sh
git clone https://gitea.tforgione.fr/tforgione/python-snake
```
Then, ensure you have `python3` and `pygame` installed. You can test you have everything by executing the following command:
```
python3 -c "import pygame"
```
- if you get a `python3: command not found`, it means you don't have `python3`, you can install it on ubuntu like so:
``` sh
sudo apt install python3
```
- if you get a `ImportError: No module named 'pygame'`, it means you don't have `pygame`, you can install it on ubuntu like so:
``` sh
sudo apt install python3-pip
sudo pip3 install pygame
```
## How to play the game
There are two runnable scripts in the repository, which are mostly here to be examples:
- `play.py` which shows how to create a game with a window and play against an AI.
- `headless.py` which shows how to run a game with AIs without watching the interface, and thus, really fast.
## How to create your own AI
You need to write a class that derives from `snake.player.Decision`. You have to define a constructor, so you can instanciate it, and implement the method `action` which takes as parameter the map of the game, and returns the direction you want to take.
For example, you can create a file `mydecision.py` at the root of this repository containing the following:
``` python
from snake.player import Decision, Direction
class MyDecision(Decision):
def __init__(self):
super(MyDecision, self).__init__()
def action(self, game_map):
# Do stuff
return Direction.DOWN
```
and you can create an executable file containing the following:
``` python
#!/usr/bin/env python3
import contextlib
with contextlib.redirect_stdout(None):
import pygame
from snake.map import Map
from snake.game import Game
from snake.window import Window
from snake.player import Player, Direction, ConstantDecision, KeyboardDecision
from other import MyDecision
def main():
pygame.init()
width = 40
height = 40
game = Game(width, height, [
Player(0, 0, (255, 0, 0), KeyboardDecision(Direction.RIGHT)),
Player(width - 1, height - 1, (0, 255, 0), MyDecision()),
])
window = Window(game, 20)
game.main_loop(window)
if __name__ == '__main__':
main()
```
and it should work.