change to new code of battlesnake

This commit is contained in:
2024-04-01 01:41:06 +02:00
parent 11c1adf96c
commit a2f8f5b800
6 changed files with 134 additions and 136 deletions
+1
View File
@@ -3,3 +3,4 @@
.cmd
.idea
.vscode
.venv/
+11
View File
@@ -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" ]
+35 -73
View File
@@ -1,97 +1,59 @@
# Getting started with [Battlesnake](http://play.battlesnake.com?utm_source=github&utm_medium=readme&utm_campaign=python_starter&utm_content=homepage) and Python
# Battlesnake Python Starter Project
An official Battlesnake template written in Python. Get started at [play.battlesnake.com](https://play.battlesnake.com).
![Battlesnake Logo](https://media.battlesnake.com/social/StarterSnakeGitHubRepos_Python.png)
This is a basic implementation of the [Battlesnake API](https://docs.battlesnake.com/references/api) in Python. It's a great starting point for anyone wanting to program their first Battlesnake using Python, and comes ready to deploy with [Replit](https://repl.it) and [Heroku](https://heroku.com), or you can use any other cloud provider you'd like.
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.
[![Run on Replit](https://repl.it/badge/github/BattlesnakeOfficial/starter-snake-python)](https://replit.com/@Battlesnake/starter-snake-python)
## Technologies Used
* [Python3](https://www.python.org/)
* [Flask](https://flask.palletsprojects.com/)
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.
## Run Your Battlesnake
## Quickstart
Install dependencies using pip
The [Quick Start Coding Guide](https://docs.battlesnake.com/guides/getting-started) provides the full set of instructions to customize, register, and create your first games with your Battlesnake! While the guide uses [Repl.it](https://repl.it) as an example host, the instructions can be modified to work with any hosting provider. You can also find advice on other hosting providers on our [Hosting Suggestions](https://docs.battlesnake.com/references/hosting-suggestions) page.
### Prerequisites
* A free [Battlesnake Account](https://play.battlesnake.com/?utm_source=github&utm_medium=readme&utm_campaign=python_starter&utm_content=homepage)
---
## Customizing Your Battlesnake
Locate the `handle_info` function inside [server.py](server.py#L15). At the end of that function you should see a line that looks like this:
```python
return {
"apiversion": "1",
"author": "",
"color": "#888888",
"head": "default",
"tail": "default",
}
```sh
pip install -r requirements.txt
```
This function is called by the game engine periodically to make sure your Battlesnake is healthy, responding correctly, and to determine how your Battlesnake will appear on the game board. See [Battlesnake Personalization](https://docs.battlesnake.com/references/personalization) for how to customize your Battlesnake's appearance using these values.
Start your Battlesnake
Whenever you update these values, go to the page for your Battlesnake and select 'Refresh Metadata' from the option menu. This will update your Battlesnake to use your latest configuration and those changes should be reflected in the UI as well as any new games created.
## Changing Behavior
On every turn of each game your Battlesnake receives information about the game board and must decide its next move.
Locate the `handle_move` function inside [server.py](server.py#L48). Possible moves are "up", "down", "left", or "right". To start your Battlesnake will choose a move randomly. Your goal as a developer is to read information sent to you about the board (available in the `data` variable) and decide where your Battlesnake should move next. Your Battlesnakes move logic lives in [server_logic.py](server_logic.py#L37). This is the code you will want to edit.
See the [Battlesnake Game Rules](https://docs.battlesnake.com/references/rules) for more information on playing the game, moving around the board, and improving your algorithm.
## (Optional) Running Your Battlesnake Locally
Eventually you might want to run your Battlesnake server locally for faster testing and debugging. You can do this by installing [Python 3.8](https://www.python.org/downloads/) and running:
```shell
python server.py
```sh
python main.py
```
**Note:** You cannot create games on [play.battlesnake.com](https://play.battlesnake.com) using a locally running Battlesnake unless you install and use a port forwarding tool like [ngrok](https://ngrok.com/). See [Hosting Suggestions.](https://docs.battlesnake.com/references/hosting-suggestions#local)
You should see the following output once it is running
## Running Tests
```sh
Running your Battlesnake at http://0.0.0.0:8000
* Serving Flask app 'My Battlesnake'
* Debug mode: off
```
This Starter Project comes with a very simple test suite for you to expand! Located in `tests.py` you can run them using the following command:
```python tests.py -v```
Open [localhost:8000](http://localhost:8000) in your browser and you should see
---
```json
{"apiversion":"1","author":"","color":"#888888","head":"default","tail":"default"}
```
## Playing Battlesnake
## Play a Game Locally
### Completing Challenges
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)
If you're looking for the Single Player Mode of Battlesnake, or something to practice with between events, check out [Challenges.](https://docs.battlesnake.com/guides/quick-start-challenges-guide)
Command to run a local game
### Joining a Battlesnake Arena
```sh
battlesnake play -W 11 -H 11 --name 'Python Starter Project' --url http://localhost:8000 -g solo --browser
```
Once you've made your Battlesnake behave and survive on its own, you can enter it into the [Global Battlesnake Arena](https://play.battlesnake.com/arena/global) to see how it performs against other Battlesnakes worldwide.
## Next Steps
Arenas will regularly create new games and rank Battlesnakes based on their results. They're a good way to get regular feedback on how well your Battlesnake is performing, and a fun way to track your progress as you develop your algorithm.
Continue with the [Battlesnake Quickstart Guide](https://docs.battlesnake.com/quickstart) to customize and improve your Battlesnake's behavior.
### Joining a Battlesnake League
Want to get out there to compete and win prizes? Check out the [Quick Start League Guide](https://docs.battlesnake.com/guides/quick-start-league-guide) for information on the how and when of our competitive seasons.
---
## Resources
All documentation is available at [docs.battlesnake.com](https://docs.battlesnake.com), including detailed Guides, API References, and Tips.
You can also join the Battlesnake Developer Community on [Discord](https://play.battlesnake.com/discord?utm_source=github&utm_medium=readme&utm_campaign=python_starter&utm_content=discord). We have a growing community of Battlesnake developers of all skill levels wanting to help everyone succeed and have fun with Battlesnake :)
Check out live Battlesnake events on [Twitch](https://www.twitch.tv/battlesnakeofficial) and see what is happening when on the [Calendar.](https://play.battlesnake.com/calendar?utm_source=github&utm_medium=readme&utm_campaign=python_starter&utm_content=calendar)
Want to contribute to Battlesnake? We have a number of open-source codebases and would love for you to get involved! Check out our page on [Contributing.](https://docs.battlesnake.com/guides/contributing)
## Feedback
**Do you have an issue or suggestions for this repository?** Head over to our [Feedback Repository](https://play.battlesnake.com/feedback?utm_source=github&utm_medium=readme&utm_campaign=python_starter&utm_content=feedback) today and let us know!
**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.
+48
View File
@@ -0,0 +1,48 @@
# 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 typing
import server_logic
# 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": "daniel156161", # TODO: Your Battlesnake Username
"color": "#00ff00", # 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")
def move(game_state: typing.Dict) -> typing.Dict:
next_move = server_logic.choose_move(game_state)
print(f"MOVE {game_state['turn']}: {next_move}")
return {"move": next_move}
# 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})
+9 -1
View File
@@ -1 +1,9 @@
Flask==2.0.1
blinker==1.7.0
click==8.1.7
Flask==3.0.2
itsdangerous==2.1.2
Jinja2==3.1.3
MarkupSafe==2.1.5
numpy==1.26.4
scipy==1.12.0
Werkzeug==3.0.1
+29 -61
View File
@@ -1,77 +1,45 @@
import logging
import os
import typing
from flask import Flask
from flask import request
import server_logic
def run_server(handlers: typing.Dict):
app = Flask("Battlesnake")
@app.get("/")
def on_info():
return handlers["info"]()
app = Flask(__name__)
@app.get("/")
def handle_info():
"""
This function is called when you register your Battlesnake on play.battlesnake.com
See https://docs.battlesnake.com/guides/getting-started#step-4-register-your-battlesnake
It controls your Battlesnake appearance and author permissions.
For customization options, see https://docs.battlesnake.com/references/personalization
TIP: If you open your Battlesnake URL in browser you should see this data.
"""
print("INFO")
return {
"apiversion": "1",
"author": "daniel156161", # TODO: Your Battlesnake Username
"color": "#00ff00", # TODO: Personalize
"head": "default", # TODO: Personalize
"tail": "default", # TODO: Personalize
}
@app.post("/start")
def handle_start():
"""
This function is called everytime your snake is entered into a game.
request.json contains information about the game that's about to be played.
"""
data = request.get_json()
print(f"{data['game']['id']} START")
@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("/move")
def handle_move():
"""
This function is called on every turn of a game. It's how your snake decides where to move.
Valid moves are "up", "down", "left", or "right".
"""
data = request.get_json()
# TODO - look at the server_logic.py file to see how we decide what move to return!
move = server_logic.choose_move(data)
return {"move": move}
@app.post("/end")
def end():
"""
This function is called when a game your snake was in ends.
It's purely for informational purposes, you don't have to make any decisions here.
"""
data = request.get_json()
print(f"{data['game']['id']} END")
@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"))
if __name__ == "__main__":
logging.getLogger("werkzeug").setLevel(logging.ERROR)
print("Starting Battlesnake Server...")
port = int(os.environ.get("PORT", "8080"))
app.run(host="0.0.0.0", port=port, debug=True)
print(f"\nRunning Battlesnake at http://{host}:{port}")
app.run(host=host, port=port)