Go to file
Thomas Forgione bb6f95bd2a
Headless doesn't import pygame
2019-03-13 18:00:46 +01:00
snake Headless doesn't import pygame 2019-03-13 18:00:46 +01:00
.gitignore Initial commit 2018-10-23 23:27:27 +09:00
README.md Fixed readme 2018-12-13 14:07:02 +01:00
headless.py Headless doesn't import pygame 2019-03-13 18:00:46 +01:00
play.py Cleaning 2019-03-13 17:27:56 +01:00

README.md

Python Snake

This program is a simple python game, made for implementing your own AIs.

Table of contents

How to download the game

The first step is to clone the repository:

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:

    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:

    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:

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:

#!/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.