Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
125 commits
Select commit Hold shift + click to select a range
e68e8cb
Update README.md
joram Oct 29, 2017
d1f7480
test hooks
Nov 12, 2017
887a2d8
test hooks
Nov 12, 2017
6b5bb6f
test hooks
Nov 12, 2017
bed1199
test hooks 2
Nov 12, 2017
a9e22bf
tested with 2018 server
joram Jan 29, 2018
1474f0b
Merge branch 'master' of github.com:sendwithus/battlesnake-python
joram Jan 29, 2018
0a0b2a2
Update README.md
joram Jan 29, 2018
b9c3642
Update main.py
joram Jan 29, 2018
b08e192
Update .gitignore
joram Jan 29, 2018
9c55e1c
Update .gitignore
joram Jan 29, 2018
834198d
Merge pull request #25 from joram/master
john-swu Feb 13, 2018
ef25417
testing
joram Feb 14, 2018
7c32462
testing
joram Feb 14, 2018
e6b5a75
Merge branch 'master' of github.com:sendwithus/battlesnake-python
joram Feb 14, 2018
0b03aaf
Update runtime.txt
john-swu Feb 23, 2018
5562aa2
Update main.py
john-swu Feb 26, 2018
517a454
Implement models for 2019 API spec.
CDFriend Apr 14, 2018
e350ccc
Add AGPL-3.0 license.
CDFriend Apr 14, 2018
cabc977
Update license to MIT.
CDFriend Apr 20, 2018
88a8d04
battlesnake changes
codeallthethingz Apr 21, 2018
6b0922a
Create CONTRIBUTING.md
codeallthethingz May 12, 2018
55dd198
Remove request processing classes from api.py.
CDFriend May 15, 2018
17af364
Merge pull request #31 from CDFriend/master
joram May 23, 2018
d9bf57c
Upgrade packages
brandonb927 Sep 4, 2018
d0d2c76
Update the version of heroku to 2.7.15
brandonb927 Sep 4, 2018
4f6fb2e
Merge pull request #33 from brandonb927/feature-upgrade-packages
brandonb927 Sep 4, 2018
f4c19ef
Update LICENSE
codeallthethingz Nov 17, 2018
716dc08
added ping. removed code that caused stack traces on start
Nov 18, 2018
116db0c
changed comments
Nov 18, 2018
934150d
Update app/main.py
codeallthethingz Nov 18, 2018
eb3e4b6
Update app/main.py
codeallthethingz Nov 18, 2018
ee1e27d
Update app/main.py
codeallthethingz Nov 18, 2018
78e5dff
Merge pull request #34 from codeallthethingz/master
codeallthethingz Nov 18, 2018
eb2fb31
Update documentation to routes, move all route HTTPResponses to API f…
SynthesizedSoul Dec 17, 2018
cd67ea7
Add back data variable to /end endpoint.
SynthesizedSoul Dec 17, 2018
1fd8456
Reintroduce the '/' route, using a SimpleEngine template to render a …
SynthesizedSoul Dec 17, 2018
d14beab
Remove unecessary bloating from adding templates directory. Instead r…
SynthesizedSoul Dec 17, 2018
90f3daa
Merge pull request #39 from SynthesizedSoul/api-route-cleanup
brandonb927 Dec 17, 2018
d192a5a
As per https://github.com/battlesnakeio/roadmap/issues/186
brandonb927 Dec 19, 2018
7628c3a
Update app/main.py
codeallthethingz Dec 21, 2018
8ded95e
Merge pull request #40 from battlesnakeio/fix-root-path-docs-link
brandonb927 Dec 21, 2018
3f03095
update docs link. cleaned up whitespace (#63)
joram Dec 20, 2019
598c18d
Updating contact info
chris-bsnake Jan 8, 2020
728a7c4
Documentation updates (#6)
brandonb927 Feb 19, 2020
5a9a53a
Create ci.yml
bvanvugt Feb 22, 2020
9c6ce10
Update ci.yml
bvanvugt Feb 22, 2020
fb8a68e
Update for Python 3.7.6 (among other things).
bvanvugt Feb 22, 2020
55d8381
Remove CI linting and formatting, we don't want to cause extra troubl…
bvanvugt Feb 22, 2020
b1e8d7f
Overhaul the Python Starter Snake to be easier to user. (#19)
bvanvugt Mar 15, 2020
bb49456
Change default move to "up".
bvanvugt Mar 15, 2020
752c86a
Update README.md
bvanvugt Mar 15, 2020
7eb225b
Update README.md
bvanvugt Mar 15, 2020
2751198
Update README.md
bvanvugt Mar 15, 2020
c892490
Update README.md
bvanvugt Mar 15, 2020
5548d9a
Bring back random moves as default.
bvanvugt Mar 16, 2020
ea518b2
Update README further.
bvanvugt Mar 16, 2020
0106e62
More README.md updates.
bvanvugt Mar 16, 2020
30100ed
Update README.md
bvanvugt Mar 16, 2020
6e3527b
Update README.md
bvanvugt Mar 16, 2020
7fa6df0
Removes the app.json, nolonger used (#20)
Apr 6, 2020
3768c9c
Update for API Version 1
bvanvugt May 18, 2020
57ae06e
Reinstate decorator calls.
bvanvugt May 18, 2020
1f59323
Reinstate default personalization.
bvanvugt May 18, 2020
40ad6ca
Update README for API Version 1.
bvanvugt May 19, 2020
0db9c1f
Update README.md
bvanvugt May 20, 2020
a9c8e6e
Add repl.it support. Bump to Python 3.8.
bvanvugt Jun 11, 2020
ac47c37
Update README.
bvanvugt Jun 11, 2020
96e6736
Update README.md
bvanvugt Jun 11, 2020
949f97b
Update README.md
bvanvugt Jun 11, 2020
6f44319
Update README.md
bvanvugt Jun 11, 2020
5b80e14
Update README.md
bvanvugt Jun 11, 2020
e97e732
Update README.md
bvanvugt Jun 11, 2020
c75c1e3
Update README.md
bvanvugt Jun 12, 2020
2a59a3e
Update README.md
bvanvugt Jun 12, 2020
baf57c2
Added the 'Run on Repl.it' button to Readme (#22)
lunaroyster Jun 20, 2020
b048642
Remove outdated TODO (#27)
dangor Nov 16, 2020
3eedcd8
Update README.md (#31)
svkers Mar 20, 2021
6c13ea7
Create CODE_OF_CONDUCT
andrewdmaclean Apr 5, 2021
4d65f22
Rename CODE_OF_CONDUCT to CODE_OF_CONDUCT.md
andrewdmaclean Apr 5, 2021
eb076cb
Update README.md
andrewdmaclean May 18, 2021
f326634
DEV-24 Adding additional starter code and updating comments/documenta…
aurorawalker Jul 7, 2021
6d6d6b2
Update LICENSE
aurorawalker Jul 9, 2021
e385cce
Dev 24 update debugging statements (#34)
aurorawalker Jul 12, 2021
4a3108d
Swap in Flask for CherryPy
bvanvugt Jul 17, 2021
4c2f34f
Update README.md
bvanvugt Jul 19, 2021
f71d959
Dev 175 (#35)
aurorawalker Jul 19, 2021
051c30e
Dev 175 (#36)
aurorawalker Jul 20, 2021
91a2400
putting back running local instructions
aurorawalker Jul 20, 2021
4dbed62
Remove reference to CherryPy in server.py (#37)
xtagon Jul 24, 2021
e6a5c15
Update README.md
bvanvugt Sep 1, 2021
7fb6344
Update README.md
bvanvugt Sep 2, 2021
ecf5973
Adding initial CODEOWNERS file
chris-bsnake Sep 7, 2021
2368999
Create CONTRIBUTING.md
aurorawalker Oct 1, 2021
6cc4bbe
Update copyright year
chris-bsnake Jan 4, 2022
b3cd721
use 'server' header to identify project (#38)
torbensky Feb 10, 2022
3fb7e11
Removing CODEOWNERS file as it doesn't make sense in a template project
chris-bsnake Mar 1, 2022
049b054
Re-organize under src directory.
bvanvugt Mar 1, 2022
591205d
Update replit support.
bvanvugt Mar 2, 2022
476801e
Try new replit run command.
bvanvugt Mar 2, 2022
0f91a2f
Try to fix replit file.
bvanvugt Mar 2, 2022
c27a696
Update poetry.lock
bvanvugt Mar 2, 2022
2b7f9b5
Update heroku procfile.
bvanvugt Mar 2, 2022
d006030
Add pycache to gitignore.
bvanvugt Mar 2, 2022
475526e
Update README and inline docs.
bvanvugt Mar 2, 2022
9247e7a
update replit file to import better (#39)
DaveMadden Jul 15, 2022
37f7da8
Rebuild python starter.
bvanvugt Aug 20, 2022
c343b8a
Add Dockerfile
bvanvugt Aug 22, 2022
2130fda
Update to latest README.
bvanvugt Aug 22, 2022
fa8d904
Add server header
bvanvugt Aug 22, 2022
4aef557
Update link in README
bvanvugt Aug 22, 2022
ed1bc03
Update README.md
bvanvugt Aug 25, 2022
4bd218a
Bump flask from 2.2.2 to 2.3.2 (#45)
dependabot[bot] May 3, 2023
3319f0d
Ignore Package
SuperMeister808 Jan 10, 2026
232e7f8
Remove old files
SuperMeister808 Jan 10, 2026
8b7650a
Restore Files
SuperMeister808 Jan 11, 2026
67a2682
Delete not relevant files from git
SuperMeister808 Jan 11, 2026
aa8ecea
Update git Ignore
SuperMeister808 Jan 11, 2026
e1cea59
Added test Module
SuperMeister808 Jan 11, 2026
eaa4232
Added class Move
SuperMeister808 Jan 11, 2026
4229057
Add Feature not_backward in Move()
SuperMeister808 Jan 11, 2026
fb4a476
Added choose_move in Move()
SuperMeister808 Jan 11, 2026
bbc5030
Test works
SuperMeister808 Jan 11, 2026
189c5a6
implement Move() in main
SuperMeister808 Jan 11, 2026
42261a6
Updated git Ignore
SuperMeister808 Jan 11, 2026
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 4 additions & 2 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
*.DS_Store
*.pyc
battlesnake
.idea
*.venv
__pycache__/
game_state_example.txt
run_local_game.txt
11 changes: 11 additions & 0 deletions Dockerfile
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
FROM python:3.10.6-slim

# Install app
COPY . /usr/app
WORKDIR /usr/app

# Install dependencies
RUN pip install --upgrade pip && pip install -r requirements.txt

# Run Battlesnake
CMD [ "python", "main.py" ]
21 changes: 21 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
MIT License

Copyright (c) 2022 Battlesnake Inc.

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
1 change: 0 additions & 1 deletion Procfile

This file was deleted.

76 changes: 36 additions & 40 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,63 +1,59 @@
# battlesnake-python
# Battlesnake Python Starter Project

A simple [BattleSnake AI](http://battlesnake.io) written in Python.
An official Battlesnake template written in Python. Get started at [play.battlesnake.com](https://play.battlesnake.com).

Visit [battlesnake.io/readme](http://battlesnake.io/readme) for API documentation and instructions for running your AI.
![Battlesnake Logo](https://media.battlesnake.com/social/StarterSnakeGitHubRepos_Python.png)

This AI client uses the [bottle web framework](http://bottlepy.org/docs/dev/index.html) to serve requests and the [gunicorn web server](http://gunicorn.org/) for running bottle on Heroku. Dependencies are listed in [requirements.txt](requirements.txt).
This project is a great starting point for anyone wanting to program their first Battlesnake in Python. It can be run locally or easily deployed to a cloud provider of your choosing. See the [Battlesnake API Docs](https://docs.battlesnake.com/api) for more detail.

[![Deploy](https://www.herokucdn.com/deploy/button.png)](https://heroku.com/deploy)
[![Run on Replit](https://repl.it/badge/github/BattlesnakeOfficial/starter-snake-python)](https://replit.com/@Battlesnake/starter-snake-python)

#### You will need...
## Technologies Used

* a working Python 2.7 development environment ([getting started guide](http://hackercodex.com/guide/python-development-environment-on-mac-osx/))
* experience [deploying Python apps to Heroku](https://devcenter.heroku.com/articles/getting-started-with-python#introduction)
* [pip](https://pip.pypa.io/en/latest/installing.html) to install Python dependencies
This project uses [Python 3](https://www.python.org/) and [Flask](https://flask.palletsprojects.com/). It also comes with an optional [Dockerfile](https://docs.docker.com/engine/reference/builder/) to help with deployment.

## Running the Snake Locally
## Run Your Battlesnake

1) [Fork this repo](https://github.com/sendwithus/battlesnake-python/fork).
Install dependencies using pip

2) Clone repo to your development environment:
```
git clone git@github.com:username/battlesnake-python.git
```

3) Install dependencies using [pip](https://pip.pypa.io/en/latest/installing.html):
```
```sh
pip install -r requirements.txt
```

4) Run local server:
```
python app/main.py
```
Start your Battlesnake

5) Test client in your browser: [http://localhost:8080](http://localhost:8080).
```sh
python main.py
```

## Deploying to Heroku
You should see the following output once it is running

1) Create a new Heroku app:
```
heroku create [APP_NAME]
```sh
Running your Battlesnake at http://0.0.0.0:8000
* Serving Flask app 'My Battlesnake'
* Debug mode: off
```

2) Deploy code to Heroku servers:
```
git push heroku master
```
Open [localhost:8000](http://localhost:8000) in your browser and you should see

3) Open Heroku app in browser:
```json
{"apiversion":"1","author":"","color":"#888888","head":"default","tail":"default"}
```
heroku open
```
or visit [http://APP_NAME.herokuapp.com](http://APP_NAME.herokuapp.com).

4) View server logs with the `heroku logs` command:
```
heroku logs --tail
## Play a Game Locally

Install the [Battlesnake CLI](https://github.com/BattlesnakeOfficial/rules/tree/main/cli)
* You can [download compiled binaries here](https://github.com/BattlesnakeOfficial/rules/releases)
* or [install as a go package](https://github.com/BattlesnakeOfficial/rules/tree/main/cli#installation) (requires Go 1.18 or higher)

Command to run a local game

```sh
battlesnake play -W 11 -H 11 --name 'Python Starter Project' --url http://localhost:8000 -g solo --browser
```

## Questions?
## Next Steps

Continue with the [Battlesnake Quickstart Guide](https://docs.battlesnake.com/quickstart) to customize and improve your Battlesnake's behavior.

Email [battlesnake@sendwithus.com](mailto:battlesnake@sendwithus.com), or tweet [@send_with_us](http://twitter.com/send_with_us).
**Note:** To play games on [play.battlesnake.com](https://play.battlesnake.com) you'll need to deploy your Battlesnake to a live web server OR use a port forwarding tool like [ngrok](https://ngrok.com/) to access your server locally.
7 changes: 0 additions & 7 deletions app.json

This file was deleted.

Empty file removed app/__init__.py
Empty file.
49 changes: 0 additions & 49 deletions app/main.py

This file was deleted.

3 changes: 0 additions & 3 deletions cloud9/run.sh

This file was deleted.

56 changes: 56 additions & 0 deletions main.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
# Welcome to
# __________ __ __ .__ __
# \______ \_____ _/ |__/ |_| | ____ ______ ____ _____ | | __ ____
# | | _/\__ \\ __\ __\ | _/ __ \ / ___// \\__ \ | |/ // __ \
# | | \ / __ \| | | | | |_\ ___/ \___ \| | \/ __ \| <\ ___/
# |________/(______/__| |__| |____/\_____>______>___|__(______/__|__\\_____>
#
# This file can be a nice home for your Battlesnake logic and helper functions.
#
# To get you started we've included code to prevent your Battlesnake from moving backwards.
# For more info see docs.battlesnake.com

import random
import typing
from move import Move

# info is called when you create your Battlesnake on play.battlesnake.com
# and controls your Battlesnake's appearance
# TIP: If you open your Battlesnake URL in a browser you should see this data
def info() -> typing.Dict:
print("INFO")

return {
"apiversion": "1",
"author": "", # TODO: Your Battlesnake Username
"color": "#888888", # TODO: Choose color
"head": "default", # TODO: Choose head
"tail": "default", # TODO: Choose tail
}


# start is called when your Battlesnake begins a game
def start(game_state: typing.Dict):
print("GAME START")


# end is called when your Battlesnake finishes a game
def end(game_state: typing.Dict):
print("GAME OVER\n")


# move is called on every turn and returns your next move
# Valid moves are "up", "down", "left", or "right"
# See https://docs.battlesnake.com/api/example-move for available data
def move(game_state: typing.Dict) -> typing.Dict:

bot = Move()

return bot.choose_move(game_state)


# Start server when `python main.py` is run
if __name__ == "__main__":
from server import run_server

run_server({"info": info, "start": start, "move": move, "end": end})
62 changes: 62 additions & 0 deletions move.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
import random

class Move():

def __init__(self):

self.is_move_safe = {"up": {"is_safe": True},
"down": {"is_safe": True},
"left": {"is_safe": True},
"right": {"is_safe": True}}

def not_backward(self, game_state):

# We've included code to prevent your Battlesnake from moving backwards
my_head = game_state["you"]["body"][0] # Coordinates of your head
my_neck = game_state["you"]["body"][1] # Coordinates of your "neck"

if my_neck["x"] < my_head["x"]: # Neck is left of head, don't move left
self.is_move_safe["left"]["is_safe"] = False

elif my_neck["x"] > my_head["x"]: # Neck is right of head, don't move right
self.is_move_safe["right"]["is_safe"] = False

elif my_neck["y"] < my_head["y"]: # Neck is below head, don't move down
self.is_move_safe["down"]["is_safe"] = False

elif my_neck["y"] > my_head["y"]: # Neck is above head, don't move up
self.is_move_safe["up"]["is_safe"] = False

def choose_move(self, game_state):

self.not_backward(game_state)

# Are there any safe moves left?
safe_moves = []
for move , data in self.is_move_safe.items():

if data["is_safe"] == True:

safe_moves.append(move)

if len(safe_moves) == 0:
print(f"MOVE {game_state['turn']}: No safe moves detected! Moving down")
return {"move": "down"}

# Choose a random move from the safe ones
next_move = random.choice(safe_moves)

return {"move": next_move}

# TODO: Step 1 - Prevent your Battlesnake from moving out of bounds
# board_width = game_state['board']['width']
# board_height = game_state['board']['height']

# TODO: Step 2 - Prevent your Battlesnake from colliding with itself
# my_body = game_state['you']['body']

# TODO: Step 3 - Prevent your Battlesnake from colliding with other Battlesnakes
# opponents = game_state['board']['snakes']

# TODO: Step 4 - Move towards food instead of random, to regain health and survive longer
# food = game_state['board']['food']
5 changes: 1 addition & 4 deletions requirements.txt
Original file line number Diff line number Diff line change
@@ -1,4 +1 @@
bottle==0.12.9
gevent==1.0.2
greenlet==0.4.9
gunicorn==19.4.5
Flask==2.3.2
1 change: 0 additions & 1 deletion runtime.txt

This file was deleted.

46 changes: 46 additions & 0 deletions server.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
import logging
import os
import typing

from flask import Flask
from flask import request


def run_server(handlers: typing.Dict):
app = Flask("Battlesnake")

@app.get("/")
def on_info():
return handlers["info"]()

@app.post("/start")
def on_start():
game_state = request.get_json()
handlers["start"](game_state)
return "ok"

@app.post("/move")
def on_move():
game_state = request.get_json()
return handlers["move"](game_state)

@app.post("/end")
def on_end():
game_state = request.get_json()
handlers["end"](game_state)
return "ok"

@app.after_request
def identify_server(response):
response.headers.set(
"server", "battlesnake/github/starter-snake-python"
)
return response

host = "0.0.0.0"
port = int(os.environ.get("PORT", "8000"))

logging.getLogger("werkzeug").setLevel(logging.ERROR)

print(f"\nRunning Battlesnake at http://{host}:{port}")
app.run(host=host, port=port)
Binary file removed static/head.png
Binary file not shown.
2 changes: 2 additions & 0 deletions tests/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@

#__init__.py
Loading