Compare commits
128 Commits
v1.0
...
c6ebb5834b
| Author | SHA1 | Date | |
|---|---|---|---|
|
c6ebb5834b
|
|||
|
dbcf9cadaf
|
|||
|
316870ef7a
|
|||
|
b0d484dbab
|
|||
|
9e826afa5f
|
|||
|
d3b0488e0f
|
|||
|
4e9a5595bc
|
|||
|
8f938ce3fe
|
|||
|
dfcdbae85b
|
|||
|
fb579e5fbc
|
|||
|
8f6bc3cfdd
|
|||
|
f124ce6f96
|
|||
|
6ab0161b49
|
|||
|
d7bd89eae9
|
|||
|
eace1872d7
|
|||
|
0a3db6ba57
|
|||
|
013ac98821
|
|||
|
a3fe386198
|
|||
|
8a431da014
|
|||
|
19e4aee454
|
|||
|
c8dd01490c
|
|||
|
1e57ad1af6
|
|||
|
4ca905fbf0
|
|||
|
8e733dfe39
|
|||
|
49f2e0b008
|
|||
|
37de34cc5e
|
|||
|
3d7f92e20f
|
|||
|
2d7a2505d4
|
|||
|
a82eaaaec5
|
|||
|
51de53d01c
|
|||
|
2e1f91355b
|
|||
|
6b69d133b6
|
|||
|
7d52d7dca8
|
|||
|
a885b624f9
|
|||
|
9e3a62d8e8
|
|||
|
9093ca0512
|
|||
|
6e74b5fb57
|
|||
|
962d8b1043
|
|||
|
8ea9cbdcee
|
|||
|
c458219125
|
|||
|
a7a463ed91
|
|||
|
5c1ef7f05f
|
|||
|
d32568cdf2
|
|||
|
61721a7eb6
|
|||
|
bcc9c71c30
|
|||
|
58bbbf3cbd
|
|||
|
4d515f0784
|
|||
|
8424c324e8
|
|||
|
c5c2652f3a
|
|||
|
0768e7f254
|
|||
|
31d2e7ea55
|
|||
|
4b51ddc84d
|
|||
|
31f5225100
|
|||
|
deb95c6246
|
|||
|
600cde4a3e
|
|||
|
e068fb8614
|
|||
|
80b7c4df89
|
|||
|
da0347731c
|
|||
|
a09c05b6ec
|
|||
|
aba457423e
|
|||
|
bb92715de1
|
|||
|
cf45aa60aa
|
|||
|
a58e9695dd
|
|||
|
b57ae5eab2
|
|||
|
817b970623
|
|||
|
c9e6947758
|
|||
|
4a1fbf2752
|
|||
|
5b8bf0da31
|
|||
|
4a8cb40bde
|
|||
|
c5342c1f4d
|
|||
|
ac7c397093
|
|||
|
7dd46dd72b
|
|||
|
10c7f2656c
|
|||
|
f00efe607f
|
|||
|
c333706b75
|
|||
|
917bd3f6bd
|
|||
|
83bcf4f194
|
|||
|
ef4dca447f
|
|||
|
db3a353090
|
|||
|
1f4d17d42f
|
|||
|
f98430462b
|
|||
|
c26824aeaf
|
|||
|
87690177a5
|
|||
|
8a2a62ef57
|
|||
|
5796ce0a6e
|
|||
|
5522a52227
|
|||
|
5743f5c111
|
|||
|
9950fa1952
|
|||
|
4620ee31eb
|
|||
|
9103e3e139
|
|||
|
04eef9229c
|
|||
|
7cb1fdc57d
|
|||
|
cceded8468
|
|||
|
8c57e48f60
|
|||
|
5ce12d70c1
|
|||
|
950351b407
|
|||
|
12ac257d19
|
|||
|
d4b54d48b9
|
|||
|
034b0e361a
|
|||
|
a57536b7cb
|
|||
|
a606ae6f94
|
|||
|
b364c6454e
|
|||
|
b9a0bca4c6
|
|||
|
ea36d60b4d
|
|||
|
0fe4e6ac83
|
|||
|
93b2c8ba99
|
|||
|
f6db5cb96a
|
|||
|
e3d7cccb64
|
|||
|
0eecbb774b
|
|||
|
9e0a919233
|
|||
|
6d9df32076
|
|||
|
863ca1b277
|
|||
|
16cab3a9ca
|
|||
|
281b52e71d
|
|||
|
38ba576de9
|
|||
|
7457e66339
|
|||
|
b601b378c8
|
|||
|
24e744f705
|
|||
|
39b16a1702
|
|||
|
87fe6550b2
|
|||
|
c854b5fec9
|
|||
|
51108ce21c
|
|||
|
2f8e35aced
|
|||
|
9869f14bbe
|
|||
|
1154127a40
|
|||
|
ae1489240d
|
|||
|
0af6d862d4
|
|||
|
f472ddd0d9
|
@@ -0,0 +1,40 @@
|
|||||||
|
name: Build and Push Docker Container
|
||||||
|
on:
|
||||||
|
push:
|
||||||
|
branches:
|
||||||
|
- main
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
build-and-push:
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
|
||||||
|
steps:
|
||||||
|
- name: Checkout repository
|
||||||
|
uses: actions/checkout@v6
|
||||||
|
with:
|
||||||
|
token: '${{ secrets.ACTION_ACCESS_TOKEN }}'
|
||||||
|
submodules: recursive
|
||||||
|
|
||||||
|
- name: Set up Docker Buildx
|
||||||
|
uses: docker/setup-buildx-action@v4
|
||||||
|
|
||||||
|
- name: Login to Docker Hub
|
||||||
|
uses: docker/login-action@v4
|
||||||
|
with:
|
||||||
|
registry: ${{ vars.DOCKER_REGISTRY_URL }}
|
||||||
|
username: ${{ secrets.DOCKER_REGISTRY_USERNAME }}
|
||||||
|
password: ${{ secrets.ACTION_ACCESS_TOKEN }}
|
||||||
|
|
||||||
|
- name: Build and push Docker image for latest tag
|
||||||
|
uses: docker/build-push-action@v7
|
||||||
|
with:
|
||||||
|
context: .
|
||||||
|
push: true
|
||||||
|
tags: ${{ vars.DOCKER_REGISTRY_URL }}/daniel156161/battlesnake:latest
|
||||||
|
platforms: linux/amd64
|
||||||
|
|
||||||
|
- name: Invoke Portainer Stack Deployment
|
||||||
|
if: ${{ vars.PORTAINER_STACK_WEBHOOK_URL && vars.PORTAINER_STACK_WEBHOOK_URL != '' }}
|
||||||
|
uses: distributhor/workflow-webhook@v3
|
||||||
|
with:
|
||||||
|
webhook_url: ${{ vars.PORTAINER_STACK_WEBHOOK_URL }}
|
||||||
@@ -7,3 +7,10 @@
|
|||||||
__pycache__/
|
__pycache__/
|
||||||
data/
|
data/
|
||||||
.env
|
.env
|
||||||
|
.tools/
|
||||||
|
|
||||||
|
dbschema/migrations/
|
||||||
|
|
||||||
|
*.jsonl
|
||||||
|
dataset/
|
||||||
|
models/
|
||||||
|
|||||||
@@ -0,0 +1,6 @@
|
|||||||
|
[submodule "quart_common"]
|
||||||
|
path = quart_common
|
||||||
|
url = git@git.yiprawr.dev:submodules/python-quart-common.git
|
||||||
|
[submodule "local-client"]
|
||||||
|
path = local-client
|
||||||
|
url = https://github.com/BattlesnakeOfficial/rules.git
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
3.13
|
||||||
+6
-4
@@ -1,11 +1,13 @@
|
|||||||
FROM python:3.10.6-slim
|
FROM ghcr.io/astral-sh/uv:python3.13-trixie-slim
|
||||||
|
|
||||||
# Install app
|
# Install app
|
||||||
COPY . /app
|
COPY . /app
|
||||||
WORKDIR /app
|
WORKDIR /app
|
||||||
|
|
||||||
# Install dependencies
|
# Install dependencies
|
||||||
RUN pip install --upgrade pip && pip install -r requirements.txt
|
RUN uv sync --no-config --frozen --compile-bytecode
|
||||||
|
|
||||||
# Run Battlesnake
|
# Starten Sie Ihre Anwendung
|
||||||
CMD [ "python", "main.py" ]
|
EXPOSE 8000
|
||||||
|
|
||||||
|
CMD [".venv/bin/hypercorn", "asgi:app", "--bind", "0.0.0.0:8000", "--workers", "1", "--websocket-ping-interval", "20", "--access-logfile", "-"]
|
||||||
|
|||||||
@@ -54,4 +54,112 @@ battlesnake play -W 11 -H 11 --name 'Python Starter Project' --url http://localh
|
|||||||
|
|
||||||
Continue with the [Battlesnake Quickstart Guide](https://docs.battlesnake.com/quickstart) to customize and improve your Battlesnake's behavior.
|
Continue with the [Battlesnake Quickstart Guide](https://docs.battlesnake.com/quickstart) to customize and improve your Battlesnake's behavior.
|
||||||
|
|
||||||
|
## Included Competitive Snake
|
||||||
|
This repo now includes `snakes/BestBattleSnake.py`, a stronger default snake that combines:
|
||||||
|
- collision and head-to-head risk checks
|
||||||
|
- flood-fill space evaluation to avoid traps
|
||||||
|
- food routing that gets more aggressive as health drops
|
||||||
|
- tail access checks for better long-term survival
|
||||||
|
|
||||||
|
Run it explicitly with:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
SNAKE=BestBattleSnake python main.py
|
||||||
|
```
|
||||||
|
|
||||||
|
Optional duel tuning (when only 2 snakes are alive):
|
||||||
|
|
||||||
|
```sh
|
||||||
|
BATTLE_SNAKE_DUEL_STYLE=balanced python main.py
|
||||||
|
```
|
||||||
|
|
||||||
|
Allowed values: `safe`, `balanced`, `aggressive`.
|
||||||
|
|
||||||
|
## Export Training Dataset
|
||||||
|
Game saves now include a `dataset` section with labeled move samples.
|
||||||
|
|
||||||
|
Export all stored samples to JSONL:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
python -m server.DatasetExporter --input data --output data/dataset/good_moves.jsonl
|
||||||
|
```
|
||||||
|
|
||||||
|
Or with `just`:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
just export-dataset
|
||||||
|
```
|
||||||
|
|
||||||
|
Curate a high-quality training subset (single file):
|
||||||
|
|
||||||
|
```sh
|
||||||
|
python -m server.DatasetCurator --input good_moves-2026-04-03.jsonl --output data/dataset/best_moves.jsonl
|
||||||
|
```
|
||||||
|
|
||||||
|
Curate from multiple JSONL sources (repeat `--input`):
|
||||||
|
|
||||||
|
```sh
|
||||||
|
python -m server.DatasetCurator \
|
||||||
|
--input good_moves-2026-04-03.jsonl \
|
||||||
|
--input good_moves-2026-04-04.jsonl \
|
||||||
|
--output data/dataset/best_moves.jsonl
|
||||||
|
```
|
||||||
|
|
||||||
|
Curate from folder or glob:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
python -m server.DatasetCurator --input data/dataset --output data/dataset/best_moves.jsonl
|
||||||
|
python -m server.DatasetCurator --input "good_moves-*.jsonl" --output data/dataset/best_moves.jsonl
|
||||||
|
```
|
||||||
|
|
||||||
|
Append mode (keeps existing curated rows and deduplicates against them):
|
||||||
|
|
||||||
|
```sh
|
||||||
|
python -m server.DatasetCurator --input "good_moves-*.jsonl" --output data/dataset/best_moves.jsonl --append
|
||||||
|
```
|
||||||
|
|
||||||
|
Archive processed input files after curation:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
python -m server.DatasetCurator --input "good_moves-*.jsonl" --output data/dataset/best_moves.jsonl --append --archive-input
|
||||||
|
python -m server.DatasetCurator --input "good_moves-*.jsonl" --output data/dataset/best_moves.jsonl --append --archive-input --archive-dir data/dataset/archive
|
||||||
|
```
|
||||||
|
|
||||||
|
Or with `just`:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
just curate-dataset
|
||||||
|
just curate-dataset append=true
|
||||||
|
just curate-dataset append=true archive=true archive_dir=data/dataset/archive
|
||||||
|
```
|
||||||
|
|
||||||
|
Analyze dataset quality overall and by day (best game overall/day included):
|
||||||
|
|
||||||
|
```sh
|
||||||
|
python -m server.DatasetStats --input "good_moves-*.jsonl"
|
||||||
|
python -m server.DatasetStats --input data/dataset --output data/dataset/stats-report.json
|
||||||
|
```
|
||||||
|
|
||||||
|
The stats report now includes both:
|
||||||
|
- `best_game` (survival/length focused)
|
||||||
|
- `best_pressure_game` (high-pressure quality focused: fewer safe options + strong survival)
|
||||||
|
|
||||||
|
Or with `just`:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
just analyze-dataset
|
||||||
|
just analyze-dataset input=data/dataset output=data/dataset/stats-report.json
|
||||||
|
```
|
||||||
|
|
||||||
|
To store compact dataset-only records (JSONL) and skip full per-game JSON files:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
STORE_DATASET_ONLY=true DATASET_JSONL_PATH=data/dataset/good_moves.jsonl python main.py
|
||||||
|
```
|
||||||
|
|
||||||
|
Optional compact storage tuning:
|
||||||
|
- `DATASET_ROTATE_DAILY=true` creates one JSONL file per day (default: `true`)
|
||||||
|
- `DATASET_JSONL_MAX_MB=50` rotates when file reaches max size in MB (default: `50`)
|
||||||
|
- `DATASET_COMPRESS_ROTATED=true` gzip-compresses rotated/old JSONL files (default: `true`)
|
||||||
|
|
||||||
**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.
|
**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.
|
||||||
|
|||||||
@@ -0,0 +1,5 @@
|
|||||||
|
from server.bootstrap import build_server_from_env
|
||||||
|
|
||||||
|
server = build_server_from_env(default_snake_type="TemplateSnake")
|
||||||
|
|
||||||
|
app = server.app
|
||||||
@@ -1,661 +0,0 @@
|
|||||||
GNU AFFERO GENERAL PUBLIC LICENSE
|
|
||||||
Version 3, 19 November 2007
|
|
||||||
|
|
||||||
Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
|
|
||||||
Everyone is permitted to copy and distribute verbatim copies
|
|
||||||
of this license document, but changing it is not allowed.
|
|
||||||
|
|
||||||
Preamble
|
|
||||||
|
|
||||||
The GNU Affero General Public License is a free, copyleft license for
|
|
||||||
software and other kinds of works, specifically designed to ensure
|
|
||||||
cooperation with the community in the case of network server software.
|
|
||||||
|
|
||||||
The licenses for most software and other practical works are designed
|
|
||||||
to take away your freedom to share and change the works. By contrast,
|
|
||||||
our General Public Licenses are intended to guarantee your freedom to
|
|
||||||
share and change all versions of a program--to make sure it remains free
|
|
||||||
software for all its users.
|
|
||||||
|
|
||||||
When we speak of free software, we are referring to freedom, not
|
|
||||||
price. Our General Public Licenses are designed to make sure that you
|
|
||||||
have the freedom to distribute copies of free software (and charge for
|
|
||||||
them if you wish), that you receive source code or can get it if you
|
|
||||||
want it, that you can change the software or use pieces of it in new
|
|
||||||
free programs, and that you know you can do these things.
|
|
||||||
|
|
||||||
Developers that use our General Public Licenses protect your rights
|
|
||||||
with two steps: (1) assert copyright on the software, and (2) offer
|
|
||||||
you this License which gives you legal permission to copy, distribute
|
|
||||||
and/or modify the software.
|
|
||||||
|
|
||||||
A secondary benefit of defending all users' freedom is that
|
|
||||||
improvements made in alternate versions of the program, if they
|
|
||||||
receive widespread use, become available for other developers to
|
|
||||||
incorporate. Many developers of free software are heartened and
|
|
||||||
encouraged by the resulting cooperation. However, in the case of
|
|
||||||
software used on network servers, this result may fail to come about.
|
|
||||||
The GNU General Public License permits making a modified version and
|
|
||||||
letting the public access it on a server without ever releasing its
|
|
||||||
source code to the public.
|
|
||||||
|
|
||||||
The GNU Affero General Public License is designed specifically to
|
|
||||||
ensure that, in such cases, the modified source code becomes available
|
|
||||||
to the community. It requires the operator of a network server to
|
|
||||||
provide the source code of the modified version running there to the
|
|
||||||
users of that server. Therefore, public use of a modified version, on
|
|
||||||
a publicly accessible server, gives the public access to the source
|
|
||||||
code of the modified version.
|
|
||||||
|
|
||||||
An older license, called the Affero General Public License and
|
|
||||||
published by Affero, was designed to accomplish similar goals. This is
|
|
||||||
a different license, not a version of the Affero GPL, but Affero has
|
|
||||||
released a new version of the Affero GPL which permits relicensing under
|
|
||||||
this license.
|
|
||||||
|
|
||||||
The precise terms and conditions for copying, distribution and
|
|
||||||
modification follow.
|
|
||||||
|
|
||||||
TERMS AND CONDITIONS
|
|
||||||
|
|
||||||
0. Definitions.
|
|
||||||
|
|
||||||
"This License" refers to version 3 of the GNU Affero General Public License.
|
|
||||||
|
|
||||||
"Copyright" also means copyright-like laws that apply to other kinds of
|
|
||||||
works, such as semiconductor masks.
|
|
||||||
|
|
||||||
"The Program" refers to any copyrightable work licensed under this
|
|
||||||
License. Each licensee is addressed as "you". "Licensees" and
|
|
||||||
"recipients" may be individuals or organizations.
|
|
||||||
|
|
||||||
To "modify" a work means to copy from or adapt all or part of the work
|
|
||||||
in a fashion requiring copyright permission, other than the making of an
|
|
||||||
exact copy. The resulting work is called a "modified version" of the
|
|
||||||
earlier work or a work "based on" the earlier work.
|
|
||||||
|
|
||||||
A "covered work" means either the unmodified Program or a work based
|
|
||||||
on the Program.
|
|
||||||
|
|
||||||
To "propagate" a work means to do anything with it that, without
|
|
||||||
permission, would make you directly or secondarily liable for
|
|
||||||
infringement under applicable copyright law, except executing it on a
|
|
||||||
computer or modifying a private copy. Propagation includes copying,
|
|
||||||
distribution (with or without modification), making available to the
|
|
||||||
public, and in some countries other activities as well.
|
|
||||||
|
|
||||||
To "convey" a work means any kind of propagation that enables other
|
|
||||||
parties to make or receive copies. Mere interaction with a user through
|
|
||||||
a computer network, with no transfer of a copy, is not conveying.
|
|
||||||
|
|
||||||
An interactive user interface displays "Appropriate Legal Notices"
|
|
||||||
to the extent that it includes a convenient and prominently visible
|
|
||||||
feature that (1) displays an appropriate copyright notice, and (2)
|
|
||||||
tells the user that there is no warranty for the work (except to the
|
|
||||||
extent that warranties are provided), that licensees may convey the
|
|
||||||
work under this License, and how to view a copy of this License. If
|
|
||||||
the interface presents a list of user commands or options, such as a
|
|
||||||
menu, a prominent item in the list meets this criterion.
|
|
||||||
|
|
||||||
1. Source Code.
|
|
||||||
|
|
||||||
The "source code" for a work means the preferred form of the work
|
|
||||||
for making modifications to it. "Object code" means any non-source
|
|
||||||
form of a work.
|
|
||||||
|
|
||||||
A "Standard Interface" means an interface that either is an official
|
|
||||||
standard defined by a recognized standards body, or, in the case of
|
|
||||||
interfaces specified for a particular programming language, one that
|
|
||||||
is widely used among developers working in that language.
|
|
||||||
|
|
||||||
The "System Libraries" of an executable work include anything, other
|
|
||||||
than the work as a whole, that (a) is included in the normal form of
|
|
||||||
packaging a Major Component, but which is not part of that Major
|
|
||||||
Component, and (b) serves only to enable use of the work with that
|
|
||||||
Major Component, or to implement a Standard Interface for which an
|
|
||||||
implementation is available to the public in source code form. A
|
|
||||||
"Major Component", in this context, means a major essential component
|
|
||||||
(kernel, window system, and so on) of the specific operating system
|
|
||||||
(if any) on which the executable work runs, or a compiler used to
|
|
||||||
produce the work, or an object code interpreter used to run it.
|
|
||||||
|
|
||||||
The "Corresponding Source" for a work in object code form means all
|
|
||||||
the source code needed to generate, install, and (for an executable
|
|
||||||
work) run the object code and to modify the work, including scripts to
|
|
||||||
control those activities. However, it does not include the work's
|
|
||||||
System Libraries, or general-purpose tools or generally available free
|
|
||||||
programs which are used unmodified in performing those activities but
|
|
||||||
which are not part of the work. For example, Corresponding Source
|
|
||||||
includes interface definition files associated with source files for
|
|
||||||
the work, and the source code for shared libraries and dynamically
|
|
||||||
linked subprograms that the work is specifically designed to require,
|
|
||||||
such as by intimate data communication or control flow between those
|
|
||||||
subprograms and other parts of the work.
|
|
||||||
|
|
||||||
The Corresponding Source need not include anything that users
|
|
||||||
can regenerate automatically from other parts of the Corresponding
|
|
||||||
Source.
|
|
||||||
|
|
||||||
The Corresponding Source for a work in source code form is that
|
|
||||||
same work.
|
|
||||||
|
|
||||||
2. Basic Permissions.
|
|
||||||
|
|
||||||
All rights granted under this License are granted for the term of
|
|
||||||
copyright on the Program, and are irrevocable provided the stated
|
|
||||||
conditions are met. This License explicitly affirms your unlimited
|
|
||||||
permission to run the unmodified Program. The output from running a
|
|
||||||
covered work is covered by this License only if the output, given its
|
|
||||||
content, constitutes a covered work. This License acknowledges your
|
|
||||||
rights of fair use or other equivalent, as provided by copyright law.
|
|
||||||
|
|
||||||
You may make, run and propagate covered works that you do not
|
|
||||||
convey, without conditions so long as your license otherwise remains
|
|
||||||
in force. You may convey covered works to others for the sole purpose
|
|
||||||
of having them make modifications exclusively for you, or provide you
|
|
||||||
with facilities for running those works, provided that you comply with
|
|
||||||
the terms of this License in conveying all material for which you do
|
|
||||||
not control copyright. Those thus making or running the covered works
|
|
||||||
for you must do so exclusively on your behalf, under your direction
|
|
||||||
and control, on terms that prohibit them from making any copies of
|
|
||||||
your copyrighted material outside their relationship with you.
|
|
||||||
|
|
||||||
Conveying under any other circumstances is permitted solely under
|
|
||||||
the conditions stated below. Sublicensing is not allowed; section 10
|
|
||||||
makes it unnecessary.
|
|
||||||
|
|
||||||
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
|
|
||||||
|
|
||||||
No covered work shall be deemed part of an effective technological
|
|
||||||
measure under any applicable law fulfilling obligations under article
|
|
||||||
11 of the WIPO copyright treaty adopted on 20 December 1996, or
|
|
||||||
similar laws prohibiting or restricting circumvention of such
|
|
||||||
measures.
|
|
||||||
|
|
||||||
When you convey a covered work, you waive any legal power to forbid
|
|
||||||
circumvention of technological measures to the extent such circumvention
|
|
||||||
is effected by exercising rights under this License with respect to
|
|
||||||
the covered work, and you disclaim any intention to limit operation or
|
|
||||||
modification of the work as a means of enforcing, against the work's
|
|
||||||
users, your or third parties' legal rights to forbid circumvention of
|
|
||||||
technological measures.
|
|
||||||
|
|
||||||
4. Conveying Verbatim Copies.
|
|
||||||
|
|
||||||
You may convey verbatim copies of the Program's source code as you
|
|
||||||
receive it, in any medium, provided that you conspicuously and
|
|
||||||
appropriately publish on each copy an appropriate copyright notice;
|
|
||||||
keep intact all notices stating that this License and any
|
|
||||||
non-permissive terms added in accord with section 7 apply to the code;
|
|
||||||
keep intact all notices of the absence of any warranty; and give all
|
|
||||||
recipients a copy of this License along with the Program.
|
|
||||||
|
|
||||||
You may charge any price or no price for each copy that you convey,
|
|
||||||
and you may offer support or warranty protection for a fee.
|
|
||||||
|
|
||||||
5. Conveying Modified Source Versions.
|
|
||||||
|
|
||||||
You may convey a work based on the Program, or the modifications to
|
|
||||||
produce it from the Program, in the form of source code under the
|
|
||||||
terms of section 4, provided that you also meet all of these conditions:
|
|
||||||
|
|
||||||
a) The work must carry prominent notices stating that you modified
|
|
||||||
it, and giving a relevant date.
|
|
||||||
|
|
||||||
b) The work must carry prominent notices stating that it is
|
|
||||||
released under this License and any conditions added under section
|
|
||||||
7. This requirement modifies the requirement in section 4 to
|
|
||||||
"keep intact all notices".
|
|
||||||
|
|
||||||
c) You must license the entire work, as a whole, under this
|
|
||||||
License to anyone who comes into possession of a copy. This
|
|
||||||
License will therefore apply, along with any applicable section 7
|
|
||||||
additional terms, to the whole of the work, and all its parts,
|
|
||||||
regardless of how they are packaged. This License gives no
|
|
||||||
permission to license the work in any other way, but it does not
|
|
||||||
invalidate such permission if you have separately received it.
|
|
||||||
|
|
||||||
d) If the work has interactive user interfaces, each must display
|
|
||||||
Appropriate Legal Notices; however, if the Program has interactive
|
|
||||||
interfaces that do not display Appropriate Legal Notices, your
|
|
||||||
work need not make them do so.
|
|
||||||
|
|
||||||
A compilation of a covered work with other separate and independent
|
|
||||||
works, which are not by their nature extensions of the covered work,
|
|
||||||
and which are not combined with it such as to form a larger program,
|
|
||||||
in or on a volume of a storage or distribution medium, is called an
|
|
||||||
"aggregate" if the compilation and its resulting copyright are not
|
|
||||||
used to limit the access or legal rights of the compilation's users
|
|
||||||
beyond what the individual works permit. Inclusion of a covered work
|
|
||||||
in an aggregate does not cause this License to apply to the other
|
|
||||||
parts of the aggregate.
|
|
||||||
|
|
||||||
6. Conveying Non-Source Forms.
|
|
||||||
|
|
||||||
You may convey a covered work in object code form under the terms
|
|
||||||
of sections 4 and 5, provided that you also convey the
|
|
||||||
machine-readable Corresponding Source under the terms of this License,
|
|
||||||
in one of these ways:
|
|
||||||
|
|
||||||
a) Convey the object code in, or embodied in, a physical product
|
|
||||||
(including a physical distribution medium), accompanied by the
|
|
||||||
Corresponding Source fixed on a durable physical medium
|
|
||||||
customarily used for software interchange.
|
|
||||||
|
|
||||||
b) Convey the object code in, or embodied in, a physical product
|
|
||||||
(including a physical distribution medium), accompanied by a
|
|
||||||
written offer, valid for at least three years and valid for as
|
|
||||||
long as you offer spare parts or customer support for that product
|
|
||||||
model, to give anyone who possesses the object code either (1) a
|
|
||||||
copy of the Corresponding Source for all the software in the
|
|
||||||
product that is covered by this License, on a durable physical
|
|
||||||
medium customarily used for software interchange, for a price no
|
|
||||||
more than your reasonable cost of physically performing this
|
|
||||||
conveying of source, or (2) access to copy the
|
|
||||||
Corresponding Source from a network server at no charge.
|
|
||||||
|
|
||||||
c) Convey individual copies of the object code with a copy of the
|
|
||||||
written offer to provide the Corresponding Source. This
|
|
||||||
alternative is allowed only occasionally and noncommercially, and
|
|
||||||
only if you received the object code with such an offer, in accord
|
|
||||||
with subsection 6b.
|
|
||||||
|
|
||||||
d) Convey the object code by offering access from a designated
|
|
||||||
place (gratis or for a charge), and offer equivalent access to the
|
|
||||||
Corresponding Source in the same way through the same place at no
|
|
||||||
further charge. You need not require recipients to copy the
|
|
||||||
Corresponding Source along with the object code. If the place to
|
|
||||||
copy the object code is a network server, the Corresponding Source
|
|
||||||
may be on a different server (operated by you or a third party)
|
|
||||||
that supports equivalent copying facilities, provided you maintain
|
|
||||||
clear directions next to the object code saying where to find the
|
|
||||||
Corresponding Source. Regardless of what server hosts the
|
|
||||||
Corresponding Source, you remain obligated to ensure that it is
|
|
||||||
available for as long as needed to satisfy these requirements.
|
|
||||||
|
|
||||||
e) Convey the object code using peer-to-peer transmission, provided
|
|
||||||
you inform other peers where the object code and Corresponding
|
|
||||||
Source of the work are being offered to the general public at no
|
|
||||||
charge under subsection 6d.
|
|
||||||
|
|
||||||
A separable portion of the object code, whose source code is excluded
|
|
||||||
from the Corresponding Source as a System Library, need not be
|
|
||||||
included in conveying the object code work.
|
|
||||||
|
|
||||||
A "User Product" is either (1) a "consumer product", which means any
|
|
||||||
tangible personal property which is normally used for personal, family,
|
|
||||||
or household purposes, or (2) anything designed or sold for incorporation
|
|
||||||
into a dwelling. In determining whether a product is a consumer product,
|
|
||||||
doubtful cases shall be resolved in favor of coverage. For a particular
|
|
||||||
product received by a particular user, "normally used" refers to a
|
|
||||||
typical or common use of that class of product, regardless of the status
|
|
||||||
of the particular user or of the way in which the particular user
|
|
||||||
actually uses, or expects or is expected to use, the product. A product
|
|
||||||
is a consumer product regardless of whether the product has substantial
|
|
||||||
commercial, industrial or non-consumer uses, unless such uses represent
|
|
||||||
the only significant mode of use of the product.
|
|
||||||
|
|
||||||
"Installation Information" for a User Product means any methods,
|
|
||||||
procedures, authorization keys, or other information required to install
|
|
||||||
and execute modified versions of a covered work in that User Product from
|
|
||||||
a modified version of its Corresponding Source. The information must
|
|
||||||
suffice to ensure that the continued functioning of the modified object
|
|
||||||
code is in no case prevented or interfered with solely because
|
|
||||||
modification has been made.
|
|
||||||
|
|
||||||
If you convey an object code work under this section in, or with, or
|
|
||||||
specifically for use in, a User Product, and the conveying occurs as
|
|
||||||
part of a transaction in which the right of possession and use of the
|
|
||||||
User Product is transferred to the recipient in perpetuity or for a
|
|
||||||
fixed term (regardless of how the transaction is characterized), the
|
|
||||||
Corresponding Source conveyed under this section must be accompanied
|
|
||||||
by the Installation Information. But this requirement does not apply
|
|
||||||
if neither you nor any third party retains the ability to install
|
|
||||||
modified object code on the User Product (for example, the work has
|
|
||||||
been installed in ROM).
|
|
||||||
|
|
||||||
The requirement to provide Installation Information does not include a
|
|
||||||
requirement to continue to provide support service, warranty, or updates
|
|
||||||
for a work that has been modified or installed by the recipient, or for
|
|
||||||
the User Product in which it has been modified or installed. Access to a
|
|
||||||
network may be denied when the modification itself materially and
|
|
||||||
adversely affects the operation of the network or violates the rules and
|
|
||||||
protocols for communication across the network.
|
|
||||||
|
|
||||||
Corresponding Source conveyed, and Installation Information provided,
|
|
||||||
in accord with this section must be in a format that is publicly
|
|
||||||
documented (and with an implementation available to the public in
|
|
||||||
source code form), and must require no special password or key for
|
|
||||||
unpacking, reading or copying.
|
|
||||||
|
|
||||||
7. Additional Terms.
|
|
||||||
|
|
||||||
"Additional permissions" are terms that supplement the terms of this
|
|
||||||
License by making exceptions from one or more of its conditions.
|
|
||||||
Additional permissions that are applicable to the entire Program shall
|
|
||||||
be treated as though they were included in this License, to the extent
|
|
||||||
that they are valid under applicable law. If additional permissions
|
|
||||||
apply only to part of the Program, that part may be used separately
|
|
||||||
under those permissions, but the entire Program remains governed by
|
|
||||||
this License without regard to the additional permissions.
|
|
||||||
|
|
||||||
When you convey a copy of a covered work, you may at your option
|
|
||||||
remove any additional permissions from that copy, or from any part of
|
|
||||||
it. (Additional permissions may be written to require their own
|
|
||||||
removal in certain cases when you modify the work.) You may place
|
|
||||||
additional permissions on material, added by you to a covered work,
|
|
||||||
for which you have or can give appropriate copyright permission.
|
|
||||||
|
|
||||||
Notwithstanding any other provision of this License, for material you
|
|
||||||
add to a covered work, you may (if authorized by the copyright holders of
|
|
||||||
that material) supplement the terms of this License with terms:
|
|
||||||
|
|
||||||
a) Disclaiming warranty or limiting liability differently from the
|
|
||||||
terms of sections 15 and 16 of this License; or
|
|
||||||
|
|
||||||
b) Requiring preservation of specified reasonable legal notices or
|
|
||||||
author attributions in that material or in the Appropriate Legal
|
|
||||||
Notices displayed by works containing it; or
|
|
||||||
|
|
||||||
c) Prohibiting misrepresentation of the origin of that material, or
|
|
||||||
requiring that modified versions of such material be marked in
|
|
||||||
reasonable ways as different from the original version; or
|
|
||||||
|
|
||||||
d) Limiting the use for publicity purposes of names of licensors or
|
|
||||||
authors of the material; or
|
|
||||||
|
|
||||||
e) Declining to grant rights under trademark law for use of some
|
|
||||||
trade names, trademarks, or service marks; or
|
|
||||||
|
|
||||||
f) Requiring indemnification of licensors and authors of that
|
|
||||||
material by anyone who conveys the material (or modified versions of
|
|
||||||
it) with contractual assumptions of liability to the recipient, for
|
|
||||||
any liability that these contractual assumptions directly impose on
|
|
||||||
those licensors and authors.
|
|
||||||
|
|
||||||
All other non-permissive additional terms are considered "further
|
|
||||||
restrictions" within the meaning of section 10. If the Program as you
|
|
||||||
received it, or any part of it, contains a notice stating that it is
|
|
||||||
governed by this License along with a term that is a further
|
|
||||||
restriction, you may remove that term. If a license document contains
|
|
||||||
a further restriction but permits relicensing or conveying under this
|
|
||||||
License, you may add to a covered work material governed by the terms
|
|
||||||
of that license document, provided that the further restriction does
|
|
||||||
not survive such relicensing or conveying.
|
|
||||||
|
|
||||||
If you add terms to a covered work in accord with this section, you
|
|
||||||
must place, in the relevant source files, a statement of the
|
|
||||||
additional terms that apply to those files, or a notice indicating
|
|
||||||
where to find the applicable terms.
|
|
||||||
|
|
||||||
Additional terms, permissive or non-permissive, may be stated in the
|
|
||||||
form of a separately written license, or stated as exceptions;
|
|
||||||
the above requirements apply either way.
|
|
||||||
|
|
||||||
8. Termination.
|
|
||||||
|
|
||||||
You may not propagate or modify a covered work except as expressly
|
|
||||||
provided under this License. Any attempt otherwise to propagate or
|
|
||||||
modify it is void, and will automatically terminate your rights under
|
|
||||||
this License (including any patent licenses granted under the third
|
|
||||||
paragraph of section 11).
|
|
||||||
|
|
||||||
However, if you cease all violation of this License, then your
|
|
||||||
license from a particular copyright holder is reinstated (a)
|
|
||||||
provisionally, unless and until the copyright holder explicitly and
|
|
||||||
finally terminates your license, and (b) permanently, if the copyright
|
|
||||||
holder fails to notify you of the violation by some reasonable means
|
|
||||||
prior to 60 days after the cessation.
|
|
||||||
|
|
||||||
Moreover, your license from a particular copyright holder is
|
|
||||||
reinstated permanently if the copyright holder notifies you of the
|
|
||||||
violation by some reasonable means, this is the first time you have
|
|
||||||
received notice of violation of this License (for any work) from that
|
|
||||||
copyright holder, and you cure the violation prior to 30 days after
|
|
||||||
your receipt of the notice.
|
|
||||||
|
|
||||||
Termination of your rights under this section does not terminate the
|
|
||||||
licenses of parties who have received copies or rights from you under
|
|
||||||
this License. If your rights have been terminated and not permanently
|
|
||||||
reinstated, you do not qualify to receive new licenses for the same
|
|
||||||
material under section 10.
|
|
||||||
|
|
||||||
9. Acceptance Not Required for Having Copies.
|
|
||||||
|
|
||||||
You are not required to accept this License in order to receive or
|
|
||||||
run a copy of the Program. Ancillary propagation of a covered work
|
|
||||||
occurring solely as a consequence of using peer-to-peer transmission
|
|
||||||
to receive a copy likewise does not require acceptance. However,
|
|
||||||
nothing other than this License grants you permission to propagate or
|
|
||||||
modify any covered work. These actions infringe copyright if you do
|
|
||||||
not accept this License. Therefore, by modifying or propagating a
|
|
||||||
covered work, you indicate your acceptance of this License to do so.
|
|
||||||
|
|
||||||
10. Automatic Licensing of Downstream Recipients.
|
|
||||||
|
|
||||||
Each time you convey a covered work, the recipient automatically
|
|
||||||
receives a license from the original licensors, to run, modify and
|
|
||||||
propagate that work, subject to this License. You are not responsible
|
|
||||||
for enforcing compliance by third parties with this License.
|
|
||||||
|
|
||||||
An "entity transaction" is a transaction transferring control of an
|
|
||||||
organization, or substantially all assets of one, or subdividing an
|
|
||||||
organization, or merging organizations. If propagation of a covered
|
|
||||||
work results from an entity transaction, each party to that
|
|
||||||
transaction who receives a copy of the work also receives whatever
|
|
||||||
licenses to the work the party's predecessor in interest had or could
|
|
||||||
give under the previous paragraph, plus a right to possession of the
|
|
||||||
Corresponding Source of the work from the predecessor in interest, if
|
|
||||||
the predecessor has it or can get it with reasonable efforts.
|
|
||||||
|
|
||||||
You may not impose any further restrictions on the exercise of the
|
|
||||||
rights granted or affirmed under this License. For example, you may
|
|
||||||
not impose a license fee, royalty, or other charge for exercise of
|
|
||||||
rights granted under this License, and you may not initiate litigation
|
|
||||||
(including a cross-claim or counterclaim in a lawsuit) alleging that
|
|
||||||
any patent claim is infringed by making, using, selling, offering for
|
|
||||||
sale, or importing the Program or any portion of it.
|
|
||||||
|
|
||||||
11. Patents.
|
|
||||||
|
|
||||||
A "contributor" is a copyright holder who authorizes use under this
|
|
||||||
License of the Program or a work on which the Program is based. The
|
|
||||||
work thus licensed is called the contributor's "contributor version".
|
|
||||||
|
|
||||||
A contributor's "essential patent claims" are all patent claims
|
|
||||||
owned or controlled by the contributor, whether already acquired or
|
|
||||||
hereafter acquired, that would be infringed by some manner, permitted
|
|
||||||
by this License, of making, using, or selling its contributor version,
|
|
||||||
but do not include claims that would be infringed only as a
|
|
||||||
consequence of further modification of the contributor version. For
|
|
||||||
purposes of this definition, "control" includes the right to grant
|
|
||||||
patent sublicenses in a manner consistent with the requirements of
|
|
||||||
this License.
|
|
||||||
|
|
||||||
Each contributor grants you a non-exclusive, worldwide, royalty-free
|
|
||||||
patent license under the contributor's essential patent claims, to
|
|
||||||
make, use, sell, offer for sale, import and otherwise run, modify and
|
|
||||||
propagate the contents of its contributor version.
|
|
||||||
|
|
||||||
In the following three paragraphs, a "patent license" is any express
|
|
||||||
agreement or commitment, however denominated, not to enforce a patent
|
|
||||||
(such as an express permission to practice a patent or covenant not to
|
|
||||||
sue for patent infringement). To "grant" such a patent license to a
|
|
||||||
party means to make such an agreement or commitment not to enforce a
|
|
||||||
patent against the party.
|
|
||||||
|
|
||||||
If you convey a covered work, knowingly relying on a patent license,
|
|
||||||
and the Corresponding Source of the work is not available for anyone
|
|
||||||
to copy, free of charge and under the terms of this License, through a
|
|
||||||
publicly available network server or other readily accessible means,
|
|
||||||
then you must either (1) cause the Corresponding Source to be so
|
|
||||||
available, or (2) arrange to deprive yourself of the benefit of the
|
|
||||||
patent license for this particular work, or (3) arrange, in a manner
|
|
||||||
consistent with the requirements of this License, to extend the patent
|
|
||||||
license to downstream recipients. "Knowingly relying" means you have
|
|
||||||
actual knowledge that, but for the patent license, your conveying the
|
|
||||||
covered work in a country, or your recipient's use of the covered work
|
|
||||||
in a country, would infringe one or more identifiable patents in that
|
|
||||||
country that you have reason to believe are valid.
|
|
||||||
|
|
||||||
If, pursuant to or in connection with a single transaction or
|
|
||||||
arrangement, you convey, or propagate by procuring conveyance of, a
|
|
||||||
covered work, and grant a patent license to some of the parties
|
|
||||||
receiving the covered work authorizing them to use, propagate, modify
|
|
||||||
or convey a specific copy of the covered work, then the patent license
|
|
||||||
you grant is automatically extended to all recipients of the covered
|
|
||||||
work and works based on it.
|
|
||||||
|
|
||||||
A patent license is "discriminatory" if it does not include within
|
|
||||||
the scope of its coverage, prohibits the exercise of, or is
|
|
||||||
conditioned on the non-exercise of one or more of the rights that are
|
|
||||||
specifically granted under this License. You may not convey a covered
|
|
||||||
work if you are a party to an arrangement with a third party that is
|
|
||||||
in the business of distributing software, under which you make payment
|
|
||||||
to the third party based on the extent of your activity of conveying
|
|
||||||
the work, and under which the third party grants, to any of the
|
|
||||||
parties who would receive the covered work from you, a discriminatory
|
|
||||||
patent license (a) in connection with copies of the covered work
|
|
||||||
conveyed by you (or copies made from those copies), or (b) primarily
|
|
||||||
for and in connection with specific products or compilations that
|
|
||||||
contain the covered work, unless you entered into that arrangement,
|
|
||||||
or that patent license was granted, prior to 28 March 2007.
|
|
||||||
|
|
||||||
Nothing in this License shall be construed as excluding or limiting
|
|
||||||
any implied license or other defenses to infringement that may
|
|
||||||
otherwise be available to you under applicable patent law.
|
|
||||||
|
|
||||||
12. No Surrender of Others' Freedom.
|
|
||||||
|
|
||||||
If conditions are imposed on you (whether by court order, agreement or
|
|
||||||
otherwise) that contradict the conditions of this License, they do not
|
|
||||||
excuse you from the conditions of this License. If you cannot convey a
|
|
||||||
covered work so as to satisfy simultaneously your obligations under this
|
|
||||||
License and any other pertinent obligations, then as a consequence you may
|
|
||||||
not convey it at all. For example, if you agree to terms that obligate you
|
|
||||||
to collect a royalty for further conveying from those to whom you convey
|
|
||||||
the Program, the only way you could satisfy both those terms and this
|
|
||||||
License would be to refrain entirely from conveying the Program.
|
|
||||||
|
|
||||||
13. Remote Network Interaction; Use with the GNU General Public License.
|
|
||||||
|
|
||||||
Notwithstanding any other provision of this License, if you modify the
|
|
||||||
Program, your modified version must prominently offer all users
|
|
||||||
interacting with it remotely through a computer network (if your version
|
|
||||||
supports such interaction) an opportunity to receive the Corresponding
|
|
||||||
Source of your version by providing access to the Corresponding Source
|
|
||||||
from a network server at no charge, through some standard or customary
|
|
||||||
means of facilitating copying of software. This Corresponding Source
|
|
||||||
shall include the Corresponding Source for any work covered by version 3
|
|
||||||
of the GNU General Public License that is incorporated pursuant to the
|
|
||||||
following paragraph.
|
|
||||||
|
|
||||||
Notwithstanding any other provision of this License, you have
|
|
||||||
permission to link or combine any covered work with a work licensed
|
|
||||||
under version 3 of the GNU General Public License into a single
|
|
||||||
combined work, and to convey the resulting work. The terms of this
|
|
||||||
License will continue to apply to the part which is the covered work,
|
|
||||||
but the work with which it is combined will remain governed by version
|
|
||||||
3 of the GNU General Public License.
|
|
||||||
|
|
||||||
14. Revised Versions of this License.
|
|
||||||
|
|
||||||
The Free Software Foundation may publish revised and/or new versions of
|
|
||||||
the GNU Affero General Public License from time to time. Such new versions
|
|
||||||
will be similar in spirit to the present version, but may differ in detail to
|
|
||||||
address new problems or concerns.
|
|
||||||
|
|
||||||
Each version is given a distinguishing version number. If the
|
|
||||||
Program specifies that a certain numbered version of the GNU Affero General
|
|
||||||
Public License "or any later version" applies to it, you have the
|
|
||||||
option of following the terms and conditions either of that numbered
|
|
||||||
version or of any later version published by the Free Software
|
|
||||||
Foundation. If the Program does not specify a version number of the
|
|
||||||
GNU Affero General Public License, you may choose any version ever published
|
|
||||||
by the Free Software Foundation.
|
|
||||||
|
|
||||||
If the Program specifies that a proxy can decide which future
|
|
||||||
versions of the GNU Affero General Public License can be used, that proxy's
|
|
||||||
public statement of acceptance of a version permanently authorizes you
|
|
||||||
to choose that version for the Program.
|
|
||||||
|
|
||||||
Later license versions may give you additional or different
|
|
||||||
permissions. However, no additional obligations are imposed on any
|
|
||||||
author or copyright holder as a result of your choosing to follow a
|
|
||||||
later version.
|
|
||||||
|
|
||||||
15. Disclaimer of Warranty.
|
|
||||||
|
|
||||||
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
|
|
||||||
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
|
|
||||||
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
|
|
||||||
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
|
|
||||||
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
|
|
||||||
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
|
|
||||||
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
|
|
||||||
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
|
|
||||||
|
|
||||||
16. Limitation of Liability.
|
|
||||||
|
|
||||||
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
|
|
||||||
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
|
|
||||||
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
|
|
||||||
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
|
|
||||||
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
|
|
||||||
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
|
|
||||||
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
|
|
||||||
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
|
|
||||||
SUCH DAMAGES.
|
|
||||||
|
|
||||||
17. Interpretation of Sections 15 and 16.
|
|
||||||
|
|
||||||
If the disclaimer of warranty and limitation of liability provided
|
|
||||||
above cannot be given local legal effect according to their terms,
|
|
||||||
reviewing courts shall apply local law that most closely approximates
|
|
||||||
an absolute waiver of all civil liability in connection with the
|
|
||||||
Program, unless a warranty or assumption of liability accompanies a
|
|
||||||
copy of the Program in return for a fee.
|
|
||||||
|
|
||||||
END OF TERMS AND CONDITIONS
|
|
||||||
|
|
||||||
How to Apply These Terms to Your New Programs
|
|
||||||
|
|
||||||
If you develop a new program, and you want it to be of the greatest
|
|
||||||
possible use to the public, the best way to achieve this is to make it
|
|
||||||
free software which everyone can redistribute and change under these terms.
|
|
||||||
|
|
||||||
To do so, attach the following notices to the program. It is safest
|
|
||||||
to attach them to the start of each source file to most effectively
|
|
||||||
state the exclusion of warranty; and each file should have at least
|
|
||||||
the "copyright" line and a pointer to where the full notice is found.
|
|
||||||
|
|
||||||
<one line to give the program's name and a brief idea of what it does.>
|
|
||||||
Copyright (C) <year> <name of author>
|
|
||||||
|
|
||||||
This program is free software: you can redistribute it and/or modify
|
|
||||||
it under the terms of the GNU Affero General Public License as published
|
|
||||||
by the Free Software Foundation, either version 3 of the License, or
|
|
||||||
(at your option) any later version.
|
|
||||||
|
|
||||||
This program is distributed in the hope that it will be useful,
|
|
||||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
|
||||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
|
||||||
GNU Affero General Public License for more details.
|
|
||||||
|
|
||||||
You should have received a copy of the GNU Affero General Public License
|
|
||||||
along with this program. If not, see <http://www.gnu.org/licenses/>.
|
|
||||||
|
|
||||||
Also add information on how to contact you by electronic and paper mail.
|
|
||||||
|
|
||||||
If your software can interact with users remotely through a computer
|
|
||||||
network, you should also make sure that it provides a way for users to
|
|
||||||
get its source. For example, if your program is a web application, its
|
|
||||||
interface could display a "Source" link that leads users to an archive
|
|
||||||
of the code. There are many ways you could offer source, and different
|
|
||||||
solutions will be better for different programs; see section 13 for the
|
|
||||||
specific requirements.
|
|
||||||
|
|
||||||
You should also get your employer (if you work as a programmer) or school,
|
|
||||||
if any, to sign a "copyright disclaimer" for the program, if necessary.
|
|
||||||
For more information on this, and how to apply and follow the GNU AGPL, see
|
|
||||||
<http://www.gnu.org/licenses/>.
|
|
||||||
@@ -1,53 +0,0 @@
|
|||||||
# BattlesnakeOfficial/rules
|
|
||||||
|
|
||||||
[](https://codecov.io/gh/BattlesnakeOfficial/rules)
|
|
||||||
|
|
||||||
[Battlesnake](https://play.battlesnake.com) rules and game logic, implemented as a Go module. This code is used in production at [play.battlesnake.com](https://play.battlesnake.com). Issues and contributions welcome!
|
|
||||||
|
|
||||||
|
|
||||||
## CLI for Running Battlesnake Games Locally
|
|
||||||
|
|
||||||
This repo provides a simple CLI tool to run games locally against your dev environment.
|
|
||||||
|
|
||||||
### Installation
|
|
||||||
|
|
||||||
Download precompiled binaries here: <br>
|
|
||||||
[https://github.com/BattlesnakeOfficial/rules/releases](https://github.com/BattlesnakeOfficial/rules/releases)
|
|
||||||
|
|
||||||
Install as a Go package. Requires Go 1.18 or higher. [[Download](https://golang.org/dl/)]
|
|
||||||
```
|
|
||||||
go install github.com/BattlesnakeOfficial/rules/cli/battlesnake@latest
|
|
||||||
```
|
|
||||||
|
|
||||||
Compile from source. Also requires Go 1.18 or higher.
|
|
||||||
```
|
|
||||||
git clone git@github.com:BattlesnakeOfficial/rules.git
|
|
||||||
cd rules
|
|
||||||
go build -o battlesnake ./cli/battlesnake/main.go
|
|
||||||
```
|
|
||||||
|
|
||||||
### Usage
|
|
||||||
|
|
||||||
Example command to run a game locally:
|
|
||||||
```
|
|
||||||
battlesnake play -W 11 -H 11 --name <SNAKE_NAME> --url <SNAKE_URL> -g solo -v
|
|
||||||
```
|
|
||||||
|
|
||||||
For more details, see the [CLI README](cli/README.md).
|
|
||||||
|
|
||||||
|
|
||||||
## FAQ
|
|
||||||
|
|
||||||
### Can I run games locally?
|
|
||||||
|
|
||||||
Yes! [See the included CLI](cli/README.md).
|
|
||||||
|
|
||||||
### How is this different from the old Battlesnake engine?
|
|
||||||
|
|
||||||
The [old game engine](https://github.com/battlesnakeio/engine) was re-written in early 2020 to handle a higher volume of concurrent games. As part of that rebuild we moved the game logic into a separate Go module that gets compiled into the production engine.
|
|
||||||
|
|
||||||
This provides two benefits: it makes it much simpler/easier to build new game modes, and it allows the community to get more involved in game development (without the maintenance overhead of the entire game engine).
|
|
||||||
|
|
||||||
### Feedback
|
|
||||||
|
|
||||||
* **Do you have an issue or suggestions for this repository?** Head over to our [Feedback Repository](https://play.battlesnake.com/feedback) today and let us know!
|
|
||||||
Binary file not shown.
@@ -0,0 +1,95 @@
|
|||||||
|
module default {
|
||||||
|
function is_winner_me(winner: str) -> bool
|
||||||
|
using (winner = "me");
|
||||||
|
|
||||||
|
function gameboard_url(id: uuid) -> str
|
||||||
|
using ("https://play.battlesnake.com/game/" ++ <str>id);
|
||||||
|
|
||||||
|
type GameBoard {
|
||||||
|
overloaded required id: uuid {
|
||||||
|
readonly := true;
|
||||||
|
constraint exclusive;
|
||||||
|
}
|
||||||
|
url := gameboard_url(.id);
|
||||||
|
|
||||||
|
required created_at: datetime {
|
||||||
|
readonly := true;
|
||||||
|
}
|
||||||
|
required turns: int32 {
|
||||||
|
readonly := true;
|
||||||
|
}
|
||||||
|
required map: str {
|
||||||
|
readonly := true;
|
||||||
|
default := "standard";
|
||||||
|
}
|
||||||
|
required single type: GameType {
|
||||||
|
readonly := true;
|
||||||
|
on source delete delete target if orphan;
|
||||||
|
}
|
||||||
|
required single ruleset: Ruleset {
|
||||||
|
readonly := true;
|
||||||
|
on source delete delete target if orphan;
|
||||||
|
}
|
||||||
|
required winner: str {
|
||||||
|
readonly := true;
|
||||||
|
}
|
||||||
|
multi moves: Moves {
|
||||||
|
default := <Moves>{};
|
||||||
|
on source delete delete target;
|
||||||
|
on target delete allow;
|
||||||
|
}
|
||||||
|
required single snake: Snake {
|
||||||
|
readonly := true;
|
||||||
|
on source delete delete target if orphan;
|
||||||
|
}
|
||||||
|
|
||||||
|
is_winner_me := is_winner_me(.winner);
|
||||||
|
has_moves := exists(.moves);
|
||||||
|
}
|
||||||
|
|
||||||
|
type GameType {
|
||||||
|
required name: str {
|
||||||
|
readonly := true;
|
||||||
|
}
|
||||||
|
required is_ladder: bool {
|
||||||
|
readonly := true;
|
||||||
|
}
|
||||||
|
constraint exclusive on ( (.name, .is_ladder) );
|
||||||
|
}
|
||||||
|
|
||||||
|
type Ruleset {
|
||||||
|
required name: str {
|
||||||
|
readonly := true;
|
||||||
|
}
|
||||||
|
required version: str {
|
||||||
|
readonly := true;
|
||||||
|
}
|
||||||
|
required settings: json {
|
||||||
|
readonly := true;
|
||||||
|
}
|
||||||
|
constraint exclusive on ( (.name, .version, .settings) );
|
||||||
|
}
|
||||||
|
|
||||||
|
type Snake {
|
||||||
|
required type: str {
|
||||||
|
readonly := true;
|
||||||
|
}
|
||||||
|
constraint exclusive on ( .type );
|
||||||
|
}
|
||||||
|
|
||||||
|
type Moves {
|
||||||
|
required turn: int32 {
|
||||||
|
readonly := true;
|
||||||
|
}
|
||||||
|
required snake_move: str {
|
||||||
|
readonly := true;
|
||||||
|
}
|
||||||
|
required game_board: json {
|
||||||
|
readonly := true;
|
||||||
|
}
|
||||||
|
calculations: array<json> {
|
||||||
|
readonly := true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
@@ -11,4 +11,9 @@ services:
|
|||||||
build:
|
build:
|
||||||
context: ./
|
context: ./
|
||||||
dockerfile: Dockerfile
|
dockerfile: Dockerfile
|
||||||
|
#environment:
|
||||||
|
# - SNAKE_COLOR=blue
|
||||||
|
# - SNAKE_HEAD=caffeine
|
||||||
|
# - SNAKE_TAIL=mlh-gene
|
||||||
|
# - STORE_GAME_HISTORY=True
|
||||||
restart: always
|
restart: always
|
||||||
|
|||||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,178 @@
|
|||||||
|
# Justfile for Migrate Database Changes Workflow
|
||||||
|
# Docs: https://just.systems/man/en/
|
||||||
|
|
||||||
|
# ------------------------------------------------------------------------------
|
||||||
|
# Global settings
|
||||||
|
# ------------------------------------------------------------------------------
|
||||||
|
|
||||||
|
# Load Env
|
||||||
|
set dotenv-load
|
||||||
|
set dotenv-required := true
|
||||||
|
|
||||||
|
# Use zsh
|
||||||
|
set shell := ["bash", "-cu"]
|
||||||
|
|
||||||
|
BATTLESNAKE_CLI_DIR := ".tools/battlesnake-cli"
|
||||||
|
BATTLESNAKE_CLI_BIN := ".tools/battlesnake-cli/battlesnake"
|
||||||
|
|
||||||
|
# ------------------------------------------------------------------------------
|
||||||
|
# Default
|
||||||
|
# ------------------------------------------------------------------------------
|
||||||
|
|
||||||
|
# List all Available recipes
|
||||||
|
[private]
|
||||||
|
default:
|
||||||
|
@just --list --unsorted
|
||||||
|
|
||||||
|
# ------------------------------------------------------------------------------
|
||||||
|
# Snake Script helpers
|
||||||
|
# ------------------------------------------------------------------------------
|
||||||
|
|
||||||
|
run:
|
||||||
|
"{{justfile_directory()}}/main.py"
|
||||||
|
|
||||||
|
run-snake port="8000" snake="BestBattleSnake":
|
||||||
|
HOST="127.0.0.1" PORT="{{port}}" SNAKE="{{snake}}" DEBUG="false" DEBUG_SERVER="false" "{{justfile_directory()}}/main.py"
|
||||||
|
|
||||||
|
run-4-snakes base_port="9101" snake="BestBattleSnake":
|
||||||
|
#!/usr/bin/env bash
|
||||||
|
set -euo pipefail
|
||||||
|
|
||||||
|
pids=()
|
||||||
|
for i in 0 1 2 3; do
|
||||||
|
port="$(({{base_port}} + i))"
|
||||||
|
echo "Starting snake on :$port"
|
||||||
|
HOST="127.0.0.1" PORT="$port" SNAKE="{{snake}}" DEBUG="false" DEBUG_SERVER="false" "{{justfile_directory()}}/main.py" &
|
||||||
|
pids[$i]="$!"
|
||||||
|
done
|
||||||
|
|
||||||
|
cleanup() {
|
||||||
|
for pid in "${pids[@]}"; do
|
||||||
|
kill "$pid" 2>/dev/null || true
|
||||||
|
done
|
||||||
|
wait || true
|
||||||
|
}
|
||||||
|
trap cleanup EXIT INT TERM
|
||||||
|
|
||||||
|
wait
|
||||||
|
|
||||||
|
bench-best-snake iterations="1000":
|
||||||
|
#!/usr/bin/env bash
|
||||||
|
set -euo pipefail
|
||||||
|
|
||||||
|
PYTHONPATH="{{justfile_directory()}}" python "{{justfile_directory()}}/tests/bench_best_battle_snake.py" --iterations "{{iterations}}"
|
||||||
|
|
||||||
|
build-battlesnake-cli:
|
||||||
|
#!/usr/bin/env bash
|
||||||
|
set -euo pipefail
|
||||||
|
|
||||||
|
install_dir="{{justfile_directory()}}/{{BATTLESNAKE_CLI_DIR}}"
|
||||||
|
bin_path="{{justfile_directory()}}/{{BATTLESNAKE_CLI_BIN}}"
|
||||||
|
mkdir -p "$install_dir"
|
||||||
|
|
||||||
|
if [ ! -f "{{justfile_directory()}}/local-client/go.mod" ]; then
|
||||||
|
echo "Missing local-client source. Run: git submodule update --init --recursive"
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
|
||||||
|
(
|
||||||
|
cd "{{justfile_directory()}}/local-client"
|
||||||
|
go build -o "$bin_path" ./cli/battlesnake/main.go
|
||||||
|
)
|
||||||
|
|
||||||
|
"$bin_path" --help > /dev/null
|
||||||
|
echo "Built Battlesnake CLI at $bin_path"
|
||||||
|
|
||||||
|
battlesnake-cli-version:
|
||||||
|
#!/usr/bin/env bash
|
||||||
|
set -euo pipefail
|
||||||
|
|
||||||
|
"{{justfile_directory()}}/{{BATTLESNAKE_CLI_BIN}}" --help
|
||||||
|
|
||||||
|
# ------------------------------------------------------------------------------
|
||||||
|
# Testing helpers
|
||||||
|
# ------------------------------------------------------------------------------
|
||||||
|
|
||||||
|
test-constrictor: build-battlesnake-cli
|
||||||
|
#!/usr/bin/env bash
|
||||||
|
set -euo pipefail
|
||||||
|
|
||||||
|
BATTLESNAKE_CLI="{{justfile_directory()}}/{{BATTLESNAKE_CLI_BIN}}"
|
||||||
|
"$BATTLESNAKE_CLI" play -W 11 -H 11 --name 'Python Starter Project' --url http://localhost:8000 -g constrictor --browser --minimumFood 0
|
||||||
|
|
||||||
|
test-seed: build-battlesnake-cli
|
||||||
|
#!/usr/bin/env bash
|
||||||
|
set -euo pipefail
|
||||||
|
|
||||||
|
BATTLESNAKE_CLI="{{justfile_directory()}}/{{BATTLESNAKE_CLI_BIN}}"
|
||||||
|
"$BATTLESNAKE_CLI" play -W 11 -H 11 --name 'Python Starter Project' --url http://localhost:8000 -g solo --browser --seed 1713099635738952360
|
||||||
|
|
||||||
|
test-local-4 mode="standard" map="standard" base_port="9101" snake="BestBattleSnake" seed="1713099635738952360" browser="true": build-battlesnake-cli
|
||||||
|
#!/usr/bin/env bash
|
||||||
|
set -euo pipefail
|
||||||
|
|
||||||
|
BATTLESNAKE_CLI="{{justfile_directory()}}/{{BATTLESNAKE_CLI_BIN}}"
|
||||||
|
LOG_DIR="{{justfile_directory()}}/.tools/snake-logs"
|
||||||
|
mkdir -p "$LOG_DIR"
|
||||||
|
|
||||||
|
pids=()
|
||||||
|
for i in 0 1 2 3; do
|
||||||
|
port="$(({{base_port}} + i))"
|
||||||
|
log_file="$LOG_DIR/snake-$((i+1)).log"
|
||||||
|
echo "Starting snake-$((i+1)) on :$port (log: $log_file)"
|
||||||
|
HOST="127.0.0.1" PORT="$port" SNAKE="{{snake}}" DEBUG="false" DEBUG_SERVER="false" "{{justfile_directory()}}/main.py" > >(tee "$log_file") 2>&1 &
|
||||||
|
pids[$i]="$!"
|
||||||
|
done
|
||||||
|
|
||||||
|
cleanup() {
|
||||||
|
for pid in "${pids[@]}"; do
|
||||||
|
kill "$pid" 2>/dev/null || true
|
||||||
|
done
|
||||||
|
wait || true
|
||||||
|
}
|
||||||
|
trap cleanup EXIT INT TERM
|
||||||
|
|
||||||
|
for i in 0 1 2 3; do
|
||||||
|
port="$(({{base_port}} + i))"
|
||||||
|
for _ in $(seq 1 30); do
|
||||||
|
if curl -fsS "http://127.0.0.1:$port" >/dev/null 2>&1; then
|
||||||
|
break
|
||||||
|
fi
|
||||||
|
sleep 0.2
|
||||||
|
done
|
||||||
|
if ! curl -fsS "http://127.0.0.1:$port" >/dev/null 2>&1; then
|
||||||
|
echo "Snake on :$port did not start correctly. Check logs in $LOG_DIR"
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
done
|
||||||
|
|
||||||
|
BROWSER_FLAG=""
|
||||||
|
if [ "{{browser}}" = "true" ]; then
|
||||||
|
BROWSER_FLAG="--browser"
|
||||||
|
fi
|
||||||
|
|
||||||
|
"$BATTLESNAKE_CLI" play -W 11 -H 11 \
|
||||||
|
--name "Snake 1" --url "http://127.0.0.1:{{base_port}}" \
|
||||||
|
--name "Snake 2" --url "http://127.0.0.1:$(({{base_port}} + 1))" \
|
||||||
|
--name "Snake 3" --url "http://127.0.0.1:$(({{base_port}} + 2))" \
|
||||||
|
--name "Snake 4" --url "http://127.0.0.1:$(({{base_port}} + 3))" \
|
||||||
|
-g "{{mode}}" --map "{{map}}" --seed "{{seed}}" $BROWSER_FLAG
|
||||||
|
|
||||||
|
# ------------------------------------------------------------------------------
|
||||||
|
# Dataset helpers
|
||||||
|
# ------------------------------------------------------------------------------
|
||||||
|
|
||||||
|
export-dataset input="data" output="data/dataset/good_moves.jsonl":
|
||||||
|
python -m server.DatasetExporter --input "{{input}}" --output "{{output}}"
|
||||||
|
|
||||||
|
curate-dataset input="good_moves-*.jsonl" output="data/dataset/best_moves.jsonl" min_turn="6" late_turn="20" max_safe_options="2" min_score="3" append="false" archive="false" archive_dir="":
|
||||||
|
FLAGS=""; if [ "{{append}}" = "true" ]; then FLAGS="$FLAGS --append"; fi; if [ "{{archive}}" = "true" ]; then FLAGS="$FLAGS --archive-input"; fi; if [ -n "{{archive_dir}}" ]; then FLAGS="$FLAGS --archive-dir {{archive_dir}}"; fi; python -m server.DatasetCurator --input "{{input}}" --output "{{output}}" --min-turn "{{min_turn}}" --late-turn "{{late_turn}}" --max-safe-options "{{max_safe_options}}" --min-score "{{min_score}}" $FLAGS
|
||||||
|
|
||||||
|
analyze-dataset input="good_moves-*.jsonl" output="":
|
||||||
|
if [ -n "{{output}}" ]; then python -m server.DatasetStats --input "{{input}}" --output "{{output}}"; else python -m server.DatasetStats --input "{{input}}"; fi
|
||||||
|
|
||||||
|
train-ai input="dataset/best_moves.jsonl" rl_input="dataset/rl_bootstrap.jsonl" output="models/battlesnake_softmax_v2.json" eval_split="0.2" seed="42" epochs="14" lr="0.08":
|
||||||
|
if [ -f "{{rl_input}}" ]; then python -m server.TrainBattleSnakeAI --input "{{input}}" --input "{{rl_input}}" --output "{{output}}" --eval-split "{{eval_split}}" --seed "{{seed}}" --epochs "{{epochs}}" --lr "{{lr}}"; else python -m server.TrainBattleSnakeAI --input "{{input}}" --output "{{output}}" --eval-split "{{eval_split}}" --seed "{{seed}}" --epochs "{{epochs}}" --lr "{{lr}}"; fi
|
||||||
|
|
||||||
|
run-trained model="models/battlesnake_softmax_v2.json" port="8000":
|
||||||
|
TRAINED_SNAKE_MODEL="{{model}}" SNAKE="TrainedBattleSnake" PORT="{{port}}" "{{justfile_directory()}}/main.py"
|
||||||
Submodule
+1
Submodule local-client added at 87e094e2e1
@@ -1,4 +1,4 @@
|
|||||||
#!/usr/bin/env python3
|
#!/usr/bin/env -S uv run --script
|
||||||
|
|
||||||
# Welcome to
|
# Welcome to
|
||||||
# __________ __ __ .__ __
|
# __________ __ __ .__ __
|
||||||
@@ -12,25 +12,20 @@
|
|||||||
# To get you started we've included code to prevent your Battlesnake from moving backwards.
|
# To get you started we've included code to prevent your Battlesnake from moving backwards.
|
||||||
# For more info see docs.battlesnake.com
|
# For more info see docs.battlesnake.com
|
||||||
|
|
||||||
from server.Server import Server
|
from server.CreateEnvironmentFile import CreateEnvironmentFile
|
||||||
|
from server.bootstrap import build_run_config, build_server_from_env
|
||||||
|
|
||||||
from dotenv import load_dotenv, find_dotenv
|
import asyncio
|
||||||
import os
|
import os
|
||||||
|
|
||||||
# Start server when `python main.py` is run
|
# Start server when `python main.py` is run
|
||||||
if __name__ == "__main__":
|
if __name__ == "__main__":
|
||||||
load_dotenv(find_dotenv())
|
if os.environ.get("CREATE_ENV_FILE", None):
|
||||||
|
CreateEnvironmentFile.load_dotenv({
|
||||||
|
"STORE_GAME_HISTORY": True,
|
||||||
|
"DEBUG": True,
|
||||||
|
"SNAKE": "TemplateSnake",
|
||||||
|
})
|
||||||
|
|
||||||
server = Server(
|
server = build_server_from_env(default_snake_type="TemplateSnake")
|
||||||
data_path=os.path.dirname(__file__),
|
asyncio.run(server.run(**build_run_config()))
|
||||||
snake_type=os.environ.get("SNAKE", "DummSnake"),
|
|
||||||
)
|
|
||||||
|
|
||||||
if os.environ.get("STORE_GAME_HISTORY", None):
|
|
||||||
server.enable_store_game_state()
|
|
||||||
|
|
||||||
server.run(
|
|
||||||
host=os.environ.get("HOST", "0.0.0.0"),
|
|
||||||
port=int(os.environ.get("PORT", "8000")),
|
|
||||||
debug=bool(os.environ.get("DEBUG", False))
|
|
||||||
)
|
|
||||||
|
|||||||
@@ -0,0 +1,12 @@
|
|||||||
|
[project]
|
||||||
|
name = "snake-python"
|
||||||
|
version = "0.1.0"
|
||||||
|
description = "Add your description here"
|
||||||
|
readme = "README.md"
|
||||||
|
requires-python = ">=3.13"
|
||||||
|
dependencies = [
|
||||||
|
"aiologger>=0.7.0",
|
||||||
|
"dotenv>=0.9.9",
|
||||||
|
"gel>=3.1.0",
|
||||||
|
"quart>=0.20.0",
|
||||||
|
]
|
||||||
Submodule
+1
Submodule quart_common added at 823560fdcd
+19
-10
@@ -1,10 +1,19 @@
|
|||||||
blinker==1.7.0
|
aiofiles==25.1.0
|
||||||
click==8.1.7
|
blinker==1.9.0
|
||||||
Flask==3.0.2
|
click==8.3.1
|
||||||
itsdangerous==2.1.2
|
dotenv==0.9.9
|
||||||
Jinja2==3.1.3
|
flask==3.1.2
|
||||||
MarkupSafe==2.1.5
|
gel==3.1.0
|
||||||
numpy==1.26.4
|
h11==0.16.0
|
||||||
python-dotenv==1.0.1
|
h2==4.3.0
|
||||||
scipy==1.12.0
|
hpack==4.1.0
|
||||||
Werkzeug==3.0.1
|
hypercorn==0.18.0
|
||||||
|
hyperframe==6.1.0
|
||||||
|
itsdangerous==2.2.0
|
||||||
|
jinja2==3.1.6
|
||||||
|
markupsafe==3.0.3
|
||||||
|
priority==2.0.0
|
||||||
|
python-dotenv==1.2.1
|
||||||
|
quart==0.20.0
|
||||||
|
werkzeug==3.1.4
|
||||||
|
wsproto==1.3.2
|
||||||
|
|||||||
@@ -0,0 +1,26 @@
|
|||||||
|
from dotenv import load_dotenv, find_dotenv
|
||||||
|
import os
|
||||||
|
|
||||||
|
class CreateEnvironmentFile:
|
||||||
|
def __init__(self):
|
||||||
|
self.path = find_dotenv()
|
||||||
|
|
||||||
|
def create_file(self, environment_vars:dict[str], path:str="./.env"):
|
||||||
|
if environment_vars:
|
||||||
|
data = self.convert_dict_to_list(environment_vars)
|
||||||
|
with open(path, 'w') as f:
|
||||||
|
f.writelines(data)
|
||||||
|
|
||||||
|
def convert_dict_to_list(self, data_dict:dict):
|
||||||
|
data = []
|
||||||
|
for k, v in data_dict.items():
|
||||||
|
data.append(f"{k}={v}\n")
|
||||||
|
return data
|
||||||
|
|
||||||
|
@classmethod
|
||||||
|
def load_dotenv(cls, environment_vars:dict[str]=None):
|
||||||
|
new_class = cls()
|
||||||
|
if os.path.exists(new_class.path):
|
||||||
|
return load_dotenv(new_class.path)
|
||||||
|
else:
|
||||||
|
return new_class.create_file(environment_vars)
|
||||||
@@ -0,0 +1,56 @@
|
|||||||
|
from server.GameBoard import GameBoard
|
||||||
|
|
||||||
|
class Dataset:
|
||||||
|
VALID_MOVES = {"up", "down", "left", "right"}
|
||||||
|
|
||||||
|
def __init__(self, game_board: GameBoard):
|
||||||
|
self.game_board = game_board
|
||||||
|
|
||||||
|
def _did_we_win(self):
|
||||||
|
winners = self.game_board.winner_snake_names or []
|
||||||
|
return "me" in winners
|
||||||
|
|
||||||
|
def _is_good_move(self, move: str):
|
||||||
|
return move in self.VALID_MOVES
|
||||||
|
|
||||||
|
def build(self, only_good_moves: bool = True):
|
||||||
|
game_type = self.game_board.get_type_of_game()
|
||||||
|
did_win = self._did_we_win()
|
||||||
|
|
||||||
|
samples = []
|
||||||
|
history = self.game_board.snake_class.get_history()
|
||||||
|
for index, turn in enumerate(self.game_board.turns):
|
||||||
|
move = turn.get("move")
|
||||||
|
is_good_move = did_win and self._is_good_move(move)
|
||||||
|
if only_good_moves and not is_good_move:
|
||||||
|
continue
|
||||||
|
|
||||||
|
samples.append({
|
||||||
|
"turn": turn.get("turn"),
|
||||||
|
"move": move,
|
||||||
|
"game_board": turn.get("game_board"),
|
||||||
|
"is_good_move": is_good_move,
|
||||||
|
"history": history[index] if index < len(history) else {},
|
||||||
|
})
|
||||||
|
|
||||||
|
return {
|
||||||
|
"game": {
|
||||||
|
"id": self.game_board.id,
|
||||||
|
"map": self.game_board.map,
|
||||||
|
"type": game_type,
|
||||||
|
},
|
||||||
|
"snake": {
|
||||||
|
"type": self.game_board.snake_class.__class__.__name__,
|
||||||
|
},
|
||||||
|
"did_win": did_win,
|
||||||
|
"total_samples": len(samples),
|
||||||
|
"samples": samples,
|
||||||
|
}
|
||||||
|
|
||||||
|
def labels_by_turn(self):
|
||||||
|
did_win = self._did_we_win()
|
||||||
|
labels = {}
|
||||||
|
for turn in self.game_board.turns:
|
||||||
|
move = turn.get("move")
|
||||||
|
labels[turn.get("turn")] = did_win and self._is_good_move(move)
|
||||||
|
return labels
|
||||||
@@ -0,0 +1,280 @@
|
|||||||
|
import argparse
|
||||||
|
import glob
|
||||||
|
import hashlib
|
||||||
|
import json
|
||||||
|
import shutil
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
class DatasetCurator:
|
||||||
|
def __init__(
|
||||||
|
self,
|
||||||
|
input_files: list[str],
|
||||||
|
output_file: str,
|
||||||
|
min_turn: int = 6,
|
||||||
|
late_turn: int = 20,
|
||||||
|
max_safe_options: int = 2,
|
||||||
|
min_score: int = 3,
|
||||||
|
append: bool = False,
|
||||||
|
archive_input: bool = False,
|
||||||
|
archive_dir: str | None = None,
|
||||||
|
):
|
||||||
|
self.input_files = input_files
|
||||||
|
self.output_file = Path(output_file)
|
||||||
|
self.min_turn = min_turn
|
||||||
|
self.late_turn = late_turn
|
||||||
|
self.max_safe_options = max_safe_options
|
||||||
|
self.min_score = min_score
|
||||||
|
self.append = append
|
||||||
|
self.archive_input = archive_input
|
||||||
|
self.archive_dir = (
|
||||||
|
Path(archive_dir) if archive_dir else self.output_file.parent / "archive"
|
||||||
|
)
|
||||||
|
|
||||||
|
def _resolve_input_files(self):
|
||||||
|
resolved = []
|
||||||
|
seen = set()
|
||||||
|
|
||||||
|
for item in self.input_files:
|
||||||
|
path = Path(item)
|
||||||
|
if path.is_dir():
|
||||||
|
for file_path in sorted(path.rglob("*.jsonl")):
|
||||||
|
key = str(file_path.resolve())
|
||||||
|
if key in seen:
|
||||||
|
continue
|
||||||
|
seen.add(key)
|
||||||
|
resolved.append(file_path)
|
||||||
|
continue
|
||||||
|
|
||||||
|
if any(ch in item for ch in "*?[]"):
|
||||||
|
for match in sorted(glob.glob(item)):
|
||||||
|
file_path = Path(match)
|
||||||
|
if not file_path.is_file():
|
||||||
|
continue
|
||||||
|
key = str(file_path.resolve())
|
||||||
|
if key in seen:
|
||||||
|
continue
|
||||||
|
seen.add(key)
|
||||||
|
resolved.append(file_path)
|
||||||
|
continue
|
||||||
|
|
||||||
|
if path.is_file():
|
||||||
|
key = str(path.resolve())
|
||||||
|
if key in seen:
|
||||||
|
continue
|
||||||
|
seen.add(key)
|
||||||
|
resolved.append(path)
|
||||||
|
|
||||||
|
return resolved
|
||||||
|
|
||||||
|
def _safe_options_count(self, row: dict):
|
||||||
|
history = row.get("history", {})
|
||||||
|
for item in history.get("data", []):
|
||||||
|
if item.get("function") == "get_possible_moves":
|
||||||
|
return len(item.get("safe_positions", {}))
|
||||||
|
return None
|
||||||
|
|
||||||
|
def _state_hash(self, row: dict):
|
||||||
|
board = row.get("game_board", {})
|
||||||
|
snakes = board.get("snakes", [])
|
||||||
|
|
||||||
|
snakes_key = []
|
||||||
|
for snake in snakes:
|
||||||
|
snakes_key.append(
|
||||||
|
(
|
||||||
|
snake.get("id"),
|
||||||
|
snake.get("health"),
|
||||||
|
tuple(
|
||||||
|
(seg.get("x"), seg.get("y")) for seg in snake.get("body", [])
|
||||||
|
),
|
||||||
|
)
|
||||||
|
)
|
||||||
|
|
||||||
|
key = {
|
||||||
|
"width": board.get("width"),
|
||||||
|
"height": board.get("height"),
|
||||||
|
"snakes": sorted(snakes_key),
|
||||||
|
"food": sorted((f.get("x"), f.get("y")) for f in board.get("food", [])),
|
||||||
|
"hazards": sorted(
|
||||||
|
(h.get("x"), h.get("y")) for h in board.get("hazards", [])
|
||||||
|
),
|
||||||
|
}
|
||||||
|
raw = json.dumps(key, sort_keys=True, separators=(",", ":"))
|
||||||
|
return hashlib.sha1(raw.encode("utf-8")).hexdigest()
|
||||||
|
|
||||||
|
def _score(self, row: dict):
|
||||||
|
score = 0
|
||||||
|
turn = int(row.get("turn", 0))
|
||||||
|
safe_options = self._safe_options_count(row)
|
||||||
|
snakes = row.get("game_board", {}).get("snakes", [])
|
||||||
|
opponents = max(0, len(snakes) - 1)
|
||||||
|
|
||||||
|
if turn >= self.late_turn:
|
||||||
|
score += 2
|
||||||
|
if safe_options is not None and safe_options <= self.max_safe_options:
|
||||||
|
score += 3
|
||||||
|
if opponents >= 1:
|
||||||
|
score += 1
|
||||||
|
|
||||||
|
return score, safe_options
|
||||||
|
|
||||||
|
def curate(self):
|
||||||
|
self.output_file.parent.mkdir(parents=True, exist_ok=True)
|
||||||
|
input_paths = self._resolve_input_files()
|
||||||
|
|
||||||
|
total = 0
|
||||||
|
kept = 0
|
||||||
|
skipped_turn = 0
|
||||||
|
skipped_quality = 0
|
||||||
|
skipped_duplicate = 0
|
||||||
|
seen_states = set()
|
||||||
|
|
||||||
|
if self.append and self.output_file.exists():
|
||||||
|
with self.output_file.open("r", encoding="utf-8") as existing:
|
||||||
|
for line in existing:
|
||||||
|
if not line.strip():
|
||||||
|
continue
|
||||||
|
row = json.loads(line)
|
||||||
|
state_key = self._state_hash(row)
|
||||||
|
seen_states.add((state_key, row.get("move")))
|
||||||
|
|
||||||
|
mode = "a" if self.append else "w"
|
||||||
|
with self.output_file.open(mode, encoding="utf-8") as dst:
|
||||||
|
for input_path in input_paths:
|
||||||
|
with input_path.open("r", encoding="utf-8") as src:
|
||||||
|
for line in src:
|
||||||
|
if not line.strip():
|
||||||
|
continue
|
||||||
|
|
||||||
|
total += 1
|
||||||
|
row = json.loads(line)
|
||||||
|
|
||||||
|
if not row.get("is_good_move", False):
|
||||||
|
skipped_quality += 1
|
||||||
|
continue
|
||||||
|
|
||||||
|
if int(row.get("turn", 0)) < self.min_turn:
|
||||||
|
skipped_turn += 1
|
||||||
|
continue
|
||||||
|
|
||||||
|
quality_score, safe_options = self._score(row)
|
||||||
|
if quality_score < self.min_score:
|
||||||
|
skipped_quality += 1
|
||||||
|
continue
|
||||||
|
|
||||||
|
state_key = self._state_hash(row)
|
||||||
|
dedupe_key = (state_key, row.get("move"))
|
||||||
|
if dedupe_key in seen_states:
|
||||||
|
skipped_duplicate += 1
|
||||||
|
continue
|
||||||
|
seen_states.add(dedupe_key)
|
||||||
|
|
||||||
|
compact_row = {
|
||||||
|
"game_id": row.get("game_id"),
|
||||||
|
"turn": row.get("turn"),
|
||||||
|
"move": row.get("move"),
|
||||||
|
"game_type": row.get("game_type"),
|
||||||
|
"quality_score": quality_score,
|
||||||
|
"safe_options": safe_options,
|
||||||
|
"game_board": row.get("game_board"),
|
||||||
|
}
|
||||||
|
dst.write(json.dumps(compact_row, ensure_ascii=False) + "\n")
|
||||||
|
kept += 1
|
||||||
|
|
||||||
|
archived_files = []
|
||||||
|
if self.archive_input:
|
||||||
|
archived_files = self._archive_processed_files(input_paths)
|
||||||
|
|
||||||
|
return {
|
||||||
|
"input_files": [str(path) for path in input_paths],
|
||||||
|
"total_rows": total,
|
||||||
|
"kept_rows": kept,
|
||||||
|
"skipped_turn": skipped_turn,
|
||||||
|
"skipped_quality": skipped_quality,
|
||||||
|
"skipped_duplicate": skipped_duplicate,
|
||||||
|
"append_mode": self.append,
|
||||||
|
"archive_input": self.archive_input,
|
||||||
|
"archived_files": archived_files,
|
||||||
|
"output_file": str(self.output_file),
|
||||||
|
}
|
||||||
|
|
||||||
|
def _archive_processed_files(self, input_paths: list[Path]):
|
||||||
|
self.archive_dir.mkdir(parents=True, exist_ok=True)
|
||||||
|
archived = []
|
||||||
|
|
||||||
|
output_resolved = (
|
||||||
|
self.output_file.resolve()
|
||||||
|
if self.output_file.exists()
|
||||||
|
else self.output_file
|
||||||
|
)
|
||||||
|
archive_resolved = self.archive_dir.resolve()
|
||||||
|
|
||||||
|
for source_path in input_paths:
|
||||||
|
if not source_path.exists():
|
||||||
|
continue
|
||||||
|
|
||||||
|
source_resolved = source_path.resolve()
|
||||||
|
if source_resolved == output_resolved:
|
||||||
|
continue
|
||||||
|
if source_resolved.parent == archive_resolved:
|
||||||
|
continue
|
||||||
|
|
||||||
|
destination = self.archive_dir / source_path.name
|
||||||
|
if destination.exists():
|
||||||
|
stem = destination.stem
|
||||||
|
suffix = destination.suffix
|
||||||
|
index = 1
|
||||||
|
while True:
|
||||||
|
candidate = self.archive_dir / f"{stem}.{index}{suffix}"
|
||||||
|
if not candidate.exists():
|
||||||
|
destination = candidate
|
||||||
|
break
|
||||||
|
index += 1
|
||||||
|
|
||||||
|
shutil.move(str(source_path), str(destination))
|
||||||
|
archived.append(str(destination))
|
||||||
|
|
||||||
|
return archived
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
parser = argparse.ArgumentParser(description="Create curated best-moves dataset")
|
||||||
|
parser.add_argument(
|
||||||
|
"--input",
|
||||||
|
action="append",
|
||||||
|
required=True,
|
||||||
|
help="Input JSONL file, directory, or glob pattern. Repeat for multiple inputs.",
|
||||||
|
)
|
||||||
|
parser.add_argument("--output", required=True, help="Output JSONL file")
|
||||||
|
parser.add_argument("--min-turn", type=int, default=6)
|
||||||
|
parser.add_argument("--late-turn", type=int, default=20)
|
||||||
|
parser.add_argument("--max-safe-options", type=int, default=2)
|
||||||
|
parser.add_argument("--min-score", type=int, default=3)
|
||||||
|
parser.add_argument(
|
||||||
|
"--append",
|
||||||
|
action="store_true",
|
||||||
|
help="Append to existing output and dedupe against existing rows",
|
||||||
|
)
|
||||||
|
parser.add_argument(
|
||||||
|
"--archive-input",
|
||||||
|
action="store_true",
|
||||||
|
help="Move processed input files to archive directory after successful curation",
|
||||||
|
)
|
||||||
|
parser.add_argument(
|
||||||
|
"--archive-dir",
|
||||||
|
default=None,
|
||||||
|
help="Archive directory for processed input files (default: <output-dir>/archive)",
|
||||||
|
)
|
||||||
|
args = parser.parse_args()
|
||||||
|
|
||||||
|
report = DatasetCurator(
|
||||||
|
input_files=args.input,
|
||||||
|
output_file=args.output,
|
||||||
|
min_turn=args.min_turn,
|
||||||
|
late_turn=args.late_turn,
|
||||||
|
max_safe_options=args.max_safe_options,
|
||||||
|
min_score=args.min_score,
|
||||||
|
append=args.append,
|
||||||
|
archive_input=args.archive_input,
|
||||||
|
archive_dir=args.archive_dir,
|
||||||
|
).curate()
|
||||||
|
print(json.dumps(report, indent=2))
|
||||||
@@ -0,0 +1,64 @@
|
|||||||
|
import argparse
|
||||||
|
import json
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
|
||||||
|
class DatasetExporter:
|
||||||
|
def __init__(self, input_dir:str, output_file:str):
|
||||||
|
self.input_dir = Path(input_dir)
|
||||||
|
self.output_file = Path(output_file)
|
||||||
|
|
||||||
|
def _iter_game_files(self):
|
||||||
|
if not self.input_dir.exists():
|
||||||
|
return []
|
||||||
|
return sorted(self.input_dir.rglob("*.json"))
|
||||||
|
|
||||||
|
def _extract_samples(self, payload:dict, source_file:Path):
|
||||||
|
dataset = payload.get("dataset", {})
|
||||||
|
game_info = dataset.get("game", payload.get("game", {}))
|
||||||
|
snake_info = dataset.get("snake", payload.get("snake", {}))
|
||||||
|
|
||||||
|
samples = []
|
||||||
|
for sample in dataset.get("samples", []):
|
||||||
|
samples.append({
|
||||||
|
"game_id": game_info.get("id"),
|
||||||
|
"game_map": game_info.get("map"),
|
||||||
|
"game_type": game_info.get("type"),
|
||||||
|
"snake_type": snake_info.get("type"),
|
||||||
|
"turn": sample.get("turn"),
|
||||||
|
"move": sample.get("move"),
|
||||||
|
"is_good_move": sample.get("is_good_move", False),
|
||||||
|
"game_board": sample.get("game_board"),
|
||||||
|
"history": sample.get("history"),
|
||||||
|
"source_file": str(source_file),
|
||||||
|
})
|
||||||
|
return samples
|
||||||
|
|
||||||
|
def export_jsonl(self):
|
||||||
|
game_files = self._iter_game_files()
|
||||||
|
self.output_file.parent.mkdir(parents=True, exist_ok=True)
|
||||||
|
|
||||||
|
sample_count = 0
|
||||||
|
with self.output_file.open("w", encoding="utf-8") as output:
|
||||||
|
for game_file in game_files:
|
||||||
|
with game_file.open("r", encoding="utf-8") as source:
|
||||||
|
payload = json.load(source)
|
||||||
|
|
||||||
|
for sample in self._extract_samples(payload, game_file):
|
||||||
|
output.write(json.dumps(sample, ensure_ascii=False) + "\n")
|
||||||
|
sample_count += 1
|
||||||
|
|
||||||
|
return {
|
||||||
|
"games_scanned": len(game_files),
|
||||||
|
"samples_exported": sample_count,
|
||||||
|
"output_file": str(self.output_file),
|
||||||
|
}
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
parser = argparse.ArgumentParser(description="Export Battlesnake dataset to JSONL")
|
||||||
|
parser.add_argument("--input", default="data", help="Input directory with stored game JSON files")
|
||||||
|
parser.add_argument("--output", default="data/dataset/good_moves.jsonl", help="Output JSONL file")
|
||||||
|
args = parser.parse_args()
|
||||||
|
|
||||||
|
report = DatasetExporter(args.input, args.output).export_jsonl()
|
||||||
|
print(json.dumps(report, indent=2))
|
||||||
@@ -0,0 +1,247 @@
|
|||||||
|
import argparse
|
||||||
|
import glob
|
||||||
|
import json
|
||||||
|
import re
|
||||||
|
from collections import Counter, defaultdict
|
||||||
|
from datetime import datetime
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
|
||||||
|
class DatasetStats:
|
||||||
|
DAY_PATTERN = re.compile(r"(\d{4}-\d{2}-\d{2})")
|
||||||
|
|
||||||
|
def __init__(self, input_files: list[str]):
|
||||||
|
self.input_files = input_files
|
||||||
|
|
||||||
|
def _resolve_input_files(self):
|
||||||
|
resolved = []
|
||||||
|
seen = set()
|
||||||
|
|
||||||
|
for item in self.input_files:
|
||||||
|
path = Path(item)
|
||||||
|
if path.is_dir():
|
||||||
|
for file_path in sorted(path.rglob("*.jsonl")):
|
||||||
|
key = str(file_path.resolve())
|
||||||
|
if key in seen:
|
||||||
|
continue
|
||||||
|
seen.add(key)
|
||||||
|
resolved.append(file_path)
|
||||||
|
continue
|
||||||
|
|
||||||
|
if any(ch in item for ch in "*?[]"):
|
||||||
|
for match in sorted(glob.glob(item)):
|
||||||
|
file_path = Path(match)
|
||||||
|
if not file_path.is_file():
|
||||||
|
continue
|
||||||
|
key = str(file_path.resolve())
|
||||||
|
if key in seen:
|
||||||
|
continue
|
||||||
|
seen.add(key)
|
||||||
|
resolved.append(file_path)
|
||||||
|
continue
|
||||||
|
|
||||||
|
if path.is_file():
|
||||||
|
key = str(path.resolve())
|
||||||
|
if key in seen:
|
||||||
|
continue
|
||||||
|
seen.add(key)
|
||||||
|
resolved.append(path)
|
||||||
|
|
||||||
|
return resolved
|
||||||
|
|
||||||
|
def _infer_day(self, file_path: Path):
|
||||||
|
match = self.DAY_PATTERN.search(file_path.name)
|
||||||
|
if match:
|
||||||
|
return match.group(1)
|
||||||
|
return datetime.fromtimestamp(file_path.stat().st_mtime).strftime("%Y-%m-%d")
|
||||||
|
|
||||||
|
def _game_score(self, game: dict):
|
||||||
|
max_turn = game["max_turn"]
|
||||||
|
rows = game["rows"]
|
||||||
|
avg_safe = game["avg_safe_options"]
|
||||||
|
pressure_bonus = 0 if avg_safe is None else max(0.0, 4.0 - avg_safe)
|
||||||
|
return round(max_turn * 2.0 + rows + pressure_bonus, 3)
|
||||||
|
|
||||||
|
def _pressure_score(self, game: dict):
|
||||||
|
max_turn = game["max_turn"]
|
||||||
|
rows = max(1, game["rows"])
|
||||||
|
pressure_turns = game["pressure_turns"]
|
||||||
|
avg_safe = game["avg_safe_options"]
|
||||||
|
|
||||||
|
pressure_ratio = pressure_turns / rows
|
||||||
|
safe_tightness = 0.0 if avg_safe is None else max(0.0, 3.0 - avg_safe)
|
||||||
|
return round(max_turn * 1.2 + pressure_ratio * 120.0 + safe_tightness * 20.0, 3)
|
||||||
|
|
||||||
|
def _extract_safe_options(self, row: dict):
|
||||||
|
top_level = row.get("safe_options")
|
||||||
|
if isinstance(top_level, int):
|
||||||
|
return top_level
|
||||||
|
|
||||||
|
history = row.get("history", {})
|
||||||
|
for item in history.get("data", []):
|
||||||
|
if item.get("function") != "get_possible_moves":
|
||||||
|
continue
|
||||||
|
safe_positions = item.get("safe_positions", {})
|
||||||
|
if isinstance(safe_positions, dict):
|
||||||
|
return len(safe_positions)
|
||||||
|
return None
|
||||||
|
|
||||||
|
def analyze(self):
|
||||||
|
files = self._resolve_input_files()
|
||||||
|
|
||||||
|
totals = {
|
||||||
|
"rows": 0,
|
||||||
|
"games": set(),
|
||||||
|
"snake_types": Counter(),
|
||||||
|
"game_types": Counter(),
|
||||||
|
"moves": Counter(),
|
||||||
|
"days": Counter(),
|
||||||
|
}
|
||||||
|
|
||||||
|
games = {}
|
||||||
|
day_games = defaultdict(set)
|
||||||
|
|
||||||
|
for file_path in files:
|
||||||
|
day = self._infer_day(file_path)
|
||||||
|
with file_path.open("r", encoding="utf-8") as source:
|
||||||
|
for line in source:
|
||||||
|
if not line.strip():
|
||||||
|
continue
|
||||||
|
|
||||||
|
row = json.loads(line)
|
||||||
|
game_id = row.get("game_id")
|
||||||
|
if not game_id:
|
||||||
|
continue
|
||||||
|
|
||||||
|
turn = int(row.get("turn", 0))
|
||||||
|
safe_options = self._extract_safe_options(row)
|
||||||
|
snake_type = row.get("snake_type", "unknown")
|
||||||
|
move = row.get("move", "unknown")
|
||||||
|
|
||||||
|
game_type = row.get("game_type", {})
|
||||||
|
if isinstance(game_type, dict):
|
||||||
|
game_type_name = game_type.get("name", "unknown")
|
||||||
|
else:
|
||||||
|
game_type_name = str(game_type)
|
||||||
|
|
||||||
|
totals["rows"] += 1
|
||||||
|
totals["games"].add(game_id)
|
||||||
|
totals["snake_types"][snake_type] += 1
|
||||||
|
totals["game_types"][game_type_name] += 1
|
||||||
|
totals["moves"][move] += 1
|
||||||
|
totals["days"][day] += 1
|
||||||
|
|
||||||
|
if game_id not in games:
|
||||||
|
games[game_id] = {
|
||||||
|
"game_id": game_id,
|
||||||
|
"day": day,
|
||||||
|
"snake_type": snake_type,
|
||||||
|
"game_type": game_type_name,
|
||||||
|
"rows": 0,
|
||||||
|
"max_turn": -1,
|
||||||
|
"safe_options_sum": 0,
|
||||||
|
"safe_options_count": 0,
|
||||||
|
"pressure_turns": 0,
|
||||||
|
}
|
||||||
|
|
||||||
|
game = games[game_id]
|
||||||
|
game["rows"] += 1
|
||||||
|
game["max_turn"] = max(game["max_turn"], turn)
|
||||||
|
if isinstance(safe_options, int):
|
||||||
|
game["safe_options_sum"] += safe_options
|
||||||
|
game["safe_options_count"] += 1
|
||||||
|
if safe_options <= 2:
|
||||||
|
game["pressure_turns"] += 1
|
||||||
|
|
||||||
|
day_games[day].add(game_id)
|
||||||
|
|
||||||
|
game_summaries = []
|
||||||
|
for game in games.values():
|
||||||
|
avg_safe = None
|
||||||
|
if game["safe_options_count"] > 0:
|
||||||
|
avg_safe = round(
|
||||||
|
game["safe_options_sum"] / game["safe_options_count"], 3
|
||||||
|
)
|
||||||
|
item = {
|
||||||
|
"game_id": game["game_id"],
|
||||||
|
"day": game["day"],
|
||||||
|
"snake_type": game["snake_type"],
|
||||||
|
"game_type": game["game_type"],
|
||||||
|
"rows": game["rows"],
|
||||||
|
"max_turn": game["max_turn"],
|
||||||
|
"avg_safe_options": avg_safe,
|
||||||
|
"pressure_turns": game["pressure_turns"],
|
||||||
|
}
|
||||||
|
item["score"] = self._game_score(item)
|
||||||
|
item["pressure_score"] = self._pressure_score(item)
|
||||||
|
game_summaries.append(item)
|
||||||
|
|
||||||
|
game_summaries.sort(
|
||||||
|
key=lambda x: (x["score"], x["max_turn"], x["rows"]), reverse=True
|
||||||
|
)
|
||||||
|
|
||||||
|
best_overall = game_summaries[0] if game_summaries else None
|
||||||
|
pressure_sorted = sorted(
|
||||||
|
game_summaries,
|
||||||
|
key=lambda x: (x["pressure_score"], x["max_turn"], x["rows"]),
|
||||||
|
reverse=True,
|
||||||
|
)
|
||||||
|
best_pressure_overall = pressure_sorted[0] if pressure_sorted else None
|
||||||
|
|
||||||
|
by_day = {}
|
||||||
|
for day, game_ids in sorted(day_games.items()):
|
||||||
|
day_list = [item for item in game_summaries if item["game_id"] in game_ids]
|
||||||
|
day_list.sort(
|
||||||
|
key=lambda x: (x["score"], x["max_turn"], x["rows"]), reverse=True
|
||||||
|
)
|
||||||
|
day_pressure = sorted(
|
||||||
|
day_list,
|
||||||
|
key=lambda x: (x["pressure_score"], x["max_turn"], x["rows"]),
|
||||||
|
reverse=True,
|
||||||
|
)
|
||||||
|
|
||||||
|
by_day[day] = {
|
||||||
|
"rows": totals["days"][day],
|
||||||
|
"games": len(game_ids),
|
||||||
|
"best_game": day_list[0] if day_list else None,
|
||||||
|
"best_pressure_game": day_pressure[0] if day_pressure else None,
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
"files_scanned": [str(path) for path in files],
|
||||||
|
"overall": {
|
||||||
|
"rows": totals["rows"],
|
||||||
|
"games": len(totals["games"]),
|
||||||
|
"snake_types": dict(totals["snake_types"]),
|
||||||
|
"game_types": dict(totals["game_types"]),
|
||||||
|
"moves": dict(totals["moves"]),
|
||||||
|
"best_game": best_overall,
|
||||||
|
"best_pressure_game": best_pressure_overall,
|
||||||
|
},
|
||||||
|
"by_day": by_day,
|
||||||
|
"top_games": game_summaries[:10],
|
||||||
|
"top_pressure_games": pressure_sorted[:10],
|
||||||
|
}
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
parser = argparse.ArgumentParser(description="Analyze Battlesnake JSONL datasets")
|
||||||
|
parser.add_argument(
|
||||||
|
"--input",
|
||||||
|
action="append",
|
||||||
|
required=True,
|
||||||
|
help="Input JSONL file, directory, or glob pattern. Repeat for multiple inputs.",
|
||||||
|
)
|
||||||
|
parser.add_argument(
|
||||||
|
"--output",
|
||||||
|
default=None,
|
||||||
|
help="Optional path to write JSON report",
|
||||||
|
)
|
||||||
|
args = parser.parse_args()
|
||||||
|
|
||||||
|
report = DatasetStats(args.input).analyze()
|
||||||
|
print(json.dumps(report, indent=2))
|
||||||
|
|
||||||
|
if args.output:
|
||||||
|
output_path = Path(args.output)
|
||||||
|
output_path.parent.mkdir(parents=True, exist_ok=True)
|
||||||
|
output_path.write_text(json.dumps(report, indent=2), encoding="utf-8")
|
||||||
+25
-11
@@ -1,16 +1,30 @@
|
|||||||
|
import aiofiles.os
|
||||||
|
import aiofiles
|
||||||
import os
|
import os
|
||||||
|
import inspect
|
||||||
|
|
||||||
def read_file(path, callback=None):
|
async def read_file(path: str, callback=None):
|
||||||
if os.path.exists(path):
|
if not await aiofiles.os.path.exists(path):
|
||||||
with open(path, 'r') as f:
|
|
||||||
data = callback(f)
|
|
||||||
return data
|
|
||||||
else:
|
|
||||||
return None
|
return None
|
||||||
|
|
||||||
def save_file(path, data, callback=None, *args, **kwargs):
|
async with aiofiles.open(path, "r") as f:
|
||||||
if not os.path.exists(path):
|
if callback:
|
||||||
os.makedirs(os.path.dirname(path), exist_ok=True)
|
result = callback(f)
|
||||||
|
if inspect.isawaitable(result):
|
||||||
|
return await result
|
||||||
|
return result
|
||||||
|
return await f.read()
|
||||||
|
|
||||||
with open(path, 'w') as f:
|
|
||||||
callback(data, f, *args, **kwargs)
|
async def save_file(path: str, data, callback=None, *args, **kwargs):
|
||||||
|
dir_path = os.path.dirname(path)
|
||||||
|
if dir_path:
|
||||||
|
await aiofiles.os.makedirs(dir_path, exist_ok=True)
|
||||||
|
|
||||||
|
async with aiofiles.open(path, "w") as f:
|
||||||
|
if callback:
|
||||||
|
result = callback(data, f, *args, **kwargs)
|
||||||
|
if inspect.isawaitable(result):
|
||||||
|
await result
|
||||||
|
else:
|
||||||
|
await f.write(data)
|
||||||
|
|||||||
@@ -0,0 +1,151 @@
|
|||||||
|
from datetime import datetime
|
||||||
|
|
||||||
|
class GameBoard:
|
||||||
|
def __init__(self, game_id:str, width:int, height:int, ruleset:dict, source:str, map:str, snake_class):
|
||||||
|
self.id = game_id
|
||||||
|
self.width = width
|
||||||
|
self.height = height
|
||||||
|
self.type = ruleset["name"]
|
||||||
|
self.snake_class = snake_class
|
||||||
|
|
||||||
|
# What will get Stored
|
||||||
|
self.winner_snake_names = None
|
||||||
|
self.now_date = datetime.now()
|
||||||
|
self.turns = []
|
||||||
|
self.is_ladder = True if source == "ladder" else False
|
||||||
|
self.ruleset = ruleset
|
||||||
|
self.map = map
|
||||||
|
self.url = self._get_game_url(True if ruleset["version"] == "cli" else False)
|
||||||
|
self.timeout = 500
|
||||||
|
|
||||||
|
# Setter Functions
|
||||||
|
def _set_snakes(self, snakes:list[dict]):
|
||||||
|
self.other_snakes = [ x for x in snakes if x["id"] != self.my_snake["id"] ]
|
||||||
|
|
||||||
|
def _set_my_snake(self, my_snake:dict):
|
||||||
|
self.my_snake = my_snake
|
||||||
|
|
||||||
|
def _set_food(self, food:list[dict]):
|
||||||
|
self.food = food
|
||||||
|
|
||||||
|
def _set_hazards(self, hazards:list[dict]):
|
||||||
|
self.hazards = hazards
|
||||||
|
|
||||||
|
def _set_turn(self, turn:int):
|
||||||
|
self.turn = turn
|
||||||
|
|
||||||
|
# Getter Functions
|
||||||
|
def get_other_snakes(self):
|
||||||
|
return self.other_snakes
|
||||||
|
|
||||||
|
def get_my_snake(self):
|
||||||
|
return self.my_snake
|
||||||
|
|
||||||
|
def get_food(self):
|
||||||
|
return self.food
|
||||||
|
|
||||||
|
def get_hazard(self):
|
||||||
|
return self.hazards
|
||||||
|
|
||||||
|
def get_turn(self):
|
||||||
|
return self.turn
|
||||||
|
|
||||||
|
def get_dimension(self):
|
||||||
|
return {"width": self.width, "height": self.height}
|
||||||
|
|
||||||
|
def get_width(self):
|
||||||
|
return self.width
|
||||||
|
|
||||||
|
def get_height(self):
|
||||||
|
return self.height
|
||||||
|
|
||||||
|
def get_type(self):
|
||||||
|
return self.type
|
||||||
|
|
||||||
|
def get_map(self):
|
||||||
|
return self.map
|
||||||
|
|
||||||
|
def get_ruleset(self):
|
||||||
|
return self.ruleset
|
||||||
|
|
||||||
|
def get_timeout(self):
|
||||||
|
return self.timeout
|
||||||
|
|
||||||
|
def get_my_snake_head(self):
|
||||||
|
return self.my_snake["head"]
|
||||||
|
|
||||||
|
def get_my_snake_body(self):
|
||||||
|
return self.my_snake["body"]
|
||||||
|
|
||||||
|
def get_my_snake_tail(self):
|
||||||
|
return self.my_snake["body"][-1]
|
||||||
|
|
||||||
|
def get_game_board_as_dict(self):
|
||||||
|
snakes = [self.my_snake]
|
||||||
|
snakes.extend(self.other_snakes)
|
||||||
|
|
||||||
|
return {
|
||||||
|
"height": self.height,
|
||||||
|
"width": self.width,
|
||||||
|
"snakes": snakes,
|
||||||
|
"food": self.food,
|
||||||
|
"hazards": self.hazards,
|
||||||
|
}
|
||||||
|
|
||||||
|
# Game Functions
|
||||||
|
def read_game_data(self, game_data:dict):
|
||||||
|
self._set_food(game_data['board']['food'])
|
||||||
|
self._set_hazards(game_data['board']['hazards'])
|
||||||
|
|
||||||
|
self._set_my_snake(game_data['you'])
|
||||||
|
self._set_snakes(game_data['board']['snakes'])
|
||||||
|
|
||||||
|
self._set_turn(game_data["turn"])
|
||||||
|
self.timeout = int(game_data.get('game', {}).get('timeout', 500))
|
||||||
|
|
||||||
|
async def start_game(self, game_data:dict):
|
||||||
|
self.init_snakes = len(game_data['board']['snakes'])
|
||||||
|
|
||||||
|
def end_game(self, game_data:dict):
|
||||||
|
self._set_winner_snake_name(game_data['board']['snakes'])
|
||||||
|
self.get_type_of_game()
|
||||||
|
|
||||||
|
# Function get Called from Server
|
||||||
|
def snake_neat_make_a_move(self):
|
||||||
|
move = self.snake_class.choose_move(self)
|
||||||
|
|
||||||
|
self.turns.append({
|
||||||
|
"turn": self.turn,
|
||||||
|
"move": move,
|
||||||
|
"game_board": self.get_game_board_as_dict()
|
||||||
|
})
|
||||||
|
|
||||||
|
return move
|
||||||
|
|
||||||
|
# Save functions
|
||||||
|
def _get_game_url(self, local_game:bool):
|
||||||
|
if local_game:
|
||||||
|
return None
|
||||||
|
return f"https://play.battlesnake.com/game/{self.id}"
|
||||||
|
|
||||||
|
def _set_winner_snake_name(self, snakes:list[dict]):
|
||||||
|
if self.my_snake["id"] in [ x["id"] for x in snakes]:
|
||||||
|
self.winner_snake_names = ["me"]
|
||||||
|
else:
|
||||||
|
self.winner_snake_names = [ x["name"] for x in snakes]
|
||||||
|
if len(self.winner_snake_names) == 0:
|
||||||
|
self.winner_snake_names = None
|
||||||
|
|
||||||
|
def get_winner(self):
|
||||||
|
return self.winner_snake_names
|
||||||
|
|
||||||
|
def get_type_of_game(self):
|
||||||
|
if self.init_snakes == 2:
|
||||||
|
return {"name": "duel", "is_ladder": self.is_ladder}
|
||||||
|
|
||||||
|
return {"name": self.type, "is_ladder": self.is_ladder}
|
||||||
|
|
||||||
|
async def save(self, store_class, **kwargs):
|
||||||
|
store = store_class(**kwargs)
|
||||||
|
await store.save(self)
|
||||||
|
del store
|
||||||
@@ -1,59 +0,0 @@
|
|||||||
from server.Files import save_file
|
|
||||||
import os
|
|
||||||
|
|
||||||
class GameStorage:
|
|
||||||
def __init__(self, snake:str, path:str):
|
|
||||||
self.snake_type = snake
|
|
||||||
self.folder = path
|
|
||||||
self.winner_snake_names = None
|
|
||||||
|
|
||||||
def start_new_game(self, game_type:dict, game_board:dict, snake:dict):
|
|
||||||
self.game_type = game_type
|
|
||||||
self.start_position = snake
|
|
||||||
self.game_board = [game_board]
|
|
||||||
self.moves = []
|
|
||||||
|
|
||||||
def add_moves(self, game_board:dict, my_move:str):
|
|
||||||
self.game_board.append(game_board)
|
|
||||||
self.moves.append(my_move)
|
|
||||||
|
|
||||||
def add_end_state(self, game_board:dict, snake_history_state:list[dict], final_turns:int):
|
|
||||||
self.game_board.append(game_board)
|
|
||||||
self.snake_history = snake_history_state
|
|
||||||
self._set_winner_snake_name(game_board['snakes'])
|
|
||||||
self.final_turns = final_turns
|
|
||||||
|
|
||||||
def _set_winner_snake_name(self, snakes:list[dict]):
|
|
||||||
if self.start_position["id"] in [ x["id"] for x in snakes]:
|
|
||||||
self.winner_snake_names = "me"
|
|
||||||
else:
|
|
||||||
self.winner_snake_names = [ x["name"] for x in snakes]
|
|
||||||
|
|
||||||
def _get_type_of_gameboard(self):
|
|
||||||
if len(self.game_board[0]["snakes"]) == 2:
|
|
||||||
return "duel"
|
|
||||||
|
|
||||||
return "standart"
|
|
||||||
|
|
||||||
def save(self, path:str, callback=None, **kwargs):
|
|
||||||
if self.winner_snake_names == "me" and self.final_turns <= 10:
|
|
||||||
return None
|
|
||||||
|
|
||||||
save_file(os.path.join(self.folder, path), {
|
|
||||||
"snake": {
|
|
||||||
"type": self.snake_type,
|
|
||||||
"choices": self.snake_history,
|
|
||||||
},
|
|
||||||
"game": {
|
|
||||||
"type": self._get_type_of_gameboard(),
|
|
||||||
"infos": self.game_type,
|
|
||||||
"snake_start": self.start_position,
|
|
||||||
"final_turns": self.final_turns,
|
|
||||||
"gameboard": self.game_board,
|
|
||||||
"my_moves": self.moves,
|
|
||||||
},
|
|
||||||
"winner": self.winner_snake_names,
|
|
||||||
}, callback=callback, **kwargs)
|
|
||||||
|
|
||||||
def __str__(self):
|
|
||||||
return f"<{self.__class__.__name__}> Snake: {self.snake_type}, Folder: {self.folder}, Winner: {self.winner_snake_names}, Old Moves: {self.moves}"
|
|
||||||
+406
-77
@@ -1,113 +1,442 @@
|
|||||||
from server.Files import read_file, save_file
|
from server.Files import read_file
|
||||||
from server.GameStorage import GameStorage
|
from server.GameBoard import GameBoard
|
||||||
from snakes.TemplateSnake import TemplateSnake
|
from snakes import SnakeBuilder
|
||||||
from server.SnakeBuilder import SnakeBuilder
|
from quart_common.web.logger import await_log
|
||||||
|
from quart_common.web.logger import build_logger
|
||||||
|
from typing import cast
|
||||||
|
|
||||||
from datetime import datetime
|
from server.storage.StorageLoader import StorageLoader
|
||||||
from flask import Flask
|
|
||||||
from flask import request
|
from quart import Quart, request, jsonify
|
||||||
import logging, json, os
|
import logging, json, os, re, time
|
||||||
|
|
||||||
class Server:
|
class Server:
|
||||||
default_snake_config = {"apiversion":"1","author":"","color":"#888888","head":"default","tail":"default"}
|
default_snake_config = {
|
||||||
|
'apiversion': '1',
|
||||||
|
'author': '',
|
||||||
|
'color': '#888888',
|
||||||
|
'head': 'default',
|
||||||
|
'tail': 'default',
|
||||||
|
'version': '1.0.0',
|
||||||
|
}
|
||||||
|
|
||||||
def __init__(self, data_path:str, snake_type:str, debug:bool=False):
|
def __init__(self, data_path:str, snake_type:str, storage_type:str, debug:bool=False, check_tls_security:bool=False):
|
||||||
self.debug = debug
|
self.debug = debug
|
||||||
self.snake_type = snake_type
|
self.snake_type = snake_type
|
||||||
|
self.storage_type = storage_type
|
||||||
|
|
||||||
self.config_file = os.path.join(data_path, 'data', 'snake-config.json')
|
self.config_file = os.path.join(data_path, 'data', 'snake-config.json')
|
||||||
self.data_path = data_path
|
self.data_path = data_path
|
||||||
|
self.check_tls_security = check_tls_security
|
||||||
|
|
||||||
self.store_game_state = False
|
self.store_game_state = False
|
||||||
self.running_games:dict[str, GameStorage] = {}
|
|
||||||
self.running_snake:dict[str, TemplateSnake] = {}
|
|
||||||
|
|
||||||
self.app = Flask("Battlesnake")
|
self.running_games:dict[str, GameBoard] = {}
|
||||||
|
self.game_move_counts:dict[str, int] = {}
|
||||||
|
self.game_last_seen_unix:dict[str, int] = {}
|
||||||
|
self.stale_game_timeout_sec = self._get_stale_game_timeout_sec()
|
||||||
|
self.metrics = {
|
||||||
|
'games_started': 0,
|
||||||
|
'games_ended': 0,
|
||||||
|
'wins': 0,
|
||||||
|
'losses': 0,
|
||||||
|
'total_moves': 0,
|
||||||
|
'total_turns': 0,
|
||||||
|
'max_turn': 0,
|
||||||
|
'active_games_peak': 0,
|
||||||
|
'games_autocreated': 0,
|
||||||
|
'http_requests_total': 0,
|
||||||
|
'http_requests_by_endpoint': {
|
||||||
|
'info': 0,
|
||||||
|
'start': 0,
|
||||||
|
'move': 0,
|
||||||
|
'end': 0,
|
||||||
|
},
|
||||||
|
'move_direction_counts': {
|
||||||
|
'up': 0,
|
||||||
|
'down': 0,
|
||||||
|
'left': 0,
|
||||||
|
'right': 0,
|
||||||
|
'unknown': 0,
|
||||||
|
},
|
||||||
|
'move_response_time_ms_total': 0.0,
|
||||||
|
'move_response_time_ms_max': 0.0,
|
||||||
|
'last_game_start_unix': 0,
|
||||||
|
'last_game_end_unix': 0,
|
||||||
|
'last_move_unix': 0,
|
||||||
|
'games_stuck_removed': 0,
|
||||||
|
}
|
||||||
|
self.logger = build_logger('Battlesnake', debug_env_var='DEBUG_SERVER')
|
||||||
|
self.snake_version = self._get_snake_version()
|
||||||
|
|
||||||
@self.app.get("/")
|
self.app = Quart('Battlesnake')
|
||||||
def on_info():
|
|
||||||
return self._info()
|
|
||||||
|
|
||||||
@self.app.post("/start")
|
# info is called when you create your Battlesnake on play.battlesnake.com
|
||||||
def on_start():
|
# and controls your Battlesnake's appearance
|
||||||
game_state = request.get_json()
|
# TIP: If you open your Battlesnake URL in a browser you should see this data
|
||||||
self._start(game_state)
|
@self.app.get('/')
|
||||||
return "ok"
|
async def on_info():
|
||||||
|
self._record_http_request('info')
|
||||||
|
snake_config = await self._read_json_config_or_create()
|
||||||
|
|
||||||
@self.app.post("/move")
|
await await_log(self.logger.info(f'INFO Snake: {snake_config}'))
|
||||||
def on_move():
|
return snake_config
|
||||||
game_state = request.get_json()
|
|
||||||
return self._move(game_state)
|
|
||||||
|
|
||||||
@self.app.post("/end")
|
# start is called when your Battlesnake begins a game
|
||||||
def on_end():
|
@self.app.post('/start')
|
||||||
game_state = request.get_json()
|
async def on_start():
|
||||||
self._end(game_state)
|
self._record_http_request('start')
|
||||||
return "ok"
|
self._prune_stale_games()
|
||||||
|
game_state = await request.get_json()
|
||||||
|
await self._create_game_board(game_state)
|
||||||
|
await await_log(self.logger.info(f'GAME START: {game_state['game']}'))
|
||||||
|
return 'ok'
|
||||||
|
|
||||||
|
# move is called when your Battlesnake game is running game
|
||||||
|
@self.app.post('/move')
|
||||||
|
async def on_move():
|
||||||
|
self._record_http_request('move')
|
||||||
|
game_state = await request.get_json()
|
||||||
|
move_started = time.perf_counter()
|
||||||
|
game_board = await self._get_game_board(game_state)
|
||||||
|
next_move = game_board.snake_neat_make_a_move()
|
||||||
|
elapsed_ms = (time.perf_counter() - move_started) * 1000.0
|
||||||
|
self.metrics['move_response_time_ms_total'] += elapsed_ms
|
||||||
|
self.metrics['move_response_time_ms_max'] = max(
|
||||||
|
self.metrics['move_response_time_ms_max'],
|
||||||
|
elapsed_ms,
|
||||||
|
)
|
||||||
|
|
||||||
|
move_counts = self.metrics['move_direction_counts']
|
||||||
|
if next_move in move_counts:
|
||||||
|
move_counts[next_move] += 1
|
||||||
|
else:
|
||||||
|
move_counts['unknown'] += 1
|
||||||
|
self.metrics['last_move_unix'] = int(time.time())
|
||||||
|
|
||||||
|
if self.debug:
|
||||||
|
await await_log(self.logger.debug(f'TURN: {game_state['turn']:3}, MOVE: {next_move:5}'))
|
||||||
|
|
||||||
|
return {'move': next_move}
|
||||||
|
|
||||||
|
# end is called when your Battlesnake finishes a game
|
||||||
|
@self.app.post('/end')
|
||||||
|
async def on_end():
|
||||||
|
self._record_http_request('end')
|
||||||
|
self._prune_stale_games()
|
||||||
|
game_state = await request.get_json()
|
||||||
|
if self.store_game_state:
|
||||||
|
game_board = await self._get_game_board(game_state, end=True)
|
||||||
|
if self.check_tls_security:
|
||||||
|
await game_board.save(
|
||||||
|
StorageLoader.build(self.storage_type),
|
||||||
|
file_path=os.path.join(self.data_path, 'data'),
|
||||||
|
database=os.getenv('EDGEDB_DATABASE', None),
|
||||||
|
tls_security=None,
|
||||||
|
)
|
||||||
|
else:
|
||||||
|
await game_board.save(
|
||||||
|
StorageLoader.build(self.storage_type),
|
||||||
|
file_path=os.path.join(self.data_path, 'data'),
|
||||||
|
database=os.getenv('EDGEDB_DATABASE', None),
|
||||||
|
)
|
||||||
|
|
||||||
|
await await_log(self.logger.info(f'GAME ENDED: Winner is {[x['name'] for x in game_state['board']['snakes']]}'))
|
||||||
|
self._delete_game_board(game_state)
|
||||||
|
return 'ok'
|
||||||
|
|
||||||
@self.app.after_request
|
@self.app.after_request
|
||||||
def identify_server(response):
|
async def identify_server(response):
|
||||||
response.headers.set(
|
response.headers.set('server', 'battlesnake/gitea/snake-python')
|
||||||
"server", "battlesnake/github/starter-snake-python"
|
|
||||||
)
|
|
||||||
return response
|
return response
|
||||||
|
|
||||||
def run(self, host:str="0.0.0.0", port:str="8000", debug:bool=False):
|
@self.app.get('/cleanup')
|
||||||
logging.getLogger("werkzeug").setLevel(logging.ERROR)
|
async def cleanup():
|
||||||
|
results = self._cleanup_database()
|
||||||
|
return jsonify(data=json.loads(results), status=200)
|
||||||
|
|
||||||
print(f"\nRunning Battlesnake at http://{host}:{port} with the {self.snake_type.replace('Snake', '')} Snake")
|
@self.app.get('/metrics')
|
||||||
self.app.run(host=host, port=port, debug=debug)
|
async def metrics():
|
||||||
|
return jsonify(self._build_metrics())
|
||||||
|
|
||||||
def _read_json_config_or_create(self):
|
@self.app.get('/metrics/prometheus')
|
||||||
snake_config = read_file(self.config_file, json.load)
|
async def metrics_prometheus():
|
||||||
|
return (
|
||||||
|
self._build_prometheus_metrics(),
|
||||||
|
200,
|
||||||
|
{'Content-Type': 'text/plain; version=0.0.4; charset=utf-8'},
|
||||||
|
)
|
||||||
|
|
||||||
|
async def run(self, host:str='0.0.0.0', port:int=8000, debug:bool=False):
|
||||||
|
logging.getLogger('werkzeug').setLevel(logging.ERROR)
|
||||||
|
|
||||||
|
await await_log(self.logger.info(f'Running Battlesnake at http://{host}:{port} with the {" ".join(re.findall("[A-Z][^A-Z]*", self.snake_type))}'))
|
||||||
|
await self.app.run_task(host=host, port=port, debug=debug)
|
||||||
|
|
||||||
|
async def _read_json_config_or_create(self) -> dict[str, str]:
|
||||||
|
snake_config = cast(dict[str, str]|None, await read_file(self.config_file, json.load))
|
||||||
if not snake_config:
|
if not snake_config:
|
||||||
snake_config = self.default_snake_config
|
return await self._override_snake_config_with_environment_variables(self.default_snake_config)
|
||||||
save_file(self.config_file, snake_config, callback=json.dump, indent=2, ensure_ascii=False)
|
return await self._override_snake_config_with_environment_variables(snake_config)
|
||||||
return snake_config
|
|
||||||
|
async def _override_snake_config_with_environment_variables(self, config:dict[str, str]) -> dict[str, str]:
|
||||||
|
config['version'] = self.snake_version
|
||||||
|
|
||||||
|
for key in ('author', 'color', 'head', 'tail'):
|
||||||
|
value = os.environ.get(f'SNAKE_{key.upper()}')
|
||||||
|
if value is not None:
|
||||||
|
config[key] = value
|
||||||
|
|
||||||
|
version_override = os.environ.get('SNAKE_VERSION')
|
||||||
|
if version_override is not None:
|
||||||
|
config['version'] = version_override
|
||||||
|
|
||||||
|
return config
|
||||||
|
|
||||||
|
def _get_snake_version(self) -> str:
|
||||||
|
configured_version = SnakeBuilder.get_version(self.snake_type)
|
||||||
|
if configured_version:
|
||||||
|
return configured_version
|
||||||
|
|
||||||
|
try:
|
||||||
|
snake = SnakeBuilder.build(self.snake_type)
|
||||||
|
except Exception:
|
||||||
|
return self.default_snake_config['version']
|
||||||
|
|
||||||
|
version = getattr(snake, 'version', None)
|
||||||
|
if version is None:
|
||||||
|
version = getattr(snake, 'VERSION', None)
|
||||||
|
if not version:
|
||||||
|
return self.default_snake_config['version']
|
||||||
|
return str(version)
|
||||||
|
|
||||||
|
def _get_stale_game_timeout_sec(self) -> int:
|
||||||
|
value = os.getenv('SNAKE_STUCK_GAME_TIMEOUT_SEC', '180')
|
||||||
|
try:
|
||||||
|
return max(30, int(value))
|
||||||
|
except ValueError:
|
||||||
|
return 180
|
||||||
|
|
||||||
|
async def _create_game_board(self, game_state: dict):
|
||||||
|
game_id = game_state['game']['id']
|
||||||
|
new_game_board = GameBoard(
|
||||||
|
game_id=game_id,
|
||||||
|
width=game_state['board']['width'],
|
||||||
|
height=game_state['board']['height'],
|
||||||
|
ruleset=game_state['game']['ruleset'],
|
||||||
|
source=game_state['game']['source'],
|
||||||
|
map=game_state['game']['map'],
|
||||||
|
snake_class=SnakeBuilder.build(self.snake_type),
|
||||||
|
)
|
||||||
|
await new_game_board.start_game(game_state)
|
||||||
|
|
||||||
|
self.running_games[game_id] = new_game_board
|
||||||
|
self.game_move_counts[game_id] = 0
|
||||||
|
self.game_last_seen_unix[game_id] = int(time.time())
|
||||||
|
self.metrics['games_started'] += 1
|
||||||
|
self.metrics['active_games_peak'] = max(
|
||||||
|
self.metrics['active_games_peak'],
|
||||||
|
len(self.running_games),
|
||||||
|
)
|
||||||
|
self.metrics['last_game_start_unix'] = int(time.time())
|
||||||
|
return new_game_board
|
||||||
|
|
||||||
|
def _delete_game_board(self, game_state:dict):
|
||||||
|
game_id = game_state['game']['id']
|
||||||
|
self.running_games.pop(game_id, None)
|
||||||
|
self.game_move_counts.pop(game_id, None)
|
||||||
|
self.game_last_seen_unix.pop(game_id, None)
|
||||||
|
|
||||||
|
async def _get_game_board(self, game_state:dict, end:bool=False):
|
||||||
|
game_id = game_state['game']['id']
|
||||||
|
try:
|
||||||
|
game_board = self.running_games[game_id]
|
||||||
|
except KeyError:
|
||||||
|
game_board = await self._create_game_board(game_state)
|
||||||
|
self.metrics['games_autocreated'] += 1
|
||||||
|
|
||||||
|
if not end:
|
||||||
|
self.metrics['total_moves'] += 1
|
||||||
|
self.game_move_counts[game_id] = self.game_move_counts.get(game_id, 0) + 1
|
||||||
|
|
||||||
|
self.game_last_seen_unix[game_id] = int(time.time())
|
||||||
|
|
||||||
|
game_board.read_game_data(game_state)
|
||||||
|
if end:
|
||||||
|
self._record_game_end(game_state)
|
||||||
|
game_board.end_game(game_state)
|
||||||
|
|
||||||
|
return game_board
|
||||||
|
|
||||||
def enable_store_game_state(self):
|
def enable_store_game_state(self):
|
||||||
self.store_game_state = True
|
self.store_game_state = True
|
||||||
|
|
||||||
# info is called when you create your Battlesnake on play.battlesnake.com
|
def _cleanup_database(self):
|
||||||
# and controls your Battlesnake's appearance
|
storage = StorageLoader.build(self.storage_type)()
|
||||||
# TIP: If you open your Battlesnake URL in a browser you should see this data
|
return storage.cleanup()
|
||||||
def _info(self) -> dict:
|
|
||||||
snake_config = self._read_json_config_or_create()
|
|
||||||
print("INFO Snake:", snake_config)
|
|
||||||
return snake_config
|
|
||||||
|
|
||||||
# start is called when your Battlesnake begins a game
|
def _prune_stale_games(self):
|
||||||
def _start(self, game_state:dict):
|
if not self.running_games:
|
||||||
if self.store_game_state:
|
return
|
||||||
self.running_games[game_state["game"]["id"]] = GameStorage(self.snake.__class__.__name__, path=os.path.join(self.data_path, 'data', 'history'))
|
|
||||||
self.running_games[game_state["game"]["id"]].start_new_game(game_state["game"], game_state["board"], game_state["you"])
|
|
||||||
|
|
||||||
self.running_snake[game_state["game"]["id"]] = SnakeBuilder.build(self.snake_type)
|
now = int(time.time())
|
||||||
print("GAME START:", game_state["game"])
|
stale_ids = [
|
||||||
|
game_id
|
||||||
|
for game_id, last_seen in self.game_last_seen_unix.items()
|
||||||
|
if now - last_seen >= self.stale_game_timeout_sec
|
||||||
|
]
|
||||||
|
for game_id in stale_ids:
|
||||||
|
self.running_games.pop(game_id, None)
|
||||||
|
self.game_move_counts.pop(game_id, None)
|
||||||
|
self.game_last_seen_unix.pop(game_id, None)
|
||||||
|
self.metrics['games_stuck_removed'] += 1
|
||||||
|
|
||||||
# move is called when your Battlesnake game is running game
|
def _record_game_end(self, game_state: dict):
|
||||||
def _move(self, game_state:dict) -> dict:
|
self.metrics['games_ended'] += 1
|
||||||
next_move = self.running_snake[game_state["game"]["id"]].choose_move(game_state)
|
self.metrics['last_game_end_unix'] = int(time.time())
|
||||||
|
|
||||||
if self.store_game_state:
|
final_turn = int(game_state.get('turn', 0))
|
||||||
self.running_games[game_state["game"]["id"]].add_moves(game_state["board"], next_move)
|
self.metrics['total_turns'] += final_turn
|
||||||
if self.debug:
|
self.metrics['max_turn'] = max(self.metrics['max_turn'], final_turn)
|
||||||
print(self.running_games[game_state["game"]["id"]])
|
|
||||||
|
|
||||||
print("MOVE:", f"{next_move:5},", "Me:", {"head": game_state["you"]["head"], "length": game_state["you"]["length"]})
|
you_id = game_state.get('you', {}).get('id')
|
||||||
return {"move": next_move}
|
alive_snakes = game_state.get('board', {}).get('snakes', [])
|
||||||
|
alive_ids = {snake.get('id') for snake in alive_snakes}
|
||||||
|
|
||||||
# end is called when your Battlesnake finishes a game
|
if you_id and you_id in alive_ids:
|
||||||
def _end(self, game_state:dict):
|
self.metrics['wins'] += 1
|
||||||
if self.store_game_state:
|
else:
|
||||||
snake = self.running_snake[game_state["game"]["id"]]
|
self.metrics['losses'] += 1
|
||||||
|
|
||||||
self.running_games[game_state["game"]["id"]].add_end_state(game_state["board"], snake.get_history(), game_state["turn"])
|
def _build_metrics(self) -> dict:
|
||||||
self.running_games[game_state["game"]["id"]].save(
|
games_ended = self.metrics['games_ended']
|
||||||
f"{snake.__class__.__name__}_{datetime.now().strftime('%d.%m.%Y_%H%M%S')}_{game_state['game']['id']}.json",
|
total_moves = self.metrics['total_moves']
|
||||||
callback=json.dump, indent=2, ensure_ascii=False
|
avg_turns = self.metrics['total_turns'] / games_ended if games_ended else 0.0
|
||||||
|
win_rate = self.metrics['wins'] / games_ended if games_ended else 0.0
|
||||||
|
avg_move_ms = self.metrics['move_response_time_ms_total'] / total_moves if total_moves else 0.0
|
||||||
|
|
||||||
|
now = int(time.time())
|
||||||
|
oldest_active_age = 0
|
||||||
|
if self.game_last_seen_unix:
|
||||||
|
oldest_active_age = max(0, now - min(self.game_last_seen_unix.values()))
|
||||||
|
stale_candidates = sum(
|
||||||
|
1
|
||||||
|
for last_seen in self.game_last_seen_unix.values()
|
||||||
|
if now - last_seen >= self.stale_game_timeout_sec
|
||||||
|
)
|
||||||
|
|
||||||
|
return {
|
||||||
|
**self.metrics,
|
||||||
|
'active_games': len(self.running_games),
|
||||||
|
'tracked_games': len(self.game_move_counts),
|
||||||
|
'avg_turns_per_game': round(avg_turns, 2),
|
||||||
|
'win_rate': round(win_rate, 4),
|
||||||
|
'avg_move_response_ms': round(avg_move_ms, 2),
|
||||||
|
'http_requests_by_endpoint': dict(self.metrics['http_requests_by_endpoint']),
|
||||||
|
'move_direction_counts': dict(self.metrics['move_direction_counts']),
|
||||||
|
'oldest_active_game_age_sec': oldest_active_age,
|
||||||
|
'stale_game_timeout_sec': self.stale_game_timeout_sec,
|
||||||
|
'active_games_stale': stale_candidates,
|
||||||
|
}
|
||||||
|
|
||||||
|
def _record_http_request(self, endpoint:str):
|
||||||
|
self.metrics['http_requests_total'] += 1
|
||||||
|
endpoint_counts = self.metrics['http_requests_by_endpoint']
|
||||||
|
endpoint_counts[endpoint] = endpoint_counts.get(endpoint, 0) + 1
|
||||||
|
|
||||||
|
def _build_prometheus_metrics(self) -> str:
|
||||||
|
snapshot = self._build_metrics()
|
||||||
|
lines = [
|
||||||
|
'# HELP snake_games_started_total Total games started by snake server.',
|
||||||
|
'# TYPE snake_games_started_total counter',
|
||||||
|
f'snake_games_started_total {snapshot['games_started']}',
|
||||||
|
'# HELP snake_games_ended_total Total games ended by snake server.',
|
||||||
|
'# TYPE snake_games_ended_total counter',
|
||||||
|
f'snake_games_ended_total {snapshot['games_ended']}',
|
||||||
|
'# HELP snake_wins_total Total games won by this snake.',
|
||||||
|
'# TYPE snake_wins_total counter',
|
||||||
|
f'snake_wins_total {snapshot['wins']}',
|
||||||
|
'# HELP snake_losses_total Total games lost by this snake.',
|
||||||
|
'# TYPE snake_losses_total counter',
|
||||||
|
f'snake_losses_total {snapshot['losses']}',
|
||||||
|
'# HELP snake_moves_total Total move decisions served by /move.',
|
||||||
|
'# TYPE snake_moves_total counter',
|
||||||
|
f'snake_moves_total {snapshot['total_moves']}',
|
||||||
|
'# HELP snake_turns_total Total turns across all ended games.',
|
||||||
|
'# TYPE snake_turns_total counter',
|
||||||
|
f'snake_turns_total {snapshot['total_turns']}',
|
||||||
|
'# HELP snake_active_games Currently active games in memory.',
|
||||||
|
'# TYPE snake_active_games gauge',
|
||||||
|
f'snake_active_games {snapshot['active_games']}',
|
||||||
|
'# HELP snake_tracked_games Currently tracked game IDs for move counters.',
|
||||||
|
'# TYPE snake_tracked_games gauge',
|
||||||
|
f'snake_tracked_games {snapshot['tracked_games']}',
|
||||||
|
'# HELP snake_max_turn Highest final turn seen in an ended game.',
|
||||||
|
'# TYPE snake_max_turn gauge',
|
||||||
|
f'snake_max_turn {snapshot['max_turn']}',
|
||||||
|
'# HELP snake_active_games_peak Highest active game count observed.',
|
||||||
|
'# TYPE snake_active_games_peak gauge',
|
||||||
|
f'snake_active_games_peak {snapshot['active_games_peak']}',
|
||||||
|
'# HELP snake_games_autocreated_total Games created on /move or /end due to missing /start.',
|
||||||
|
'# TYPE snake_games_autocreated_total counter',
|
||||||
|
f'snake_games_autocreated_total {snapshot['games_autocreated']}',
|
||||||
|
'# HELP snake_http_requests_total Total HTTP requests handled by this process.',
|
||||||
|
'# TYPE snake_http_requests_total counter',
|
||||||
|
f'snake_http_requests_total {snapshot['http_requests_total']}',
|
||||||
|
'# HELP snake_move_response_ms_total Total move endpoint compute time in milliseconds.',
|
||||||
|
'# TYPE snake_move_response_ms_total counter',
|
||||||
|
f'snake_move_response_ms_total {round(snapshot['move_response_time_ms_total'], 3)}',
|
||||||
|
'# HELP snake_move_response_ms_max Maximum move endpoint compute time in milliseconds.',
|
||||||
|
'# TYPE snake_move_response_ms_max gauge',
|
||||||
|
f'snake_move_response_ms_max {round(snapshot['move_response_time_ms_max'], 3)}',
|
||||||
|
'# HELP snake_avg_turns_per_game Average final turn per ended game.',
|
||||||
|
'# TYPE snake_avg_turns_per_game gauge',
|
||||||
|
f'snake_avg_turns_per_game {snapshot['avg_turns_per_game']}',
|
||||||
|
'# HELP snake_avg_move_response_ms Average move endpoint compute time in milliseconds.',
|
||||||
|
'# TYPE snake_avg_move_response_ms gauge',
|
||||||
|
f'snake_avg_move_response_ms {snapshot['avg_move_response_ms']}',
|
||||||
|
'# HELP snake_win_rate Win ratio from ended games (0.0 - 1.0).',
|
||||||
|
'# TYPE snake_win_rate gauge',
|
||||||
|
f'snake_win_rate {snapshot['win_rate']}',
|
||||||
|
'# HELP snake_last_game_start_unix Unix timestamp of most recent /start request.',
|
||||||
|
'# TYPE snake_last_game_start_unix gauge',
|
||||||
|
f'snake_last_game_start_unix {snapshot['last_game_start_unix']}',
|
||||||
|
'# HELP snake_last_game_end_unix Unix timestamp of most recent /end request.',
|
||||||
|
'# TYPE snake_last_game_end_unix gauge',
|
||||||
|
f'snake_last_game_end_unix {snapshot['last_game_end_unix']}',
|
||||||
|
'# HELP snake_last_move_unix Unix timestamp of most recent /move response.',
|
||||||
|
'# TYPE snake_last_move_unix gauge',
|
||||||
|
f'snake_last_move_unix {snapshot['last_move_unix']}',
|
||||||
|
'# HELP snake_games_stuck_removed_total Active games auto-removed due to inactivity timeout.',
|
||||||
|
'# TYPE snake_games_stuck_removed_total counter',
|
||||||
|
f'snake_games_stuck_removed_total {snapshot['games_stuck_removed']}',
|
||||||
|
'# HELP snake_oldest_active_game_age_sec Age in seconds of the oldest active game.',
|
||||||
|
'# TYPE snake_oldest_active_game_age_sec gauge',
|
||||||
|
f'snake_oldest_active_game_age_sec {snapshot['oldest_active_game_age_sec']}',
|
||||||
|
'# HELP snake_stale_game_timeout_sec Configured inactivity timeout for stale games.',
|
||||||
|
'# TYPE snake_stale_game_timeout_sec gauge',
|
||||||
|
f'snake_stale_game_timeout_sec {snapshot['stale_game_timeout_sec']}',
|
||||||
|
'# HELP snake_active_games_stale Active games currently beyond stale timeout.',
|
||||||
|
'# TYPE snake_active_games_stale gauge',
|
||||||
|
f'snake_active_games_stale {snapshot['active_games_stale']}',
|
||||||
|
]
|
||||||
|
|
||||||
|
lines.extend([
|
||||||
|
'# HELP snake_http_requests_by_endpoint_total Requests served grouped by endpoint.',
|
||||||
|
'# TYPE snake_http_requests_by_endpoint_total counter',
|
||||||
|
])
|
||||||
|
for endpoint, count in snapshot['http_requests_by_endpoint'].items():
|
||||||
|
lines.append(
|
||||||
|
f'snake_http_requests_by_endpoint_total{{endpoint="{endpoint}"}} {count}'
|
||||||
)
|
)
|
||||||
del self.running_games[game_state["game"]["id"]]
|
|
||||||
|
|
||||||
print("GAME OVER:\n- Winner is", [ x["name"] for x in game_state["board"]['snakes']])
|
lines.extend([
|
||||||
del self.running_snake[game_state["game"]["id"]]
|
'# HELP snake_moves_by_direction_total Move responses grouped by direction.',
|
||||||
|
'# TYPE snake_moves_by_direction_total counter',
|
||||||
|
])
|
||||||
|
for direction, count in snapshot['move_direction_counts'].items():
|
||||||
|
lines.append(
|
||||||
|
f'snake_moves_by_direction_total{{direction="{direction}"}} {count}'
|
||||||
|
)
|
||||||
|
|
||||||
|
return '\n'.join(lines) + '\n'
|
||||||
|
|||||||
@@ -1,7 +0,0 @@
|
|||||||
|
|
||||||
class SnakeBuilder:
|
|
||||||
@classmethod
|
|
||||||
def build(self, selected_snake:str):
|
|
||||||
snake_module = __import__(f'snakes.{selected_snake}', fromlist=[selected_snake])
|
|
||||||
snake_class = getattr(snake_module, selected_snake)
|
|
||||||
return snake_class()
|
|
||||||
@@ -0,0 +1,290 @@
|
|||||||
|
import argparse, random, glob, json, math
|
||||||
|
from collections import Counter
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
MOVES = ["up", "down", "left", "right"]
|
||||||
|
|
||||||
|
def resolve_input_files(inputs:list[str]) -> list[Path]:
|
||||||
|
resolved:list[Path] = []
|
||||||
|
seen:set[str] = set()
|
||||||
|
|
||||||
|
for item in inputs:
|
||||||
|
path = Path(item)
|
||||||
|
if path.is_dir():
|
||||||
|
for file_path in sorted(path.rglob("*.jsonl")):
|
||||||
|
key = str(file_path.resolve())
|
||||||
|
if key in seen:
|
||||||
|
continue
|
||||||
|
seen.add(key)
|
||||||
|
resolved.append(file_path)
|
||||||
|
continue
|
||||||
|
|
||||||
|
if any(ch in item for ch in "*?[]"):
|
||||||
|
for match in sorted(glob.glob(item)):
|
||||||
|
file_path = Path(match)
|
||||||
|
if not file_path.is_file():
|
||||||
|
continue
|
||||||
|
key = str(file_path.resolve())
|
||||||
|
if key in seen:
|
||||||
|
continue
|
||||||
|
seen.add(key)
|
||||||
|
resolved.append(file_path)
|
||||||
|
continue
|
||||||
|
|
||||||
|
if path.is_file():
|
||||||
|
key = str(path.resolve())
|
||||||
|
if key in seen:
|
||||||
|
continue
|
||||||
|
seen.add(key)
|
||||||
|
resolved.append(path)
|
||||||
|
|
||||||
|
return resolved
|
||||||
|
|
||||||
|
def _neighbors(x:int, y:int) -> list[tuple[int, int, str]]:
|
||||||
|
return [
|
||||||
|
(x, y + 1, "up"),
|
||||||
|
(x, y - 1, "down"),
|
||||||
|
(x - 1, y, "left"),
|
||||||
|
(x + 1, y, "right"),
|
||||||
|
]
|
||||||
|
|
||||||
|
def _safe_neighbor_count(point:tuple[int, int], blocked:set[tuple[int, int]], width:int, height:int) -> int:
|
||||||
|
count = 0
|
||||||
|
for nx, ny, _ in _neighbors(point[0], point[1]):
|
||||||
|
if not (0 <= nx < width and 0 <= ny < height):
|
||||||
|
continue
|
||||||
|
if (nx, ny) in blocked:
|
||||||
|
continue
|
||||||
|
count += 1
|
||||||
|
return count
|
||||||
|
|
||||||
|
def _manhattan_to_nearest_food(point: tuple[int, int], food: set[tuple[int, int]]) -> int:
|
||||||
|
if not food:
|
||||||
|
return 25
|
||||||
|
return min(abs(point[0] - fx) + abs(point[1] - fy) for fx, fy in food)
|
||||||
|
|
||||||
|
def extract_feature_values(row:dict) -> dict[str, float]:
|
||||||
|
board = row.get("game_board", {})
|
||||||
|
snakes = board.get("snakes", [])
|
||||||
|
if not snakes:
|
||||||
|
return {}
|
||||||
|
|
||||||
|
me = snakes[0]
|
||||||
|
body = me.get("body", [])
|
||||||
|
if not body:
|
||||||
|
return {}
|
||||||
|
|
||||||
|
width = int(board.get("width", 0))
|
||||||
|
height = int(board.get("height", 0))
|
||||||
|
head = body[0]
|
||||||
|
hx = int(head.get("x", 0))
|
||||||
|
hy = int(head.get("y", 0))
|
||||||
|
health = int(me.get("health", 100))
|
||||||
|
length = int(me.get("length", len(body)))
|
||||||
|
|
||||||
|
food_set = {(int(f.get("x", 0)), int(f.get("y", 0))) for f in board.get("food", [])}
|
||||||
|
hazard_set = {(int(h.get("x", 0)), int(h.get("y", 0))) for h in board.get("hazards", [])}
|
||||||
|
blocked = set()
|
||||||
|
for snake in snakes:
|
||||||
|
for seg in snake.get("body", []):
|
||||||
|
blocked.add((int(seg.get("x", 0)), int(seg.get("y", 0))))
|
||||||
|
|
||||||
|
features:dict[str, float] = {
|
||||||
|
"bias": 1.0,
|
||||||
|
"health_norm": max(0.0, min(1.0, health / 100.0)),
|
||||||
|
"length_norm": min(1.0, length / max(1.0, width * height)),
|
||||||
|
"turn_norm": min(1.0, int(row.get("turn", 0)) / 100.0),
|
||||||
|
"food_count_norm": min(1.0, len(food_set) / 10.0),
|
||||||
|
"hazard_count_norm": min(1.0, len(hazard_set) / 20.0),
|
||||||
|
"opponent_count_norm": min(1.0, max(0, len(snakes) - 1) / 7.0),
|
||||||
|
}
|
||||||
|
|
||||||
|
safe_total = 0
|
||||||
|
for nx, ny, move in _neighbors(hx, hy):
|
||||||
|
in_bounds = 1.0 if (0 <= nx < width and 0 <= ny < height) else 0.0
|
||||||
|
blocked_next = 1.0 if (nx, ny) in blocked else 0.0
|
||||||
|
food_next = 1.0 if (nx, ny) in food_set else 0.0
|
||||||
|
hazard_next = 1.0 if (nx, ny) in hazard_set else 0.0
|
||||||
|
|
||||||
|
if in_bounds and not blocked_next:
|
||||||
|
safe_total += 1
|
||||||
|
open_next = float(_safe_neighbor_count((nx, ny), blocked, width, height))
|
||||||
|
dist_food = float(_manhattan_to_nearest_food((nx, ny), food_set))
|
||||||
|
else:
|
||||||
|
open_next = 0.0
|
||||||
|
dist_food = 25.0
|
||||||
|
|
||||||
|
prefix = f"m:{move}:"
|
||||||
|
features[prefix + "in_bounds"] = in_bounds
|
||||||
|
features[prefix + "blocked"] = blocked_next
|
||||||
|
features[prefix + "food"] = food_next
|
||||||
|
features[prefix + "hazard"] = hazard_next
|
||||||
|
features[prefix + "open_next"] = min(4.0, open_next) / 4.0
|
||||||
|
features[prefix + "food_dist"] = min(25.0, dist_food) / 25.0
|
||||||
|
|
||||||
|
features["safe_total_norm"] = safe_total / 4.0
|
||||||
|
return features
|
||||||
|
|
||||||
|
class SoftmaxMoveModel:
|
||||||
|
def __init__(self):
|
||||||
|
self.weights = {move: {} for move in MOVES}
|
||||||
|
self.bias = {move: 0.0 for move in MOVES}
|
||||||
|
|
||||||
|
def _score(self, move:str, features:dict[str, float]) -> float:
|
||||||
|
weight_map = self.weights[move]
|
||||||
|
value = self.bias[move]
|
||||||
|
for name, feat in features.items():
|
||||||
|
value += weight_map.get(name, 0.0) * feat
|
||||||
|
return value
|
||||||
|
|
||||||
|
def fit(self, rows:list[dict], epochs:int=14, lr:float=0.08, l2:float=1e-6) -> None:
|
||||||
|
examples = []
|
||||||
|
for row in rows:
|
||||||
|
label = row.get("move")
|
||||||
|
if label not in MOVES:
|
||||||
|
continue
|
||||||
|
features = extract_feature_values(row)
|
||||||
|
if not features:
|
||||||
|
continue
|
||||||
|
examples.append((features, label))
|
||||||
|
|
||||||
|
if not examples:
|
||||||
|
return
|
||||||
|
|
||||||
|
for _ in range(epochs):
|
||||||
|
random.shuffle(examples)
|
||||||
|
for features, label in examples:
|
||||||
|
scores = {move: self._score(move, features) for move in MOVES}
|
||||||
|
max_score = max(scores.values())
|
||||||
|
exp_scores = {
|
||||||
|
move: math.exp(scores[move] - max_score) for move in MOVES
|
||||||
|
}
|
||||||
|
z = sum(exp_scores.values())
|
||||||
|
probs = {move: exp_scores[move] / z for move in MOVES}
|
||||||
|
|
||||||
|
for move in MOVES:
|
||||||
|
target = 1.0 if move == label else 0.0
|
||||||
|
gradient = target - probs[move]
|
||||||
|
self.bias[move] += lr * gradient
|
||||||
|
|
||||||
|
w = self.weights[move]
|
||||||
|
for name, feat in features.items():
|
||||||
|
current = w.get(name, 0.0)
|
||||||
|
update = lr * ((gradient * feat) - (l2 * current))
|
||||||
|
w[name] = current + update
|
||||||
|
|
||||||
|
def predict_scores(self, row:dict) -> dict[str, float]:
|
||||||
|
features = extract_feature_values(row)
|
||||||
|
if not features:
|
||||||
|
return {move: 0.0 for move in MOVES}
|
||||||
|
return {move: self._score(move, features) for move in MOVES}
|
||||||
|
|
||||||
|
def predict(self, row:dict) -> str:
|
||||||
|
scores = self.predict_scores(row)
|
||||||
|
return max(scores, key=lambda move: scores[move])
|
||||||
|
|
||||||
|
def evaluate(self, rows:list[dict]) -> dict:
|
||||||
|
total = 0
|
||||||
|
correct = 0
|
||||||
|
top2 = 0
|
||||||
|
confusion = {move: Counter() for move in MOVES}
|
||||||
|
|
||||||
|
for row in rows:
|
||||||
|
expected = row.get("move")
|
||||||
|
if expected not in MOVES:
|
||||||
|
continue
|
||||||
|
|
||||||
|
scores = self.predict_scores(row)
|
||||||
|
ranked = sorted(scores.items(), key=lambda item: item[1], reverse=True)
|
||||||
|
predicted = ranked[0][0]
|
||||||
|
|
||||||
|
total += 1
|
||||||
|
if predicted == expected:
|
||||||
|
correct += 1
|
||||||
|
if expected in {
|
||||||
|
ranked[0][0],
|
||||||
|
ranked[1][0] if len(ranked) > 1 else ranked[0][0],
|
||||||
|
}:
|
||||||
|
top2 += 1
|
||||||
|
|
||||||
|
confusion[expected][predicted] += 1
|
||||||
|
|
||||||
|
return {
|
||||||
|
"total": total,
|
||||||
|
"correct": correct,
|
||||||
|
"accuracy": round((correct / total) if total else 0.0, 4),
|
||||||
|
"top2_accuracy": round((top2 / total) if total else 0.0, 4),
|
||||||
|
"confusion": {label: dict(confusion[label]) for label in MOVES},
|
||||||
|
}
|
||||||
|
|
||||||
|
def to_dict(self) -> dict:
|
||||||
|
return {
|
||||||
|
"model_type": "softmax_moves_v2",
|
||||||
|
"moves": MOVES,
|
||||||
|
"weights": self.weights,
|
||||||
|
"bias": self.bias,
|
||||||
|
}
|
||||||
|
|
||||||
|
def read_rows(paths:list[Path]) -> list[dict]:
|
||||||
|
rows: list[dict] = []
|
||||||
|
for path in paths:
|
||||||
|
with path.open("r", encoding="utf-8") as handle:
|
||||||
|
for line in handle:
|
||||||
|
if not line.strip():
|
||||||
|
continue
|
||||||
|
row = json.loads(line)
|
||||||
|
if row.get("move") not in MOVES:
|
||||||
|
continue
|
||||||
|
if not row.get("game_board"):
|
||||||
|
continue
|
||||||
|
rows.append(row)
|
||||||
|
return rows
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
parser = argparse.ArgumentParser(description="Train Battlesnake move model")
|
||||||
|
parser.add_argument("--input", action="append", required=True)
|
||||||
|
parser.add_argument("--output", required=True)
|
||||||
|
parser.add_argument("--eval-split", type=float, default=0.2)
|
||||||
|
parser.add_argument("--seed", type=int, default=42)
|
||||||
|
parser.add_argument("--epochs", type=int, default=14)
|
||||||
|
parser.add_argument("--lr", type=float, default=0.08)
|
||||||
|
args = parser.parse_args()
|
||||||
|
|
||||||
|
paths = resolve_input_files(args.input)
|
||||||
|
if not paths:
|
||||||
|
raise SystemExit("No input files found")
|
||||||
|
|
||||||
|
rows = read_rows(paths)
|
||||||
|
if len(rows) < 50:
|
||||||
|
raise SystemExit("Need at least 50 rows for training")
|
||||||
|
|
||||||
|
random.seed(args.seed)
|
||||||
|
random.shuffle(rows)
|
||||||
|
eval_count = int(len(rows) * max(0.0, min(0.5, args.eval_split)))
|
||||||
|
eval_rows = rows[:eval_count]
|
||||||
|
train_rows = rows[eval_count:]
|
||||||
|
|
||||||
|
model = SoftmaxMoveModel()
|
||||||
|
model.fit(train_rows, epochs=max(1, args.epochs), lr=max(1e-4, args.lr))
|
||||||
|
metrics = model.evaluate(eval_rows)
|
||||||
|
|
||||||
|
output = Path(args.output)
|
||||||
|
output.parent.mkdir(parents=True, exist_ok=True)
|
||||||
|
payload = {
|
||||||
|
"input_files": [str(p) for p in paths],
|
||||||
|
"train_rows": len(train_rows),
|
||||||
|
"eval_rows": len(eval_rows),
|
||||||
|
"eval_metrics": metrics,
|
||||||
|
"model": model.to_dict(),
|
||||||
|
}
|
||||||
|
output.write_text(json.dumps(payload, indent=2), encoding="utf-8")
|
||||||
|
|
||||||
|
print(json.dumps({
|
||||||
|
"output": str(output),
|
||||||
|
"train_rows": len(train_rows),
|
||||||
|
"eval_rows": len(eval_rows),
|
||||||
|
"accuracy": metrics.get("accuracy"),
|
||||||
|
"top2_accuracy": metrics.get("top2_accuracy"),
|
||||||
|
},
|
||||||
|
indent=2,
|
||||||
|
))
|
||||||
@@ -0,0 +1,39 @@
|
|||||||
|
from typing import TypedDict
|
||||||
|
from pathlib import Path
|
||||||
|
import os
|
||||||
|
|
||||||
|
from server.Server import Server
|
||||||
|
|
||||||
|
class RunConfig(TypedDict):
|
||||||
|
host: str
|
||||||
|
port: int
|
||||||
|
debug: bool
|
||||||
|
|
||||||
|
def env_bool(name:str, default:bool=False) -> bool:
|
||||||
|
value = os.environ.get(name)
|
||||||
|
if value is None:
|
||||||
|
return default
|
||||||
|
return value.lower() in {'1', 'true', 'yes', 'on'}
|
||||||
|
|
||||||
|
def build_server_from_env(default_snake_type:str) -> Server:
|
||||||
|
data_path = str(Path(__file__).resolve().parent.parent)
|
||||||
|
server = Server(
|
||||||
|
data_path=data_path,
|
||||||
|
snake_type=os.environ.get('SNAKE', default_snake_type),
|
||||||
|
storage_type=os.environ.get('STORAGE', 'LocalStorage'),
|
||||||
|
debug=env_bool('DEBUG_SERVER'),
|
||||||
|
check_tls_security=False,
|
||||||
|
)
|
||||||
|
|
||||||
|
if env_bool('STORE_GAME_HISTORY'):
|
||||||
|
server.enable_store_game_state()
|
||||||
|
|
||||||
|
return server
|
||||||
|
|
||||||
|
|
||||||
|
def build_run_config() -> RunConfig:
|
||||||
|
return {
|
||||||
|
'host': os.environ.get('HOST', '0.0.0.0'),
|
||||||
|
'port': int(os.environ.get('PORT', '8000')),
|
||||||
|
'debug': env_bool('DEBUG'),
|
||||||
|
}
|
||||||
@@ -0,0 +1,156 @@
|
|||||||
|
from server.GameBoard import GameBoard
|
||||||
|
from server.Dataset import Dataset
|
||||||
|
|
||||||
|
from datetime import datetime
|
||||||
|
import json, time
|
||||||
|
|
||||||
|
try:
|
||||||
|
import gel as _gel # type: ignore[import-not-found]
|
||||||
|
except ImportError: # pragma: no cover
|
||||||
|
_gel = None
|
||||||
|
|
||||||
|
class EdgeDB:
|
||||||
|
def __init__(self, database:str=None, tls_security:str='insecure', **kwargs):
|
||||||
|
self.database = database
|
||||||
|
self.tls_security = tls_security
|
||||||
|
self._connect()
|
||||||
|
|
||||||
|
def _connect(self):
|
||||||
|
if _gel is None:
|
||||||
|
raise ImportError("The 'gel' package is required to use EdgeDB storage")
|
||||||
|
self.client = _gel.create_client(
|
||||||
|
tls_security=self.tls_security, database=self.database
|
||||||
|
)
|
||||||
|
|
||||||
|
def run_query_with_reconnection(self, function, *args, **kwargs):
|
||||||
|
while True:
|
||||||
|
try:
|
||||||
|
return function(*args, **kwargs)
|
||||||
|
except Exception as error:
|
||||||
|
if error.__class__.__name__ != "ClientConnectionFailedError":
|
||||||
|
raise
|
||||||
|
|
||||||
|
self._connect()
|
||||||
|
time.sleep(0.5)
|
||||||
|
|
||||||
|
def insert_game_type(self, name:str, is_ladder:bool):
|
||||||
|
return self.run_query_with_reconnection(
|
||||||
|
self.client.query_required_single,
|
||||||
|
"""
|
||||||
|
insert GameType {
|
||||||
|
name := <str>$name,
|
||||||
|
is_ladder := <bool>$is_ladder
|
||||||
|
}""",
|
||||||
|
name=name,
|
||||||
|
is_ladder=is_ladder
|
||||||
|
)
|
||||||
|
|
||||||
|
def create_moves_with_calculations(self, game_board:GameBoard):
|
||||||
|
data = []
|
||||||
|
moves = game_board.turns
|
||||||
|
snake_calulations = [[calc for calc in ele["data"]] for ele in game_board.snake_class.get_history() ]
|
||||||
|
labels_by_turn = Dataset(game_board).labels_by_turn()
|
||||||
|
|
||||||
|
for i in range(len(moves)):
|
||||||
|
calculations = snake_calulations[i] if i < len(snake_calulations) else []
|
||||||
|
calculations.append({
|
||||||
|
"dataset": {
|
||||||
|
"is_good_move": labels_by_turn.get(moves[i]["turn"], False)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
data.append({
|
||||||
|
"turn": moves[i]["turn"],
|
||||||
|
"move": moves[i]["move"],
|
||||||
|
"game_board": moves[i]["game_board"],
|
||||||
|
"calculations": calculations,
|
||||||
|
})
|
||||||
|
|
||||||
|
return data
|
||||||
|
|
||||||
|
async def insert(self, game_board:GameBoard):
|
||||||
|
game_type = game_board.get_type_of_game()
|
||||||
|
|
||||||
|
self.run_query_with_reconnection(
|
||||||
|
self.client.query,
|
||||||
|
"""
|
||||||
|
insert GameBoard {
|
||||||
|
id := <uuid>$id,
|
||||||
|
created_at := <datetime>$created_at,
|
||||||
|
turns := <int32>$turns,
|
||||||
|
map := <str>$map,
|
||||||
|
winner := <str>$winner,
|
||||||
|
moves := (
|
||||||
|
with input_data := <array <tuple <turn: int32, `move`: str, game_board: json, calculations: array<json> >>>$moves
|
||||||
|
for data in array_unpack(input_data)
|
||||||
|
insert Moves {
|
||||||
|
turn := data.turn,
|
||||||
|
snake_move := data.`move`,
|
||||||
|
game_board := data.game_board,
|
||||||
|
calculations := data.calculations
|
||||||
|
}
|
||||||
|
),
|
||||||
|
type := (
|
||||||
|
insert GameType {
|
||||||
|
name := <str>$game_type,
|
||||||
|
is_ladder := <bool>$is_ladder
|
||||||
|
} unless conflict on (.name, .is_ladder) else GameType
|
||||||
|
),
|
||||||
|
ruleset := (
|
||||||
|
insert Ruleset {
|
||||||
|
name := <str>$ruleset,
|
||||||
|
version := <str>$version,
|
||||||
|
settings := to_json(<str>$settings)
|
||||||
|
} unless conflict on (.name, .version, .settings) else Ruleset
|
||||||
|
),
|
||||||
|
snake := (
|
||||||
|
insert Snake {
|
||||||
|
type := <str>$snake_type
|
||||||
|
} unless conflict on .type else Snake
|
||||||
|
)
|
||||||
|
}""",
|
||||||
|
|
||||||
|
id=game_board.id,
|
||||||
|
created_at=datetime.fromtimestamp(game_board.now_date.timestamp(), game_board.now_date.astimezone().tzinfo),
|
||||||
|
turns=game_board.turn,
|
||||||
|
map=game_board.map if game_board.map else "standard",
|
||||||
|
winner=', '.join(game_board.winner_snake_names)
|
||||||
|
if game_board.winner_snake_names
|
||||||
|
else "",
|
||||||
|
moves=[
|
||||||
|
tuple(
|
||||||
|
[
|
||||||
|
x["turn"],
|
||||||
|
x["move"],
|
||||||
|
json.dumps(x["game_board"]),
|
||||||
|
[json.dumps(ele) for ele in x["calculations"]],
|
||||||
|
]
|
||||||
|
)
|
||||||
|
for x in self.create_moves_with_calculations(game_board)
|
||||||
|
],
|
||||||
|
game_type=game_type["name"],
|
||||||
|
is_ladder=game_type["is_ladder"],
|
||||||
|
|
||||||
|
ruleset=game_board.ruleset["name"],
|
||||||
|
version=game_board.ruleset["version"],
|
||||||
|
settings=json.dumps(game_board.ruleset["settings"]),
|
||||||
|
|
||||||
|
snake_type=game_board.snake_class.__class__.__name__,
|
||||||
|
)
|
||||||
|
|
||||||
|
async def save(self, game_board:GameBoard):
|
||||||
|
await self.insert(game_board)
|
||||||
|
|
||||||
|
def __del__(self):
|
||||||
|
self.client.close()
|
||||||
|
|
||||||
|
def cleanup(self):
|
||||||
|
return self.run_query_with_reconnection(
|
||||||
|
self.client.query_json,
|
||||||
|
"""
|
||||||
|
delete Moves { };
|
||||||
|
|
||||||
|
with gameboard := (delete GameBoard filter .turns < <std::int32>"200" or .is_winner_me = <std::bool>"false")
|
||||||
|
select gameboard {id, url, winner, turns, type: { is_ladder, name } } order by .turns desc;
|
||||||
|
|
||||||
|
"""
|
||||||
|
)
|
||||||
@@ -0,0 +1,177 @@
|
|||||||
|
from server.GameBoard import GameBoard
|
||||||
|
from server.Dataset import Dataset
|
||||||
|
from server.Files import save_file
|
||||||
|
|
||||||
|
import aiofiles
|
||||||
|
import aiofiles.os
|
||||||
|
import gzip
|
||||||
|
import json, os
|
||||||
|
|
||||||
|
class LocalStorage:
|
||||||
|
def __init__(self, file_path:str, **kwargs):
|
||||||
|
self.save_folder_dict = {
|
||||||
|
"standard": "01_Standard",
|
||||||
|
"duel": "02_Duels",
|
||||||
|
"constrictor": "04_Constrictor",
|
||||||
|
"solo": "05_Solo",
|
||||||
|
}
|
||||||
|
self.file_path = file_path
|
||||||
|
self.dataset_only = os.getenv("STORE_DATASET_ONLY", "false").strip().lower() in ("1", "true", "yes", "on")
|
||||||
|
self.dataset_jsonl_path = os.getenv("DATASET_JSONL_PATH", os.path.join(self.file_path, "dataset", "good_moves.jsonl"))
|
||||||
|
self.dataset_rotate_daily = os.getenv("DATASET_ROTATE_DAILY", "true").strip().lower() in ("1", "true", "yes", "on")
|
||||||
|
self.dataset_compress_rotated = os.getenv("DATASET_COMPRESS_ROTATED", "true").strip().lower() in ("1", "true", "yes", "on")
|
||||||
|
self.dataset_max_bytes = int(float(os.getenv("DATASET_JSONL_MAX_MB", "50")) * 1024 * 1024)
|
||||||
|
|
||||||
|
def _get_active_dataset_path(self, game_board:GameBoard):
|
||||||
|
if not self.dataset_rotate_daily:
|
||||||
|
return self.dataset_jsonl_path
|
||||||
|
|
||||||
|
base, ext = os.path.splitext(self.dataset_jsonl_path)
|
||||||
|
if ext == "":
|
||||||
|
ext = ".jsonl"
|
||||||
|
return f"{base}-{game_board.now_date.strftime('%Y-%m-%d')}{ext}"
|
||||||
|
|
||||||
|
def _gzip_file(self, file_path:str):
|
||||||
|
gz_path = f"{file_path}.gz"
|
||||||
|
with open(file_path, "rb") as src:
|
||||||
|
with gzip.open(gz_path, "wb") as dst:
|
||||||
|
dst.writelines(src)
|
||||||
|
os.remove(file_path)
|
||||||
|
|
||||||
|
async def _compress_old_daily_files(self, active_path:str):
|
||||||
|
if not self.dataset_compress_rotated:
|
||||||
|
return
|
||||||
|
|
||||||
|
folder = os.path.dirname(active_path)
|
||||||
|
base_name = os.path.basename(self.dataset_jsonl_path)
|
||||||
|
base_stem, _ = os.path.splitext(base_name)
|
||||||
|
prefix = f"{base_stem}-"
|
||||||
|
active_name = os.path.basename(active_path)
|
||||||
|
|
||||||
|
if folder == "" or not await aiofiles.os.path.exists(folder):
|
||||||
|
return
|
||||||
|
|
||||||
|
for name in os.listdir(folder):
|
||||||
|
if name == active_name:
|
||||||
|
continue
|
||||||
|
if not name.startswith(prefix):
|
||||||
|
continue
|
||||||
|
if not name.endswith(".jsonl"):
|
||||||
|
continue
|
||||||
|
|
||||||
|
self._gzip_file(os.path.join(folder, name))
|
||||||
|
|
||||||
|
async def _rotate_if_needed(self, active_path:str, game_board:GameBoard):
|
||||||
|
if self.dataset_max_bytes <= 0:
|
||||||
|
return
|
||||||
|
if not await aiofiles.os.path.exists(active_path):
|
||||||
|
return
|
||||||
|
|
||||||
|
file_size = (await aiofiles.os.stat(active_path)).st_size
|
||||||
|
if file_size < self.dataset_max_bytes:
|
||||||
|
return
|
||||||
|
|
||||||
|
timestamp = game_board.now_date.strftime("%Y%m%d-%H%M%S")
|
||||||
|
rotated_path = f"{active_path}.{timestamp}.jsonl"
|
||||||
|
suffix = 1
|
||||||
|
while await aiofiles.os.path.exists(rotated_path):
|
||||||
|
suffix += 1
|
||||||
|
rotated_path = f"{active_path}.{timestamp}.{suffix}.jsonl"
|
||||||
|
|
||||||
|
await aiofiles.os.rename(active_path, rotated_path)
|
||||||
|
if self.dataset_compress_rotated:
|
||||||
|
self._gzip_file(rotated_path)
|
||||||
|
|
||||||
|
def _build_dataset_rows(self, dataset_payload:dict, game_board:GameBoard):
|
||||||
|
game_info = dataset_payload.get("game", {})
|
||||||
|
snake_info = dataset_payload.get("snake", {})
|
||||||
|
|
||||||
|
rows = []
|
||||||
|
for sample in dataset_payload.get("samples", []):
|
||||||
|
rows.append({
|
||||||
|
"game_id": game_info.get("id", game_board.id),
|
||||||
|
"game_map": game_info.get("map", game_board.map),
|
||||||
|
"game_type": game_info.get("type", game_board.get_type_of_game()),
|
||||||
|
"snake_type": snake_info.get(
|
||||||
|
"type", game_board.snake_class.__class__.__name__
|
||||||
|
),
|
||||||
|
"turn": sample.get("turn"),
|
||||||
|
"move": sample.get("move"),
|
||||||
|
"is_good_move": sample.get("is_good_move", False),
|
||||||
|
"game_board": sample.get("game_board"),
|
||||||
|
"history": sample.get("history"),
|
||||||
|
})
|
||||||
|
return rows
|
||||||
|
|
||||||
|
async def _append_dataset_jsonl(self, dataset_payload:dict, game_board:GameBoard):
|
||||||
|
rows = self._build_dataset_rows(dataset_payload, game_board)
|
||||||
|
if len(rows) == 0:
|
||||||
|
return
|
||||||
|
|
||||||
|
active_path = self._get_active_dataset_path(game_board)
|
||||||
|
await aiofiles.os.makedirs(os.path.dirname(active_path), exist_ok=True)
|
||||||
|
await self._compress_old_daily_files(active_path)
|
||||||
|
await self._rotate_if_needed(active_path, game_board)
|
||||||
|
|
||||||
|
async with aiofiles.open(active_path, "a") as f:
|
||||||
|
for row in rows:
|
||||||
|
await f.write(json.dumps(row, ensure_ascii=False) + "\n")
|
||||||
|
|
||||||
|
def _get_correct_folder_for_save_file(self, game_board:GameBoard, file_name:str, game_type:str, leader_board:bool, winner:bool):
|
||||||
|
storage_folder = self.file_path
|
||||||
|
if leader_board:
|
||||||
|
storage_folder = os.path.join(storage_folder, "00_Leaderboards")
|
||||||
|
|
||||||
|
storage_folder = os.path.join(storage_folder, self.save_folder_dict[game_type])
|
||||||
|
storage_folder = os.path.join(
|
||||||
|
storage_folder,
|
||||||
|
game_board.now_date.strftime("%Y"),
|
||||||
|
game_board.now_date.strftime("%m_%B"),
|
||||||
|
game_board.now_date.strftime("%d"),
|
||||||
|
)
|
||||||
|
|
||||||
|
if winner:
|
||||||
|
storage_folder = os.path.join(storage_folder, "Winner")
|
||||||
|
else:
|
||||||
|
storage_folder = os.path.join(storage_folder, "Lost")
|
||||||
|
|
||||||
|
return os.path.join(storage_folder, file_name)
|
||||||
|
|
||||||
|
async def save(self, game_board:GameBoard):
|
||||||
|
game_type = game_board.get_type_of_game()
|
||||||
|
dataset = Dataset(game_board).build(only_good_moves=True)
|
||||||
|
|
||||||
|
await self._append_dataset_jsonl(dataset, game_board)
|
||||||
|
if self.dataset_only:
|
||||||
|
return
|
||||||
|
|
||||||
|
save_file_path = self._get_correct_folder_for_save_file(
|
||||||
|
game_board,
|
||||||
|
f"{game_board.snake_class.__class__.__name__}_{game_board.now_date.strftime('%H-%M-%S')}_{game_board.id}.json",
|
||||||
|
game_type["name"],
|
||||||
|
game_type["is_ladder"],
|
||||||
|
True if game_board.winner_snake_names and "me" in game_board.winner_snake_names else False
|
||||||
|
)
|
||||||
|
|
||||||
|
payload = {
|
||||||
|
"winner": game_board.winner_snake_names,
|
||||||
|
"game": {
|
||||||
|
"url": game_board.url,
|
||||||
|
"id": game_board.id,
|
||||||
|
"final_turns": game_board.turn,
|
||||||
|
"map": game_board.map,
|
||||||
|
"type": game_type,
|
||||||
|
"ruleset": game_board.ruleset,
|
||||||
|
},
|
||||||
|
"moves": game_board.turns,
|
||||||
|
"snake": {
|
||||||
|
"type": game_board.snake_class.__class__.__name__,
|
||||||
|
"calculations": game_board.snake_class.get_history(),
|
||||||
|
},
|
||||||
|
"dataset": dataset,
|
||||||
|
}
|
||||||
|
|
||||||
|
await save_file(save_file_path, json.dumps(payload, indent=2, ensure_ascii=False))
|
||||||
|
|
||||||
|
def cleanup(self):
|
||||||
|
pass
|
||||||
@@ -0,0 +1,7 @@
|
|||||||
|
|
||||||
|
class StorageLoader:
|
||||||
|
@classmethod
|
||||||
|
def build(self, selected_storage:str):
|
||||||
|
storage_module = __import__(f'server.storage.{selected_storage}', fromlist=[selected_storage])
|
||||||
|
storage_class = getattr(storage_module, selected_storage)
|
||||||
|
return storage_class
|
||||||
@@ -1,165 +0,0 @@
|
|||||||
from snakes.TemplateSnake import TemplateSnake
|
|
||||||
|
|
||||||
from queue import PriorityQueue, Queue
|
|
||||||
import random
|
|
||||||
|
|
||||||
class AStarSnake(TemplateSnake):
|
|
||||||
def avoid_my_body(self, my_body, possible_moves: dict) -> list:
|
|
||||||
"""
|
|
||||||
my_body: Set of tuples representing x/y coordinates for every segment of a Battlesnake.
|
|
||||||
e.g. {(0, 0), (1, 0), (2, 0)}
|
|
||||||
possible_moves: Dictionary of moves to pick from, with coordinates as tuples.
|
|
||||||
e.g. {"up": (0, 1), "down": (0, -1), "left": (-1, 0), "right": (1, 0)}
|
|
||||||
|
|
||||||
return: The dictionary of remaining possible_moves, with the moves leading to self-collision removed
|
|
||||||
"""
|
|
||||||
remove = []
|
|
||||||
for direction, location in possible_moves.items():
|
|
||||||
if location in my_body:
|
|
||||||
remove.append(direction)
|
|
||||||
|
|
||||||
for direction in remove:
|
|
||||||
del possible_moves[direction]
|
|
||||||
|
|
||||||
return possible_moves
|
|
||||||
|
|
||||||
def avoid_walls(self, board_width: int, board_height: int, possible_moves: dict):
|
|
||||||
remove = []
|
|
||||||
for direction, location in possible_moves.items():
|
|
||||||
x_out_range = (location[0] < 0 or location[0] == board_width)
|
|
||||||
y_out_range = (location[1] < 0 or location[1] == board_height)
|
|
||||||
if x_out_range or y_out_range:
|
|
||||||
remove.append(direction)
|
|
||||||
|
|
||||||
for direction in remove:
|
|
||||||
del possible_moves[direction]
|
|
||||||
|
|
||||||
return possible_moves
|
|
||||||
|
|
||||||
def avoid_snakes(self, snakes: list, possible_moves: dict):
|
|
||||||
remove = []
|
|
||||||
for snake in snakes:
|
|
||||||
for direction, location in possible_moves.items():
|
|
||||||
if location in snake["body"]:
|
|
||||||
remove.append(direction)
|
|
||||||
|
|
||||||
remove = set(remove)
|
|
||||||
for direction in remove:
|
|
||||||
del possible_moves[direction]
|
|
||||||
|
|
||||||
return possible_moves
|
|
||||||
|
|
||||||
def get_target_close(self, foods: list, my_head: tuple):
|
|
||||||
if len(foods) == 0:
|
|
||||||
return None
|
|
||||||
return min(foods, key=lambda food: abs(food["x"] - my_head[0]) + abs(food["y"] - my_head[1]))
|
|
||||||
|
|
||||||
def flood_fill(self, board_width: int, board_height: int, my_body: set):
|
|
||||||
"""
|
|
||||||
Perform Flood Fill to identify safe areas on the board.
|
|
||||||
"""
|
|
||||||
visited = set()
|
|
||||||
safe_cells = set()
|
|
||||||
|
|
||||||
# Define directions (up, down, left, right)
|
|
||||||
directions = [(0, 1), (0, -1), (-1, 0), (1, 0)]
|
|
||||||
|
|
||||||
# Perform Flood Fill from each cell not occupied by the snake's body
|
|
||||||
for x in range(board_width):
|
|
||||||
for y in range(board_height):
|
|
||||||
if (x, y) not in my_body and (x, y) not in visited:
|
|
||||||
# Start Flood Fill from this cell
|
|
||||||
q = Queue()
|
|
||||||
q.put((x, y))
|
|
||||||
visited.add((x, y))
|
|
||||||
safe_cells.add((x, y))
|
|
||||||
|
|
||||||
# Continue Flood Fill until the queue is empty
|
|
||||||
while not q.empty():
|
|
||||||
current_cell = q.get()
|
|
||||||
for dx, dy in directions:
|
|
||||||
new_cell = (current_cell[0] + dx, current_cell[1] + dy)
|
|
||||||
if 0 <= new_cell[0] < board_width and 0 <= new_cell[1] < board_height:
|
|
||||||
if new_cell not in my_body and new_cell not in visited:
|
|
||||||
q.put(new_cell)
|
|
||||||
visited.add(new_cell)
|
|
||||||
safe_cells.add(new_cell)
|
|
||||||
|
|
||||||
return safe_cells
|
|
||||||
|
|
||||||
def choose_move(self, data: dict) -> str:
|
|
||||||
my_head = (data["you"]["head"]["x"], data["you"]["head"]["y"])
|
|
||||||
my_body = {(part["x"], part["y"]) for part in data["you"]["body"]}
|
|
||||||
board_height = data["board"]["height"]
|
|
||||||
board_width = data["board"]["width"]
|
|
||||||
foods = data["board"]["food"]
|
|
||||||
|
|
||||||
# Perform Flood Fill to identify safe areas on the board
|
|
||||||
safe_cells = self.flood_fill(board_width, board_height, my_body)
|
|
||||||
|
|
||||||
# Find the nearest food located in a safe area using A* algorithm
|
|
||||||
def heuristic(a, b):
|
|
||||||
return abs(a[0] - b[0]) + abs(a[1] - b[1])
|
|
||||||
|
|
||||||
def a_star(start, goal:set=()):
|
|
||||||
open_set = Queue()
|
|
||||||
open_set.put(start)
|
|
||||||
came_from = {}
|
|
||||||
g_score = {start: 0}
|
|
||||||
|
|
||||||
while not open_set.empty():
|
|
||||||
current = open_set.get()
|
|
||||||
|
|
||||||
if current == goal:
|
|
||||||
path = []
|
|
||||||
while current in came_from:
|
|
||||||
path.append(current)
|
|
||||||
current = came_from[current]
|
|
||||||
return path[::-1][0]
|
|
||||||
|
|
||||||
for dx, dy in [(0, 1), (0, -1), (-1, 0), (1, 0)]:
|
|
||||||
new_cell = (current[0] + dx, current[1] + dy)
|
|
||||||
if new_cell in safe_cells:
|
|
||||||
tentative_g_score = g_score[current] + 1
|
|
||||||
if new_cell not in g_score or tentative_g_score < g_score[new_cell]:
|
|
||||||
came_from[new_cell] = current
|
|
||||||
g_score[new_cell] = tentative_g_score
|
|
||||||
open_set.put(new_cell)
|
|
||||||
|
|
||||||
return None
|
|
||||||
|
|
||||||
try:
|
|
||||||
nearest_food = min(foods, key=lambda food: heuristic(my_head, (food["x"], food["y"])))
|
|
||||||
target_position = (nearest_food["x"], nearest_food["y"])
|
|
||||||
move_target = a_star(my_head, target_position)
|
|
||||||
except ValueError:
|
|
||||||
# TODO: What to do when no food is available?
|
|
||||||
# - Avoid own body and other snakes
|
|
||||||
# - Flut fill?
|
|
||||||
move_target = a_star(my_head, safe_cells)
|
|
||||||
print(move_target)
|
|
||||||
|
|
||||||
# Choose the next move based on the path obtained from A* algorithm
|
|
||||||
if move_target:
|
|
||||||
dx = move_target[0] - my_head[0]
|
|
||||||
dy = move_target[1] - my_head[1]
|
|
||||||
|
|
||||||
self.add_to_history({"my_head": my_head, "my_body": tuple(my_body), "target": move_target, "target_position": target_position, "nearest_food": nearest_food, "dx": dx, "dy": dy})
|
|
||||||
if dx == 1:
|
|
||||||
return "right"
|
|
||||||
elif dx == -1:
|
|
||||||
return "left"
|
|
||||||
elif dy == 1:
|
|
||||||
return "up"
|
|
||||||
elif dy == -1:
|
|
||||||
return "down"
|
|
||||||
|
|
||||||
# If no safe path to food is found, choose a random move
|
|
||||||
random_move = random.choice(["up", "down", "left", "right"])
|
|
||||||
|
|
||||||
try:
|
|
||||||
self.add_to_history({"my_head": my_head, "my_body": tuple(my_body), "target": move_target, "target_position": target_position, "nearest_food": nearest_food, "random_move": random_move})
|
|
||||||
except UnboundLocalError:
|
|
||||||
self.add_to_history({"my_head": my_head, "my_body": tuple(my_body), "target": move_target, "random_move": random_move})
|
|
||||||
|
|
||||||
return random_move
|
|
||||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,224 @@
|
|||||||
|
from snakes.TemplateSnake import TemplateSnake
|
||||||
|
from server.GameBoard import GameBoard
|
||||||
|
from collections import deque
|
||||||
|
|
||||||
|
class BetterMasterSnake(TemplateSnake):
|
||||||
|
VERSION = "1.3.0"
|
||||||
|
|
||||||
|
def __init__(self):
|
||||||
|
super().__init__()
|
||||||
|
self.name = "BetterMasterSnake"
|
||||||
|
self.version = self.VERSION
|
||||||
|
# Definiere die möglichen Bewegungsrichtungen
|
||||||
|
self.min_safe_area = 2
|
||||||
|
|
||||||
|
def choose_move(self, game_data:GameBoard):
|
||||||
|
self.game_board = game_data
|
||||||
|
self.calculations = []
|
||||||
|
self.eat_the_snake_overwrite = False
|
||||||
|
|
||||||
|
self.safe_positions = self.find_safe_positions(add_to_calculations=True)
|
||||||
|
if self.eat_the_snake_overwrite:
|
||||||
|
return self.overwrite_eat_the_other_snake(game_data.get_turn())
|
||||||
|
|
||||||
|
if game_data.get_type() == "constrictor":
|
||||||
|
move = self.selected_move_constrictor()
|
||||||
|
else:
|
||||||
|
move = self.selected_move_standard()
|
||||||
|
|
||||||
|
self.add_to_history({"turn": game_data.get_turn(), "data": self.calculations})
|
||||||
|
return move if move else "up"
|
||||||
|
|
||||||
|
def overwrite_eat_the_other_snake(self, turn:int):
|
||||||
|
self.add_calculations({"function": "eat_the_snake_overwrite", "my_head": self.game_board.get_my_snake_head(), "move": self.kill_the_snake, "safe_positions": self.safe_positions})
|
||||||
|
self.add_to_history({"turn": turn, "data": self.calculations})
|
||||||
|
return self.kill_the_snake
|
||||||
|
|
||||||
|
#TODO: How to Fill the Gameboard best?
|
||||||
|
def selected_move_constrictor(self):
|
||||||
|
move = self.move_close_to_body()
|
||||||
|
self.add_calculations({"function": "move_close_to_body", "my_head": self.game_board.get_my_snake_head(), "move": move})
|
||||||
|
move = self.ensure_escape_route(move)
|
||||||
|
self.add_calculations({"function": "ensure_escape_route", "my_head": self.game_board.get_my_snake_head(), "move": move, "safe_positions": self.safe_positions})
|
||||||
|
return move
|
||||||
|
|
||||||
|
def selected_move_standard(self, move=None):
|
||||||
|
# Finde den besten Weg zur Nahrung
|
||||||
|
path_to_food = self.find_path_to_food()
|
||||||
|
if path_to_food:
|
||||||
|
move = self.move_towards(path_to_food[0])
|
||||||
|
self.add_calculations({"function": "move_towards", "my_head": self.game_board.get_my_snake_head(), "path_to_food": path_to_food, "move": move})
|
||||||
|
|
||||||
|
if not move or self.would_eating_the_food_kill_the_snake(move):
|
||||||
|
move = self.move_close_to_body(move_close_to_tail=True)
|
||||||
|
self.add_calculations({"function": "move_close_to_body", "my_head": self.game_board.get_my_snake_head(), "move": move})
|
||||||
|
|
||||||
|
# Überprfe, ob der Zug einen Ausweg lässt
|
||||||
|
move = self.ensure_escape_route(move)
|
||||||
|
self.add_calculations({"function": "ensure_escape_route", "my_head": self.game_board.get_my_snake_head(), "move": move, "safe_positions": self.safe_positions})
|
||||||
|
return move
|
||||||
|
|
||||||
|
def find_path_to_food(self):
|
||||||
|
# Exclude own snake's body from obstacles
|
||||||
|
obstacles = set((part['x'], part['y']) for part in self.game_board.get_my_snake_body())
|
||||||
|
|
||||||
|
for snake in self.game_board.get_other_snakes():
|
||||||
|
for part in snake['body']:
|
||||||
|
obstacles.add((part['x'], part['y']))
|
||||||
|
|
||||||
|
other_snakes_other_snake_posible_moves_set = {(d['x'], d['y']) for d in self.other_snake_posible_moves}
|
||||||
|
removed_elements_set = set([(elem['x'], elem['y']) for elem in self.game_board.get_food() if (elem['x'], elem['y']) in other_snakes_other_snake_posible_moves_set])
|
||||||
|
obstacles |= removed_elements_set
|
||||||
|
|
||||||
|
self.food_positions = [elem for elem in self.game_board.get_food() if (elem['x'], elem['y']) not in other_snakes_other_snake_posible_moves_set]
|
||||||
|
|
||||||
|
if len(self.food_positions) > 0:
|
||||||
|
# Choose the closest food source based on the heuristic
|
||||||
|
closest_food = min(self.food_positions, key=lambda food: abs(food['x'] - self.game_board.get_my_snake_head()['x']) + abs(food['y'] - self.game_board.get_my_snake_head()['y']))
|
||||||
|
self.set_target_food(closest_food)
|
||||||
|
|
||||||
|
# Use A* to search for a safe path
|
||||||
|
return self.a_star_search(self.game_board.get_my_snake_head(), closest_food, obstacles)
|
||||||
|
return None
|
||||||
|
|
||||||
|
def find_path_to_tail(self):
|
||||||
|
# Exclude other snake's body from obstacles
|
||||||
|
obstacles = set((part['x'], part['y']) for part in self.game_board.get_my_snake_body())
|
||||||
|
for snake in self.game_board.get_other_snakes():
|
||||||
|
for part in snake['body']:
|
||||||
|
obstacles.add((part['x'], part['y']))
|
||||||
|
|
||||||
|
my_snake_tail = {"x": self.game_board.get_my_snake_tail()['x'], "y": self.game_board.get_my_snake_tail()['y']}
|
||||||
|
|
||||||
|
# Use A* to search for a safe path
|
||||||
|
path = self.a_star_search(self.game_board.get_my_snake_head(), my_snake_tail, obstacles)
|
||||||
|
return path
|
||||||
|
|
||||||
|
def move_towards(self, target):
|
||||||
|
best_direction = None
|
||||||
|
min_distance = float('inf')
|
||||||
|
for direction, coords in self.safe_positions.items():
|
||||||
|
distance = abs(target['x'] - coords['x']) + abs(target['y'] - coords['y'])
|
||||||
|
if distance < min_distance:
|
||||||
|
min_distance = distance
|
||||||
|
best_direction = direction
|
||||||
|
|
||||||
|
return best_direction if best_direction else "up"
|
||||||
|
|
||||||
|
def move_close_to_body(self, move_close_to_tail=False):
|
||||||
|
# Heuristik, um Positionen nahe dem eigenen Körper zu bevorzugen
|
||||||
|
body_positions = set((part['x'], part['y']) for part in self.game_board.get_my_snake_body())
|
||||||
|
tail_position = (self.game_board.get_my_snake_tail()['x'], self.game_board.get_my_snake_tail()['y'])
|
||||||
|
|
||||||
|
best_move = None
|
||||||
|
max_distance = -1 # Initialize maximum distance
|
||||||
|
for direction, pos in self.safe_positions.items():
|
||||||
|
next_position = (pos['x'], pos['y'])
|
||||||
|
if next_position in self.safe_positions:
|
||||||
|
# Berechne die Distanz zum eigenen Körper
|
||||||
|
distance_to_body = min(abs(next_position[0] - part[0]) + abs(next_position[1] - part[1]) for part in body_positions)
|
||||||
|
# Berechne die Distanz zum eigenen Schwanz
|
||||||
|
distance_to_tail = abs(next_position[0] - tail_position[0]) + abs(next_position[1] - tail_position[1])
|
||||||
|
# Wähle die maximale Distanz (Körper oder Schwanz)
|
||||||
|
if move_close_to_tail:
|
||||||
|
distance = min(next_position, distance_to_tail)
|
||||||
|
else:
|
||||||
|
distance = max(next_position, distance_to_body)
|
||||||
|
# Update max_distance if a larger distance is found
|
||||||
|
if distance > max_distance:
|
||||||
|
max_distance = distance
|
||||||
|
best_move = direction
|
||||||
|
return best_move if best_move else "up" # Standardbewegung, falls keine bessere gefunden wird
|
||||||
|
|
||||||
|
#TODO: Neat to Implement Function to check if eating the food would kill the snake?
|
||||||
|
def would_eating_the_food_kill_the_snake(self, move:str):
|
||||||
|
return False
|
||||||
|
|
||||||
|
def ensure_escape_route(self, move:str):
|
||||||
|
try:
|
||||||
|
future_position = self.safe_positions[move]
|
||||||
|
except KeyError:
|
||||||
|
for move, pos in self.safe_positions.items():
|
||||||
|
if self.is_near_tail(pos, (self.game_board.get_my_snake_tail()['x'], self.game_board.get_my_snake_tail()['y'])):
|
||||||
|
self.add_calculations({"function": "ensure_escape_route", "move": move, "is_near_tail": True})
|
||||||
|
move = self.move_towards(pos)
|
||||||
|
return move
|
||||||
|
else:
|
||||||
|
path_to_tail = self.find_path_to_tail()
|
||||||
|
if path_to_tail:
|
||||||
|
self.add_calculations({"function": "move_towards", "my_head": self.game_board.get_my_snake_head(), "path_to_tail": path_to_tail, "move": move})
|
||||||
|
move = self.move_towards(path_to_tail[0])
|
||||||
|
|
||||||
|
self.add_calculations({"function": "ensure_escape_route", "move": move, "KeyError": "Snake Coild itself up"})
|
||||||
|
#return move
|
||||||
|
|
||||||
|
# TODO: Fix - Snake Neat to find the best way - Close to the Tail and maybe fill most free cells as posible
|
||||||
|
return move
|
||||||
|
|
||||||
|
def is_near_tail(self, position, tail):
|
||||||
|
return abs(position["x"] - tail[0]) + abs(position["y"] - tail[1]) <= 2
|
||||||
|
|
||||||
|
def a_star_search(self, start, goal, obstacles):
|
||||||
|
# Helper functions
|
||||||
|
def is_position_safe(position):
|
||||||
|
return 0 <= position['x'] < self.game_board.get_width() and 0 <= position['y'] < self.game_board.get_height() and (position['x'], position['y']) not in obstacles
|
||||||
|
|
||||||
|
def get_neighbors(position):
|
||||||
|
neighbors = []
|
||||||
|
for dx, dy in [(-1, 0), (1, 0), (0, -1), (0, 1)]: # links, rechts, oben, unten
|
||||||
|
neighbor = {'x': position['x'] + dx, 'y': position['y'] + dy}
|
||||||
|
if is_position_safe(neighbor):
|
||||||
|
neighbors.append(neighbor)
|
||||||
|
return neighbors
|
||||||
|
|
||||||
|
def heuristic(position, goal):
|
||||||
|
# Verwenden Sie eine Heuristik, die immer positiv ist, selbst wenn das Ziel in der Nähe ist
|
||||||
|
return max(abs(position['x'] - goal['x']), abs(position['y'] - goal['y']))
|
||||||
|
|
||||||
|
# Überprüfen, ob das Ziel direkt neben dem Startpunkt liegt
|
||||||
|
if start == goal or (abs(start['x'] - goal['x']) <= 1 and abs(start['y'] - goal['y']) <= 1):
|
||||||
|
# Wenn das Ziel neben dem Startpunkt liegt, ist der Pfad das Ziel selbst
|
||||||
|
return [goal]
|
||||||
|
|
||||||
|
# Initialize the open and closed list
|
||||||
|
open_set = set([(start['x'], start['y'])])
|
||||||
|
came_from = {}
|
||||||
|
g_score = {(start['x'], start['y']): 0}
|
||||||
|
f_score = {(start['x'], start['y']): heuristic(start, goal)}
|
||||||
|
|
||||||
|
while open_set:
|
||||||
|
current = min(open_set, key=lambda pos: f_score.get(pos, float('inf')))
|
||||||
|
current_dict = {'x': current[0], 'y': current[1]}
|
||||||
|
if current_dict == goal:
|
||||||
|
# Reconstruct the path
|
||||||
|
path = []
|
||||||
|
while current in came_from:
|
||||||
|
current = came_from[current]
|
||||||
|
path.append({'x': current[0], 'y': current[1]})
|
||||||
|
path.reverse()
|
||||||
|
if path and path[0] == start:
|
||||||
|
path.pop(0) # Entferne das erste Element, wenn es dem Start entspricht
|
||||||
|
return path # Return the path as a list of dicts
|
||||||
|
|
||||||
|
open_set.remove(current)
|
||||||
|
for neighbor in get_neighbors(current_dict):
|
||||||
|
neighbor_tuple = (neighbor['x'], neighbor['y'])
|
||||||
|
tentative_g_score = g_score[current] + 1 # Distance between neighbors is always 1
|
||||||
|
if tentative_g_score < g_score.get(neighbor_tuple, float('inf')):
|
||||||
|
came_from[neighbor_tuple] = current
|
||||||
|
g_score[neighbor_tuple] = tentative_g_score
|
||||||
|
f_score[neighbor_tuple] = g_score[neighbor_tuple] + heuristic(neighbor, goal)
|
||||||
|
if neighbor_tuple not in open_set:
|
||||||
|
open_set.add(neighbor_tuple)
|
||||||
|
|
||||||
|
return None # Kein Pfad gefunden
|
||||||
|
|
||||||
|
def find_direction(self):
|
||||||
|
# Beispielhafte Logik zur Auswahl einer Bewegungsrichtung
|
||||||
|
for direction, pos in self.safe_positions.items():
|
||||||
|
next_position = (pos['x'], pos['y'])
|
||||||
|
# Konvertiere safe_positions in eine Liste von Tupeln für den Vergleich
|
||||||
|
safe_positions_tuples = [(pos['x'], pos['y']) for pos in self.safe_positions.values()]
|
||||||
|
if next_position in safe_positions_tuples:
|
||||||
|
return direction
|
||||||
|
return "up" # Standardbewegung, falls keine sichere Position gefunden wird
|
||||||
+38
-36
@@ -3,53 +3,55 @@ from snakes.TemplateSnake import TemplateSnake
|
|||||||
import random
|
import random
|
||||||
|
|
||||||
class DummSnake(TemplateSnake):
|
class DummSnake(TemplateSnake):
|
||||||
def choose_move(self, data: dict) -> str:
|
VERSION = "1.0.0"
|
||||||
is_move_safe = {"up": True, "down": True, "left": True, "right": True}
|
|
||||||
|
|
||||||
# We've included code to prevent your Battlesnake from moving backwards
|
def choose_move(self, data: dict) -> str:
|
||||||
my_head = data["you"]["body"][0] # Coordinates of your head
|
is_move_safe = {"up": True, "down": True, "left": True, "right": True}
|
||||||
my_neck = data["you"]["body"][1] # Coordinates of your "neck"
|
|
||||||
|
|
||||||
if my_neck["x"] < my_head["x"]: # Neck is left of head, don't move left
|
# We've included code to prevent your Battlesnake from moving backwards
|
||||||
is_move_safe["left"] = False
|
my_head = data["you"]["body"][0] # Coordinates of your head
|
||||||
|
my_neck = data["you"]["body"][1] # Coordinates of your "neck"
|
||||||
|
|
||||||
elif my_neck["x"] > my_head["x"]: # Neck is right of head, don't move right
|
if my_neck["x"] < my_head["x"]: # Neck is left of head, don't move left
|
||||||
is_move_safe["right"] = False
|
is_move_safe["left"] = False
|
||||||
|
|
||||||
elif my_neck["y"] < my_head["y"]: # Neck is below head, don't move down
|
elif my_neck["x"] > my_head["x"]: # Neck is right of head, don't move right
|
||||||
is_move_safe["down"] = False
|
is_move_safe["right"] = False
|
||||||
|
|
||||||
elif my_neck["y"] > my_head["y"]: # Neck is above head, don't move up
|
elif my_neck["y"] < my_head["y"]: # Neck is below head, don't move down
|
||||||
is_move_safe["up"] = False
|
is_move_safe["down"] = False
|
||||||
|
|
||||||
# TODO: Step 1 - Prevent your Battlesnake from moving out of bounds
|
elif my_neck["y"] > my_head["y"]: # Neck is above head, don't move up
|
||||||
# board_width = game_state['board']['width']
|
is_move_safe["up"] = False
|
||||||
# board_height = game_state['board']['height']
|
|
||||||
|
|
||||||
# TODO: Step 2 - Prevent your Battlesnake from colliding with itself
|
# TODO: Step 1 - Prevent your Battlesnake from moving out of bounds
|
||||||
# my_body = game_state['you']['body']
|
# board_width = game_state['board']['width']
|
||||||
|
# board_height = game_state['board']['height']
|
||||||
|
|
||||||
# TODO: Step 3 - Prevent your Battlesnake from colliding with other Battlesnakes
|
# TODO: Step 2 - Prevent your Battlesnake from colliding with itself
|
||||||
# opponents = game_state['board']['snakes']
|
# my_body = game_state['you']['body']
|
||||||
|
|
||||||
# Are there any safe moves left?
|
# TODO: Step 3 - Prevent your Battlesnake from colliding with other Battlesnakes
|
||||||
safe_moves = []
|
# opponents = game_state['board']['snakes']
|
||||||
for move, isSafe in is_move_safe.items():
|
|
||||||
if isSafe:
|
|
||||||
safe_moves.append(move)
|
|
||||||
|
|
||||||
if len(safe_moves) == 0:
|
# Are there any safe moves left?
|
||||||
print(f"MOVE {data['turn']}: No safe moves detected! Moving down")
|
safe_moves = []
|
||||||
self.add_to_history({"my_head": my_head, "my_neck": my_neck, "move": move, "safe_moves": safe_moves, "is_move_safe": is_move_safe})
|
for move, isSafe in is_move_safe.items():
|
||||||
return {"move": "down"}
|
if isSafe:
|
||||||
|
safe_moves.append(move)
|
||||||
|
|
||||||
# Choose a random move from the safe ones
|
if len(safe_moves) == 0:
|
||||||
move = random.choice(safe_moves)
|
print(f"MOVE {data['turn']}: No safe moves detected! Moving down")
|
||||||
|
self.add_to_history({"my_head": my_head, "my_neck": my_neck, "move": move, "safe_moves": safe_moves, "is_move_safe": is_move_safe})
|
||||||
|
return {"move": "down"}
|
||||||
|
|
||||||
# TODO: Step 4 - Move towards food instead of random, to regain health and survive longer
|
# Choose a random move from the safe ones
|
||||||
# food = game_state['board']['food']
|
move = random.choice(safe_moves)
|
||||||
|
|
||||||
self.add_to_history({"my_head": my_head, "my_neck": my_neck, "move": move, "safe_moves": safe_moves, "is_move_safe": is_move_safe})
|
# TODO: Step 4 - Move towards food instead of random, to regain health and survive longer
|
||||||
print(f"{data['game']['id']} MOVE {data['turn']}: {move} picked from all valid options in {is_move_safe}")
|
# food = game_state['board']['food']
|
||||||
|
|
||||||
return move
|
self.add_to_history({"my_head": my_head, "my_neck": my_neck, "move": move, "safe_moves": safe_moves, "is_move_safe": is_move_safe})
|
||||||
|
print(f"{data['game']['id']} MOVE {data['turn']}: {move} picked from all valid options in {is_move_safe}")
|
||||||
|
|
||||||
|
return move
|
||||||
|
|||||||
@@ -4,6 +4,8 @@ import random
|
|||||||
from scipy import spatial
|
from scipy import spatial
|
||||||
|
|
||||||
class LogicSnake(TemplateSnake):
|
class LogicSnake(TemplateSnake):
|
||||||
|
VERSION = "1.1.0"
|
||||||
|
|
||||||
def avoid_my_body(self, my_body, possible_moves: dict) -> list:
|
def avoid_my_body(self, my_body, possible_moves: dict) -> list:
|
||||||
"""
|
"""
|
||||||
my_body: List of dictionaries of x/y coordinates for every segment of a Battlesnake.
|
my_body: List of dictionaries of x/y coordinates for every segment of a Battlesnake.
|
||||||
|
|||||||
+211
-208
@@ -1,246 +1,249 @@
|
|||||||
from snakes.TemplateSnake import TemplateSnake
|
from snakes.TemplateSnake import TemplateSnake
|
||||||
|
|
||||||
class MasterSnake(TemplateSnake):
|
class MasterSnake(TemplateSnake):
|
||||||
def __init__(self):
|
VERSION = "1.2.0"
|
||||||
super().__init__()
|
|
||||||
self.name = "MasterSnake"
|
|
||||||
self.disabled_find_near_by_food = True
|
|
||||||
|
|
||||||
def is_food_nearby(self, head, food_positions):
|
def __init__(self):
|
||||||
for food in food_positions:
|
super().__init__()
|
||||||
if abs(head['x'] - food['x']) <= 1 and abs(head['y'] - food['y']) <= 1:
|
self.name = "MasterSnake"
|
||||||
return True
|
self.version = self.VERSION
|
||||||
return False
|
self.disabled_find_near_by_food = True
|
||||||
|
|
||||||
def avoid_snake_body(self, snakes, board_width, board_height):
|
def is_food_nearby(self, head, food_positions):
|
||||||
# Konvertiere die Körperpositionen der Schlangen in ein Set von Tupeln für schnellen Zugriff
|
for food in food_positions:
|
||||||
body_positions = set()
|
if abs(head['x'] - food['x']) <= 1 and abs(head['y'] - food['y']) <= 1:
|
||||||
for snake in snakes:
|
return True
|
||||||
for part in snake['body']:
|
return False
|
||||||
body_positions.add((part['x'], part['y']))
|
|
||||||
|
|
||||||
# Implementiere die Logik, um Positionen zu finden, die nicht von Schlangenkörpern belegt sind
|
def avoid_snake_body(self, snakes, board_width, board_height):
|
||||||
safe_positions = self.find_safe_positions(body_positions, board_width, board_height)
|
# Konvertiere die Körperpositionen der Schlangen in ein Set von Tupeln für schnellen Zugriff
|
||||||
return safe_positions
|
body_positions = set()
|
||||||
|
for snake in snakes:
|
||||||
|
for part in snake['body']:
|
||||||
|
body_positions.add((part['x'], part['y']))
|
||||||
|
|
||||||
def find_safe_positions(self, body_positions, board_width, board_height):
|
# Implementiere die Logik, um Positionen zu finden, die nicht von Schlangenkörpern belegt sind
|
||||||
# Finde sichere Positionen basierend auf den Körperpositionen und der Größe des Spielbretts
|
safe_positions = self.find_safe_positions(body_positions, board_width, board_height)
|
||||||
safe_positions = []
|
return safe_positions
|
||||||
for x in range(board_width): # Nutze die tatsächliche Breite des Spielbretts
|
|
||||||
for y in range(board_height): # Nutze die tatsächliche Höhe des Spielbretts
|
|
||||||
if (x, y) not in body_positions:
|
|
||||||
safe_positions.append({'x': x, 'y': y})
|
|
||||||
return safe_positions
|
|
||||||
|
|
||||||
def choose_move(self, game_data):
|
def find_safe_positions(self, body_positions, board_width, board_height):
|
||||||
board_width = game_data['board']['width']
|
# Finde sichere Positionen basierend auf den Körperpositionen und der Größe des Spielbretts
|
||||||
board_height = game_data['board']['height']
|
safe_positions = []
|
||||||
snakes = game_data['board']['snakes']
|
for x in range(board_width): # Nutze die tatsächliche Breite des Spielbretts
|
||||||
my_snake = game_data['you']
|
for y in range(board_height): # Nutze die tatsächliche Höhe des Spielbretts
|
||||||
my_head = my_snake['head']
|
if (x, y) not in body_positions:
|
||||||
|
safe_positions.append({'x': x, 'y': y})
|
||||||
|
return safe_positions
|
||||||
|
|
||||||
# Vermeide Schlangenkörper
|
def choose_move(self, game_data):
|
||||||
safe_positions = self.avoid_snake_body(snakes, board_width, board_height)
|
board_width = game_data['board']['width']
|
||||||
|
board_height = game_data['board']['height']
|
||||||
|
snakes = game_data['board']['snakes']
|
||||||
|
my_snake = game_data['you']
|
||||||
|
my_head = my_snake['head']
|
||||||
|
|
||||||
# Finde die nächstgelegene Nahrungsquelle, wenn Nahrung vorhanden ist
|
# Vermeide Schlangenkörper
|
||||||
try:
|
safe_positions = self.avoid_snake_body(snakes, board_width, board_height)
|
||||||
if self.is_food_nearby(my_head, game_data['board']['food']) or self.disabled_find_near_by_food:
|
|
||||||
path_to_food = self.find_path_to_food(game_data)
|
|
||||||
if path_to_food:
|
|
||||||
# Implementiere Logik, um in Richtung der Nahrungsquelle zu bewegen, falls sicher
|
|
||||||
move = self.move_towards(my_head, path_to_food[0], safe_positions)
|
|
||||||
self.add_to_history({"my_head": my_head, "path_to_food": path_to_food, "move": move})
|
|
||||||
else:
|
|
||||||
# Einfache Logik, um eine Bewegungsrichtung zu wählen, wenn keine Nahrung vorhanden ist
|
|
||||||
move = self.find_direction(my_head, safe_positions)
|
|
||||||
self.add_to_history({"my_head": my_head, "move": move})
|
|
||||||
else:
|
|
||||||
# Wenn keine Nahrung in der Nähe ist, bewege dich in eine Richtung, die dich nahe an deinem eigenen Körper hält
|
|
||||||
move = self.find_direction(my_head, safe_positions)
|
|
||||||
self.add_to_history({"my_head": my_head, "move": move})
|
|
||||||
except ValueError:
|
|
||||||
move = self.find_direction(my_head, safe_positions)
|
|
||||||
self.add_to_history({"my_head": my_head, "move": move})
|
|
||||||
|
|
||||||
# Finde den größten sicheren Bereich
|
# Finde die nächstgelegene Nahrungsquelle, wenn Nahrung vorhanden ist
|
||||||
max_area_start, max_area = self.flood_fill(my_head, safe_positions)
|
try:
|
||||||
# Wenn der Schwanz der Schlange im größten sicheren Bereich liegt, bewege dich in Richtung des Schwanzes
|
if self.is_food_nearby(my_head, game_data['board']['food']) or self.disabled_find_near_by_food:
|
||||||
my_tail = (my_snake['body'][-1]['x'], my_snake['body'][-1]['y']) # Convert to tuple
|
path_to_food = self.find_path_to_food(game_data)
|
||||||
if my_tail in max_area:
|
if path_to_food:
|
||||||
move = self.move_towards(my_head, my_tail, safe_positions)
|
# Implementiere Logik, um in Richtung der Nahrungsquelle zu bewegen, falls sicher
|
||||||
|
move = self.move_towards(my_head, path_to_food[0], safe_positions)
|
||||||
# Überprüfe zukünftige Bewegungen, um Sackgassen zu vermeiden
|
self.add_to_history({"my_head": my_head, "path_to_food": path_to_food, "move": move})
|
||||||
move = self.avoid_dead_ends(my_head, move, safe_positions, snakes)
|
else:
|
||||||
|
# Einfache Logik, um eine Bewegungsrichtung zu wählen, wenn keine Nahrung vorhanden ist
|
||||||
|
move = self.find_direction(my_head, safe_positions)
|
||||||
|
self.add_to_history({"my_head": my_head, "move": move})
|
||||||
|
else:
|
||||||
|
# Wenn keine Nahrung in der Nähe ist, bewege dich in eine Richtung, die dich nahe an deinem eigenen Körper hält
|
||||||
|
move = self.find_direction(my_head, safe_positions)
|
||||||
self.add_to_history({"my_head": my_head, "move": move})
|
self.add_to_history({"my_head": my_head, "move": move})
|
||||||
|
except ValueError:
|
||||||
|
move = self.find_direction(my_head, safe_positions)
|
||||||
|
self.add_to_history({"my_head": my_head, "move": move})
|
||||||
|
|
||||||
return move
|
# Finde den größten sicheren Bereich
|
||||||
|
max_area_start, max_area = self.flood_fill(my_head, safe_positions)
|
||||||
|
# Wenn der Schwanz der Schlange im größten sicheren Bereich liegt, bewege dich in Richtung des Schwanzes
|
||||||
|
my_tail = (my_snake['body'][-1]['x'], my_snake['body'][-1]['y']) # Convert to tuple
|
||||||
|
if my_tail in max_area:
|
||||||
|
move = self.move_towards(my_head, my_tail, safe_positions)
|
||||||
|
|
||||||
def move_towards(self, head, target, safe_positions):
|
# Überprüfe zukünftige Bewegungen, um Sackgassen zu vermeiden
|
||||||
directions = {'up': (0, 1), 'down': (0, -1), 'left': (-1, 0), 'right': (1, 0)}
|
move = self.avoid_dead_ends(my_head, move, safe_positions, snakes)
|
||||||
best_direction = None
|
self.add_to_history({"my_head": my_head, "move": move})
|
||||||
min_distance = float('inf')
|
|
||||||
min_distance_to_body = float('inf')
|
|
||||||
body_positions = set((pos['x'], pos['y']) for pos in safe_positions[:-1]) # Exclude the head from body positions
|
|
||||||
|
|
||||||
for direction, (dx, dy) in directions.items():
|
return move
|
||||||
next_position = {'x': head['x'] + dx, 'y': head['y'] + dy}
|
|
||||||
if next_position in safe_positions:
|
|
||||||
distance = abs(target[0] - next_position['x']) + abs(target[1] - next_position['y'])
|
|
||||||
distance_to_body = sum(abs(part[0] - next_position['x']) + abs(part[1] - next_position['y']) for part in body_positions)
|
|
||||||
if distance < min_distance or (distance == min_distance and distance_to_body < min_distance_to_body):
|
|
||||||
best_direction = direction
|
|
||||||
min_distance = distance
|
|
||||||
min_distance_to_body = distance_to_body
|
|
||||||
|
|
||||||
return best_direction if best_direction else "up" # Default to moving up if no safe direction found
|
def move_towards(self, head, target, safe_positions):
|
||||||
|
directions = {'up': (0, 1), 'down': (0, -1), 'left': (-1, 0), 'right': (1, 0)}
|
||||||
|
best_direction = None
|
||||||
|
min_distance = float('inf')
|
||||||
|
min_distance_to_body = float('inf')
|
||||||
|
body_positions = set((pos['x'], pos['y']) for pos in safe_positions[:-1]) # Exclude the head from body positions
|
||||||
|
|
||||||
def find_path_to_food(self, game_data):
|
for direction, (dx, dy) in directions.items():
|
||||||
my_head = game_data['you']['head']
|
next_position = {'x': head['x'] + dx, 'y': head['y'] + dy}
|
||||||
food_positions = game_data['board']['food']
|
if next_position in safe_positions:
|
||||||
snakes = game_data['board']['snakes']
|
distance = abs(target[0] - next_position['x']) + abs(target[1] - next_position['y'])
|
||||||
board_width = game_data['board']['width']
|
distance_to_body = sum(abs(part[0] - next_position['x']) + abs(part[1] - next_position['y']) for part in body_positions)
|
||||||
board_height = game_data['board']['height']
|
if distance < min_distance or (distance == min_distance and distance_to_body < min_distance_to_body):
|
||||||
|
best_direction = direction
|
||||||
# Exclude own snake's body from obstacles
|
min_distance = distance
|
||||||
own_snake_body = game_data['you']['body']
|
min_distance_to_body = distance_to_body
|
||||||
obstacles = set((part['x'], part['y']) for part in own_snake_body)
|
|
||||||
|
|
||||||
for snake in snakes:
|
|
||||||
if snake['id'] != game_data['you']['id']:
|
|
||||||
for part in snake['body']:
|
|
||||||
obstacles.add((part['x'], part['y']))
|
|
||||||
|
|
||||||
# Choose the closest food source based on the heuristic
|
|
||||||
closest_food = min(food_positions, key=lambda food: abs(food['x'] - my_head['x']) + abs(food['y'] - my_head['y']))
|
|
||||||
|
|
||||||
# Use A* to search for a safe path
|
|
||||||
path = self.a_star_search(my_head, closest_food, obstacles, board_width, board_height)
|
|
||||||
return path
|
|
||||||
|
|
||||||
def a_star_search(self, start, goal, obstacles, board_width, board_height):
|
return best_direction if best_direction else "up" # Default to moving up if no safe direction found
|
||||||
# Convert snake positions into a set of obstacles
|
|
||||||
# Helper functions
|
|
||||||
def is_position_safe(position):
|
|
||||||
x, y = position
|
|
||||||
return 0 <= x < board_width and 0 <= y < board_height and position not in obstacles
|
|
||||||
|
|
||||||
def get_neighbors(position):
|
def find_path_to_food(self, game_data):
|
||||||
x, y = position
|
my_head = game_data['you']['head']
|
||||||
return [(nx, ny) for nx, ny in [(x-1, y), (x+1, y), (x, y-1), (x, y+1)] if is_position_safe((nx, ny))]
|
food_positions = game_data['board']['food']
|
||||||
|
snakes = game_data['board']['snakes']
|
||||||
|
board_width = game_data['board']['width']
|
||||||
|
board_height = game_data['board']['height']
|
||||||
|
|
||||||
|
# Exclude own snake's body from obstacles
|
||||||
|
own_snake_body = game_data['you']['body']
|
||||||
|
obstacles = set((part['x'], part['y']) for part in own_snake_body)
|
||||||
|
|
||||||
|
for snake in snakes:
|
||||||
|
if snake['id'] != game_data['you']['id']:
|
||||||
|
for part in snake['body']:
|
||||||
|
obstacles.add((part['x'], part['y']))
|
||||||
|
|
||||||
|
# Choose the closest food source based on the heuristic
|
||||||
|
closest_food = min(food_positions, key=lambda food: abs(food['x'] - my_head['x']) + abs(food['y'] - my_head['y']))
|
||||||
|
|
||||||
|
# Use A* to search for a safe path
|
||||||
|
path = self.a_star_search(my_head, closest_food, obstacles, board_width, board_height)
|
||||||
|
return path
|
||||||
|
|
||||||
def heuristic(position, goal):
|
def a_star_search(self, start, goal, obstacles, board_width, board_height):
|
||||||
return abs(position[0] - goal[0]) + abs(position[1] - goal[1])
|
# Convert snake positions into a set of obstacles
|
||||||
|
# Helper functions
|
||||||
|
def is_position_safe(position):
|
||||||
|
x, y = position
|
||||||
|
return 0 <= x < board_width and 0 <= y < board_height and position not in obstacles
|
||||||
|
|
||||||
# Initialize start and goal positions
|
def get_neighbors(position):
|
||||||
start = (start['x'], start['y'])
|
x, y = position
|
||||||
goal = (goal['x'], goal['y'])
|
return [(nx, ny) for nx, ny in [(x-1, y), (x+1, y), (x, y-1), (x, y+1)] if is_position_safe((nx, ny))]
|
||||||
|
|
||||||
# Initialize the open and closed list
|
def heuristic(position, goal):
|
||||||
open_set = set([start])
|
return abs(position[0] - goal[0]) + abs(position[1] - goal[1])
|
||||||
came_from = {}
|
|
||||||
g_score = {start: 0}
|
|
||||||
f_score = {start: heuristic(start, goal)}
|
|
||||||
|
|
||||||
while open_set:
|
# Initialize start and goal positions
|
||||||
current = min(open_set, key=lambda pos: f_score.get(pos, float('inf')))
|
start = (start['x'], start['y'])
|
||||||
if current == goal:
|
goal = (goal['x'], goal['y'])
|
||||||
# Reconstruct the path
|
|
||||||
path = []
|
|
||||||
while current in came_from:
|
|
||||||
path.append(current)
|
|
||||||
current = came_from[current]
|
|
||||||
path.reverse()
|
|
||||||
return path # Return the path as a list of tuples
|
|
||||||
|
|
||||||
open_set.remove(current)
|
# Initialize the open and closed list
|
||||||
for neighbor in get_neighbors(current):
|
open_set = set([start])
|
||||||
tentative_g_score = g_score[current] + 1 # Distance between neighbors is always 1
|
came_from = {}
|
||||||
if tentative_g_score < g_score.get(neighbor, float('inf')):
|
g_score = {start: 0}
|
||||||
came_from[neighbor] = current
|
f_score = {start: heuristic(start, goal)}
|
||||||
g_score[neighbor] = tentative_g_score
|
|
||||||
f_score[neighbor] = g_score[neighbor] + heuristic(neighbor, goal)
|
|
||||||
if neighbor not in open_set:
|
|
||||||
open_set.add(neighbor)
|
|
||||||
|
|
||||||
return None # Kein Pfad gefunden
|
while open_set:
|
||||||
|
current = min(open_set, key=lambda pos: f_score.get(pos, float('inf')))
|
||||||
|
if current == goal:
|
||||||
|
# Reconstruct the path
|
||||||
|
path = []
|
||||||
|
while current in came_from:
|
||||||
|
path.append(current)
|
||||||
|
current = came_from[current]
|
||||||
|
path.reverse()
|
||||||
|
return path # Return the path as a list of tuples
|
||||||
|
|
||||||
def find_direction(self, head, safe_positions):
|
open_set.remove(current)
|
||||||
# Beispielhafte Logik zur Auswahl einer Bewegungsrichtung
|
for neighbor in get_neighbors(current):
|
||||||
directions = {'up': (0, 1), 'down': (0, -1), 'left': (-1, 0), 'right': (1, 0)}
|
tentative_g_score = g_score[current] + 1 # Distance between neighbors is always 1
|
||||||
for direction, (dx, dy) in directions.items():
|
if tentative_g_score < g_score.get(neighbor, float('inf')):
|
||||||
next_position = {'x': head['x'] + dx, 'y': head['y'] + dy}
|
came_from[neighbor] = current
|
||||||
if next_position in safe_positions:
|
g_score[neighbor] = tentative_g_score
|
||||||
return direction
|
f_score[neighbor] = g_score[neighbor] + heuristic(neighbor, goal)
|
||||||
return "up" # Standardbewegung, falls keine sichere Position gefunden wird
|
if neighbor not in open_set:
|
||||||
|
open_set.add(neighbor)
|
||||||
|
|
||||||
def avoid_self_collision(self, future_head, body_positions):
|
return None # Kein Pfad gefunden
|
||||||
# Überprüft, ob die zukünftige Kopfposition im Körper der Schlange liegt
|
|
||||||
return (future_head['x'], future_head['y']) not in body_positions
|
|
||||||
|
|
||||||
def avoid_dead_ends(self, head, move, safe_positions, snakes):
|
def find_direction(self, head, safe_positions):
|
||||||
directions = {'up': (0, 1), 'down': (0, -1), 'left': (-1, 0), 'right': (1, 0)}
|
# Beispielhafte Logik zur Auswahl einer Bewegungsrichtung
|
||||||
dx, dy = directions[move]
|
directions = {'up': (0, 1), 'down': (0, -1), 'left': (-1, 0), 'right': (1, 0)}
|
||||||
future_head = {'x': head['x'] + dx, 'y': head['y'] + dy}
|
for direction, (dx, dy) in directions.items():
|
||||||
body_positions = set((part['x'], part['y']) for part in snakes[0]['body'])
|
next_position = {'x': head['x'] + dx, 'y': head['y'] + dy}
|
||||||
|
if next_position in safe_positions:
|
||||||
|
return direction
|
||||||
|
return "up" # Standardbewegung, falls keine sichere Position gefunden wird
|
||||||
|
|
||||||
if not self.is_future_move_safe(future_head, safe_positions, snakes) or not self.avoid_self_collision(future_head, body_positions):
|
def avoid_self_collision(self, future_head, body_positions):
|
||||||
for alternative_move in directions.keys():
|
# Überprüft, ob die zukünftige Kopfposition im Körper der Schlange liegt
|
||||||
dx, dy = directions[alternative_move]
|
return (future_head['x'], future_head['y']) not in body_positions
|
||||||
alternative_future_head = {'x': head['x'] + dx, 'y': head['y'] + dy}
|
|
||||||
if self.is_future_move_safe(alternative_future_head, safe_positions, snakes) and self.avoid_self_collision(alternative_future_head, body_positions):
|
|
||||||
return alternative_move
|
|
||||||
return move
|
|
||||||
|
|
||||||
def simulate_snake_movement(self, snakes):
|
def avoid_dead_ends(self, head, move, safe_positions, snakes):
|
||||||
future_body_positions = set()
|
directions = {'up': (0, 1), 'down': (0, -1), 'left': (-1, 0), 'right': (1, 0)}
|
||||||
for snake in snakes:
|
dx, dy = directions[move]
|
||||||
# Beachte, dass dies nur ein Beispiel ist und angepasst werden muss, um deine spezifische Spiellogik zu berücksichtigen
|
future_head = {'x': head['x'] + dx, 'y': head['y'] + dy}
|
||||||
for part in snake['body'][:-1]: # Ignoriere den letzten Teil des Körpers, da er sich bewegt
|
body_positions = set((part['x'], part['y']) for part in snakes[0]['body'])
|
||||||
future_body_positions.add((part['x'], part['y']))
|
|
||||||
return future_body_positions
|
|
||||||
|
|
||||||
def is_future_move_safe(self, future_head, safe_positions, snakes):
|
if not self.is_future_move_safe(future_head, safe_positions, snakes) or not self.avoid_self_collision(future_head, body_positions):
|
||||||
# Simuliere die Bewegung der Schlange und aktualisiere die Positionen des eigenen Körpers
|
for alternative_move in directions.keys():
|
||||||
future_body_positions = self.simulate_snake_movement(snakes)
|
dx, dy = directions[alternative_move]
|
||||||
# Konvertiere safe_positions in ein Set von Tupeln für den Flood Fill Algorithmus
|
alternative_future_head = {'x': head['x'] + dx, 'y': head['y'] + dy}
|
||||||
safe_positions_set = set((pos['x'], pos['y']) for pos in safe_positions)
|
if self.is_future_move_safe(alternative_future_head, safe_positions, snakes) and self.avoid_self_collision(alternative_future_head, body_positions):
|
||||||
# Entferne die zukünftigen Körperpositionen aus den sicheren Positionen
|
return alternative_move
|
||||||
safe_positions_set = safe_positions_set - future_body_positions
|
return move
|
||||||
# Füge die zukünftige Kopfposition hinzu, um sie als Startpunkt zu verwenden
|
|
||||||
safe_positions_set.add((future_head['x'], future_head['y']))
|
|
||||||
# Berechne die Anzahl der erreichbaren sicheren Positionen von der zukünftigen Kopfposition aus
|
|
||||||
reachable_positions = self.flood_fill((future_head['x'], future_head['y']), safe_positions_set)
|
|
||||||
# Entscheide, ob die Bewegung sicher ist, basierend auf der Anzahl der erreichbaren Positionen
|
|
||||||
|
|
||||||
fill_bool = len(reachable_positions) > len(safe_positions_set) * 0.25
|
def simulate_snake_movement(self, snakes):
|
||||||
if fill_bool:
|
future_body_positions = set()
|
||||||
return fill_bool
|
for snake in snakes:
|
||||||
|
# Beachte, dass dies nur ein Beispiel ist und angepasst werden muss, um deine spezifische Spiellogik zu berücksichtigen
|
||||||
|
for part in snake['body'][:-1]: # Ignoriere den letzten Teil des Körpers, da er sich bewegt
|
||||||
|
future_body_positions.add((part['x'], part['y']))
|
||||||
|
return future_body_positions
|
||||||
|
|
||||||
return len(safe_positions_set) >= len(snakes[0]['body'])
|
def is_future_move_safe(self, future_head, safe_positions, snakes):
|
||||||
|
# Simuliere die Bewegung der Schlange und aktualisiere die Positionen des eigenen Körpers
|
||||||
|
future_body_positions = self.simulate_snake_movement(snakes)
|
||||||
|
# Konvertiere safe_positions in ein Set von Tupeln für den Flood Fill Algorithmus
|
||||||
|
safe_positions_set = set((pos['x'], pos['y']) for pos in safe_positions)
|
||||||
|
# Entferne die zukünftigen Körperpositionen aus den sicheren Positionen
|
||||||
|
safe_positions_set = safe_positions_set - future_body_positions
|
||||||
|
# Füge die zukünftige Kopfposition hinzu, um sie als Startpunkt zu verwenden
|
||||||
|
safe_positions_set.add((future_head['x'], future_head['y']))
|
||||||
|
# Berechne die Anzahl der erreichbaren sicheren Positionen von der zukünftigen Kopfposition aus
|
||||||
|
reachable_positions = self.flood_fill((future_head['x'], future_head['y']), safe_positions_set)
|
||||||
|
# Entscheide, ob die Bewegung sicher ist, basierend auf der Anzahl der erreichbaren Positionen
|
||||||
|
|
||||||
def flood_fill(self, start, safe_positions):
|
fill_bool = len(reachable_positions) > len(safe_positions_set) * 0.25
|
||||||
stack = [start]
|
if fill_bool:
|
||||||
visited = set()
|
return fill_bool
|
||||||
max_area = 0
|
|
||||||
max_area_start = None
|
|
||||||
|
|
||||||
while stack:
|
return len(safe_positions_set) >= len(snakes[0]['body'])
|
||||||
position = stack.pop()
|
|
||||||
if isinstance(position, dict):
|
|
||||||
position = tuple(position.values())
|
|
||||||
else:
|
|
||||||
position = tuple(position)
|
|
||||||
|
|
||||||
if position not in visited:
|
def flood_fill(self, start, safe_positions):
|
||||||
visited.add(position)
|
stack = [start]
|
||||||
for dx, dy in [(-1, 0), (1, 0), (0, -1), (0, 1)]: # links, rechts, oben, unten
|
visited = set()
|
||||||
next_position = tuple([position[0] + dx, position[1] + dy])
|
max_area = 0
|
||||||
if next_position in safe_positions:
|
max_area_start = None
|
||||||
stack.append(next_position)
|
|
||||||
|
|
||||||
# Überprüfe, ob der aktuelle Bereich größer ist als der bisher größte Bereich
|
while stack:
|
||||||
if len(visited) > max_area:
|
position = stack.pop()
|
||||||
max_area = len(visited)
|
if isinstance(position, dict):
|
||||||
max_area_start = position
|
position = tuple(position.values())
|
||||||
|
else:
|
||||||
|
position = tuple(position)
|
||||||
|
|
||||||
return max_area_start, visited
|
if position not in visited:
|
||||||
|
visited.add(position)
|
||||||
|
for dx, dy in [(-1, 0), (1, 0), (0, -1), (0, 1)]: # links, rechts, oben, unten
|
||||||
|
next_position = tuple([position[0] + dx, position[1] + dy])
|
||||||
|
if next_position in safe_positions:
|
||||||
|
stack.append(next_position)
|
||||||
|
|
||||||
|
# Überprüfe, ob der aktuelle Bereich größer ist als der bisher größte Bereich
|
||||||
|
if len(visited) > max_area:
|
||||||
|
max_area = len(visited)
|
||||||
|
max_area_start = position
|
||||||
|
|
||||||
|
return max_area_start, visited
|
||||||
|
|||||||
@@ -1,256 +0,0 @@
|
|||||||
from snakes.TemplateSnake import TemplateSnake
|
|
||||||
|
|
||||||
class MasterSnake(TemplateSnake):
|
|
||||||
def __init__(self):
|
|
||||||
super().__init__()
|
|
||||||
self.name = "MasterSnake"
|
|
||||||
self.history_head = []
|
|
||||||
|
|
||||||
def avoid_snake_body(self, snakes, board_width, board_height):
|
|
||||||
# Konvertiere die Körperpositionen der Schlangen in ein Set von Tupeln für schnellen Zugriff
|
|
||||||
body_positions = set()
|
|
||||||
for snake in snakes:
|
|
||||||
for part in snake['body']:
|
|
||||||
body_positions.add((part['x'], part['y']))
|
|
||||||
|
|
||||||
# Implementiere die Logik, um Positionen zu finden, die nicht von Schlangenkörpern belegt sind
|
|
||||||
safe_positions = self.find_safe_positions(body_positions, board_width, board_height)
|
|
||||||
return safe_positions
|
|
||||||
|
|
||||||
def find_safe_positions(self, body_positions, board_width, board_height):
|
|
||||||
# Finde sichere Positionen basierend auf den Körperpositionen und der Größe des Spielbretts
|
|
||||||
safe_positions = []
|
|
||||||
for x in range(board_width): # Nutze die tatsächliche Breite des Spielbretts
|
|
||||||
for y in range(board_height): # Nutze die tatsächliche Höhe des Spielbretts
|
|
||||||
if (x, y) not in body_positions:
|
|
||||||
safe_positions.append({'x': x, 'y': y})
|
|
||||||
return safe_positions
|
|
||||||
|
|
||||||
def choose_move(self, game_data):
|
|
||||||
board_width = game_data['board']['width']
|
|
||||||
board_height = game_data['board']['height']
|
|
||||||
snakes = game_data['board']['snakes']
|
|
||||||
my_snake = game_data['you']
|
|
||||||
my_head = my_snake['head']
|
|
||||||
|
|
||||||
# Vermeide Schlangenkörper
|
|
||||||
safe_positions = self.avoid_snake_body(snakes, board_width, board_height)
|
|
||||||
|
|
||||||
# Wähle Nahrung basierend auf verfügbarem Platz
|
|
||||||
try:
|
|
||||||
chosen_food = self.choose_food_based_on_space(game_data)
|
|
||||||
if chosen_food:
|
|
||||||
path_to_food = self.a_star_search(my_head, chosen_food, self.get_obstacles(game_data), board_width, board_height)
|
|
||||||
if path_to_food:
|
|
||||||
# Implementiere Logik, um in Richtung der Nahrungsquelle zu bewegen, falls sicher
|
|
||||||
move = self.move_towards_food(my_head, path_to_food[0], safe_positions)
|
|
||||||
self.add_to_history({"my_head": my_head, "path_to_food": path_to_food, "move": move})
|
|
||||||
else:
|
|
||||||
# Einfache Logik, um eine Bewegungsrichtung zu wählen, wenn kein Pfad zur Nahrung vorhanden ist
|
|
||||||
move = self.find_direction(my_head, safe_positions)
|
|
||||||
self.add_to_history({"my_head": my_head, "move": move})
|
|
||||||
else:
|
|
||||||
# Einfache Logik, um eine Bewegungsrichtung zu wählen, wenn keine geeignete Nahrung gefunden wird
|
|
||||||
move = self.find_direction(my_head, safe_positions)
|
|
||||||
self.add_to_history({"my_head": my_head, "move": move})
|
|
||||||
except ValueError:
|
|
||||||
move = self.find_direction(my_head, safe_positions)
|
|
||||||
self.add_to_history({"my_head": my_head, "move": move})
|
|
||||||
|
|
||||||
# Überprüfe zukünftige Bewegungen, um Sackgassen zu vermeiden
|
|
||||||
move = self.avoid_dead_ends_and_circles(my_head, move, safe_positions, board_width, board_height, snakes)
|
|
||||||
self.add_to_history({"my_head": my_head, "move": move})
|
|
||||||
self.add_to_history_head({"my_head": my_head, "move": move})
|
|
||||||
|
|
||||||
return move
|
|
||||||
|
|
||||||
def move_towards_food(self, head, food, safe_positions):
|
|
||||||
directions = {'up': (0, 1), 'down': (0, -1), 'left': (-1, 0), 'right': (1, 0)}
|
|
||||||
best_direction = None
|
|
||||||
min_distance = float('inf')
|
|
||||||
min_distance_to_body = float('inf')
|
|
||||||
body_positions = set((pos['x'], pos['y']) for pos in safe_positions[:-1]) # Exclude the head from body positions
|
|
||||||
|
|
||||||
for direction, (dx, dy) in directions.items():
|
|
||||||
next_position = {'x': head['x'] + dx, 'y': head['y'] + dy}
|
|
||||||
if next_position in safe_positions:
|
|
||||||
distance = abs(food[0] - next_position['x']) + abs(food[1] - next_position['y'])
|
|
||||||
distance_to_body = sum(abs(part[0] - next_position['x']) + abs(part[1] - next_position['y']) for part in body_positions)
|
|
||||||
if distance < min_distance or (distance == min_distance and distance_to_body < min_distance_to_body):
|
|
||||||
best_direction = direction
|
|
||||||
min_distance = distance
|
|
||||||
min_distance_to_body = distance_to_body
|
|
||||||
|
|
||||||
return best_direction if best_direction else "up" # Default to moving up if no safe direction found
|
|
||||||
|
|
||||||
def find_path_to_food(self, game_data):
|
|
||||||
my_head = game_data['you']['head']
|
|
||||||
food_positions = game_data['board']['food']
|
|
||||||
snakes = game_data['board']['snakes']
|
|
||||||
board_width = game_data['board']['width']
|
|
||||||
board_height = game_data['board']['height']
|
|
||||||
|
|
||||||
# Exclude own snake's body from obstacles
|
|
||||||
own_snake_body = game_data['you']['body']
|
|
||||||
obstacles = set((part['x'], part['y']) for part in own_snake_body)
|
|
||||||
|
|
||||||
for snake in snakes:
|
|
||||||
if snake['id'] != game_data['you']['id']:
|
|
||||||
for part in snake['body']:
|
|
||||||
obstacles.add((part['x'], part['y']))
|
|
||||||
|
|
||||||
# Choose the closest food source based on the heuristic
|
|
||||||
closest_food = min(food_positions, key=lambda food: abs(food['x'] - my_head['x']) + abs(food['y'] - my_head['y']))
|
|
||||||
|
|
||||||
# Use A* to search for a safe path
|
|
||||||
path = self.a_star_search(my_head, closest_food, obstacles, board_width, board_height)
|
|
||||||
return path
|
|
||||||
|
|
||||||
def choose_food_based_on_space(self, game_data):
|
|
||||||
my_head = game_data['you']['head']
|
|
||||||
food_positions = game_data['board']['food']
|
|
||||||
snakes = game_data['board']['snakes']
|
|
||||||
board_width = game_data['board']['width']
|
|
||||||
board_height = game_data['board']['height']
|
|
||||||
my_length = game_data['you']['length']
|
|
||||||
|
|
||||||
# Sortiere die Nahrungsquellen basierend auf ihrer Entfernung
|
|
||||||
sorted_food = sorted(food_positions, key=lambda food: abs(food['x'] - my_head['x']) + abs(food['y'] - my_head['y']))
|
|
||||||
|
|
||||||
for food in sorted_food:
|
|
||||||
path = self.a_star_search(my_head, food, self.get_obstacles(game_data), board_width, board_height)
|
|
||||||
if path and self.will_fit_in_space(path, my_length, board_width, board_height):
|
|
||||||
return food # Diese Nahrung ist erreichbar und es gibt genug Platz
|
|
||||||
|
|
||||||
# Wenn keine geeignete Nahrung gefunden wird, gib ein Standard-Nahrungsobjekt zurück oder löse eine Ausnahme aus
|
|
||||||
if food_positions:
|
|
||||||
return food_positions[0] # Gib das erste Nahrungsobjekt zurück
|
|
||||||
else:
|
|
||||||
raise ValueError("Keine Nahrung gefunden") # Oder löse eine Ausnahme aus
|
|
||||||
|
|
||||||
def will_fit_in_space(self, path, snake_length, board_width, board_height):
|
|
||||||
# Überprüfe, ob die Länge des Pfades größer oder gleich der Länge der Schlange ist
|
|
||||||
if len(path) >= snake_length:
|
|
||||||
return True
|
|
||||||
|
|
||||||
# Überprüfe, ob es genügend Platz um den Endpunkt des Pfades gibt
|
|
||||||
end_of_path = path[-1]
|
|
||||||
space_count = self.count_space_around(end_of_path, board_width, board_height)
|
|
||||||
return space_count >= snake_length
|
|
||||||
|
|
||||||
def count_space_around(self, position, board_width, board_height):
|
|
||||||
# Zähle die Anzahl der erreichbaren Positionen um einen Punkt herum
|
|
||||||
x, y = position
|
|
||||||
count = 0
|
|
||||||
for dx in [-1, 0, 1]:
|
|
||||||
for dy in [-1, 0, 1]:
|
|
||||||
if (dx != 0 or dy != 0) and 0 <= x + dx < board_width and 0 <= y + dy < board_height:
|
|
||||||
count += 1
|
|
||||||
return count
|
|
||||||
|
|
||||||
def get_obstacles(self, game_data):
|
|
||||||
# Erstelle ein Set von Hindernissen für die A* Suche
|
|
||||||
obstacles = set()
|
|
||||||
for snake in game_data['board']['snakes']:
|
|
||||||
for part in snake['body']:
|
|
||||||
obstacles.add((part['x'], part['y']))
|
|
||||||
return obstacles
|
|
||||||
|
|
||||||
def a_star_search(self, start, goal, obstacles, board_width, board_height):
|
|
||||||
# Convert snake positions into a set of obstacles
|
|
||||||
# Helper functions
|
|
||||||
def is_position_safe(position):
|
|
||||||
x, y = position
|
|
||||||
return 0 <= x < board_width and 0 <= y < board_height and position not in obstacles
|
|
||||||
|
|
||||||
def get_neighbors(position):
|
|
||||||
x, y = position
|
|
||||||
return [(nx, ny) for nx, ny in [(x-1, y), (x+1, y), (x, y-1), (x, y+1)] if is_position_safe((nx, ny))]
|
|
||||||
|
|
||||||
def heuristic(position, goal):
|
|
||||||
return abs(position[0] - goal[0]) + abs(position[1] - goal[1])
|
|
||||||
|
|
||||||
# Initialize start and goal positions
|
|
||||||
start = (start['x'], start['y'])
|
|
||||||
goal = (goal['x'], goal['y'])
|
|
||||||
|
|
||||||
# Initialize the open and closed list
|
|
||||||
open_set = set([start])
|
|
||||||
came_from = {}
|
|
||||||
g_score = {start: 0}
|
|
||||||
f_score = {start: heuristic(start, goal)}
|
|
||||||
|
|
||||||
while open_set:
|
|
||||||
current = min(open_set, key=lambda pos: f_score.get(pos, float('inf')))
|
|
||||||
if current == goal:
|
|
||||||
# Reconstruct the path
|
|
||||||
path = []
|
|
||||||
while current in came_from:
|
|
||||||
path.append(current)
|
|
||||||
current = came_from[current]
|
|
||||||
path.reverse()
|
|
||||||
return path # Return the path as a list of tuples
|
|
||||||
|
|
||||||
open_set.remove(current)
|
|
||||||
for neighbor in get_neighbors(current):
|
|
||||||
tentative_g_score = g_score[current] + 1 # Distance between neighbors is always 1
|
|
||||||
if tentative_g_score < g_score.get(neighbor, float('inf')):
|
|
||||||
came_from[neighbor] = current
|
|
||||||
g_score[neighbor] = tentative_g_score
|
|
||||||
f_score[neighbor] = g_score[neighbor] + heuristic(neighbor, goal)
|
|
||||||
if neighbor not in open_set:
|
|
||||||
open_set.add(neighbor)
|
|
||||||
|
|
||||||
return None # Kein Pfad gefunden
|
|
||||||
|
|
||||||
def find_direction(self, head, safe_positions):
|
|
||||||
# Beispielhafte Logik zur Auswahl einer Bewegungsrichtung
|
|
||||||
directions = {'up': (0, 1), 'down': (0, -1), 'left': (-1, 0), 'right': (1, 0)}
|
|
||||||
for direction, (dx, dy) in directions.items():
|
|
||||||
next_position = {'x': head['x'] + dx, 'y': head['y'] + dy}
|
|
||||||
if next_position in safe_positions:
|
|
||||||
return direction
|
|
||||||
return "up" # Standardbewegung, falls keine sichere Position gefunden wird
|
|
||||||
|
|
||||||
def is_in_history(self, future_head):
|
|
||||||
# Überprüfe, ob die zukünftige Kopfposition in den letzten N Bewegungen vorkommt
|
|
||||||
return any(future_head == move_data["my_head"] for move_data in self.history_head[-10:])
|
|
||||||
|
|
||||||
def avoid_dead_ends_and_circles(self, head, move, safe_positions, board_width, board_height, snakes):
|
|
||||||
directions = {'up': (0, 1), 'down': (0, -1), 'left': (-1, 0), 'right': (1, 0)}
|
|
||||||
dx, dy = directions[move]
|
|
||||||
future_head = {'x': head['x'] + dx, 'y': head['y'] + dy}
|
|
||||||
|
|
||||||
if not self.is_future_move_safe(future_head, safe_positions, board_width, board_height, snakes) or self.is_in_history(future_head):
|
|
||||||
for alternative_move in directions.keys():
|
|
||||||
dx, dy = directions[alternative_move]
|
|
||||||
alternative_future_head = {'x': head['x'] + dx, 'y': head['y'] + dy}
|
|
||||||
if self.is_future_move_safe(alternative_future_head, safe_positions, board_width, board_height, snakes) and not self.is_in_history(alternative_future_head):
|
|
||||||
return alternative_move
|
|
||||||
return move
|
|
||||||
|
|
||||||
def add_to_history_head(self, move_data):
|
|
||||||
# Füge die aktuelle Kopfposition zur Historie hinzu und behalte nur die letzten 10 Positionen
|
|
||||||
self.history_head.append(move_data)
|
|
||||||
self.history_head = self.history_head[-10:]
|
|
||||||
|
|
||||||
def simulate_snake_movement(self, snakes):
|
|
||||||
future_body_positions = set()
|
|
||||||
for snake in snakes:
|
|
||||||
# Beachte, dass dies nur ein Beispiel ist und angepasst werden muss, um deine spezifische Spiellogik zu berücksichtigen
|
|
||||||
for part in snake['body'][:-1]: # Ignoriere den letzten Teil des Körpers, da er sich bewegt
|
|
||||||
future_body_positions.add((part['x'], part['y']))
|
|
||||||
return future_body_positions
|
|
||||||
|
|
||||||
def is_future_move_safe(self, future_head, safe_positions, board_width, board_height, snakes):
|
|
||||||
# Simuliere die Bewegung der Schlange und aktualisiere die Positionen des eigenen Körpers
|
|
||||||
future_body_positions = self.simulate_snake_movement(snakes)
|
|
||||||
# Konvertiere safe_positions in ein Set von Tupeln für den Flood Fill Algorithmus
|
|
||||||
safe_positions_set = set((pos['x'], pos['y']) for pos in safe_positions)
|
|
||||||
# Entferne die zukünftigen Körperpositionen aus den sicheren Positionen
|
|
||||||
safe_positions_set = safe_positions_set - future_body_positions
|
|
||||||
# Füge die zukünftige Kopfposition hinzu, um sie als Startpunkt zu verwenden
|
|
||||||
safe_positions_set.add((future_head['x'], future_head['y']))
|
|
||||||
# Berechne die Anzahl der erreichbaren sicheren Positionen von der zukünftigen Kopfposition aus
|
|
||||||
# Entscheide, ob die Bewegung sicher ist, basierend auf der Anzahl der erreichbaren Positionen
|
|
||||||
return safe_positions_set # oder wähle einen anderen Schwellenwert
|
|
||||||
+187
-2
@@ -1,6 +1,14 @@
|
|||||||
|
from server.GameBoard import GameBoard
|
||||||
|
import random
|
||||||
|
|
||||||
class TemplateSnake:
|
class TemplateSnake:
|
||||||
|
VERSION = "1.0.0"
|
||||||
|
|
||||||
def __init__(self):
|
def __init__(self):
|
||||||
self.history = []
|
self.history = []
|
||||||
|
self.target_food = None
|
||||||
|
self.name = self.__class__.__name__
|
||||||
|
self.version = getattr(self, "VERSION", "1.0.0")
|
||||||
|
|
||||||
def clear_history(self):
|
def clear_history(self):
|
||||||
self.history = []
|
self.history = []
|
||||||
@@ -11,5 +19,182 @@ class TemplateSnake:
|
|||||||
def get_history(self):
|
def get_history(self):
|
||||||
return self.history
|
return self.history
|
||||||
|
|
||||||
def choose_move(self, game_data:dict):
|
def add_calculations(self, calculations:dict):
|
||||||
pass
|
self.calculations.append(calculations)
|
||||||
|
|
||||||
|
def choose_move(self, game_data:GameBoard):
|
||||||
|
self.game_board = game_data
|
||||||
|
self.calculations = []
|
||||||
|
self.eat_the_snake_overwrite = False
|
||||||
|
|
||||||
|
self.safe_positions = self.find_safe_positions(add_to_calculations=True)
|
||||||
|
moves = list(self.safe_positions.keys())
|
||||||
|
if len(moves) > 0:
|
||||||
|
move = random.choice(moves)
|
||||||
|
else:
|
||||||
|
print("No safe positions left - Going to Die")
|
||||||
|
move = None
|
||||||
|
|
||||||
|
self.add_to_history({"turn": game_data.get_turn(), "data": self.calculations})
|
||||||
|
return move if move else "up"
|
||||||
|
|
||||||
|
def get_possible_moves(self, snake_head):
|
||||||
|
return {
|
||||||
|
"up": {
|
||||||
|
"x": snake_head["x"],
|
||||||
|
"y": snake_head["y"] + 1
|
||||||
|
},
|
||||||
|
"down": {
|
||||||
|
"x": snake_head["x"],
|
||||||
|
"y": snake_head["y"] - 1
|
||||||
|
},
|
||||||
|
"left": {
|
||||||
|
"x": snake_head["x"] - 1,
|
||||||
|
"y": snake_head["y"]
|
||||||
|
},
|
||||||
|
"right": {
|
||||||
|
"x": snake_head["x"] + 1,
|
||||||
|
"y": snake_head["y"]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
def get_snake_body_without_snake_tail(self, snake:list[dict]):
|
||||||
|
if len(set((pos["x"], pos["y"]) for pos in snake)) < 3:
|
||||||
|
return snake
|
||||||
|
|
||||||
|
snake.pop()
|
||||||
|
return snake
|
||||||
|
|
||||||
|
def avoid_my_body(self, my_body:list[dict], my_head:dict, safe_positions:dict[str, dict], add_to_calculations:bool=False) -> list:
|
||||||
|
"""
|
||||||
|
my_body: List of dictionaries of x/y coordinates for every segment of a Battlesnake.
|
||||||
|
e.g. [ {"x": 0, "y": 0}, {"x": 1, "y": 0}, {"x": 2, "y": 0} ]
|
||||||
|
possible_moves: List of strings. Moves to pick from.
|
||||||
|
e.g. ["up", "down", "left", "right"]
|
||||||
|
|
||||||
|
return: The list of remaining possible_moves, with the 'neck' direction removed
|
||||||
|
"""
|
||||||
|
remove = []
|
||||||
|
my_body = self.did_snake_eat_food(my_body, my_head, add_to_calculations)
|
||||||
|
for direction, location in safe_positions.items():
|
||||||
|
if location in my_body:
|
||||||
|
remove.append(direction)
|
||||||
|
|
||||||
|
for direction in remove:
|
||||||
|
del safe_positions[direction]
|
||||||
|
|
||||||
|
if add_to_calculations:
|
||||||
|
self.add_calculations({"function": "avoid_my_body", "my_body": my_body, "safe_positions": safe_positions})
|
||||||
|
|
||||||
|
return safe_positions
|
||||||
|
|
||||||
|
def avoid_walls(self, safe_positions:dict[str, dict], add_to_calculations:bool=False):
|
||||||
|
remove = []
|
||||||
|
for direction, location in list(safe_positions.items()):
|
||||||
|
x_out_range = (location["x"] < 0 or location["x"] == self.game_board.get_width())
|
||||||
|
y_out_range = (location["y"] < 0 or location["y"] == self.game_board.get_height())
|
||||||
|
if x_out_range or y_out_range:
|
||||||
|
remove.append(direction)
|
||||||
|
|
||||||
|
for direction in remove:
|
||||||
|
del safe_positions[direction]
|
||||||
|
|
||||||
|
if add_to_calculations:
|
||||||
|
self.add_calculations({"function": "avoid_walls", "board_width": self.game_board.get_width(), "board_height": self.game_board.get_height(), "safe_positions": safe_positions})
|
||||||
|
|
||||||
|
return safe_positions
|
||||||
|
|
||||||
|
def avoid_snakes(self, other_snakes:list[dict], safe_positions:dict[str, dict], add_to_calculations:bool=False):
|
||||||
|
remove = []
|
||||||
|
for snake in other_snakes:
|
||||||
|
for direction, location in safe_positions.items():
|
||||||
|
#if self.game_type == "constrictor":
|
||||||
|
if location in snake["body"]:
|
||||||
|
remove.append(direction)
|
||||||
|
#else:
|
||||||
|
# if location in self.get_snake_body_without_snake_tail(snake["body"]):
|
||||||
|
# remove.append(direction)
|
||||||
|
|
||||||
|
remove = set(remove)
|
||||||
|
for direction in remove:
|
||||||
|
del safe_positions[direction]
|
||||||
|
|
||||||
|
if add_to_calculations:
|
||||||
|
self.add_calculations({"function": "avoid_snakes", "other_snakes": other_snakes, "safe_positions": safe_positions})
|
||||||
|
|
||||||
|
return safe_positions
|
||||||
|
|
||||||
|
def avoid_get_eaten_by_other_snakes(self, other_snakes:list[dict], safe_positions:dict[str, dict], add_to_calculations:bool=False):
|
||||||
|
remove = []
|
||||||
|
no_way_out = {}
|
||||||
|
self.other_snake_posible_moves = []
|
||||||
|
|
||||||
|
for snake in other_snakes:
|
||||||
|
for direction, location in safe_positions.items():
|
||||||
|
if len(safe_positions) > 1:
|
||||||
|
self.other_snake_posible_moves = [{"x": v["x"], "y": v["y"]} for k, v in self.get_possible_moves(snake["head"]).items()]
|
||||||
|
if snake["length"] < self.game_board.get_my_snake()["length"] and location in self.other_snake_posible_moves:
|
||||||
|
self.eat_the_snake_overwrite = True
|
||||||
|
self.kill_the_snake = direction
|
||||||
|
#TODO: Testing - Check if snake on the way to the food here and only remove this pos
|
||||||
|
elif location in self.other_snake_posible_moves and location in [{"x": food["x"], "y": food["y"]} for food in self.game_board.get_food()]:
|
||||||
|
remove.append(direction)
|
||||||
|
elif location in self.other_snake_posible_moves:
|
||||||
|
no_way_out[direction] = location
|
||||||
|
remove.append(direction)
|
||||||
|
|
||||||
|
remove = set(remove)
|
||||||
|
for direction in remove:
|
||||||
|
del safe_positions[direction]
|
||||||
|
|
||||||
|
if len(safe_positions) == 0:
|
||||||
|
safe_positions = no_way_out
|
||||||
|
|
||||||
|
if add_to_calculations:
|
||||||
|
self.add_calculations({"function": "avoid_get_eaten_by_other_snakes", "other_snakes": other_snakes, "safe_positions": safe_positions})
|
||||||
|
|
||||||
|
return safe_positions
|
||||||
|
|
||||||
|
def find_safe_positions(self, add_to_calculations:bool=False):
|
||||||
|
safe_positions = self.get_possible_moves(self.game_board.get_my_snake_head())
|
||||||
|
if add_to_calculations:
|
||||||
|
self.add_calculations({"function": "get_possible_moves", "safe_positions": safe_positions})
|
||||||
|
|
||||||
|
safe_positions = self.avoid_my_body(self.game_board.get_my_snake_body(), self.game_board.get_my_snake_head(), safe_positions, add_to_calculations)
|
||||||
|
safe_positions = self.avoid_walls(safe_positions, add_to_calculations)
|
||||||
|
safe_positions = self.avoid_snakes(self.game_board.get_other_snakes(), safe_positions, add_to_calculations)
|
||||||
|
safe_positions = self.avoid_get_eaten_by_other_snakes(self.game_board.get_other_snakes(), safe_positions, add_to_calculations)
|
||||||
|
return safe_positions
|
||||||
|
|
||||||
|
def calculate_new_body_position(self, move:str=None, with_tail:bool=False):
|
||||||
|
if move:
|
||||||
|
head = self.get_possible_moves(self.game_board.get_my_snake_head())[move]
|
||||||
|
|
||||||
|
body = [head]
|
||||||
|
body.extend(self.game_board.get_my_snake_body())
|
||||||
|
body.pop()
|
||||||
|
|
||||||
|
if not with_tail:
|
||||||
|
body.pop()
|
||||||
|
|
||||||
|
return body
|
||||||
|
return move
|
||||||
|
|
||||||
|
def did_snake_eat_food(self, my_body:list[dict], my_head:dict, add_to_calculations:bool=False):
|
||||||
|
if self.target_food is None:
|
||||||
|
if add_to_calculations:
|
||||||
|
self.add_calculations({"function": "did_snake_eat_food", "my_body": my_body, "my_head": my_head, "target_food": self.target_food, "action": "No Target Food"})
|
||||||
|
return my_body
|
||||||
|
|
||||||
|
if self.target_food["x"] == my_head["x"] and self.target_food["y"] == my_head["y"]:
|
||||||
|
if add_to_calculations:
|
||||||
|
self.add_calculations({"function": "did_snake_eat_food", "my_body": my_body, "my_head": my_head, "target_food": self.target_food, "action": "Snake Eat no food"})
|
||||||
|
return my_body
|
||||||
|
|
||||||
|
if add_to_calculations:
|
||||||
|
self.add_calculations({"function": "did_snake_eat_food", "my_body": my_body[:-1], "my_head": my_head, "target_food": self.target_food, "action": "Remove Tail from Body"})
|
||||||
|
return my_body[:-1]
|
||||||
|
|
||||||
|
def set_target_food(self, target_food:dict):
|
||||||
|
self.target_food = target_food
|
||||||
|
return True
|
||||||
|
|||||||
@@ -0,0 +1,91 @@
|
|||||||
|
from pathlib import Path
|
||||||
|
from typing import Any
|
||||||
|
import random, json, os
|
||||||
|
|
||||||
|
from server.TrainBattleSnakeAI import MOVES, extract_feature_values
|
||||||
|
from snakes.TemplateSnake import TemplateSnake
|
||||||
|
|
||||||
|
class TrainedBattleSnake(TemplateSnake):
|
||||||
|
VERSION = "0.1.0"
|
||||||
|
|
||||||
|
def __init__(self):
|
||||||
|
super().__init__()
|
||||||
|
self.name = "TrainedBattleSnake"
|
||||||
|
self.version = self.VERSION
|
||||||
|
self._model_path:Path|None=None
|
||||||
|
self._model_data:dict[str, Any]|None=None
|
||||||
|
|
||||||
|
def choose_move(self, game_data) -> str:
|
||||||
|
self.game_board = game_data
|
||||||
|
self.calculations = []
|
||||||
|
|
||||||
|
safe_positions = self.find_safe_positions(add_to_calculations=True)
|
||||||
|
if not safe_positions:
|
||||||
|
self.add_to_history({"turn": game_data.get_turn(), "reason": "no_safe_moves"})
|
||||||
|
return "up"
|
||||||
|
|
||||||
|
model = self._load_model()
|
||||||
|
if not model:
|
||||||
|
move = random.choice(list(safe_positions.keys()))
|
||||||
|
self.add_to_history({
|
||||||
|
"turn": game_data.get_turn(),
|
||||||
|
"move": move,
|
||||||
|
"reason": "model_missing",
|
||||||
|
"safe_moves": list(safe_positions.keys()),
|
||||||
|
})
|
||||||
|
return move
|
||||||
|
|
||||||
|
row = {
|
||||||
|
"turn": game_data.get_turn(),
|
||||||
|
"game_board": game_data.get_game_board_as_dict(),
|
||||||
|
}
|
||||||
|
scores = self._predict_scores(model, row)
|
||||||
|
|
||||||
|
best_safe_move = max(safe_positions.keys(), key=lambda move: scores.get(move, float("-inf")))
|
||||||
|
self.add_to_history({
|
||||||
|
"turn": game_data.get_turn(),
|
||||||
|
"move": best_safe_move,
|
||||||
|
"safe_moves": list(safe_positions.keys()),
|
||||||
|
"scores": {move: round(scores.get(move, 0.0), 5) for move in MOVES},
|
||||||
|
})
|
||||||
|
return best_safe_move
|
||||||
|
|
||||||
|
def _load_model(self) -> dict[str, Any] | None:
|
||||||
|
env_path = os.getenv("TRAINED_SNAKE_MODEL", "models/battlesnake_softmax_v2.json")
|
||||||
|
path = Path(env_path)
|
||||||
|
|
||||||
|
if self._model_path == path and self._model_data is not None:
|
||||||
|
return self._model_data
|
||||||
|
|
||||||
|
if not path.exists() or not path.is_file():
|
||||||
|
self._model_path = path
|
||||||
|
self._model_data = None
|
||||||
|
return None
|
||||||
|
|
||||||
|
payload = json.loads(path.read_text(encoding="utf-8"))
|
||||||
|
model = payload.get("model")
|
||||||
|
if not isinstance(model, dict):
|
||||||
|
self._model_path = path
|
||||||
|
self._model_data = None
|
||||||
|
return None
|
||||||
|
|
||||||
|
self._model_path = path
|
||||||
|
self._model_data = model
|
||||||
|
return model
|
||||||
|
|
||||||
|
def _predict_scores(self, model:dict[str, Any], row:dict[str, Any]) -> dict[str, float]:
|
||||||
|
return self._predict_scores_softmax_v2(model, row)
|
||||||
|
|
||||||
|
def _predict_scores_softmax_v2(self, model:dict[str, Any], row:dict[str, Any]) -> dict[str, float]:
|
||||||
|
features = extract_feature_values(row)
|
||||||
|
weights = model.get("weights", {})
|
||||||
|
bias = model.get("bias", {})
|
||||||
|
scores:dict[str, float] = {}
|
||||||
|
|
||||||
|
for move in MOVES:
|
||||||
|
move_weights = weights.get(move, {})
|
||||||
|
score = float(bias.get(move, 0.0))
|
||||||
|
for name, value in features.items():
|
||||||
|
score += float(move_weights.get(name, 0.0)) * float(value)
|
||||||
|
scores[move] = score
|
||||||
|
return scores
|
||||||
@@ -0,0 +1,34 @@
|
|||||||
|
import importlib
|
||||||
|
|
||||||
|
SNAKE_REGISTRY = {
|
||||||
|
"TemplateSnake": "1.0.0",
|
||||||
|
"DummSnake": "1.0.0",
|
||||||
|
"LogicSnake": "1.1.0",
|
||||||
|
"MasterSnake": "1.2.0",
|
||||||
|
"BetterMasterSnake": "1.3.0",
|
||||||
|
"BestBattleSnake": "2.6.0",
|
||||||
|
"TrainedBattleSnake": "0.1.0",
|
||||||
|
}
|
||||||
|
|
||||||
|
def build_snake(selected_snake: str):
|
||||||
|
if selected_snake not in SNAKE_REGISTRY:
|
||||||
|
raise ValueError(f"Unknown snake: {selected_snake}")
|
||||||
|
|
||||||
|
snake_module = importlib.import_module(f"snakes.{selected_snake}")
|
||||||
|
snake_class = getattr(snake_module, selected_snake)
|
||||||
|
return snake_class()
|
||||||
|
|
||||||
|
def get_snake_version(selected_snake: str) -> str | None:
|
||||||
|
version = SNAKE_REGISTRY.get(selected_snake)
|
||||||
|
if version is None:
|
||||||
|
return None
|
||||||
|
return str(version)
|
||||||
|
|
||||||
|
class SnakeBuilder:
|
||||||
|
@classmethod
|
||||||
|
def build(self, selected_snake: str):
|
||||||
|
return build_snake(selected_snake)
|
||||||
|
|
||||||
|
@classmethod
|
||||||
|
def get_version(self, selected_snake: str) -> str | None:
|
||||||
|
return get_snake_version(selected_snake)
|
||||||
|
|||||||
@@ -1,4 +0,0 @@
|
|||||||
BATTLESNAKE_CLI=battlesnake_cli_1.2.3_Linux_x86_64/battlesnake
|
|
||||||
|
|
||||||
|
|
||||||
$BATTLESNAKE_CLI play -W 11 -H 11 --name 'Python Starter Project' --url http://localhost:8000 -g solo --browser
|
|
||||||
@@ -0,0 +1,109 @@
|
|||||||
|
#!/usr/bin/env python3
|
||||||
|
import argparse
|
||||||
|
import time
|
||||||
|
|
||||||
|
from server.GameBoard import GameBoard
|
||||||
|
from snakes.BestBattleSnake import BestBattleSnake
|
||||||
|
|
||||||
|
def build_game_state() -> dict:
|
||||||
|
return {
|
||||||
|
"game": {
|
||||||
|
"id": "bench-best-snake",
|
||||||
|
"ruleset": {
|
||||||
|
"name": "standard",
|
||||||
|
"version": "v1.0.0",
|
||||||
|
"settings": {"hazardDamagePerTurn": 14},
|
||||||
|
},
|
||||||
|
"source": "custom",
|
||||||
|
"map": "standard",
|
||||||
|
},
|
||||||
|
"turn": 42,
|
||||||
|
"board": {
|
||||||
|
"height": 11,
|
||||||
|
"width": 11,
|
||||||
|
"food": [{"x": 1, "y": 9}, {"x": 9, "y": 1}],
|
||||||
|
"hazards": [],
|
||||||
|
"snakes": [
|
||||||
|
{
|
||||||
|
"id": "me",
|
||||||
|
"name": "me",
|
||||||
|
"health": 74,
|
||||||
|
"length": 8,
|
||||||
|
"head": {"x": 5, "y": 5},
|
||||||
|
"body": [
|
||||||
|
{"x": 5, "y": 5},
|
||||||
|
{"x": 5, "y": 4},
|
||||||
|
{"x": 5, "y": 3},
|
||||||
|
{"x": 4, "y": 3},
|
||||||
|
{"x": 3, "y": 3},
|
||||||
|
{"x": 3, "y": 4},
|
||||||
|
{"x": 3, "y": 5},
|
||||||
|
{"x": 4, "y": 5},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": "enemy",
|
||||||
|
"name": "enemy",
|
||||||
|
"health": 70,
|
||||||
|
"length": 8,
|
||||||
|
"head": {"x": 7, "y": 7},
|
||||||
|
"body": [
|
||||||
|
{"x": 7, "y": 7},
|
||||||
|
{"x": 7, "y": 6},
|
||||||
|
{"x": 7, "y": 5},
|
||||||
|
{"x": 8, "y": 5},
|
||||||
|
{"x": 9, "y": 5},
|
||||||
|
{"x": 9, "y": 6},
|
||||||
|
{"x": 9, "y": 7},
|
||||||
|
{"x": 8, "y": 7},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
"you": {
|
||||||
|
"id": "me",
|
||||||
|
"name": "me",
|
||||||
|
"health": 74,
|
||||||
|
"length": 8,
|
||||||
|
"head": {"x": 5, "y": 5},
|
||||||
|
"body": [
|
||||||
|
{"x": 5, "y": 5},
|
||||||
|
{"x": 5, "y": 4},
|
||||||
|
{"x": 5, "y": 3},
|
||||||
|
{"x": 4, "y": 3},
|
||||||
|
{"x": 3, "y": 3},
|
||||||
|
{"x": 3, "y": 4},
|
||||||
|
{"x": 3, "y": 5},
|
||||||
|
{"x": 4, "y": 5},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
def main() -> None:
|
||||||
|
parser = argparse.ArgumentParser()
|
||||||
|
parser.add_argument("--iterations", type=int, default=1000)
|
||||||
|
args = parser.parse_args()
|
||||||
|
|
||||||
|
game_state = build_game_state()
|
||||||
|
board = GameBoard(
|
||||||
|
game_id=game_state["game"]["id"],
|
||||||
|
width=game_state["board"]["width"],
|
||||||
|
height=game_state["board"]["height"],
|
||||||
|
ruleset=game_state["game"]["ruleset"],
|
||||||
|
source=game_state["game"]["source"],
|
||||||
|
map=game_state["game"]["map"],
|
||||||
|
snake_class=BestBattleSnake(),
|
||||||
|
)
|
||||||
|
|
||||||
|
start = time.perf_counter()
|
||||||
|
for i in range(args.iterations):
|
||||||
|
game_state["turn"] = i + 1
|
||||||
|
board.read_game_data(game_state)
|
||||||
|
board.snake_neat_make_a_move()
|
||||||
|
elapsed = time.perf_counter() - start
|
||||||
|
|
||||||
|
avg_ms = (elapsed / max(1, args.iterations)) * 1000.0
|
||||||
|
print(f"BestBattleSnake benchmark: {args.iterations} moves in {elapsed:.4f}s ({avg_ms:.3f} ms/move)")
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
main()
|
||||||
@@ -0,0 +1,833 @@
|
|||||||
|
import unittest
|
||||||
|
|
||||||
|
from snakes.BestBattleSnake import BestBattleSnake
|
||||||
|
from server.GameBoard import GameBoard
|
||||||
|
|
||||||
|
def make_board(game_state):
|
||||||
|
board = GameBoard(
|
||||||
|
game_id=game_state["game"]["id"],
|
||||||
|
width=game_state["board"]["width"],
|
||||||
|
height=game_state["board"]["height"],
|
||||||
|
ruleset=game_state["game"]["ruleset"],
|
||||||
|
source=game_state["game"]["source"],
|
||||||
|
map=game_state["game"]["map"],
|
||||||
|
snake_class=BestBattleSnake(),
|
||||||
|
)
|
||||||
|
board.read_game_data(game_state)
|
||||||
|
return board
|
||||||
|
|
||||||
|
class TestBestBattleSnake(unittest.TestCase):
|
||||||
|
def test_avoids_walls_and_body(self):
|
||||||
|
game_state = {
|
||||||
|
"game": {
|
||||||
|
"id": "test-wall-body",
|
||||||
|
"ruleset": {"name": "standard", "version": "v1.0.0"},
|
||||||
|
"source": "custom",
|
||||||
|
"map": "standard",
|
||||||
|
},
|
||||||
|
"turn": 20,
|
||||||
|
"board": {
|
||||||
|
"height": 7,
|
||||||
|
"width": 7,
|
||||||
|
"food": [{"x": 5, "y": 5}],
|
||||||
|
"hazards": [],
|
||||||
|
"snakes": [
|
||||||
|
{
|
||||||
|
"id": "me",
|
||||||
|
"name": "me",
|
||||||
|
"health": 90,
|
||||||
|
"length": 4,
|
||||||
|
"head": {"x": 0, "y": 0},
|
||||||
|
"body": [
|
||||||
|
{"x": 0, "y": 0},
|
||||||
|
{"x": 0, "y": 1},
|
||||||
|
{"x": 1, "y": 1},
|
||||||
|
{"x": 1, "y": 0},
|
||||||
|
],
|
||||||
|
}
|
||||||
|
],
|
||||||
|
},
|
||||||
|
"you": {
|
||||||
|
"id": "me",
|
||||||
|
"name": "me",
|
||||||
|
"health": 90,
|
||||||
|
"length": 4,
|
||||||
|
"head": {"x": 0, "y": 0},
|
||||||
|
"body": [
|
||||||
|
{"x": 0, "y": 0},
|
||||||
|
{"x": 0, "y": 1},
|
||||||
|
{"x": 1, "y": 1},
|
||||||
|
{"x": 1, "y": 0},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
move = make_board(game_state).snake_neat_make_a_move()
|
||||||
|
self.assertEqual(move, "right")
|
||||||
|
|
||||||
|
def test_prioritizes_food_when_low_health(self):
|
||||||
|
game_state = {
|
||||||
|
"game": {
|
||||||
|
"id": "test-food-low-health",
|
||||||
|
"ruleset": {"name": "standard", "version": "v1.0.0"},
|
||||||
|
"source": "custom",
|
||||||
|
"map": "standard",
|
||||||
|
},
|
||||||
|
"turn": 32,
|
||||||
|
"board": {
|
||||||
|
"height": 11,
|
||||||
|
"width": 11,
|
||||||
|
"food": [{"x": 6, "y": 5}],
|
||||||
|
"hazards": [],
|
||||||
|
"snakes": [
|
||||||
|
{
|
||||||
|
"id": "me",
|
||||||
|
"name": "me",
|
||||||
|
"health": 10,
|
||||||
|
"length": 3,
|
||||||
|
"head": {"x": 5, "y": 5},
|
||||||
|
"body": [
|
||||||
|
{"x": 5, "y": 5},
|
||||||
|
{"x": 5, "y": 4},
|
||||||
|
{"x": 5, "y": 3},
|
||||||
|
],
|
||||||
|
}
|
||||||
|
],
|
||||||
|
},
|
||||||
|
"you": {
|
||||||
|
"id": "me",
|
||||||
|
"name": "me",
|
||||||
|
"health": 10,
|
||||||
|
"length": 3,
|
||||||
|
"head": {"x": 5, "y": 5},
|
||||||
|
"body": [
|
||||||
|
{"x": 5, "y": 5},
|
||||||
|
{"x": 5, "y": 4},
|
||||||
|
{"x": 5, "y": 3},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
move = make_board(game_state).snake_neat_make_a_move()
|
||||||
|
self.assertEqual(move, "right")
|
||||||
|
|
||||||
|
def test_prioritizes_food_when_safe(self):
|
||||||
|
game_state = {
|
||||||
|
"game": {
|
||||||
|
"id": "test-food-safe",
|
||||||
|
"ruleset": {"name": "standard", "version": "v1.0.0"},
|
||||||
|
"source": "custom",
|
||||||
|
"map": "standard",
|
||||||
|
},
|
||||||
|
"turn": 8,
|
||||||
|
"board": {
|
||||||
|
"height": 11,
|
||||||
|
"width": 11,
|
||||||
|
"food": [{"x": 6, "y": 5}],
|
||||||
|
"hazards": [],
|
||||||
|
"snakes": [
|
||||||
|
{
|
||||||
|
"id": "me",
|
||||||
|
"name": "me",
|
||||||
|
"health": 95,
|
||||||
|
"length": 3,
|
||||||
|
"head": {"x": 5, "y": 5},
|
||||||
|
"body": [
|
||||||
|
{"x": 5, "y": 5},
|
||||||
|
{"x": 5, "y": 4},
|
||||||
|
{"x": 5, "y": 3},
|
||||||
|
],
|
||||||
|
}
|
||||||
|
],
|
||||||
|
},
|
||||||
|
"you": {
|
||||||
|
"id": "me",
|
||||||
|
"name": "me",
|
||||||
|
"health": 95,
|
||||||
|
"length": 3,
|
||||||
|
"head": {"x": 5, "y": 5},
|
||||||
|
"body": [
|
||||||
|
{"x": 5, "y": 5},
|
||||||
|
{"x": 5, "y": 4},
|
||||||
|
{"x": 5, "y": 3},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
move = make_board(game_state).snake_neat_make_a_move()
|
||||||
|
self.assertEqual(move, "right")
|
||||||
|
|
||||||
|
def test_avoids_losing_head_to_head(self):
|
||||||
|
game_state = {
|
||||||
|
"game": {
|
||||||
|
"id": "test-head-to-head",
|
||||||
|
"ruleset": {"name": "standard", "version": "v1.0.0"},
|
||||||
|
"source": "custom",
|
||||||
|
"map": "standard",
|
||||||
|
},
|
||||||
|
"turn": 44,
|
||||||
|
"board": {
|
||||||
|
"height": 11,
|
||||||
|
"width": 11,
|
||||||
|
"food": [{"x": 1, "y": 1}],
|
||||||
|
"hazards": [],
|
||||||
|
"snakes": [
|
||||||
|
{
|
||||||
|
"id": "me",
|
||||||
|
"name": "me",
|
||||||
|
"health": 90,
|
||||||
|
"length": 3,
|
||||||
|
"head": {"x": 5, "y": 5},
|
||||||
|
"body": [
|
||||||
|
{"x": 5, "y": 5},
|
||||||
|
{"x": 5, "y": 4},
|
||||||
|
{"x": 5, "y": 3},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": "enemy",
|
||||||
|
"name": "enemy",
|
||||||
|
"health": 90,
|
||||||
|
"length": 6,
|
||||||
|
"head": {"x": 7, "y": 5},
|
||||||
|
"body": [
|
||||||
|
{"x": 7, "y": 5},
|
||||||
|
{"x": 7, "y": 4},
|
||||||
|
{"x": 7, "y": 3},
|
||||||
|
{"x": 7, "y": 2},
|
||||||
|
{"x": 7, "y": 1},
|
||||||
|
{"x": 6, "y": 1},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
"you": {
|
||||||
|
"id": "me",
|
||||||
|
"name": "me",
|
||||||
|
"health": 90,
|
||||||
|
"length": 3,
|
||||||
|
"head": {"x": 5, "y": 5},
|
||||||
|
"body": [
|
||||||
|
{"x": 5, "y": 5},
|
||||||
|
{"x": 5, "y": 4},
|
||||||
|
{"x": 5, "y": 3},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
move = make_board(game_state).snake_neat_make_a_move()
|
||||||
|
self.assertNotEqual(move, "right")
|
||||||
|
|
||||||
|
def test_duel_small_length_lead_does_not_head_hunt(self):
|
||||||
|
game_state = {
|
||||||
|
"game": {
|
||||||
|
"id": "test-duel-small-no-head-hunt",
|
||||||
|
"ruleset": {"name": "standard", "version": "v1.0.0"},
|
||||||
|
"source": "custom",
|
||||||
|
"map": "standard",
|
||||||
|
},
|
||||||
|
"turn": 20,
|
||||||
|
"board": {
|
||||||
|
"height": 11,
|
||||||
|
"width": 11,
|
||||||
|
"food": [{"x": 1, "y": 1}],
|
||||||
|
"hazards": [],
|
||||||
|
"snakes": [
|
||||||
|
{
|
||||||
|
"id": "me",
|
||||||
|
"name": "me",
|
||||||
|
"health": 90,
|
||||||
|
"length": 7,
|
||||||
|
"head": {"x": 5, "y": 5},
|
||||||
|
"body": [
|
||||||
|
{"x": 5, "y": 5},
|
||||||
|
{"x": 5, "y": 4},
|
||||||
|
{"x": 5, "y": 3},
|
||||||
|
{"x": 4, "y": 3},
|
||||||
|
{"x": 4, "y": 4},
|
||||||
|
{"x": 4, "y": 5},
|
||||||
|
{"x": 4, "y": 6},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": "enemy",
|
||||||
|
"name": "enemy",
|
||||||
|
"health": 90,
|
||||||
|
"length": 6,
|
||||||
|
"head": {"x": 7, "y": 5},
|
||||||
|
"body": [
|
||||||
|
{"x": 7, "y": 5},
|
||||||
|
{"x": 7, "y": 4},
|
||||||
|
{"x": 7, "y": 3},
|
||||||
|
{"x": 7, "y": 2},
|
||||||
|
{"x": 7, "y": 1},
|
||||||
|
{"x": 6, "y": 1},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
"you": {
|
||||||
|
"id": "me",
|
||||||
|
"name": "me",
|
||||||
|
"health": 90,
|
||||||
|
"length": 7,
|
||||||
|
"head": {"x": 5, "y": 5},
|
||||||
|
"body": [
|
||||||
|
{"x": 5, "y": 5},
|
||||||
|
{"x": 5, "y": 4},
|
||||||
|
{"x": 5, "y": 3},
|
||||||
|
{"x": 4, "y": 3},
|
||||||
|
{"x": 4, "y": 4},
|
||||||
|
{"x": 4, "y": 5},
|
||||||
|
{"x": 4, "y": 6},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
move = make_board(game_state).snake_neat_make_a_move()
|
||||||
|
self.assertNotEqual(move, "right")
|
||||||
|
|
||||||
|
def test_duel_big_length_lead_can_head_hunt(self):
|
||||||
|
game_state = {
|
||||||
|
"game": {
|
||||||
|
"id": "test-duel-big-head-hunt",
|
||||||
|
"ruleset": {"name": "standard", "version": "v1.0.0"},
|
||||||
|
"source": "custom",
|
||||||
|
"map": "standard",
|
||||||
|
},
|
||||||
|
"turn": 20,
|
||||||
|
"board": {
|
||||||
|
"height": 11,
|
||||||
|
"width": 11,
|
||||||
|
"food": [{"x": 1, "y": 1}],
|
||||||
|
"hazards": [],
|
||||||
|
"snakes": [
|
||||||
|
{
|
||||||
|
"id": "me",
|
||||||
|
"name": "me",
|
||||||
|
"health": 90,
|
||||||
|
"length": 8,
|
||||||
|
"head": {"x": 5, "y": 5},
|
||||||
|
"body": [
|
||||||
|
{"x": 5, "y": 5},
|
||||||
|
{"x": 5, "y": 4},
|
||||||
|
{"x": 5, "y": 3},
|
||||||
|
{"x": 4, "y": 3},
|
||||||
|
{"x": 4, "y": 4},
|
||||||
|
{"x": 4, "y": 5},
|
||||||
|
{"x": 4, "y": 6},
|
||||||
|
{"x": 5, "y": 6},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": "enemy",
|
||||||
|
"name": "enemy",
|
||||||
|
"health": 90,
|
||||||
|
"length": 6,
|
||||||
|
"head": {"x": 7, "y": 5},
|
||||||
|
"body": [
|
||||||
|
{"x": 7, "y": 5},
|
||||||
|
{"x": 7, "y": 4},
|
||||||
|
{"x": 7, "y": 3},
|
||||||
|
{"x": 7, "y": 2},
|
||||||
|
{"x": 7, "y": 1},
|
||||||
|
{"x": 6, "y": 1},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
"you": {
|
||||||
|
"id": "me",
|
||||||
|
"name": "me",
|
||||||
|
"health": 90,
|
||||||
|
"length": 8,
|
||||||
|
"head": {"x": 5, "y": 5},
|
||||||
|
"body": [
|
||||||
|
{"x": 5, "y": 5},
|
||||||
|
{"x": 5, "y": 4},
|
||||||
|
{"x": 5, "y": 3},
|
||||||
|
{"x": 4, "y": 3},
|
||||||
|
{"x": 4, "y": 4},
|
||||||
|
{"x": 4, "y": 5},
|
||||||
|
{"x": 4, "y": 6},
|
||||||
|
{"x": 5, "y": 6},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
move = make_board(game_state).snake_neat_make_a_move()
|
||||||
|
self.assertEqual(move, "right")
|
||||||
|
|
||||||
|
def test_does_not_step_into_stacked_tail(self):
|
||||||
|
game_state = {
|
||||||
|
"game": {
|
||||||
|
"id": "test-stacked-tail",
|
||||||
|
"ruleset": {"name": "standard", "version": "v1.0.0"},
|
||||||
|
"source": "custom",
|
||||||
|
"map": "standard",
|
||||||
|
},
|
||||||
|
"turn": 15,
|
||||||
|
"board": {
|
||||||
|
"height": 11,
|
||||||
|
"width": 11,
|
||||||
|
"food": [{"x": 10, "y": 10}],
|
||||||
|
"hazards": [],
|
||||||
|
"snakes": [
|
||||||
|
{
|
||||||
|
"id": "me",
|
||||||
|
"name": "me",
|
||||||
|
"health": 90,
|
||||||
|
"length": 5,
|
||||||
|
"head": {"x": 5, "y": 5},
|
||||||
|
"body": [
|
||||||
|
{"x": 5, "y": 5},
|
||||||
|
{"x": 5, "y": 4},
|
||||||
|
{"x": 4, "y": 4},
|
||||||
|
{"x": 4, "y": 5},
|
||||||
|
{"x": 4, "y": 5},
|
||||||
|
],
|
||||||
|
}
|
||||||
|
],
|
||||||
|
},
|
||||||
|
"you": {
|
||||||
|
"id": "me",
|
||||||
|
"name": "me",
|
||||||
|
"health": 90,
|
||||||
|
"length": 5,
|
||||||
|
"head": {"x": 5, "y": 5},
|
||||||
|
"body": [
|
||||||
|
{"x": 5, "y": 5},
|
||||||
|
{"x": 5, "y": 4},
|
||||||
|
{"x": 4, "y": 4},
|
||||||
|
{"x": 4, "y": 5},
|
||||||
|
{"x": 4, "y": 5},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
move = make_board(game_state).snake_neat_make_a_move()
|
||||||
|
self.assertNotEqual(move, "left")
|
||||||
|
|
||||||
|
def test_avoids_food_if_it_is_a_dead_end(self):
|
||||||
|
game_state = {
|
||||||
|
"game": {
|
||||||
|
"id": "test-food-dead-end",
|
||||||
|
"ruleset": {"name": "standard", "version": "v1.0.0"},
|
||||||
|
"source": "custom",
|
||||||
|
"map": "standard",
|
||||||
|
},
|
||||||
|
"turn": 30,
|
||||||
|
"board": {
|
||||||
|
"height": 7,
|
||||||
|
"width": 7,
|
||||||
|
"food": [{"x": 3, "y": 4}],
|
||||||
|
"hazards": [],
|
||||||
|
"snakes": [
|
||||||
|
{
|
||||||
|
"id": "me",
|
||||||
|
"name": "me",
|
||||||
|
"health": 70,
|
||||||
|
"length": 3,
|
||||||
|
"head": {"x": 3, "y": 3},
|
||||||
|
"body": [
|
||||||
|
{"x": 3, "y": 3},
|
||||||
|
{"x": 3, "y": 2},
|
||||||
|
{"x": 3, "y": 1},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": "enemy",
|
||||||
|
"name": "enemy",
|
||||||
|
"health": 90,
|
||||||
|
"length": 5,
|
||||||
|
"head": {"x": 2, "y": 4},
|
||||||
|
"body": [
|
||||||
|
{"x": 2, "y": 4},
|
||||||
|
{"x": 2, "y": 5},
|
||||||
|
{"x": 3, "y": 5},
|
||||||
|
{"x": 4, "y": 5},
|
||||||
|
{"x": 4, "y": 4},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
"you": {
|
||||||
|
"id": "me",
|
||||||
|
"name": "me",
|
||||||
|
"health": 70,
|
||||||
|
"length": 3,
|
||||||
|
"head": {"x": 3, "y": 3},
|
||||||
|
"body": [
|
||||||
|
{"x": 3, "y": 3},
|
||||||
|
{"x": 3, "y": 2},
|
||||||
|
{"x": 3, "y": 1},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
move = make_board(game_state).snake_neat_make_a_move()
|
||||||
|
self.assertNotEqual(move, "up")
|
||||||
|
|
||||||
|
def test_avoids_enemy_block_in_trap(self):
|
||||||
|
game_state = {
|
||||||
|
"game": {
|
||||||
|
"id": "test-enemy-block-in-trap",
|
||||||
|
"ruleset": {"name": "standard", "version": "v1.0.0"},
|
||||||
|
"source": "custom",
|
||||||
|
"map": "standard",
|
||||||
|
},
|
||||||
|
"turn": 24,
|
||||||
|
"board": {
|
||||||
|
"height": 7,
|
||||||
|
"width": 7,
|
||||||
|
"food": [{"x": 3, "y": 3}],
|
||||||
|
"hazards": [],
|
||||||
|
"snakes": [
|
||||||
|
{
|
||||||
|
"id": "me",
|
||||||
|
"name": "me",
|
||||||
|
"health": 72,
|
||||||
|
"length": 4,
|
||||||
|
"head": {"x": 3, "y": 2},
|
||||||
|
"body": [
|
||||||
|
{"x": 3, "y": 2},
|
||||||
|
{"x": 3, "y": 1},
|
||||||
|
{"x": 2, "y": 1},
|
||||||
|
{"x": 2, "y": 2},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": "enemy-a",
|
||||||
|
"name": "enemy-a",
|
||||||
|
"health": 90,
|
||||||
|
"length": 6,
|
||||||
|
"head": {"x": 4, "y": 4},
|
||||||
|
"body": [
|
||||||
|
{"x": 4, "y": 4},
|
||||||
|
{"x": 4, "y": 3},
|
||||||
|
{"x": 4, "y": 2},
|
||||||
|
{"x": 5, "y": 2},
|
||||||
|
{"x": 5, "y": 3},
|
||||||
|
{"x": 5, "y": 4},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": "enemy-b",
|
||||||
|
"name": "enemy-b",
|
||||||
|
"health": 90,
|
||||||
|
"length": 6,
|
||||||
|
"head": {"x": 1, "y": 3},
|
||||||
|
"body": [
|
||||||
|
{"x": 1, "y": 3},
|
||||||
|
{"x": 1, "y": 4},
|
||||||
|
{"x": 0, "y": 4},
|
||||||
|
{"x": 0, "y": 3},
|
||||||
|
{"x": 0, "y": 2},
|
||||||
|
{"x": 1, "y": 2},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
"you": {
|
||||||
|
"id": "me",
|
||||||
|
"name": "me",
|
||||||
|
"health": 72,
|
||||||
|
"length": 4,
|
||||||
|
"head": {"x": 3, "y": 2},
|
||||||
|
"body": [
|
||||||
|
{"x": 3, "y": 2},
|
||||||
|
{"x": 3, "y": 1},
|
||||||
|
{"x": 2, "y": 1},
|
||||||
|
{"x": 2, "y": 2},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
move = make_board(game_state).snake_neat_make_a_move()
|
||||||
|
self.assertEqual(move, "left")
|
||||||
|
|
||||||
|
def test_royale_uses_ruleset_hazard_damage_setting(self):
|
||||||
|
game_state = {
|
||||||
|
"game": {
|
||||||
|
"id": "test-royale-hazard-setting",
|
||||||
|
"ruleset": {
|
||||||
|
"name": "standard",
|
||||||
|
"version": "v1.0.0",
|
||||||
|
"settings": {"hazardDamagePerTurn": 22},
|
||||||
|
},
|
||||||
|
"source": "custom",
|
||||||
|
"map": "royale",
|
||||||
|
},
|
||||||
|
"turn": 5,
|
||||||
|
"board": {
|
||||||
|
"height": 11,
|
||||||
|
"width": 11,
|
||||||
|
"food": [],
|
||||||
|
"hazards": [],
|
||||||
|
"snakes": [
|
||||||
|
{
|
||||||
|
"id": "me",
|
||||||
|
"name": "me",
|
||||||
|
"health": 80,
|
||||||
|
"length": 3,
|
||||||
|
"head": {"x": 5, "y": 5},
|
||||||
|
"body": [
|
||||||
|
{"x": 5, "y": 5},
|
||||||
|
{"x": 5, "y": 4},
|
||||||
|
{"x": 5, "y": 3},
|
||||||
|
],
|
||||||
|
}
|
||||||
|
],
|
||||||
|
},
|
||||||
|
"you": {
|
||||||
|
"id": "me",
|
||||||
|
"name": "me",
|
||||||
|
"health": 80,
|
||||||
|
"length": 3,
|
||||||
|
"head": {"x": 5, "y": 5},
|
||||||
|
"body": [
|
||||||
|
{"x": 5, "y": 5},
|
||||||
|
{"x": 5, "y": 4},
|
||||||
|
{"x": 5, "y": 3},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
board = make_board(game_state)
|
||||||
|
snake = board.snake_class
|
||||||
|
self.assertEqual(snake._hazard_damage_per_turn(board), 22)
|
||||||
|
|
||||||
|
def test_royale_new_hazard_has_spawn_grace(self):
|
||||||
|
snake = BestBattleSnake()
|
||||||
|
point = (4, 4)
|
||||||
|
hazard_set = {point}
|
||||||
|
|
||||||
|
self.assertFalse(
|
||||||
|
snake._hazard_is_active(
|
||||||
|
point, ate_food=False, hazard_set=hazard_set, previous_hazard_set=set()
|
||||||
|
)
|
||||||
|
)
|
||||||
|
self.assertTrue(
|
||||||
|
snake._hazard_is_active(
|
||||||
|
point,
|
||||||
|
ate_food=False,
|
||||||
|
hazard_set=hazard_set,
|
||||||
|
previous_hazard_set=hazard_set,
|
||||||
|
)
|
||||||
|
)
|
||||||
|
self.assertFalse(
|
||||||
|
snake._hazard_is_active(
|
||||||
|
point,
|
||||||
|
ate_food=True,
|
||||||
|
hazard_set=hazard_set,
|
||||||
|
previous_hazard_set=hazard_set,
|
||||||
|
)
|
||||||
|
)
|
||||||
|
|
||||||
|
def test_constrictor_avoids_growth_dead_end(self):
|
||||||
|
game_state = {
|
||||||
|
"game": {
|
||||||
|
"id": "test-constrictor-dead-end",
|
||||||
|
"ruleset": {"name": "constrictor", "version": "v1.0.0"},
|
||||||
|
"source": "custom",
|
||||||
|
"map": "standard",
|
||||||
|
},
|
||||||
|
"turn": 12,
|
||||||
|
"board": {
|
||||||
|
"height": 7,
|
||||||
|
"width": 7,
|
||||||
|
"food": [],
|
||||||
|
"hazards": [],
|
||||||
|
"snakes": [
|
||||||
|
{
|
||||||
|
"id": "me",
|
||||||
|
"name": "me",
|
||||||
|
"health": 100,
|
||||||
|
"length": 4,
|
||||||
|
"head": {"x": 1, "y": 1},
|
||||||
|
"body": [
|
||||||
|
{"x": 1, "y": 1},
|
||||||
|
{"x": 1, "y": 0},
|
||||||
|
{"x": 0, "y": 0},
|
||||||
|
{"x": 0, "y": 1},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": "enemy",
|
||||||
|
"name": "enemy",
|
||||||
|
"health": 100,
|
||||||
|
"length": 8,
|
||||||
|
"head": {"x": 4, "y": 4},
|
||||||
|
"body": [
|
||||||
|
{"x": 4, "y": 4},
|
||||||
|
{"x": 3, "y": 4},
|
||||||
|
{"x": 3, "y": 3},
|
||||||
|
{"x": 2, "y": 3},
|
||||||
|
{"x": 2, "y": 2},
|
||||||
|
{"x": 2, "y": 0},
|
||||||
|
{"x": 2, "y": 2},
|
||||||
|
{"x": 3, "y": 1},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
"you": {
|
||||||
|
"id": "me",
|
||||||
|
"name": "me",
|
||||||
|
"health": 100,
|
||||||
|
"length": 4,
|
||||||
|
"head": {"x": 1, "y": 1},
|
||||||
|
"body": [
|
||||||
|
{"x": 1, "y": 1},
|
||||||
|
{"x": 1, "y": 0},
|
||||||
|
{"x": 0, "y": 0},
|
||||||
|
{"x": 0, "y": 1},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
move = make_board(game_state).snake_neat_make_a_move()
|
||||||
|
self.assertEqual(move, "up")
|
||||||
|
|
||||||
|
def test_duel_tightens_space_when_enemy_is_encased(self):
|
||||||
|
game_state = {
|
||||||
|
"game": {
|
||||||
|
"id": "test-encase-tighten",
|
||||||
|
"ruleset": {"name": "standard", "version": "v1.0.0"},
|
||||||
|
"source": "custom",
|
||||||
|
"map": "standard",
|
||||||
|
},
|
||||||
|
"turn": 40,
|
||||||
|
"board": {
|
||||||
|
"height": 7,
|
||||||
|
"width": 7,
|
||||||
|
"food": [{"x": 0, "y": 0}],
|
||||||
|
"hazards": [],
|
||||||
|
"snakes": [
|
||||||
|
{
|
||||||
|
"id": "me",
|
||||||
|
"name": "me",
|
||||||
|
"health": 92,
|
||||||
|
"length": 8,
|
||||||
|
"head": {"x": 2, "y": 3},
|
||||||
|
"body": [
|
||||||
|
{"x": 2, "y": 3},
|
||||||
|
{"x": 2, "y": 2},
|
||||||
|
{"x": 1, "y": 2},
|
||||||
|
{"x": 1, "y": 3},
|
||||||
|
{"x": 1, "y": 4},
|
||||||
|
{"x": 2, "y": 4},
|
||||||
|
{"x": 3, "y": 4},
|
||||||
|
{"x": 3, "y": 5},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": "enemy",
|
||||||
|
"name": "enemy",
|
||||||
|
"health": 88,
|
||||||
|
"length": 5,
|
||||||
|
"head": {"x": 4, "y": 3},
|
||||||
|
"body": [
|
||||||
|
{"x": 4, "y": 3},
|
||||||
|
{"x": 5, "y": 3},
|
||||||
|
{"x": 5, "y": 2},
|
||||||
|
{"x": 4, "y": 2},
|
||||||
|
{"x": 4, "y": 1},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
"you": {
|
||||||
|
"id": "me",
|
||||||
|
"name": "me",
|
||||||
|
"health": 92,
|
||||||
|
"length": 8,
|
||||||
|
"head": {"x": 2, "y": 3},
|
||||||
|
"body": [
|
||||||
|
{"x": 2, "y": 3},
|
||||||
|
{"x": 2, "y": 2},
|
||||||
|
{"x": 1, "y": 2},
|
||||||
|
{"x": 1, "y": 3},
|
||||||
|
{"x": 1, "y": 4},
|
||||||
|
{"x": 2, "y": 4},
|
||||||
|
{"x": 3, "y": 4},
|
||||||
|
{"x": 3, "y": 5},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
move = make_board(game_state).snake_neat_make_a_move()
|
||||||
|
self.assertEqual(move, "right")
|
||||||
|
|
||||||
|
def test_constrictor_prefers_choke_when_safe(self):
|
||||||
|
game_state = {
|
||||||
|
"game": {
|
||||||
|
"id": "test-constrictor-choke",
|
||||||
|
"ruleset": {"name": "constrictor", "version": "v1.0.0"},
|
||||||
|
"source": "custom",
|
||||||
|
"map": "standard",
|
||||||
|
},
|
||||||
|
"turn": 25,
|
||||||
|
"board": {
|
||||||
|
"height": 7,
|
||||||
|
"width": 7,
|
||||||
|
"food": [],
|
||||||
|
"hazards": [],
|
||||||
|
"snakes": [
|
||||||
|
{
|
||||||
|
"id": "me",
|
||||||
|
"name": "me",
|
||||||
|
"health": 100,
|
||||||
|
"length": 7,
|
||||||
|
"head": {"x": 2, "y": 3},
|
||||||
|
"body": [
|
||||||
|
{"x": 2, "y": 3},
|
||||||
|
{"x": 2, "y": 2},
|
||||||
|
{"x": 1, "y": 2},
|
||||||
|
{"x": 1, "y": 3},
|
||||||
|
{"x": 1, "y": 4},
|
||||||
|
{"x": 2, "y": 4},
|
||||||
|
{"x": 2, "y": 5},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": "enemy",
|
||||||
|
"name": "enemy",
|
||||||
|
"health": 100,
|
||||||
|
"length": 7,
|
||||||
|
"head": {"x": 4, "y": 3},
|
||||||
|
"body": [
|
||||||
|
{"x": 4, "y": 3},
|
||||||
|
{"x": 5, "y": 3},
|
||||||
|
{"x": 5, "y": 2},
|
||||||
|
{"x": 4, "y": 2},
|
||||||
|
{"x": 4, "y": 1},
|
||||||
|
{"x": 5, "y": 1},
|
||||||
|
{"x": 6, "y": 1},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
"you": {
|
||||||
|
"id": "me",
|
||||||
|
"name": "me",
|
||||||
|
"health": 100,
|
||||||
|
"length": 7,
|
||||||
|
"head": {"x": 2, "y": 3},
|
||||||
|
"body": [
|
||||||
|
{"x": 2, "y": 3},
|
||||||
|
{"x": 2, "y": 2},
|
||||||
|
{"x": 1, "y": 2},
|
||||||
|
{"x": 1, "y": 3},
|
||||||
|
{"x": 1, "y": 4},
|
||||||
|
{"x": 2, "y": 4},
|
||||||
|
{"x": 2, "y": 5},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
move = make_board(game_state).snake_neat_make_a_move()
|
||||||
|
self.assertEqual(move, "right")
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
unittest.main()
|
||||||
@@ -0,0 +1,52 @@
|
|||||||
|
import unittest
|
||||||
|
from typing import cast
|
||||||
|
|
||||||
|
from server.Dataset import Dataset
|
||||||
|
from server.GameBoard import GameBoard
|
||||||
|
|
||||||
|
class DummySnake:
|
||||||
|
def get_history(self):
|
||||||
|
return [
|
||||||
|
{"turn": 1, "data": [{"score": 1}]},
|
||||||
|
{"turn": 2, "data": [{"score": 2}]},
|
||||||
|
]
|
||||||
|
|
||||||
|
class DummyGameBoard:
|
||||||
|
def __init__(self, winners):
|
||||||
|
self.id = "game-1"
|
||||||
|
self.map = "standard"
|
||||||
|
self.winner_snake_names = winners
|
||||||
|
self.snake_class = DummySnake()
|
||||||
|
self.turns = [
|
||||||
|
{"turn": 1, "move": "up", "game_board": {"width": 11, "height": 11}},
|
||||||
|
{"turn": 2, "move": "left", "game_board": {"width": 11, "height": 11}},
|
||||||
|
]
|
||||||
|
|
||||||
|
def get_type_of_game(self):
|
||||||
|
return {"name": "standard", "is_ladder": False}
|
||||||
|
|
||||||
|
class TestDataset(unittest.TestCase):
|
||||||
|
def test_build_only_good_moves_for_wins(self):
|
||||||
|
dataset = Dataset(cast(GameBoard, DummyGameBoard(["me"])))
|
||||||
|
payload = dataset.build(only_good_moves=True)
|
||||||
|
|
||||||
|
self.assertTrue(payload["did_win"])
|
||||||
|
self.assertEqual(payload["total_samples"], 2)
|
||||||
|
self.assertTrue(all(sample["is_good_move"] for sample in payload["samples"]))
|
||||||
|
|
||||||
|
def test_build_returns_no_samples_for_losses_when_only_good(self):
|
||||||
|
dataset = Dataset(cast(GameBoard, DummyGameBoard(["enemy"])))
|
||||||
|
payload = dataset.build(only_good_moves=True)
|
||||||
|
|
||||||
|
self.assertFalse(payload["did_win"])
|
||||||
|
self.assertEqual(payload["total_samples"], 0)
|
||||||
|
|
||||||
|
def test_labels_by_turn(self):
|
||||||
|
winner_labels = Dataset(cast(GameBoard, DummyGameBoard(["me"]))).labels_by_turn()
|
||||||
|
loser_labels = Dataset(cast(GameBoard, DummyGameBoard(["enemy"]))).labels_by_turn()
|
||||||
|
|
||||||
|
self.assertEqual(winner_labels, {1: True, 2: True})
|
||||||
|
self.assertEqual(loser_labels, {1: False, 2: False})
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
unittest.main()
|
||||||
@@ -0,0 +1,47 @@
|
|||||||
|
import json
|
||||||
|
import tempfile
|
||||||
|
import unittest
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
from server.DatasetExporter import DatasetExporter
|
||||||
|
|
||||||
|
class TestDatasetExporter(unittest.TestCase):
|
||||||
|
def test_export_jsonl(self):
|
||||||
|
with tempfile.TemporaryDirectory() as tmp:
|
||||||
|
input_dir = Path(tmp) / "data"
|
||||||
|
output_file = Path(tmp) / "out" / "dataset.jsonl"
|
||||||
|
game_file = input_dir / "game-1.json"
|
||||||
|
game_file.parent.mkdir(parents=True, exist_ok=True)
|
||||||
|
|
||||||
|
game_payload = {
|
||||||
|
"dataset": {
|
||||||
|
"game": {"id": "g-1", "map": "standard", "type": {"name": "duel"}},
|
||||||
|
"snake": {"type": "BestBattleSnake"},
|
||||||
|
"samples": [
|
||||||
|
{
|
||||||
|
"turn": 1,
|
||||||
|
"move": "up",
|
||||||
|
"is_good_move": True,
|
||||||
|
"game_board": {"width": 11, "height": 11},
|
||||||
|
"history": {"data": []},
|
||||||
|
}
|
||||||
|
],
|
||||||
|
}
|
||||||
|
}
|
||||||
|
game_file.write_text(json.dumps(game_payload), encoding="utf-8")
|
||||||
|
|
||||||
|
report = DatasetExporter(str(input_dir), str(output_file)).export_jsonl()
|
||||||
|
|
||||||
|
self.assertEqual(report["games_scanned"], 1)
|
||||||
|
self.assertEqual(report["samples_exported"], 1)
|
||||||
|
self.assertTrue(output_file.exists())
|
||||||
|
|
||||||
|
lines = output_file.read_text(encoding="utf-8").strip().splitlines()
|
||||||
|
self.assertEqual(len(lines), 1)
|
||||||
|
first = json.loads(lines[0])
|
||||||
|
self.assertEqual(first["game_id"], "g-1")
|
||||||
|
self.assertEqual(first["move"], "up")
|
||||||
|
self.assertTrue(first["is_good_move"])
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
unittest.main()
|
||||||
@@ -0,0 +1,310 @@
|
|||||||
|
version = 1
|
||||||
|
revision = 3
|
||||||
|
requires-python = ">=3.13"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "aiofiles"
|
||||||
|
version = "25.1.0"
|
||||||
|
source = { registry = "https://pypi.org/simple" }
|
||||||
|
sdist = { url = "https://files.pythonhosted.org/packages/41/c3/534eac40372d8ee36ef40df62ec129bee4fdb5ad9706e58a29be53b2c970/aiofiles-25.1.0.tar.gz", hash = "sha256:a8d728f0a29de45dc521f18f07297428d56992a742f0cd2701ba86e44d23d5b2", size = 46354, upload-time = "2025-10-09T20:51:04.358Z" }
|
||||||
|
wheels = [
|
||||||
|
{ url = "https://files.pythonhosted.org/packages/bc/8a/340a1555ae33d7354dbca4faa54948d76d89a27ceef032c8c3bc661d003e/aiofiles-25.1.0-py3-none-any.whl", hash = "sha256:abe311e527c862958650f9438e859c1fa7568a141b22abcd015e120e86a85695", size = 14668, upload-time = "2025-10-09T20:51:03.174Z" },
|
||||||
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "aiologger"
|
||||||
|
version = "0.7.0"
|
||||||
|
source = { registry = "https://pypi.org/simple" }
|
||||||
|
sdist = { url = "https://files.pythonhosted.org/packages/76/a8/ca4c00b319b877d29aa792cdd4ae3fb2a9f57268d94708a637abe9ae58c5/aiologger-0.7.0.tar.gz", hash = "sha256:7a4d5c91b836b61e842a791071786a3d80d6b6fa46fb8fd8e73391253ecb72ac", size = 20485, upload-time = "2022-10-05T01:03:22.199Z" }
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "blinker"
|
||||||
|
version = "1.9.0"
|
||||||
|
source = { registry = "https://pypi.org/simple" }
|
||||||
|
sdist = { url = "https://files.pythonhosted.org/packages/21/28/9b3f50ce0e048515135495f198351908d99540d69bfdc8c1d15b73dc55ce/blinker-1.9.0.tar.gz", hash = "sha256:b4ce2265a7abece45e7cc896e98dbebe6cead56bcf805a3d23136d145f5445bf", size = 22460, upload-time = "2024-11-08T17:25:47.436Z" }
|
||||||
|
wheels = [
|
||||||
|
{ url = "https://files.pythonhosted.org/packages/10/cb/f2ad4230dc2eb1a74edf38f1a38b9b52277f75bef262d8908e60d957e13c/blinker-1.9.0-py3-none-any.whl", hash = "sha256:ba0efaa9080b619ff2f3459d1d500c57bddea4a6b424b60a91141db6fd2f08bc", size = 8458, upload-time = "2024-11-08T17:25:46.184Z" },
|
||||||
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "certifi"
|
||||||
|
version = "2026.2.25"
|
||||||
|
source = { registry = "https://pypi.org/simple" }
|
||||||
|
sdist = { url = "https://files.pythonhosted.org/packages/af/2d/7bf41579a8986e348fa033a31cdd0e4121114f6bce2457e8876010b092dd/certifi-2026.2.25.tar.gz", hash = "sha256:e887ab5cee78ea814d3472169153c2d12cd43b14bd03329a39a9c6e2e80bfba7", size = 155029, upload-time = "2026-02-25T02:54:17.342Z" }
|
||||||
|
wheels = [
|
||||||
|
{ url = "https://files.pythonhosted.org/packages/9a/3c/c17fb3ca2d9c3acff52e30b309f538586f9f5b9c9cf454f3845fc9af4881/certifi-2026.2.25-py3-none-any.whl", hash = "sha256:027692e4402ad994f1c42e52a4997a9763c646b73e4096e4d5d6db8af1d6f0fa", size = 153684, upload-time = "2026-02-25T02:54:15.766Z" },
|
||||||
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "click"
|
||||||
|
version = "8.3.2"
|
||||||
|
source = { registry = "https://pypi.org/simple" }
|
||||||
|
dependencies = [
|
||||||
|
{ name = "colorama", marker = "sys_platform == 'win32'" },
|
||||||
|
]
|
||||||
|
sdist = { url = "https://files.pythonhosted.org/packages/57/75/31212c6bf2503fdf920d87fee5d7a86a2e3bcf444984126f13d8e4016804/click-8.3.2.tar.gz", hash = "sha256:14162b8b3b3550a7d479eafa77dfd3c38d9dc8951f6f69c78913a8f9a7540fd5", size = 302856, upload-time = "2026-04-03T19:14:45.118Z" }
|
||||||
|
wheels = [
|
||||||
|
{ url = "https://files.pythonhosted.org/packages/e4/20/71885d8b97d4f3dde17b1fdb92dbd4908b00541c5a3379787137285f602e/click-8.3.2-py3-none-any.whl", hash = "sha256:1924d2c27c5653561cd2cae4548d1406039cb79b858b747cfea24924bbc1616d", size = 108379, upload-time = "2026-04-03T19:14:43.505Z" },
|
||||||
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "colorama"
|
||||||
|
version = "0.4.6"
|
||||||
|
source = { registry = "https://pypi.org/simple" }
|
||||||
|
sdist = { url = "https://files.pythonhosted.org/packages/d8/53/6f443c9a4a8358a93a6792e2acffb9d9d5cb0a5cfd8802644b7b1c9a02e4/colorama-0.4.6.tar.gz", hash = "sha256:08695f5cb7ed6e0531a20572697297273c47b8cae5a63ffc6d6ed5c201be6e44", size = 27697, upload-time = "2022-10-25T02:36:22.414Z" }
|
||||||
|
wheels = [
|
||||||
|
{ url = "https://files.pythonhosted.org/packages/d1/d6/3965ed04c63042e047cb6a3e6ed1a63a35087b6a609aa3a15ed8ac56c221/colorama-0.4.6-py2.py3-none-any.whl", hash = "sha256:4f1d9991f5acc0ca119f9d443620b77f9d6b33703e51011c16baf57afb285fc6", size = 25335, upload-time = "2022-10-25T02:36:20.889Z" },
|
||||||
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "dotenv"
|
||||||
|
version = "0.9.9"
|
||||||
|
source = { registry = "https://pypi.org/simple" }
|
||||||
|
dependencies = [
|
||||||
|
{ name = "python-dotenv" },
|
||||||
|
]
|
||||||
|
wheels = [
|
||||||
|
{ url = "https://files.pythonhosted.org/packages/b2/b7/545d2c10c1fc15e48653c91efde329a790f2eecfbbf2bd16003b5db2bab0/dotenv-0.9.9-py2.py3-none-any.whl", hash = "sha256:29cf74a087b31dafdb5a446b6d7e11cbce8ed2741540e2339c69fbef92c94ce9", size = 1892, upload-time = "2025-02-19T22:15:01.647Z" },
|
||||||
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "flask"
|
||||||
|
version = "3.1.3"
|
||||||
|
source = { registry = "https://pypi.org/simple" }
|
||||||
|
dependencies = [
|
||||||
|
{ name = "blinker" },
|
||||||
|
{ name = "click" },
|
||||||
|
{ name = "itsdangerous" },
|
||||||
|
{ name = "jinja2" },
|
||||||
|
{ name = "markupsafe" },
|
||||||
|
{ name = "werkzeug" },
|
||||||
|
]
|
||||||
|
sdist = { url = "https://files.pythonhosted.org/packages/26/00/35d85dcce6c57fdc871f3867d465d780f302a175ea360f62533f12b27e2b/flask-3.1.3.tar.gz", hash = "sha256:0ef0e52b8a9cd932855379197dd8f94047b359ca0a78695144304cb45f87c9eb", size = 759004, upload-time = "2026-02-19T05:00:57.678Z" }
|
||||||
|
wheels = [
|
||||||
|
{ url = "https://files.pythonhosted.org/packages/7f/9c/34f6962f9b9e9c71f6e5ed806e0d0ff03c9d1b0b2340088a0cf4bce09b18/flask-3.1.3-py3-none-any.whl", hash = "sha256:f4bcbefc124291925f1a26446da31a5178f9483862233b23c0c96a20701f670c", size = 103424, upload-time = "2026-02-19T05:00:56.027Z" },
|
||||||
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "gel"
|
||||||
|
version = "3.1.0"
|
||||||
|
source = { registry = "https://pypi.org/simple" }
|
||||||
|
dependencies = [
|
||||||
|
{ name = "certifi", marker = "sys_platform == 'win32'" },
|
||||||
|
]
|
||||||
|
sdist = { url = "https://files.pythonhosted.org/packages/9c/70/84cee8eb48a2760893e60e8267502bc16ddef2197dd41f20c103a3f04e01/gel-3.1.0.tar.gz", hash = "sha256:3bb0b21167e00c976675a7d5dd73c21002e659651bf9de7fa46cd418bfa3eb85", size = 1331332, upload-time = "2025-04-29T20:44:49.659Z" }
|
||||||
|
wheels = [
|
||||||
|
{ url = "https://files.pythonhosted.org/packages/d1/f4/69cf0d0753e93526659d4810d7816d33a6c72f2934b26d14da283602d175/gel-3.1.0-cp313-cp313-macosx_10_13_x86_64.whl", hash = "sha256:f5e41f4ddc86e054256e81302905e671647577c1aed7249e1781aee1e0cb2f7c", size = 907956, upload-time = "2025-04-29T20:44:28.285Z" },
|
||||||
|
{ url = "https://files.pythonhosted.org/packages/4f/1b/88cc28e5c58e912b9d74f5b27bb41203af88cac9ea6cf329ccb9f4a23fab/gel-3.1.0-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:cd20c45beec358197293ad5c1fcf7fd383153e0d8d7038322085cf27436dc975", size = 863463, upload-time = "2025-04-29T20:44:29.906Z" },
|
||||||
|
{ url = "https://files.pythonhosted.org/packages/e2/52/57ce33203a606dac51abf16aaa2388d31a4efac434bb3730dc22494cea13/gel-3.1.0-cp313-cp313-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:8a526e11ba696d1cf6c876c08afe6ab5f762a227faaa3b78523ebc2511567609", size = 4619168, upload-time = "2025-04-29T20:44:32.895Z" },
|
||||||
|
{ url = "https://files.pythonhosted.org/packages/eb/ad/eb7958f8197ba763054a706892c4948753f210c6f82ce46f7de9d13d4f94/gel-3.1.0-cp313-cp313-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:c06f11fcde231d6264dbe0b19d7b2942767a196e9c6f2cabf22fbb04094134af", size = 4729625, upload-time = "2025-04-29T20:44:34.747Z" },
|
||||||
|
{ url = "https://files.pythonhosted.org/packages/cd/62/7b89eb81430f5714bf56f257679998a9a09f327f60d3c061dece5b5b2797/gel-3.1.0-cp313-cp313-win_amd64.whl", hash = "sha256:48235a5082f03d7eccbcaa4255260c8a3cdb2cfd123f121dd6b0d3ebc51421ac", size = 831743, upload-time = "2025-04-29T20:44:36.992Z" },
|
||||||
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "h11"
|
||||||
|
version = "0.16.0"
|
||||||
|
source = { registry = "https://pypi.org/simple" }
|
||||||
|
sdist = { url = "https://files.pythonhosted.org/packages/01/ee/02a2c011bdab74c6fb3c75474d40b3052059d95df7e73351460c8588d963/h11-0.16.0.tar.gz", hash = "sha256:4e35b956cf45792e4caa5885e69fba00bdbc6ffafbfa020300e549b208ee5ff1", size = 101250, upload-time = "2025-04-24T03:35:25.427Z" }
|
||||||
|
wheels = [
|
||||||
|
{ url = "https://files.pythonhosted.org/packages/04/4b/29cac41a4d98d144bf5f6d33995617b185d14b22401f75ca86f384e87ff1/h11-0.16.0-py3-none-any.whl", hash = "sha256:63cf8bbe7522de3bf65932fda1d9c2772064ffb3dae62d55932da54b31cb6c86", size = 37515, upload-time = "2025-04-24T03:35:24.344Z" },
|
||||||
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "h2"
|
||||||
|
version = "4.3.0"
|
||||||
|
source = { registry = "https://pypi.org/simple" }
|
||||||
|
dependencies = [
|
||||||
|
{ name = "hpack" },
|
||||||
|
{ name = "hyperframe" },
|
||||||
|
]
|
||||||
|
sdist = { url = "https://files.pythonhosted.org/packages/1d/17/afa56379f94ad0fe8defd37d6eb3f89a25404ffc71d4d848893d270325fc/h2-4.3.0.tar.gz", hash = "sha256:6c59efe4323fa18b47a632221a1888bd7fde6249819beda254aeca909f221bf1", size = 2152026, upload-time = "2025-08-23T18:12:19.778Z" }
|
||||||
|
wheels = [
|
||||||
|
{ url = "https://files.pythonhosted.org/packages/69/b2/119f6e6dcbd96f9069ce9a2665e0146588dc9f88f29549711853645e736a/h2-4.3.0-py3-none-any.whl", hash = "sha256:c438f029a25f7945c69e0ccf0fb951dc3f73a5f6412981daee861431b70e2bdd", size = 61779, upload-time = "2025-08-23T18:12:17.779Z" },
|
||||||
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "hpack"
|
||||||
|
version = "4.1.0"
|
||||||
|
source = { registry = "https://pypi.org/simple" }
|
||||||
|
sdist = { url = "https://files.pythonhosted.org/packages/2c/48/71de9ed269fdae9c8057e5a4c0aa7402e8bb16f2c6e90b3aa53327b113f8/hpack-4.1.0.tar.gz", hash = "sha256:ec5eca154f7056aa06f196a557655c5b009b382873ac8d1e66e79e87535f1dca", size = 51276, upload-time = "2025-01-22T21:44:58.347Z" }
|
||||||
|
wheels = [
|
||||||
|
{ url = "https://files.pythonhosted.org/packages/07/c6/80c95b1b2b94682a72cbdbfb85b81ae2daffa4291fbfa1b1464502ede10d/hpack-4.1.0-py3-none-any.whl", hash = "sha256:157ac792668d995c657d93111f46b4535ed114f0c9c8d672271bbec7eae1b496", size = 34357, upload-time = "2025-01-22T21:44:56.92Z" },
|
||||||
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "hypercorn"
|
||||||
|
version = "0.18.0"
|
||||||
|
source = { registry = "https://pypi.org/simple" }
|
||||||
|
dependencies = [
|
||||||
|
{ name = "h11" },
|
||||||
|
{ name = "h2" },
|
||||||
|
{ name = "priority" },
|
||||||
|
{ name = "wsproto" },
|
||||||
|
]
|
||||||
|
sdist = { url = "https://files.pythonhosted.org/packages/44/01/39f41a014b83dd5c795217362f2ca9071cf243e6a75bdcd6cd5b944658cc/hypercorn-0.18.0.tar.gz", hash = "sha256:d63267548939c46b0247dc8e5b45a9947590e35e64ee73a23c074aa3cf88e9da", size = 68420, upload-time = "2025-11-08T13:54:04.78Z" }
|
||||||
|
wheels = [
|
||||||
|
{ url = "https://files.pythonhosted.org/packages/93/35/850277d1b17b206bd10874c8a9a3f52e059452fb49bb0d22cbb908f6038b/hypercorn-0.18.0-py3-none-any.whl", hash = "sha256:225e268f2c1c2f28f6d8f6db8f40cb8c992963610c5725e13ccfcddccb24b1cd", size = 61640, upload-time = "2025-11-08T13:54:03.202Z" },
|
||||||
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "hyperframe"
|
||||||
|
version = "6.1.0"
|
||||||
|
source = { registry = "https://pypi.org/simple" }
|
||||||
|
sdist = { url = "https://files.pythonhosted.org/packages/02/e7/94f8232d4a74cc99514c13a9f995811485a6903d48e5d952771ef6322e30/hyperframe-6.1.0.tar.gz", hash = "sha256:f630908a00854a7adeabd6382b43923a4c4cd4b821fcb527e6ab9e15382a3b08", size = 26566, upload-time = "2025-01-22T21:41:49.302Z" }
|
||||||
|
wheels = [
|
||||||
|
{ url = "https://files.pythonhosted.org/packages/48/30/47d0bf6072f7252e6521f3447ccfa40b421b6824517f82854703d0f5a98b/hyperframe-6.1.0-py3-none-any.whl", hash = "sha256:b03380493a519fce58ea5af42e4a42317bf9bd425596f7a0835ffce80f1a42e5", size = 13007, upload-time = "2025-01-22T21:41:47.295Z" },
|
||||||
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "itsdangerous"
|
||||||
|
version = "2.2.0"
|
||||||
|
source = { registry = "https://pypi.org/simple" }
|
||||||
|
sdist = { url = "https://files.pythonhosted.org/packages/9c/cb/8ac0172223afbccb63986cc25049b154ecfb5e85932587206f42317be31d/itsdangerous-2.2.0.tar.gz", hash = "sha256:e0050c0b7da1eea53ffaf149c0cfbb5c6e2e2b69c4bef22c81fa6eb73e5f6173", size = 54410, upload-time = "2024-04-16T21:28:15.614Z" }
|
||||||
|
wheels = [
|
||||||
|
{ url = "https://files.pythonhosted.org/packages/04/96/92447566d16df59b2a776c0fb82dbc4d9e07cd95062562af01e408583fc4/itsdangerous-2.2.0-py3-none-any.whl", hash = "sha256:c6242fc49e35958c8b15141343aa660db5fc54d4f13a1db01a3f5891b98700ef", size = 16234, upload-time = "2024-04-16T21:28:14.499Z" },
|
||||||
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "jinja2"
|
||||||
|
version = "3.1.6"
|
||||||
|
source = { registry = "https://pypi.org/simple" }
|
||||||
|
dependencies = [
|
||||||
|
{ name = "markupsafe" },
|
||||||
|
]
|
||||||
|
sdist = { url = "https://files.pythonhosted.org/packages/df/bf/f7da0350254c0ed7c72f3e33cef02e048281fec7ecec5f032d4aac52226b/jinja2-3.1.6.tar.gz", hash = "sha256:0137fb05990d35f1275a587e9aee6d56da821fc83491a0fb838183be43f66d6d", size = 245115, upload-time = "2025-03-05T20:05:02.478Z" }
|
||||||
|
wheels = [
|
||||||
|
{ url = "https://files.pythonhosted.org/packages/62/a1/3d680cbfd5f4b8f15abc1d571870c5fc3e594bb582bc3b64ea099db13e56/jinja2-3.1.6-py3-none-any.whl", hash = "sha256:85ece4451f492d0c13c5dd7c13a64681a86afae63a5f347908daf103ce6d2f67", size = 134899, upload-time = "2025-03-05T20:05:00.369Z" },
|
||||||
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "markupsafe"
|
||||||
|
version = "3.0.3"
|
||||||
|
source = { registry = "https://pypi.org/simple" }
|
||||||
|
sdist = { url = "https://files.pythonhosted.org/packages/7e/99/7690b6d4034fffd95959cbe0c02de8deb3098cc577c67bb6a24fe5d7caa7/markupsafe-3.0.3.tar.gz", hash = "sha256:722695808f4b6457b320fdc131280796bdceb04ab50fe1795cd540799ebe1698", size = 80313, upload-time = "2025-09-27T18:37:40.426Z" }
|
||||||
|
wheels = [
|
||||||
|
{ url = "https://files.pythonhosted.org/packages/38/2f/907b9c7bbba283e68f20259574b13d005c121a0fa4c175f9bed27c4597ff/markupsafe-3.0.3-cp313-cp313-macosx_10_13_x86_64.whl", hash = "sha256:e1cf1972137e83c5d4c136c43ced9ac51d0e124706ee1c8aa8532c1287fa8795", size = 11622, upload-time = "2025-09-27T18:36:41.777Z" },
|
||||||
|
{ url = "https://files.pythonhosted.org/packages/9c/d9/5f7756922cdd676869eca1c4e3c0cd0df60ed30199ffd775e319089cb3ed/markupsafe-3.0.3-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:116bb52f642a37c115f517494ea5feb03889e04df47eeff5b130b1808ce7c219", size = 12029, upload-time = "2025-09-27T18:36:43.257Z" },
|
||||||
|
{ url = "https://files.pythonhosted.org/packages/00/07/575a68c754943058c78f30db02ee03a64b3c638586fba6a6dd56830b30a3/markupsafe-3.0.3-cp313-cp313-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:133a43e73a802c5562be9bbcd03d090aa5a1fe899db609c29e8c8d815c5f6de6", size = 24374, upload-time = "2025-09-27T18:36:44.508Z" },
|
||||||
|
{ url = "https://files.pythonhosted.org/packages/a9/21/9b05698b46f218fc0e118e1f8168395c65c8a2c750ae2bab54fc4bd4e0e8/markupsafe-3.0.3-cp313-cp313-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:ccfcd093f13f0f0b7fdd0f198b90053bf7b2f02a3927a30e63f3ccc9df56b676", size = 22980, upload-time = "2025-09-27T18:36:45.385Z" },
|
||||||
|
{ url = "https://files.pythonhosted.org/packages/7f/71/544260864f893f18b6827315b988c146b559391e6e7e8f7252839b1b846a/markupsafe-3.0.3-cp313-cp313-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:509fa21c6deb7a7a273d629cf5ec029bc209d1a51178615ddf718f5918992ab9", size = 21990, upload-time = "2025-09-27T18:36:46.916Z" },
|
||||||
|
{ url = "https://files.pythonhosted.org/packages/c2/28/b50fc2f74d1ad761af2f5dcce7492648b983d00a65b8c0e0cb457c82ebbe/markupsafe-3.0.3-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:a4afe79fb3de0b7097d81da19090f4df4f8d3a2b3adaa8764138aac2e44f3af1", size = 23784, upload-time = "2025-09-27T18:36:47.884Z" },
|
||||||
|
{ url = "https://files.pythonhosted.org/packages/ed/76/104b2aa106a208da8b17a2fb72e033a5a9d7073c68f7e508b94916ed47a9/markupsafe-3.0.3-cp313-cp313-musllinux_1_2_riscv64.whl", hash = "sha256:795e7751525cae078558e679d646ae45574b47ed6e7771863fcc079a6171a0fc", size = 21588, upload-time = "2025-09-27T18:36:48.82Z" },
|
||||||
|
{ url = "https://files.pythonhosted.org/packages/b5/99/16a5eb2d140087ebd97180d95249b00a03aa87e29cc224056274f2e45fd6/markupsafe-3.0.3-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:8485f406a96febb5140bfeca44a73e3ce5116b2501ac54fe953e488fb1d03b12", size = 23041, upload-time = "2025-09-27T18:36:49.797Z" },
|
||||||
|
{ url = "https://files.pythonhosted.org/packages/19/bc/e7140ed90c5d61d77cea142eed9f9c303f4c4806f60a1044c13e3f1471d0/markupsafe-3.0.3-cp313-cp313-win32.whl", hash = "sha256:bdd37121970bfd8be76c5fb069c7751683bdf373db1ed6c010162b2a130248ed", size = 14543, upload-time = "2025-09-27T18:36:51.584Z" },
|
||||||
|
{ url = "https://files.pythonhosted.org/packages/05/73/c4abe620b841b6b791f2edc248f556900667a5a1cf023a6646967ae98335/markupsafe-3.0.3-cp313-cp313-win_amd64.whl", hash = "sha256:9a1abfdc021a164803f4d485104931fb8f8c1efd55bc6b748d2f5774e78b62c5", size = 15113, upload-time = "2025-09-27T18:36:52.537Z" },
|
||||||
|
{ url = "https://files.pythonhosted.org/packages/f0/3a/fa34a0f7cfef23cf9500d68cb7c32dd64ffd58a12b09225fb03dd37d5b80/markupsafe-3.0.3-cp313-cp313-win_arm64.whl", hash = "sha256:7e68f88e5b8799aa49c85cd116c932a1ac15caaa3f5db09087854d218359e485", size = 13911, upload-time = "2025-09-27T18:36:53.513Z" },
|
||||||
|
{ url = "https://files.pythonhosted.org/packages/e4/d7/e05cd7efe43a88a17a37b3ae96e79a19e846f3f456fe79c57ca61356ef01/markupsafe-3.0.3-cp313-cp313t-macosx_10_13_x86_64.whl", hash = "sha256:218551f6df4868a8d527e3062d0fb968682fe92054e89978594c28e642c43a73", size = 11658, upload-time = "2025-09-27T18:36:54.819Z" },
|
||||||
|
{ url = "https://files.pythonhosted.org/packages/99/9e/e412117548182ce2148bdeacdda3bb494260c0b0184360fe0d56389b523b/markupsafe-3.0.3-cp313-cp313t-macosx_11_0_arm64.whl", hash = "sha256:3524b778fe5cfb3452a09d31e7b5adefeea8c5be1d43c4f810ba09f2ceb29d37", size = 12066, upload-time = "2025-09-27T18:36:55.714Z" },
|
||||||
|
{ url = "https://files.pythonhosted.org/packages/bc/e6/fa0ffcda717ef64a5108eaa7b4f5ed28d56122c9a6d70ab8b72f9f715c80/markupsafe-3.0.3-cp313-cp313t-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:4e885a3d1efa2eadc93c894a21770e4bc67899e3543680313b09f139e149ab19", size = 25639, upload-time = "2025-09-27T18:36:56.908Z" },
|
||||||
|
{ url = "https://files.pythonhosted.org/packages/96/ec/2102e881fe9d25fc16cb4b25d5f5cde50970967ffa5dddafdb771237062d/markupsafe-3.0.3-cp313-cp313t-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:8709b08f4a89aa7586de0aadc8da56180242ee0ada3999749b183aa23df95025", size = 23569, upload-time = "2025-09-27T18:36:57.913Z" },
|
||||||
|
{ url = "https://files.pythonhosted.org/packages/4b/30/6f2fce1f1f205fc9323255b216ca8a235b15860c34b6798f810f05828e32/markupsafe-3.0.3-cp313-cp313t-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:b8512a91625c9b3da6f127803b166b629725e68af71f8184ae7e7d54686a56d6", size = 23284, upload-time = "2025-09-27T18:36:58.833Z" },
|
||||||
|
{ url = "https://files.pythonhosted.org/packages/58/47/4a0ccea4ab9f5dcb6f79c0236d954acb382202721e704223a8aafa38b5c8/markupsafe-3.0.3-cp313-cp313t-musllinux_1_2_aarch64.whl", hash = "sha256:9b79b7a16f7fedff2495d684f2b59b0457c3b493778c9eed31111be64d58279f", size = 24801, upload-time = "2025-09-27T18:36:59.739Z" },
|
||||||
|
{ url = "https://files.pythonhosted.org/packages/6a/70/3780e9b72180b6fecb83a4814d84c3bf4b4ae4bf0b19c27196104149734c/markupsafe-3.0.3-cp313-cp313t-musllinux_1_2_riscv64.whl", hash = "sha256:12c63dfb4a98206f045aa9563db46507995f7ef6d83b2f68eda65c307c6829eb", size = 22769, upload-time = "2025-09-27T18:37:00.719Z" },
|
||||||
|
{ url = "https://files.pythonhosted.org/packages/98/c5/c03c7f4125180fc215220c035beac6b9cb684bc7a067c84fc69414d315f5/markupsafe-3.0.3-cp313-cp313t-musllinux_1_2_x86_64.whl", hash = "sha256:8f71bc33915be5186016f675cd83a1e08523649b0e33efdb898db577ef5bb009", size = 23642, upload-time = "2025-09-27T18:37:01.673Z" },
|
||||||
|
{ url = "https://files.pythonhosted.org/packages/80/d6/2d1b89f6ca4bff1036499b1e29a1d02d282259f3681540e16563f27ebc23/markupsafe-3.0.3-cp313-cp313t-win32.whl", hash = "sha256:69c0b73548bc525c8cb9a251cddf1931d1db4d2258e9599c28c07ef3580ef354", size = 14612, upload-time = "2025-09-27T18:37:02.639Z" },
|
||||||
|
{ url = "https://files.pythonhosted.org/packages/2b/98/e48a4bfba0a0ffcf9925fe2d69240bfaa19c6f7507b8cd09c70684a53c1e/markupsafe-3.0.3-cp313-cp313t-win_amd64.whl", hash = "sha256:1b4b79e8ebf6b55351f0d91fe80f893b4743f104bff22e90697db1590e47a218", size = 15200, upload-time = "2025-09-27T18:37:03.582Z" },
|
||||||
|
{ url = "https://files.pythonhosted.org/packages/0e/72/e3cc540f351f316e9ed0f092757459afbc595824ca724cbc5a5d4263713f/markupsafe-3.0.3-cp313-cp313t-win_arm64.whl", hash = "sha256:ad2cf8aa28b8c020ab2fc8287b0f823d0a7d8630784c31e9ee5edea20f406287", size = 13973, upload-time = "2025-09-27T18:37:04.929Z" },
|
||||||
|
{ url = "https://files.pythonhosted.org/packages/33/8a/8e42d4838cd89b7dde187011e97fe6c3af66d8c044997d2183fbd6d31352/markupsafe-3.0.3-cp314-cp314-macosx_10_13_x86_64.whl", hash = "sha256:eaa9599de571d72e2daf60164784109f19978b327a3910d3e9de8c97b5b70cfe", size = 11619, upload-time = "2025-09-27T18:37:06.342Z" },
|
||||||
|
{ url = "https://files.pythonhosted.org/packages/b5/64/7660f8a4a8e53c924d0fa05dc3a55c9cee10bbd82b11c5afb27d44b096ce/markupsafe-3.0.3-cp314-cp314-macosx_11_0_arm64.whl", hash = "sha256:c47a551199eb8eb2121d4f0f15ae0f923d31350ab9280078d1e5f12b249e0026", size = 12029, upload-time = "2025-09-27T18:37:07.213Z" },
|
||||||
|
{ url = "https://files.pythonhosted.org/packages/da/ef/e648bfd021127bef5fa12e1720ffed0c6cbb8310c8d9bea7266337ff06de/markupsafe-3.0.3-cp314-cp314-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:f34c41761022dd093b4b6896d4810782ffbabe30f2d443ff5f083e0cbbb8c737", size = 24408, upload-time = "2025-09-27T18:37:09.572Z" },
|
||||||
|
{ url = "https://files.pythonhosted.org/packages/41/3c/a36c2450754618e62008bf7435ccb0f88053e07592e6028a34776213d877/markupsafe-3.0.3-cp314-cp314-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:457a69a9577064c05a97c41f4e65148652db078a3a509039e64d3467b9e7ef97", size = 23005, upload-time = "2025-09-27T18:37:10.58Z" },
|
||||||
|
{ url = "https://files.pythonhosted.org/packages/bc/20/b7fdf89a8456b099837cd1dc21974632a02a999ec9bf7ca3e490aacd98e7/markupsafe-3.0.3-cp314-cp314-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:e8afc3f2ccfa24215f8cb28dcf43f0113ac3c37c2f0f0806d8c70e4228c5cf4d", size = 22048, upload-time = "2025-09-27T18:37:11.547Z" },
|
||||||
|
{ url = "https://files.pythonhosted.org/packages/9a/a7/591f592afdc734f47db08a75793a55d7fbcc6902a723ae4cfbab61010cc5/markupsafe-3.0.3-cp314-cp314-musllinux_1_2_aarch64.whl", hash = "sha256:ec15a59cf5af7be74194f7ab02d0f59a62bdcf1a537677ce67a2537c9b87fcda", size = 23821, upload-time = "2025-09-27T18:37:12.48Z" },
|
||||||
|
{ url = "https://files.pythonhosted.org/packages/7d/33/45b24e4f44195b26521bc6f1a82197118f74df348556594bd2262bda1038/markupsafe-3.0.3-cp314-cp314-musllinux_1_2_riscv64.whl", hash = "sha256:0eb9ff8191e8498cca014656ae6b8d61f39da5f95b488805da4bb029cccbfbaf", size = 21606, upload-time = "2025-09-27T18:37:13.485Z" },
|
||||||
|
{ url = "https://files.pythonhosted.org/packages/ff/0e/53dfaca23a69fbfbbf17a4b64072090e70717344c52eaaaa9c5ddff1e5f0/markupsafe-3.0.3-cp314-cp314-musllinux_1_2_x86_64.whl", hash = "sha256:2713baf880df847f2bece4230d4d094280f4e67b1e813eec43b4c0e144a34ffe", size = 23043, upload-time = "2025-09-27T18:37:14.408Z" },
|
||||||
|
{ url = "https://files.pythonhosted.org/packages/46/11/f333a06fc16236d5238bfe74daccbca41459dcd8d1fa952e8fbd5dccfb70/markupsafe-3.0.3-cp314-cp314-win32.whl", hash = "sha256:729586769a26dbceff69f7a7dbbf59ab6572b99d94576a5592625d5b411576b9", size = 14747, upload-time = "2025-09-27T18:37:15.36Z" },
|
||||||
|
{ url = "https://files.pythonhosted.org/packages/28/52/182836104b33b444e400b14f797212f720cbc9ed6ba34c800639d154e821/markupsafe-3.0.3-cp314-cp314-win_amd64.whl", hash = "sha256:bdc919ead48f234740ad807933cdf545180bfbe9342c2bb451556db2ed958581", size = 15341, upload-time = "2025-09-27T18:37:16.496Z" },
|
||||||
|
{ url = "https://files.pythonhosted.org/packages/6f/18/acf23e91bd94fd7b3031558b1f013adfa21a8e407a3fdb32745538730382/markupsafe-3.0.3-cp314-cp314-win_arm64.whl", hash = "sha256:5a7d5dc5140555cf21a6fefbdbf8723f06fcd2f63ef108f2854de715e4422cb4", size = 14073, upload-time = "2025-09-27T18:37:17.476Z" },
|
||||||
|
{ url = "https://files.pythonhosted.org/packages/3c/f0/57689aa4076e1b43b15fdfa646b04653969d50cf30c32a102762be2485da/markupsafe-3.0.3-cp314-cp314t-macosx_10_13_x86_64.whl", hash = "sha256:1353ef0c1b138e1907ae78e2f6c63ff67501122006b0f9abad68fda5f4ffc6ab", size = 11661, upload-time = "2025-09-27T18:37:18.453Z" },
|
||||||
|
{ url = "https://files.pythonhosted.org/packages/89/c3/2e67a7ca217c6912985ec766c6393b636fb0c2344443ff9d91404dc4c79f/markupsafe-3.0.3-cp314-cp314t-macosx_11_0_arm64.whl", hash = "sha256:1085e7fbddd3be5f89cc898938f42c0b3c711fdcb37d75221de2666af647c175", size = 12069, upload-time = "2025-09-27T18:37:19.332Z" },
|
||||||
|
{ url = "https://files.pythonhosted.org/packages/f0/00/be561dce4e6ca66b15276e184ce4b8aec61fe83662cce2f7d72bd3249d28/markupsafe-3.0.3-cp314-cp314t-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:1b52b4fb9df4eb9ae465f8d0c228a00624de2334f216f178a995ccdcf82c4634", size = 25670, upload-time = "2025-09-27T18:37:20.245Z" },
|
||||||
|
{ url = "https://files.pythonhosted.org/packages/50/09/c419f6f5a92e5fadde27efd190eca90f05e1261b10dbd8cbcb39cd8ea1dc/markupsafe-3.0.3-cp314-cp314t-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:fed51ac40f757d41b7c48425901843666a6677e3e8eb0abcff09e4ba6e664f50", size = 23598, upload-time = "2025-09-27T18:37:21.177Z" },
|
||||||
|
{ url = "https://files.pythonhosted.org/packages/22/44/a0681611106e0b2921b3033fc19bc53323e0b50bc70cffdd19f7d679bb66/markupsafe-3.0.3-cp314-cp314t-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:f190daf01f13c72eac4efd5c430a8de82489d9cff23c364c3ea822545032993e", size = 23261, upload-time = "2025-09-27T18:37:22.167Z" },
|
||||||
|
{ url = "https://files.pythonhosted.org/packages/5f/57/1b0b3f100259dc9fffe780cfb60d4be71375510e435efec3d116b6436d43/markupsafe-3.0.3-cp314-cp314t-musllinux_1_2_aarch64.whl", hash = "sha256:e56b7d45a839a697b5eb268c82a71bd8c7f6c94d6fd50c3d577fa39a9f1409f5", size = 24835, upload-time = "2025-09-27T18:37:23.296Z" },
|
||||||
|
{ url = "https://files.pythonhosted.org/packages/26/6a/4bf6d0c97c4920f1597cc14dd720705eca0bf7c787aebc6bb4d1bead5388/markupsafe-3.0.3-cp314-cp314t-musllinux_1_2_riscv64.whl", hash = "sha256:f3e98bb3798ead92273dc0e5fd0f31ade220f59a266ffd8a4f6065e0a3ce0523", size = 22733, upload-time = "2025-09-27T18:37:24.237Z" },
|
||||||
|
{ url = "https://files.pythonhosted.org/packages/14/c7/ca723101509b518797fedc2fdf79ba57f886b4aca8a7d31857ba3ee8281f/markupsafe-3.0.3-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:5678211cb9333a6468fb8d8be0305520aa073f50d17f089b5b4b477ea6e67fdc", size = 23672, upload-time = "2025-09-27T18:37:25.271Z" },
|
||||||
|
{ url = "https://files.pythonhosted.org/packages/fb/df/5bd7a48c256faecd1d36edc13133e51397e41b73bb77e1a69deab746ebac/markupsafe-3.0.3-cp314-cp314t-win32.whl", hash = "sha256:915c04ba3851909ce68ccc2b8e2cd691618c4dc4c4232fb7982bca3f41fd8c3d", size = 14819, upload-time = "2025-09-27T18:37:26.285Z" },
|
||||||
|
{ url = "https://files.pythonhosted.org/packages/1a/8a/0402ba61a2f16038b48b39bccca271134be00c5c9f0f623208399333c448/markupsafe-3.0.3-cp314-cp314t-win_amd64.whl", hash = "sha256:4faffd047e07c38848ce017e8725090413cd80cbc23d86e55c587bf979e579c9", size = 15426, upload-time = "2025-09-27T18:37:27.316Z" },
|
||||||
|
{ url = "https://files.pythonhosted.org/packages/70/bc/6f1c2f612465f5fa89b95bead1f44dcb607670fd42891d8fdcd5d039f4f4/markupsafe-3.0.3-cp314-cp314t-win_arm64.whl", hash = "sha256:32001d6a8fc98c8cb5c947787c5d08b0a50663d139f1305bac5885d98d9b40fa", size = 14146, upload-time = "2025-09-27T18:37:28.327Z" },
|
||||||
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "priority"
|
||||||
|
version = "2.0.0"
|
||||||
|
source = { registry = "https://pypi.org/simple" }
|
||||||
|
sdist = { url = "https://files.pythonhosted.org/packages/f5/3c/eb7c35f4dcede96fca1842dac5f4f5d15511aa4b52f3a961219e68ae9204/priority-2.0.0.tar.gz", hash = "sha256:c965d54f1b8d0d0b19479db3924c7c36cf672dbf2aec92d43fbdaf4492ba18c0", size = 24792, upload-time = "2021-06-27T10:15:05.487Z" }
|
||||||
|
wheels = [
|
||||||
|
{ url = "https://files.pythonhosted.org/packages/5e/5f/82c8074f7e84978129347c2c6ec8b6c59f3584ff1a20bc3c940a3e061790/priority-2.0.0-py3-none-any.whl", hash = "sha256:6f8eefce5f3ad59baf2c080a664037bb4725cd0a790d53d59ab4059288faf6aa", size = 8946, upload-time = "2021-06-27T10:15:03.856Z" },
|
||||||
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "python-dotenv"
|
||||||
|
version = "1.2.2"
|
||||||
|
source = { registry = "https://pypi.org/simple" }
|
||||||
|
sdist = { url = "https://files.pythonhosted.org/packages/82/ed/0301aeeac3e5353ef3d94b6ec08bbcabd04a72018415dcb29e588514bba8/python_dotenv-1.2.2.tar.gz", hash = "sha256:2c371a91fbd7ba082c2c1dc1f8bf89ca22564a087c2c287cd9b662adde799cf3", size = 50135, upload-time = "2026-03-01T16:00:26.196Z" }
|
||||||
|
wheels = [
|
||||||
|
{ url = "https://files.pythonhosted.org/packages/0b/d7/1959b9648791274998a9c3526f6d0ec8fd2233e4d4acce81bbae76b44b2a/python_dotenv-1.2.2-py3-none-any.whl", hash = "sha256:1d8214789a24de455a8b8bd8ae6fe3c6b69a5e3d64aa8a8e5d68e694bbcb285a", size = 22101, upload-time = "2026-03-01T16:00:25.09Z" },
|
||||||
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "quart"
|
||||||
|
version = "0.20.0"
|
||||||
|
source = { registry = "https://pypi.org/simple" }
|
||||||
|
dependencies = [
|
||||||
|
{ name = "aiofiles" },
|
||||||
|
{ name = "blinker" },
|
||||||
|
{ name = "click" },
|
||||||
|
{ name = "flask" },
|
||||||
|
{ name = "hypercorn" },
|
||||||
|
{ name = "itsdangerous" },
|
||||||
|
{ name = "jinja2" },
|
||||||
|
{ name = "markupsafe" },
|
||||||
|
{ name = "werkzeug" },
|
||||||
|
]
|
||||||
|
sdist = { url = "https://files.pythonhosted.org/packages/1d/9d/12e1143a5bd2ccc05c293a6f5ae1df8fd94a8fc1440ecc6c344b2b30ce13/quart-0.20.0.tar.gz", hash = "sha256:08793c206ff832483586f5ae47018c7e40bdd75d886fee3fabbdaa70c2cf505d", size = 63874, upload-time = "2024-12-23T13:53:05.664Z" }
|
||||||
|
wheels = [
|
||||||
|
{ url = "https://files.pythonhosted.org/packages/7e/e9/cc28f21f52913adf333f653b9e0a3bf9cb223f5083a26422968ba73edd8d/quart-0.20.0-py3-none-any.whl", hash = "sha256:003c08f551746710acb757de49d9b768986fd431517d0eb127380b656b98b8f1", size = 77960, upload-time = "2024-12-23T13:53:02.842Z" },
|
||||||
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "snake-python"
|
||||||
|
version = "0.1.0"
|
||||||
|
source = { virtual = "." }
|
||||||
|
dependencies = [
|
||||||
|
{ name = "aiologger" },
|
||||||
|
{ name = "dotenv" },
|
||||||
|
{ name = "gel" },
|
||||||
|
{ name = "quart" },
|
||||||
|
]
|
||||||
|
|
||||||
|
[package.metadata]
|
||||||
|
requires-dist = [
|
||||||
|
{ name = "aiologger", specifier = ">=0.7.0" },
|
||||||
|
{ name = "dotenv", specifier = ">=0.9.9" },
|
||||||
|
{ name = "gel", specifier = ">=3.1.0" },
|
||||||
|
{ name = "quart", specifier = ">=0.20.0" },
|
||||||
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "werkzeug"
|
||||||
|
version = "3.1.8"
|
||||||
|
source = { registry = "https://pypi.org/simple" }
|
||||||
|
dependencies = [
|
||||||
|
{ name = "markupsafe" },
|
||||||
|
]
|
||||||
|
sdist = { url = "https://files.pythonhosted.org/packages/dd/b2/381be8cfdee792dd117872481b6e378f85c957dd7c5bca38897b08f765fd/werkzeug-3.1.8.tar.gz", hash = "sha256:9bad61a4268dac112f1c5cd4630a56ede601b6ed420300677a869083d70a4c44", size = 875852, upload-time = "2026-04-02T18:49:14.268Z" }
|
||||||
|
wheels = [
|
||||||
|
{ url = "https://files.pythonhosted.org/packages/93/8c/2e650f2afeb7ee576912636c23ddb621c91ac6a98e66dc8d29c3c69446e1/werkzeug-3.1.8-py3-none-any.whl", hash = "sha256:63a77fb8892bf28ebc3178683445222aa500e48ebad5ec77b0ad80f8726b1f50", size = 226459, upload-time = "2026-04-02T18:49:12.72Z" },
|
||||||
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "wsproto"
|
||||||
|
version = "1.3.2"
|
||||||
|
source = { registry = "https://pypi.org/simple" }
|
||||||
|
dependencies = [
|
||||||
|
{ name = "h11" },
|
||||||
|
]
|
||||||
|
sdist = { url = "https://files.pythonhosted.org/packages/c7/79/12135bdf8b9c9367b8701c2c19a14c913c120b882d50b014ca0d38083c2c/wsproto-1.3.2.tar.gz", hash = "sha256:b86885dcf294e15204919950f666e06ffc6c7c114ca900b060d6e16293528294", size = 50116, upload-time = "2025-11-20T18:18:01.871Z" }
|
||||||
|
wheels = [
|
||||||
|
{ url = "https://files.pythonhosted.org/packages/a4/f5/10b68b7b1544245097b2a1b8238f66f2fc6dcaeb24ba5d917f52bd2eed4f/wsproto-1.3.2-py3-none-any.whl", hash = "sha256:61eea322cdf56e8cc904bd3ad7573359a242ba65688716b0710a5eb12beab584", size = 24405, upload-time = "2025-11-20T18:18:00.454Z" },
|
||||||
|
]
|
||||||
Reference in New Issue
Block a user