Compare commits
19 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
8f938ce3fe
|
|||
|
dfcdbae85b
|
|||
|
fb579e5fbc
|
|||
|
8f6bc3cfdd
|
|||
|
f124ce6f96
|
|||
|
6ab0161b49
|
|||
|
d7bd89eae9
|
|||
|
eace1872d7
|
|||
|
0a3db6ba57
|
|||
|
013ac98821
|
|||
|
a3fe386198
|
|||
|
8a431da014
|
|||
|
19e4aee454
|
|||
|
c8dd01490c
|
|||
|
1e57ad1af6
|
|||
|
4ca905fbf0
|
|||
|
8e733dfe39
|
|||
|
49f2e0b008
|
|||
|
37de34cc5e
|
@@ -7,4 +7,7 @@
|
|||||||
__pycache__/
|
__pycache__/
|
||||||
data/
|
data/
|
||||||
.env
|
.env
|
||||||
|
.tools/
|
||||||
|
|
||||||
dbschema/migrations/
|
dbschema/migrations/
|
||||||
|
*.jsonl
|
||||||
@@ -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 = git@github.com:BattlesnakeOfficial/rules.git
|
||||||
@@ -90,6 +90,67 @@ Or with `just`:
|
|||||||
just export-dataset
|
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:
|
To store compact dataset-only records (JSONL) and skip full per-game JSON files:
|
||||||
|
|
||||||
```sh
|
```sh
|
||||||
|
|||||||
@@ -1,16 +1,5 @@
|
|||||||
from server.Server import Server
|
from server.bootstrap import build_server_from_env
|
||||||
import os
|
|
||||||
|
|
||||||
server = Server(
|
server = build_server_from_env(default_snake_type="TemplateSnake")
|
||||||
data_path=os.path.dirname(__file__),
|
|
||||||
snake_type=os.environ.get("SNAKE", "BestBattleSnake"),
|
|
||||||
storage_type=os.environ.get("STORAGE", "LocalStorage"),
|
|
||||||
store_game_when_win_and_moves_are_bigger_as=int(os.environ.get("STORE_IF_WIN_AND_MOVES_ARE_BIGGER_AS", 10)),
|
|
||||||
debug=os.environ.get("DEBUG_SERVER", False),
|
|
||||||
check_tls_security=False,
|
|
||||||
)
|
|
||||||
|
|
||||||
if os.environ.get("STORE_GAME_HISTORY", None):
|
|
||||||
server.enable_store_game_state()
|
|
||||||
|
|
||||||
app = server.app
|
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.
@@ -12,6 +12,9 @@ set dotenv-required := true
|
|||||||
# Use zsh
|
# Use zsh
|
||||||
set shell := ["bash", "-cu"]
|
set shell := ["bash", "-cu"]
|
||||||
|
|
||||||
|
BATTLESNAKE_CLI_DIR := ".tools/battlesnake-cli"
|
||||||
|
BATTLESNAKE_CLI_BIN := ".tools/battlesnake-cli/battlesnake"
|
||||||
|
|
||||||
# ------------------------------------------------------------------------------
|
# ------------------------------------------------------------------------------
|
||||||
# Default
|
# Default
|
||||||
# ------------------------------------------------------------------------------
|
# ------------------------------------------------------------------------------
|
||||||
@@ -28,23 +31,132 @@ default:
|
|||||||
run:
|
run:
|
||||||
"{{justfile_directory()}}/main.py"
|
"{{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
|
# Testing helpers
|
||||||
# ------------------------------------------------------------------------------
|
# ------------------------------------------------------------------------------
|
||||||
|
|
||||||
test-constrictor:
|
test-constrictor: build-battlesnake-cli
|
||||||
#!/usr/bin/env bash
|
#!/usr/bin/env bash
|
||||||
set -euo pipefail
|
set -euo pipefail
|
||||||
|
|
||||||
BATTLESNAKE_CLI=battlesnake_cli_1.2.3_Linux_x86_64/battlesnake
|
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
|
"$BATTLESNAKE_CLI" play -W 11 -H 11 --name 'Python Starter Project' --url http://localhost:8000 -g constrictor --browser --minimumFood 0
|
||||||
|
|
||||||
test-seed:
|
test-seed: build-battlesnake-cli
|
||||||
#!/usr/bin/env bash
|
#!/usr/bin/env bash
|
||||||
set -euo pipefail
|
set -euo pipefail
|
||||||
|
|
||||||
BATTLESNAKE_CLI=battlesnake_cli_1.2.3_Linux_x86_64/battlesnake
|
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
|
"$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
|
||||||
|
|
||||||
# ------------------------------------------------------------------------------
|
# ------------------------------------------------------------------------------
|
||||||
# Fataset helpers
|
# Fataset helpers
|
||||||
@@ -52,3 +164,9 @@ test-seed:
|
|||||||
|
|
||||||
export-dataset input="data" output="data/dataset/good_moves.jsonl":
|
export-dataset input="data" output="data/dataset/good_moves.jsonl":
|
||||||
python -m server.DatasetExporter --input "{{input}}" --output "{{output}}"
|
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
|
||||||
|
|||||||
Submodule
+1
Submodule local-client added at 87e094e2e1
@@ -13,8 +13,9 @@
|
|||||||
# For more info see docs.battlesnake.com
|
# For more info see docs.battlesnake.com
|
||||||
|
|
||||||
from server.CreateEnvironmentFile import CreateEnvironmentFile
|
from server.CreateEnvironmentFile import CreateEnvironmentFile
|
||||||
from server.Server import Server
|
from server.bootstrap import build_run_config, build_server_from_env
|
||||||
|
|
||||||
|
import asyncio
|
||||||
import os
|
import os
|
||||||
|
|
||||||
# Start server when `python main.py` is run
|
# Start server when `python main.py` is run
|
||||||
@@ -24,23 +25,7 @@ if __name__ == "__main__":
|
|||||||
"STORE_GAME_HISTORY": True,
|
"STORE_GAME_HISTORY": True,
|
||||||
"DEBUG": True,
|
"DEBUG": True,
|
||||||
"SNAKE": "TemplateSnake",
|
"SNAKE": "TemplateSnake",
|
||||||
"STORE_IF_WIN_AND_MOVES_ARE_BIGGER_AS": 10,
|
|
||||||
})
|
})
|
||||||
|
|
||||||
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", "TemplateSnake"),
|
|
||||||
storage_type=os.environ.get("STORAGE", "LocalStorage"),
|
|
||||||
store_game_when_win_and_moves_are_bigger_as=int(os.environ.get("STORE_IF_WIN_AND_MOVES_ARE_BIGGER_AS", 10)),
|
|
||||||
debug=os.environ.get("DEBUG_SERVER", False),
|
|
||||||
check_tls_security=False,
|
|
||||||
)
|
|
||||||
|
|
||||||
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)),
|
|
||||||
)
|
|
||||||
|
|||||||
@@ -5,6 +5,7 @@ description = "Add your description here"
|
|||||||
readme = "README.md"
|
readme = "README.md"
|
||||||
requires-python = ">=3.13"
|
requires-python = ">=3.13"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
|
"aiologger>=0.7.0",
|
||||||
"dotenv>=0.9.9",
|
"dotenv>=0.9.9",
|
||||||
"gel>=3.1.0",
|
"gel>=3.1.0",
|
||||||
"quart>=0.20.0",
|
"quart>=0.20.0",
|
||||||
|
|||||||
Submodule
+1
Submodule quart_common added at 823560fdcd
@@ -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,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")
|
||||||
+13
-2
@@ -16,12 +16,13 @@ class GameBoard:
|
|||||||
self.ruleset = ruleset
|
self.ruleset = ruleset
|
||||||
self.map = map
|
self.map = map
|
||||||
self.url = self._get_game_url(True if ruleset["version"] == "cli" else False)
|
self.url = self._get_game_url(True if ruleset["version"] == "cli" else False)
|
||||||
|
self.timeout = 500
|
||||||
|
|
||||||
# Setter Functions
|
# Setter Functions
|
||||||
def _set_snakes(self, snakes:list[dict]):
|
def _set_snakes(self, snakes:list[dict]):
|
||||||
self.other_snakes = [ x for x in snakes if x["id"] != self.my_snake["id"] ]
|
self.other_snakes = [ x for x in snakes if x["id"] != self.my_snake["id"] ]
|
||||||
|
|
||||||
def _set_my_snake(self, my_snake:str):
|
def _set_my_snake(self, my_snake:dict):
|
||||||
self.my_snake = my_snake
|
self.my_snake = my_snake
|
||||||
|
|
||||||
def _set_food(self, food:list[dict]):
|
def _set_food(self, food:list[dict]):
|
||||||
@@ -61,6 +62,15 @@ class GameBoard:
|
|||||||
def get_type(self):
|
def get_type(self):
|
||||||
return self.type
|
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):
|
def get_my_snake_head(self):
|
||||||
return self.my_snake["head"]
|
return self.my_snake["head"]
|
||||||
|
|
||||||
@@ -79,7 +89,7 @@ class GameBoard:
|
|||||||
"width": self.width,
|
"width": self.width,
|
||||||
"snakes": snakes,
|
"snakes": snakes,
|
||||||
"food": self.food,
|
"food": self.food,
|
||||||
"hazards": self.hazards
|
"hazards": self.hazards,
|
||||||
}
|
}
|
||||||
|
|
||||||
# Game Functions
|
# Game Functions
|
||||||
@@ -91,6 +101,7 @@ class GameBoard:
|
|||||||
self._set_snakes(game_data['board']['snakes'])
|
self._set_snakes(game_data['board']['snakes'])
|
||||||
|
|
||||||
self._set_turn(game_data["turn"])
|
self._set_turn(game_data["turn"])
|
||||||
|
self.timeout = int(game_data.get('game', {}).get('timeout', 500))
|
||||||
|
|
||||||
async def start_game(self, game_data:dict):
|
async def start_game(self, game_data:dict):
|
||||||
self.init_snakes = len(game_data['board']['snakes'])
|
self.init_snakes = len(game_data['board']['snakes'])
|
||||||
|
|||||||
+173
-40
@@ -1,6 +1,9 @@
|
|||||||
from server.Files import read_file
|
from server.Files import read_file
|
||||||
from server.GameBoard import GameBoard
|
from server.GameBoard import GameBoard
|
||||||
from server.SnakeBuilder import SnakeBuilder
|
from snakes import SnakeBuilder
|
||||||
|
from quart_common.web.logger import await_log
|
||||||
|
from quart_common.web.logger import build_logger
|
||||||
|
from typing import cast
|
||||||
|
|
||||||
from server.storage.StorageLoader import StorageLoader
|
from server.storage.StorageLoader import StorageLoader
|
||||||
|
|
||||||
@@ -8,9 +11,16 @@ from quart import Quart, request, jsonify
|
|||||||
import logging, json, os, re
|
import logging, json, os, re
|
||||||
|
|
||||||
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, storage_type:str, debug:bool=False, store_game_when_win_and_moves_are_bigger_as:int=10, check_tls_security: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.storage_type = storage_type
|
||||||
@@ -20,124 +30,179 @@ class Server:
|
|||||||
self.check_tls_security = check_tls_security
|
self.check_tls_security = check_tls_security
|
||||||
|
|
||||||
self.store_game_state = False
|
self.store_game_state = False
|
||||||
self.store_game_when_win_and_moves_are_bigger_as = store_game_when_win_and_moves_are_bigger_as
|
|
||||||
|
|
||||||
self.running_games:dict[str, GameBoard] = {}
|
self.running_games:dict[str, GameBoard] = {}
|
||||||
|
self.game_move_counts:dict[str, int] = {}
|
||||||
|
self.metrics = {
|
||||||
|
'games_started': 0,
|
||||||
|
'games_ended': 0,
|
||||||
|
'wins': 0,
|
||||||
|
'losses': 0,
|
||||||
|
'total_moves': 0,
|
||||||
|
'total_turns': 0,
|
||||||
|
'max_turn': 0,
|
||||||
|
}
|
||||||
|
self.logger = build_logger('Battlesnake', debug_env_var='DEBUG_SERVER')
|
||||||
|
self.snake_version = self._get_snake_version()
|
||||||
|
|
||||||
self.app = Quart("Battlesnake")
|
self.app = Quart('Battlesnake')
|
||||||
|
|
||||||
# info is called when you create your Battlesnake on play.battlesnake.com
|
# info is called when you create your Battlesnake on play.battlesnake.com
|
||||||
# and controls your Battlesnake's appearance
|
# and controls your Battlesnake's appearance
|
||||||
# TIP: If you open your Battlesnake URL in a browser you should see this data
|
# TIP: If you open your Battlesnake URL in a browser you should see this data
|
||||||
@self.app.get("/")
|
@self.app.get('/')
|
||||||
async def on_info():
|
async def on_info():
|
||||||
snake_config = await self._read_json_config_or_create()
|
snake_config = await self._read_json_config_or_create()
|
||||||
|
|
||||||
print("INFO Snake:", snake_config)
|
await await_log(self.logger.info(f'INFO Snake: {snake_config}'))
|
||||||
return snake_config
|
return snake_config
|
||||||
|
|
||||||
# start is called when your Battlesnake begins a game
|
# start is called when your Battlesnake begins a game
|
||||||
@self.app.post("/start")
|
@self.app.post('/start')
|
||||||
async def on_start():
|
async def on_start():
|
||||||
game_state = await request.get_json()
|
game_state = await request.get_json()
|
||||||
await self._create_game_board(game_state)
|
await self._create_game_board(game_state)
|
||||||
print("GAME START:", game_state["game"])
|
await await_log(self.logger.info(f'GAME START: {game_state['game']}'))
|
||||||
return "ok"
|
return 'ok'
|
||||||
|
|
||||||
# move is called when your Battlesnake game is running game
|
# move is called when your Battlesnake game is running game
|
||||||
@self.app.post("/move")
|
@self.app.post('/move')
|
||||||
async def on_move():
|
async def on_move():
|
||||||
game_state = await request.get_json()
|
game_state = await request.get_json()
|
||||||
game_board = await self._get_game_board(game_state)
|
game_board = await self._get_game_board(game_state)
|
||||||
next_move = game_board.snake_neat_make_a_move()
|
next_move = game_board.snake_neat_make_a_move()
|
||||||
|
|
||||||
if self.debug:
|
if self.debug:
|
||||||
print("TURN:", f'{game_state["turn"]:3},', "MOVE:", f"{next_move:5}")
|
await await_log(self.logger.debug(f'TURN: {game_state['turn']:3}, MOVE: {next_move:5}'))
|
||||||
|
|
||||||
return {"move": next_move}
|
return {'move': next_move}
|
||||||
|
|
||||||
# end is called when your Battlesnake finishes a game
|
# end is called when your Battlesnake finishes a game
|
||||||
@self.app.post("/end")
|
@self.app.post('/end')
|
||||||
async def on_end():
|
async def on_end():
|
||||||
game_state = await request.get_json()
|
game_state = await request.get_json()
|
||||||
if self.store_game_state:
|
if self.store_game_state:
|
||||||
game_board = await self._get_game_board(game_state, end=True)
|
game_board = await self._get_game_board(game_state, end=True)
|
||||||
#if not game_board.get_winner() == "me" and not game_board.get_turn() <= self.store_game_when_win_and_moves_are_bigger_as:
|
|
||||||
if self.check_tls_security:
|
if self.check_tls_security:
|
||||||
await game_board.save(
|
await game_board.save(
|
||||||
StorageLoader.build(self.storage_type),
|
StorageLoader.build(self.storage_type),
|
||||||
file_path=os.path.join(self.data_path, 'data'),
|
file_path=os.path.join(self.data_path, 'data'),
|
||||||
database=os.getenv("EDGEDB_DATABASE", None),
|
database=os.getenv('EDGEDB_DATABASE', None),
|
||||||
tls_security=None
|
tls_security=None
|
||||||
)
|
)
|
||||||
else:
|
else:
|
||||||
await game_board.save(
|
await game_board.save(
|
||||||
StorageLoader.build(self.storage_type),
|
StorageLoader.build(self.storage_type),
|
||||||
file_path=os.path.join(self.data_path, 'data'),
|
file_path=os.path.join(self.data_path, 'data'),
|
||||||
database=os.getenv("EDGEDB_DATABASE", None),
|
database=os.getenv('EDGEDB_DATABASE', None),
|
||||||
)
|
)
|
||||||
|
|
||||||
print("GAME ENDED: Winner is", [ x["name"] for x in game_state["board"]['snakes']])
|
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)
|
self._delete_game_board(game_state)
|
||||||
return "ok"
|
return 'ok'
|
||||||
|
|
||||||
@self.app.after_request
|
@self.app.after_request
|
||||||
async def identify_server(response):
|
async def identify_server(response):
|
||||||
response.headers.set(
|
response.headers.set('server', 'battlesnake/gitea/snake-python')
|
||||||
"server", "battlesnake/gitea/snake-python"
|
|
||||||
)
|
|
||||||
return response
|
return response
|
||||||
|
|
||||||
@self.app.get("/cleanup")
|
@self.app.get('/cleanup')
|
||||||
async def cleanup():
|
async def cleanup():
|
||||||
results = self._cleanup_database()
|
results = self._cleanup_database()
|
||||||
return jsonify(data=json.loads(results), status=200)
|
return jsonify(data=json.loads(results), status=200)
|
||||||
|
|
||||||
def run(self, host:str="0.0.0.0", port:str="8000", debug:bool=False):
|
@self.app.get('/metrics')
|
||||||
logging.getLogger("werkzeug").setLevel(logging.ERROR)
|
async def metrics():
|
||||||
|
return jsonify(self._build_metrics())
|
||||||
|
|
||||||
print(f"\nRunning Battlesnake at http://{host}:{port} with the {' '.join(re.findall('[A-Z][^A-Z]*', self.snake_type))}")
|
@self.app.get('/metrics/prometheus')
|
||||||
self.app.run(host=host, port=port, debug=debug)
|
async def metrics_prometheus():
|
||||||
|
return (
|
||||||
|
self._build_prometheus_metrics(),
|
||||||
|
200,
|
||||||
|
{'Content-Type': 'text/plain; version=0.0.4; charset=utf-8'},
|
||||||
|
)
|
||||||
|
|
||||||
async def _read_json_config_or_create(self):
|
async def run(self, host:str='0.0.0.0', port:int=8000, debug:bool=False):
|
||||||
snake_config = await read_file(self.config_file, json.load)
|
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:
|
||||||
return await self._override_snake_config_with_environment_variables(self.default_snake_config)
|
return await self._override_snake_config_with_environment_variables(self.default_snake_config)
|
||||||
return await self._override_snake_config_with_environment_variables(snake_config)
|
return await self._override_snake_config_with_environment_variables(snake_config)
|
||||||
|
|
||||||
async def _override_snake_config_with_environment_variables(self, config: dict[str, str]) -> dict[str, str]:
|
async def _override_snake_config_with_environment_variables(self, config:dict[str, str]) -> dict[str, str]:
|
||||||
for key in ("author", "color", "head", "tail"):
|
config['version'] = self.snake_version
|
||||||
value = os.environ.get(f"SNAKE_{key.upper()}")
|
|
||||||
|
for key in ('author', 'color', 'head', 'tail'):
|
||||||
|
value = os.environ.get(f'SNAKE_{key.upper()}')
|
||||||
if value is not None:
|
if value is not None:
|
||||||
config[key] = value
|
config[key] = value
|
||||||
|
|
||||||
|
version_override = os.environ.get('SNAKE_VERSION')
|
||||||
|
if version_override is not None:
|
||||||
|
config['version'] = version_override
|
||||||
|
|
||||||
return config
|
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)
|
||||||
|
|
||||||
async def _create_game_board(self, game_state:dict):
|
async def _create_game_board(self, game_state:dict):
|
||||||
|
game_id = game_state['game']['id']
|
||||||
new_game_board = GameBoard(
|
new_game_board = GameBoard(
|
||||||
game_id=game_state["game"]["id"],
|
game_id=game_id,
|
||||||
width=game_state['board']['width'],
|
width=game_state['board']['width'],
|
||||||
height=game_state['board']['height'],
|
height=game_state['board']['height'],
|
||||||
ruleset=game_state['game']["ruleset"],
|
ruleset=game_state['game']['ruleset'],
|
||||||
source=game_state['game']['source'],
|
source=game_state['game']['source'],
|
||||||
map=game_state['game']['map'],
|
map=game_state['game']['map'],
|
||||||
snake_class=SnakeBuilder.build(self.snake_type)
|
snake_class=SnakeBuilder.build(self.snake_type),
|
||||||
)
|
)
|
||||||
await new_game_board.start_game(game_state)
|
await new_game_board.start_game(game_state)
|
||||||
|
|
||||||
self.running_games[game_state["game"]["id"]] = new_game_board
|
self.running_games[game_id] = new_game_board
|
||||||
|
self.game_move_counts[game_id] = 0
|
||||||
|
self.metrics['games_started'] += 1
|
||||||
return new_game_board
|
return new_game_board
|
||||||
|
|
||||||
def _delete_game_board(self, game_state):
|
def _delete_game_board(self, game_state:dict):
|
||||||
del self.running_games[game_state["game"]["id"]]
|
game_id = game_state['game']['id']
|
||||||
|
del self.running_games[game_id]
|
||||||
|
self.game_move_counts.pop(game_id, None)
|
||||||
|
|
||||||
async def _get_game_board(self, game_state:str, end:bool=False):
|
async def _get_game_board(self, game_state:dict, end:bool=False):
|
||||||
|
game_id = game_state['game']['id']
|
||||||
try:
|
try:
|
||||||
game_board = self.running_games[game_state["game"]["id"]]
|
game_board = self.running_games[game_id]
|
||||||
except KeyError:
|
except KeyError:
|
||||||
game_board = await self._create_game_board(game_state)
|
game_board = await self._create_game_board(game_state)
|
||||||
|
|
||||||
|
if not end:
|
||||||
|
self.metrics['total_moves'] += 1
|
||||||
|
self.game_move_counts[game_id] = self.game_move_counts.get(game_id, 0) + 1
|
||||||
|
|
||||||
game_board.read_game_data(game_state)
|
game_board.read_game_data(game_state)
|
||||||
if end:
|
if end:
|
||||||
|
self._record_game_end(game_state)
|
||||||
game_board.end_game(game_state)
|
game_board.end_game(game_state)
|
||||||
|
|
||||||
return game_board
|
return game_board
|
||||||
@@ -148,3 +213,71 @@ class Server:
|
|||||||
def _cleanup_database(self):
|
def _cleanup_database(self):
|
||||||
storage = StorageLoader.build(self.storage_type)()
|
storage = StorageLoader.build(self.storage_type)()
|
||||||
return storage.cleanup()
|
return storage.cleanup()
|
||||||
|
|
||||||
|
def _record_game_end(self, game_state: dict):
|
||||||
|
self.metrics['games_ended'] += 1
|
||||||
|
|
||||||
|
final_turn = int(game_state.get('turn', 0))
|
||||||
|
self.metrics['total_turns'] += final_turn
|
||||||
|
self.metrics['max_turn'] = max(self.metrics['max_turn'], final_turn)
|
||||||
|
|
||||||
|
you_id = game_state.get('you', {}).get('id')
|
||||||
|
alive_snakes = game_state.get('board', {}).get('snakes', [])
|
||||||
|
alive_ids = {snake.get('id') for snake in alive_snakes}
|
||||||
|
|
||||||
|
if you_id and you_id in alive_ids:
|
||||||
|
self.metrics['wins'] += 1
|
||||||
|
else:
|
||||||
|
self.metrics['losses'] += 1
|
||||||
|
|
||||||
|
def _build_metrics(self) -> dict:
|
||||||
|
games_ended = self.metrics['games_ended']
|
||||||
|
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
|
||||||
|
|
||||||
|
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),
|
||||||
|
}
|
||||||
|
|
||||||
|
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_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_win_rate Win ratio from ended games (0.0 - 1.0).',
|
||||||
|
'# TYPE snake_win_rate gauge',
|
||||||
|
f'snake_win_rate {snapshot['win_rate']}',
|
||||||
|
]
|
||||||
|
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,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'),
|
||||||
|
}
|
||||||
+275
-106
@@ -1,11 +1,19 @@
|
|||||||
|
from collections.abc import Iterator
|
||||||
from collections import deque
|
from collections import deque
|
||||||
from typing import Any, cast
|
from typing import Any, cast
|
||||||
import random
|
import random, os
|
||||||
import os
|
from time import perf_counter
|
||||||
|
|
||||||
from snakes.TemplateSnake import TemplateSnake
|
from snakes.TemplateSnake import TemplateSnake
|
||||||
|
|
||||||
class BestBattleSnake(TemplateSnake):
|
class BestBattleSnake(TemplateSnake):
|
||||||
|
VERSION = "2.6.0"
|
||||||
|
Point = tuple[int, int]
|
||||||
|
Coord = dict[str, int]
|
||||||
|
SnakeState = dict[str, Any]
|
||||||
|
MoveMap = dict[str, Coord]
|
||||||
|
AttackMap = dict[Point, int]
|
||||||
|
|
||||||
DIRECTIONS = {
|
DIRECTIONS = {
|
||||||
"up": (0, 1),
|
"up": (0, 1),
|
||||||
"down": (0, -1),
|
"down": (0, -1),
|
||||||
@@ -23,12 +31,16 @@ class BestBattleSnake(TemplateSnake):
|
|||||||
def __init__(self):
|
def __init__(self):
|
||||||
super().__init__()
|
super().__init__()
|
||||||
self.name = "BestBattleSnake"
|
self.name = "BestBattleSnake"
|
||||||
|
self.version = self.VERSION
|
||||||
self.recent_heads = deque(maxlen=14)
|
self.recent_heads = deque(maxlen=14)
|
||||||
self.last_move = None
|
self.last_move = None
|
||||||
self.last_game_id = None
|
self.last_game_id = None
|
||||||
|
self.previous_hazards = set()
|
||||||
self.duel_style = self._get_duel_style()
|
self.duel_style = self._get_duel_style()
|
||||||
|
self.timeout_buffer_ms = self._get_timeout_buffer_ms()
|
||||||
|
|
||||||
def _get_duel_style(self):
|
def _get_duel_style(self) -> str:
|
||||||
|
"""Resolve duel tuning style from `BATTLE_SNAKE_DUEL_STYLE` or `DUEL_STYLE`."""
|
||||||
value = os.getenv("BATTLE_SNAKE_DUEL_STYLE")
|
value = os.getenv("BATTLE_SNAKE_DUEL_STYLE")
|
||||||
if value is None:
|
if value is None:
|
||||||
value = os.getenv("DUEL_STYLE", "balanced")
|
value = os.getenv("DUEL_STYLE", "balanced")
|
||||||
@@ -38,7 +50,8 @@ class BestBattleSnake(TemplateSnake):
|
|||||||
return "balanced"
|
return "balanced"
|
||||||
return style
|
return style
|
||||||
|
|
||||||
def _duel_weights(self, style):
|
def _duel_weights(self, style:str) -> dict[str, float]:
|
||||||
|
"""Return score multipliers for the selected duel style preset."""
|
||||||
if style == "safe":
|
if style == "safe":
|
||||||
return {
|
return {
|
||||||
"head_pressure": 0.65,
|
"head_pressure": 0.65,
|
||||||
@@ -57,16 +70,32 @@ class BestBattleSnake(TemplateSnake):
|
|||||||
"food_bias": 1.00,
|
"food_bias": 1.00,
|
||||||
}
|
}
|
||||||
|
|
||||||
def choose_move(self, game_data):
|
def _get_timeout_buffer_ms(self) -> int:
|
||||||
|
"""Read response-time safety buffer from `SNAKE_TIMEOUT_BUFFER_MS`."""
|
||||||
|
raw_value = os.getenv("SNAKE_TIMEOUT_BUFFER_MS", "120")
|
||||||
|
try:
|
||||||
|
return max(25, int(raw_value))
|
||||||
|
except ValueError:
|
||||||
|
return 120
|
||||||
|
|
||||||
|
def choose_move(self, game_data:dict) -> str:
|
||||||
|
"""Pick the next move from a Battlesnake move request.
|
||||||
|
|
||||||
|
Docs: https://docs.battlesnake.com/api/example-move
|
||||||
|
"""
|
||||||
self.game_board = game_data
|
self.game_board = game_data
|
||||||
self.calculations = []
|
self.calculations = []
|
||||||
self.duel_style = self._get_duel_style()
|
self.duel_style = self._get_duel_style()
|
||||||
|
self.timeout_buffer_ms = self._get_timeout_buffer_ms()
|
||||||
|
timeout_ms = (game_data.get_timeout() if hasattr(game_data, "get_timeout") else 500)
|
||||||
|
deadline = perf_counter() + (max(50, int(timeout_ms) - self.timeout_buffer_ms) / 1000.0)
|
||||||
|
|
||||||
game_id = getattr(game_data, "id", None)
|
game_id = getattr(game_data, "id", None)
|
||||||
turn = game_data.get_turn()
|
turn = game_data.get_turn()
|
||||||
if game_id != self.last_game_id or turn <= 1:
|
if game_id != self.last_game_id or turn <= 1:
|
||||||
self.recent_heads.clear()
|
self.recent_heads.clear()
|
||||||
self.last_move = None
|
self.last_move = None
|
||||||
|
self.previous_hazards = set()
|
||||||
self.last_game_id = game_id
|
self.last_game_id = game_id
|
||||||
|
|
||||||
my_snake = cast(dict[str, Any], game_data.get_my_snake())
|
my_snake = cast(dict[str, Any], game_data.get_my_snake())
|
||||||
@@ -87,6 +116,16 @@ class BestBattleSnake(TemplateSnake):
|
|||||||
|
|
||||||
food_set = {(food["x"], food["y"]) for food in foods}
|
food_set = {(food["x"], food["y"]) for food in foods}
|
||||||
hazard_set = {(hazard["x"], hazard["y"]) for hazard in hazards}
|
hazard_set = {(hazard["x"], hazard["y"]) for hazard in hazards}
|
||||||
|
previous_hazard_set = set(self.previous_hazards)
|
||||||
|
hazard_damage = self._hazard_damage_per_turn(game_data)
|
||||||
|
enemy_heads = [
|
||||||
|
(snake["head"]["x"], snake["head"]["y"]) for snake in other_snakes
|
||||||
|
]
|
||||||
|
enemy_can_grow_cache = {
|
||||||
|
snake["id"]: self._enemy_can_grow_this_turn(snake, food_set)
|
||||||
|
for snake in other_snakes
|
||||||
|
if "id" in snake
|
||||||
|
}
|
||||||
current_head_point = (my_head["x"], my_head["y"])
|
current_head_point = (my_head["x"], my_head["y"])
|
||||||
|
|
||||||
safe_moves = self._legal_moves(
|
safe_moves = self._legal_moves(
|
||||||
@@ -110,6 +149,7 @@ class BestBattleSnake(TemplateSnake):
|
|||||||
"reason": "no_safe_moves",
|
"reason": "no_safe_moves",
|
||||||
}
|
}
|
||||||
)
|
)
|
||||||
|
self.previous_hazards = set(hazard_set)
|
||||||
return fallback
|
return fallback
|
||||||
|
|
||||||
enemy_attack_map = self._build_enemy_attack_map(
|
enemy_attack_map = self._build_enemy_attack_map(
|
||||||
@@ -119,6 +159,7 @@ class BestBattleSnake(TemplateSnake):
|
|||||||
is_constrictor=is_constrictor,
|
is_constrictor=is_constrictor,
|
||||||
width=width,
|
width=width,
|
||||||
height=height,
|
height=height,
|
||||||
|
enemy_can_grow_cache=enemy_can_grow_cache,
|
||||||
)
|
)
|
||||||
|
|
||||||
if is_constrictor:
|
if is_constrictor:
|
||||||
@@ -129,12 +170,16 @@ class BestBattleSnake(TemplateSnake):
|
|||||||
other_snakes=other_snakes,
|
other_snakes=other_snakes,
|
||||||
food_set=food_set,
|
food_set=food_set,
|
||||||
enemy_attack_map=enemy_attack_map,
|
enemy_attack_map=enemy_attack_map,
|
||||||
|
enemy_heads=enemy_heads,
|
||||||
|
enemy_can_grow_cache=enemy_can_grow_cache,
|
||||||
width=width,
|
width=width,
|
||||||
height=height,
|
height=height,
|
||||||
|
deadline=deadline,
|
||||||
)
|
)
|
||||||
self.recent_heads.append(current_head_point)
|
self.recent_heads.append(current_head_point)
|
||||||
self.last_move = best_move
|
self.last_move = best_move
|
||||||
self.add_to_history({"turn": turn, "move": best_move, "scores": scores})
|
self.add_to_history({"turn": turn, "move": best_move, "scores": scores})
|
||||||
|
self.previous_hazards = set(hazard_set)
|
||||||
return best_move
|
return best_move
|
||||||
|
|
||||||
if len(other_snakes) == 1:
|
if len(other_snakes) == 1:
|
||||||
@@ -143,23 +188,28 @@ class BestBattleSnake(TemplateSnake):
|
|||||||
my_body=my_body,
|
my_body=my_body,
|
||||||
my_len=my_len,
|
my_len=my_len,
|
||||||
my_health=my_health,
|
my_health=my_health,
|
||||||
foods=foods,
|
|
||||||
food_set=food_set,
|
food_set=food_set,
|
||||||
hazards=hazards,
|
|
||||||
hazard_set=hazard_set,
|
hazard_set=hazard_set,
|
||||||
other_snakes=other_snakes,
|
other_snakes=other_snakes,
|
||||||
enemy_attack_map=enemy_attack_map,
|
enemy_attack_map=enemy_attack_map,
|
||||||
|
enemy_can_grow_cache=enemy_can_grow_cache,
|
||||||
|
previous_hazard_set=previous_hazard_set,
|
||||||
|
hazard_damage=hazard_damage,
|
||||||
width=width,
|
width=width,
|
||||||
height=height,
|
height=height,
|
||||||
|
deadline=deadline,
|
||||||
)
|
)
|
||||||
self.recent_heads.append(current_head_point)
|
self.recent_heads.append(current_head_point)
|
||||||
self.last_move = best_move
|
self.last_move = best_move
|
||||||
self.add_to_history({"turn": turn, "move": best_move, "scores": scores})
|
self.add_to_history({"turn": turn, "move": best_move, "scores": scores})
|
||||||
|
self.previous_hazards = set(hazard_set)
|
||||||
return best_move
|
return best_move
|
||||||
|
|
||||||
scores: dict[str, float] = {}
|
scores:dict[str, float] = {}
|
||||||
move_safety: dict[str, dict[str, Any]] = {}
|
move_safety:dict[str, dict[str, Any]] = {}
|
||||||
for move, pos in safe_moves.items():
|
for move, pos in safe_moves.items():
|
||||||
|
if self._time_exceeded(deadline):
|
||||||
|
break
|
||||||
point = (pos["x"], pos["y"])
|
point = (pos["x"], pos["y"])
|
||||||
ate_food = point in food_set
|
ate_food = point in food_set
|
||||||
|
|
||||||
@@ -169,6 +219,7 @@ class BestBattleSnake(TemplateSnake):
|
|||||||
other_snakes=other_snakes,
|
other_snakes=other_snakes,
|
||||||
food_set=food_set,
|
food_set=food_set,
|
||||||
is_constrictor=is_constrictor,
|
is_constrictor=is_constrictor,
|
||||||
|
enemy_can_grow_cache=enemy_can_grow_cache,
|
||||||
)
|
)
|
||||||
blocked.discard(point)
|
blocked.discard(point)
|
||||||
|
|
||||||
@@ -180,17 +231,13 @@ class BestBattleSnake(TemplateSnake):
|
|||||||
)
|
)
|
||||||
territory = self._territory_control_score(
|
territory = self._territory_control_score(
|
||||||
my_start=point,
|
my_start=point,
|
||||||
enemy_starts=[
|
enemy_starts=enemy_heads,
|
||||||
(snake["head"]["x"], snake["head"]["y"]) for snake in other_snakes
|
|
||||||
],
|
|
||||||
blocked=blocked,
|
blocked=blocked,
|
||||||
width=width,
|
width=width,
|
||||||
height=height,
|
height=height,
|
||||||
)
|
)
|
||||||
|
|
||||||
nearest_food_dist = self._nearest_food_distance(
|
nearest_food_dist = self._nearest_food_distance(point, food_set, blocked, width, height)
|
||||||
point, foods, blocked, width, height
|
|
||||||
)
|
|
||||||
future_tail = future_body[-1]
|
future_tail = future_body[-1]
|
||||||
tail_point = (future_tail["x"], future_tail["y"])
|
tail_point = (future_tail["x"], future_tail["y"])
|
||||||
tail_dist = self._path_distance(
|
tail_dist = self._path_distance(
|
||||||
@@ -242,7 +289,9 @@ class BestBattleSnake(TemplateSnake):
|
|||||||
score -= 40.0
|
score -= 40.0
|
||||||
|
|
||||||
if point in hazard_set:
|
if point in hazard_set:
|
||||||
score -= 70.0 if my_health > 35 else 250.0
|
hazard_scale = max(0.5, hazard_damage / 14.0)
|
||||||
|
if not ate_food:
|
||||||
|
score -= (70.0 if my_health > 35 else 250.0) * hazard_scale
|
||||||
|
|
||||||
score -= self._revisit_penalty(point)
|
score -= self._revisit_penalty(point)
|
||||||
|
|
||||||
@@ -256,8 +305,9 @@ class BestBattleSnake(TemplateSnake):
|
|||||||
score -= 20.0
|
score -= 20.0
|
||||||
|
|
||||||
health_after_move = 100 if ate_food else my_health - 1
|
health_after_move = 100 if ate_food else my_health - 1
|
||||||
if point in hazard_set:
|
hazard_active = self._hazard_is_active(point, ate_food, hazard_set, previous_hazard_set)
|
||||||
health_after_move -= 15
|
if hazard_active:
|
||||||
|
health_after_move -= hazard_damage
|
||||||
if health_after_move <= 0:
|
if health_after_move <= 0:
|
||||||
score -= 10000.0
|
score -= 10000.0
|
||||||
|
|
||||||
@@ -274,6 +324,18 @@ class BestBattleSnake(TemplateSnake):
|
|||||||
|
|
||||||
scores[move] = round(score, 5)
|
scores[move] = round(score, 5)
|
||||||
|
|
||||||
|
if not scores:
|
||||||
|
quick_move = (
|
||||||
|
self.last_move
|
||||||
|
if self.last_move in safe_moves
|
||||||
|
else random.choice(list(safe_moves.keys()))
|
||||||
|
)
|
||||||
|
self.recent_heads.append(current_head_point)
|
||||||
|
self.last_move = quick_move
|
||||||
|
self.add_to_history({"turn": turn, "move": quick_move, "reason": "timeout_budget"})
|
||||||
|
self.previous_hazards = set(hazard_set)
|
||||||
|
return quick_move
|
||||||
|
|
||||||
survivable_moves = [
|
survivable_moves = [
|
||||||
move for move, data in move_safety.items() if data["is_survivable"]
|
move for move, data in move_safety.items() if data["is_survivable"]
|
||||||
]
|
]
|
||||||
@@ -305,32 +367,24 @@ class BestBattleSnake(TemplateSnake):
|
|||||||
self.recent_heads.append(current_head_point)
|
self.recent_heads.append(current_head_point)
|
||||||
self.last_move = best_move
|
self.last_move = best_move
|
||||||
self.add_to_history({"turn": turn, "move": best_move, "scores": scores})
|
self.add_to_history({"turn": turn, "move": best_move, "scores": scores})
|
||||||
|
self.previous_hazards = set(hazard_set)
|
||||||
return best_move
|
return best_move
|
||||||
|
|
||||||
def _choose_duel_move(
|
def _choose_duel_move(self, safe_moves:MoveMap, my_body:list[Coord], my_len:int, my_health:int, food_set:set[Point], hazard_set:set[Point], other_snakes:list[SnakeState], enemy_attack_map:AttackMap, enemy_can_grow_cache:dict[Any, bool], previous_hazard_set:set[Point], hazard_damage:int, width:int, height:int, deadline:float|None=None) -> tuple[str, dict[str, float]]:
|
||||||
self,
|
"""Score and select a move for one-vs-one games."""
|
||||||
safe_moves,
|
|
||||||
my_body,
|
|
||||||
my_len,
|
|
||||||
my_health,
|
|
||||||
foods,
|
|
||||||
food_set,
|
|
||||||
hazards,
|
|
||||||
hazard_set,
|
|
||||||
other_snakes,
|
|
||||||
enemy_attack_map,
|
|
||||||
width,
|
|
||||||
height,
|
|
||||||
):
|
|
||||||
duel_weights = self._duel_weights(self.duel_style)
|
duel_weights = self._duel_weights(self.duel_style)
|
||||||
enemy = other_snakes[0]
|
enemy = other_snakes[0]
|
||||||
enemy_head = (enemy["head"]["x"], enemy["head"]["y"])
|
enemy_head = (enemy["head"]["x"], enemy["head"]["y"])
|
||||||
enemy_len = enemy.get("length", len(enemy["body"]))
|
enemy_len = enemy.get("length", len(enemy["body"]))
|
||||||
|
encase_target_space = max(8, enemy_len * 2)
|
||||||
|
can_head_hunt = my_len > enemy_len and my_len >= 8
|
||||||
|
|
||||||
scores: dict[str, float] = {}
|
scores:dict[str, float] = {}
|
||||||
move_safety: dict[str, dict[str, Any]] = {}
|
move_safety:dict[str, dict[str, Any]] = {}
|
||||||
|
|
||||||
for move, pos in safe_moves.items():
|
for move, pos in safe_moves.items():
|
||||||
|
if self._time_exceeded(deadline):
|
||||||
|
break
|
||||||
point = (pos["x"], pos["y"])
|
point = (pos["x"], pos["y"])
|
||||||
ate_food = point in food_set
|
ate_food = point in food_set
|
||||||
|
|
||||||
@@ -342,6 +396,7 @@ class BestBattleSnake(TemplateSnake):
|
|||||||
other_snakes=other_snakes,
|
other_snakes=other_snakes,
|
||||||
food_set=food_set,
|
food_set=food_set,
|
||||||
is_constrictor=False,
|
is_constrictor=False,
|
||||||
|
enemy_can_grow_cache=enemy_can_grow_cache,
|
||||||
)
|
)
|
||||||
blocked.discard(point)
|
blocked.discard(point)
|
||||||
|
|
||||||
@@ -352,9 +407,7 @@ class BestBattleSnake(TemplateSnake):
|
|||||||
future_body, blocked, width, height
|
future_body, blocked, width, height
|
||||||
)
|
)
|
||||||
|
|
||||||
nearest_food_dist = self._nearest_food_distance(
|
nearest_food_dist = self._nearest_food_distance(point, food_set, blocked, width, height)
|
||||||
point, foods, blocked, width, height
|
|
||||||
)
|
|
||||||
future_tail = future_body[-1]
|
future_tail = future_body[-1]
|
||||||
tail_point = (future_tail["x"], future_tail["y"])
|
tail_point = (future_tail["x"], future_tail["y"])
|
||||||
tail_dist = self._path_distance(
|
tail_dist = self._path_distance(
|
||||||
@@ -380,6 +433,7 @@ class BestBattleSnake(TemplateSnake):
|
|||||||
enemy_attack_len is not None and enemy_attack_len >= my_len
|
enemy_attack_len is not None and enemy_attack_len >= my_len
|
||||||
)
|
)
|
||||||
direct_head_distance = self._manhattan(point, enemy_head)
|
direct_head_distance = self._manhattan(point, enemy_head)
|
||||||
|
enemy_space, enemy_options = self._enemy_confinement_metrics(enemy_head, blocked, width, height)
|
||||||
|
|
||||||
score = 0.0
|
score = 0.0
|
||||||
score += reachable_space * 2.8
|
score += reachable_space * 2.8
|
||||||
@@ -393,7 +447,16 @@ class BestBattleSnake(TemplateSnake):
|
|||||||
if losing_head_to_head:
|
if losing_head_to_head:
|
||||||
score -= 1500.0
|
score -= 1500.0
|
||||||
|
|
||||||
if my_len > enemy_len:
|
is_safe_tightening_move = not likely_dead_end and not losing_head_to_head
|
||||||
|
if is_safe_tightening_move and enemy_space <= encase_target_space:
|
||||||
|
score += (encase_target_space - enemy_space) * 42.0
|
||||||
|
score += max(0, 3 - enemy_options) * 95.0
|
||||||
|
if reachable_space > enemy_space:
|
||||||
|
score += 120.0
|
||||||
|
if direct_head_distance <= 2 and can_head_hunt:
|
||||||
|
score += 40.0
|
||||||
|
|
||||||
|
if can_head_hunt:
|
||||||
if direct_head_distance == 1:
|
if direct_head_distance == 1:
|
||||||
score += 220.0 * duel_weights["head_pressure"]
|
score += 220.0 * duel_weights["head_pressure"]
|
||||||
elif direct_head_distance == 2:
|
elif direct_head_distance == 2:
|
||||||
@@ -401,6 +464,8 @@ class BestBattleSnake(TemplateSnake):
|
|||||||
else:
|
else:
|
||||||
if direct_head_distance <= 2:
|
if direct_head_distance <= 2:
|
||||||
score -= 120.0 * duel_weights["distance_safety"]
|
score -= 120.0 * duel_weights["distance_safety"]
|
||||||
|
if direct_head_distance == 1:
|
||||||
|
score -= 180.0 * duel_weights["distance_safety"]
|
||||||
|
|
||||||
hunger_urgency = max(0.0, (65.0 - my_health) / 65.0)
|
hunger_urgency = max(0.0, (65.0 - my_health) / 65.0)
|
||||||
if nearest_food_dist is not None:
|
if nearest_food_dist is not None:
|
||||||
@@ -420,7 +485,9 @@ class BestBattleSnake(TemplateSnake):
|
|||||||
score -= 50.0
|
score -= 50.0
|
||||||
|
|
||||||
if point in hazard_set:
|
if point in hazard_set:
|
||||||
score -= 70.0 if my_health > 35 else 250.0
|
hazard_scale = max(0.5, hazard_damage / 14.0)
|
||||||
|
if not ate_food:
|
||||||
|
score -= (70.0 if my_health > 35 else 250.0) * hazard_scale
|
||||||
|
|
||||||
score -= self._revisit_penalty(point)
|
score -= self._revisit_penalty(point)
|
||||||
|
|
||||||
@@ -434,8 +501,9 @@ class BestBattleSnake(TemplateSnake):
|
|||||||
score -= 20.0
|
score -= 20.0
|
||||||
|
|
||||||
health_after_move = 100 if ate_food else my_health - 1
|
health_after_move = 100 if ate_food else my_health - 1
|
||||||
if point in hazard_set:
|
hazard_active = self._hazard_is_active(point, ate_food, hazard_set, previous_hazard_set)
|
||||||
health_after_move -= 15
|
if hazard_active:
|
||||||
|
health_after_move -= hazard_damage
|
||||||
if health_after_move <= 0:
|
if health_after_move <= 0:
|
||||||
score -= 10000.0
|
score -= 10000.0
|
||||||
|
|
||||||
@@ -472,27 +540,23 @@ class BestBattleSnake(TemplateSnake):
|
|||||||
else:
|
else:
|
||||||
considered_moves = list(scores.keys())
|
considered_moves = list(scores.keys())
|
||||||
|
|
||||||
|
if not scores:
|
||||||
|
return random.choice(list(safe_moves.keys())), {}
|
||||||
|
|
||||||
best_score = max(scores[move] for move in considered_moves)
|
best_score = max(scores[move] for move in considered_moves)
|
||||||
top_moves = [
|
top_moves = [
|
||||||
move for move in considered_moves if best_score - scores[move] <= 1.5
|
move for move in considered_moves if best_score - scores[move] <= 1.5
|
||||||
]
|
]
|
||||||
return random.choice(top_moves), scores
|
return random.choice(top_moves), scores
|
||||||
|
|
||||||
def _choose_constrictor_move(
|
def _choose_constrictor_move(self, safe_moves:MoveMap, my_body:list[Coord], my_len:int, other_snakes:list[SnakeState], food_set:set[Point], enemy_attack_map:AttackMap, enemy_heads:list[Point], enemy_can_grow_cache:dict[Any, bool], width:int, height:int, deadline:float|None=None) -> tuple[str, dict[str, float]]:
|
||||||
self,
|
"""Score and select a move for constrictor games."""
|
||||||
safe_moves,
|
scores:dict[str, float] = {}
|
||||||
my_body,
|
move_safety:dict[str, dict[str, Any]] = {}
|
||||||
my_len,
|
|
||||||
other_snakes,
|
|
||||||
food_set,
|
|
||||||
enemy_attack_map,
|
|
||||||
width,
|
|
||||||
height,
|
|
||||||
):
|
|
||||||
scores: dict[str, float] = {}
|
|
||||||
move_safety: dict[str, dict[str, Any]] = {}
|
|
||||||
|
|
||||||
for move, pos in safe_moves.items():
|
for move, pos in safe_moves.items():
|
||||||
|
if self._time_exceeded(deadline):
|
||||||
|
break
|
||||||
point = (pos["x"], pos["y"])
|
point = (pos["x"], pos["y"])
|
||||||
future_body = self._future_body(
|
future_body = self._future_body(
|
||||||
my_body, pos, ate_food=False, is_constrictor=True
|
my_body, pos, ate_food=False, is_constrictor=True
|
||||||
@@ -502,6 +566,7 @@ class BestBattleSnake(TemplateSnake):
|
|||||||
other_snakes=other_snakes,
|
other_snakes=other_snakes,
|
||||||
food_set=food_set,
|
food_set=food_set,
|
||||||
is_constrictor=True,
|
is_constrictor=True,
|
||||||
|
enemy_can_grow_cache=enemy_can_grow_cache,
|
||||||
)
|
)
|
||||||
blocked.discard(point)
|
blocked.discard(point)
|
||||||
|
|
||||||
@@ -513,9 +578,13 @@ class BestBattleSnake(TemplateSnake):
|
|||||||
)
|
)
|
||||||
territory = self._territory_control_score(
|
territory = self._territory_control_score(
|
||||||
my_start=point,
|
my_start=point,
|
||||||
enemy_starts=[
|
enemy_starts=enemy_heads,
|
||||||
(snake["head"]["x"], snake["head"]["y"]) for snake in other_snakes
|
blocked=blocked,
|
||||||
],
|
width=width,
|
||||||
|
height=height,
|
||||||
|
)
|
||||||
|
enemy_best_space, enemy_total_options = self._enemy_constrictor_projection(
|
||||||
|
other_snakes=other_snakes,
|
||||||
blocked=blocked,
|
blocked=blocked,
|
||||||
width=width,
|
width=width,
|
||||||
height=height,
|
height=height,
|
||||||
@@ -533,6 +602,13 @@ class BestBattleSnake(TemplateSnake):
|
|||||||
score += liberties * 24.0
|
score += liberties * 24.0
|
||||||
score += next_options * 16.0
|
score += next_options * 16.0
|
||||||
score += territory * 0.65
|
score += territory * 0.65
|
||||||
|
score += (reachable_space - enemy_best_space) * 3.2
|
||||||
|
score += (max(0, 8 - enemy_total_options)) * 18.0
|
||||||
|
|
||||||
|
if enemy_total_options <= 2:
|
||||||
|
score += 110.0
|
||||||
|
if enemy_best_space > int(reachable_space * 1.2):
|
||||||
|
score -= 320.0
|
||||||
|
|
||||||
if is_dead_end:
|
if is_dead_end:
|
||||||
score -= 2600.0
|
score -= 2600.0
|
||||||
@@ -577,22 +653,24 @@ class BestBattleSnake(TemplateSnake):
|
|||||||
else:
|
else:
|
||||||
considered_moves = list(scores.keys())
|
considered_moves = list(scores.keys())
|
||||||
|
|
||||||
|
if not scores:
|
||||||
|
return random.choice(list(safe_moves.keys())), {}
|
||||||
|
|
||||||
best_score = max(scores[move] for move in considered_moves)
|
best_score = max(scores[move] for move in considered_moves)
|
||||||
top_moves = [
|
top_moves = [
|
||||||
move for move in considered_moves if best_score - scores[move] <= 2.0
|
move for move in considered_moves if best_score - scores[move] <= 2.0
|
||||||
]
|
]
|
||||||
return random.choice(top_moves), scores
|
return random.choice(top_moves), scores
|
||||||
|
|
||||||
def _legal_moves(
|
def _legal_moves(self, my_head:Coord, my_body:list[Coord], other_snakes:list[SnakeState], food_set:set[Point], is_constrictor:bool, width:int, height:int) -> MoveMap:
|
||||||
self, my_head, my_body, other_snakes, food_set, is_constrictor, width, height
|
"""Return legal immediate moves after body, wall, and tail checks."""
|
||||||
):
|
|
||||||
occupied = self._occupied_cells(my_body, other_snakes)
|
occupied = self._occupied_cells(my_body, other_snakes)
|
||||||
own_tail = (my_body[-1]["x"], my_body[-1]["y"])
|
own_tail = (my_body[-1]["x"], my_body[-1]["y"])
|
||||||
own_tail_stacked = self._is_tail_stacked(my_body)
|
own_tail_stacked = self._is_tail_stacked(my_body)
|
||||||
|
|
||||||
safe_moves = {}
|
safe_moves = {}
|
||||||
for move, pos in self.get_possible_moves(my_head).items():
|
for move, (dx, dy) in self.DIRECTIONS.items():
|
||||||
point = (pos["x"], pos["y"])
|
point = (my_head["x"] + dx, my_head["y"] + dy)
|
||||||
if not self._in_bounds(point, width, height):
|
if not self._in_bounds(point, width, height):
|
||||||
continue
|
continue
|
||||||
|
|
||||||
@@ -608,17 +686,19 @@ class BestBattleSnake(TemplateSnake):
|
|||||||
if point in occupied and not can_step_on_tail:
|
if point in occupied and not can_step_on_tail:
|
||||||
continue
|
continue
|
||||||
|
|
||||||
safe_moves[move] = pos
|
safe_moves[move] = {"x": point[0], "y": point[1]}
|
||||||
|
|
||||||
return safe_moves
|
return safe_moves
|
||||||
|
|
||||||
def _occupied_cells(self, my_body, other_snakes):
|
def _occupied_cells(self, my_body:list[Coord], other_snakes:list[SnakeState]) -> set[Point]:
|
||||||
|
"""Build a set of occupied coordinates for all snake bodies."""
|
||||||
occupied = {(segment["x"], segment["y"]) for segment in my_body}
|
occupied = {(segment["x"], segment["y"]) for segment in my_body}
|
||||||
for snake in other_snakes:
|
for snake in other_snakes:
|
||||||
occupied |= {(segment["x"], segment["y"]) for segment in snake["body"]}
|
occupied |= {(segment["x"], segment["y"]) for segment in snake["body"]}
|
||||||
return occupied
|
return occupied
|
||||||
|
|
||||||
def _simulation_blocked(self, future_body, other_snakes, food_set, is_constrictor):
|
def _simulation_blocked(self, future_body:list[Coord], other_snakes:list[SnakeState], food_set:set[Point], is_constrictor:bool, enemy_can_grow_cache:dict[Any, bool]|None=None) -> set[Point]:
|
||||||
|
"""Build blocked cells for evaluating the board one turn ahead."""
|
||||||
blocked = {(segment["x"], segment["y"]) for segment in future_body}
|
blocked = {(segment["x"], segment["y"]) for segment in future_body}
|
||||||
|
|
||||||
if not is_constrictor and not self._is_tail_stacked(future_body):
|
if not is_constrictor and not self._is_tail_stacked(future_body):
|
||||||
@@ -632,7 +712,13 @@ class BestBattleSnake(TemplateSnake):
|
|||||||
if is_constrictor:
|
if is_constrictor:
|
||||||
continue
|
continue
|
||||||
|
|
||||||
if self._enemy_can_grow_this_turn(snake, food_set):
|
snake_id = snake.get("id")
|
||||||
|
enemy_can_grow = (
|
||||||
|
enemy_can_grow_cache.get(snake_id)
|
||||||
|
if enemy_can_grow_cache and snake_id is not None
|
||||||
|
else self._enemy_can_grow_this_turn(snake, food_set)
|
||||||
|
)
|
||||||
|
if enemy_can_grow:
|
||||||
continue
|
continue
|
||||||
|
|
||||||
if self._is_tail_stacked(snake["body"]):
|
if self._is_tail_stacked(snake["body"]):
|
||||||
@@ -643,20 +729,26 @@ class BestBattleSnake(TemplateSnake):
|
|||||||
|
|
||||||
return blocked
|
return blocked
|
||||||
|
|
||||||
def _build_enemy_attack_map(
|
def _build_enemy_attack_map(self, my_snake:SnakeState, other_snakes:list[SnakeState], food_set:set[Point], is_constrictor:bool, width:int, height:int, enemy_can_grow_cache:dict[Any, bool]|None=None) -> AttackMap:
|
||||||
self, my_snake, other_snakes, food_set, is_constrictor, width, height
|
"""Map cells enemies can contest next turn to their effective length."""
|
||||||
):
|
|
||||||
occupied = self._occupied_cells(my_snake["body"], other_snakes)
|
occupied = self._occupied_cells(my_snake["body"], other_snakes)
|
||||||
my_id = my_snake["id"]
|
my_body_points = {(segment["x"], segment["y"]) for segment in my_snake["body"]}
|
||||||
attack_map = {}
|
attack_map = {}
|
||||||
|
|
||||||
for enemy in other_snakes:
|
for enemy in other_snakes:
|
||||||
enemy_len = enemy.get("length", len(enemy["body"]))
|
enemy_len = enemy.get("length", len(enemy["body"]))
|
||||||
enemy_tail = (enemy["body"][-1]["x"], enemy["body"][-1]["y"])
|
enemy_tail = (enemy["body"][-1]["x"], enemy["body"][-1]["y"])
|
||||||
enemy_tail_stacked = self._is_tail_stacked(enemy["body"])
|
enemy_tail_stacked = self._is_tail_stacked(enemy["body"])
|
||||||
|
snake_id = enemy.get("id")
|
||||||
|
enemy_can_grow = (
|
||||||
|
enemy_can_grow_cache.get(snake_id)
|
||||||
|
if enemy_can_grow_cache and snake_id is not None
|
||||||
|
else self._enemy_can_grow_this_turn(enemy, food_set)
|
||||||
|
)
|
||||||
|
|
||||||
for pos in self.get_possible_moves(enemy["head"]).values():
|
enemy_head = enemy["head"]
|
||||||
point = (pos["x"], pos["y"])
|
for dx, dy in self.DIRECTIONS.values():
|
||||||
|
point = (enemy_head["x"] + dx, enemy_head["y"] + dy)
|
||||||
if not self._in_bounds(point, width, height):
|
if not self._in_bounds(point, width, height):
|
||||||
continue
|
continue
|
||||||
|
|
||||||
@@ -664,18 +756,14 @@ class BestBattleSnake(TemplateSnake):
|
|||||||
not is_constrictor
|
not is_constrictor
|
||||||
and point == enemy_tail
|
and point == enemy_tail
|
||||||
and not enemy_tail_stacked
|
and not enemy_tail_stacked
|
||||||
and not self._enemy_can_grow_this_turn(enemy, food_set)
|
and not enemy_can_grow
|
||||||
)
|
)
|
||||||
|
|
||||||
if point in occupied and not can_step_on_enemy_tail:
|
if point in occupied and not can_step_on_enemy_tail:
|
||||||
continue
|
continue
|
||||||
|
|
||||||
# Do not consider impossible overlap directly into my own occupied body except head swap possibilities.
|
# Do not consider impossible overlap directly into my own occupied body except head swap possibilities.
|
||||||
if point in {
|
if point in my_body_points:
|
||||||
(segment["x"], segment["y"])
|
|
||||||
for segment in my_snake["body"]
|
|
||||||
if my_snake["id"] == my_id
|
|
||||||
}:
|
|
||||||
continue
|
continue
|
||||||
|
|
||||||
previous = attack_map.get(point)
|
previous = attack_map.get(point)
|
||||||
@@ -684,7 +772,8 @@ class BestBattleSnake(TemplateSnake):
|
|||||||
|
|
||||||
return attack_map
|
return attack_map
|
||||||
|
|
||||||
def _future_body(self, current_body, next_head, ate_food, is_constrictor):
|
def _future_body(self, current_body:list[Coord], next_head:Coord, ate_food:bool, is_constrictor:bool) -> list[Coord]:
|
||||||
|
"""Simulate future body segments after a candidate move."""
|
||||||
next_body = [next_head]
|
next_body = [next_head]
|
||||||
next_body.extend(current_body)
|
next_body.extend(current_body)
|
||||||
|
|
||||||
@@ -694,9 +783,8 @@ class BestBattleSnake(TemplateSnake):
|
|||||||
next_body.pop()
|
next_body.pop()
|
||||||
return next_body
|
return next_body
|
||||||
|
|
||||||
def _can_step_on_own_tail(
|
def _can_step_on_own_tail(self, point:Point, own_tail:Point, own_tail_is_stacked:bool, ate_food:bool, is_constrictor:bool) -> bool:
|
||||||
self, point, own_tail, own_tail_is_stacked, ate_food, is_constrictor
|
"""Return whether stepping onto our tail is allowed this turn."""
|
||||||
):
|
|
||||||
if is_constrictor:
|
if is_constrictor:
|
||||||
return False
|
return False
|
||||||
if ate_food:
|
if ate_food:
|
||||||
@@ -705,29 +793,60 @@ class BestBattleSnake(TemplateSnake):
|
|||||||
return False
|
return False
|
||||||
return point == own_tail
|
return point == own_tail
|
||||||
|
|
||||||
def _is_tail_stacked(self, body):
|
def _is_tail_stacked(self, body:list[Coord]) -> bool:
|
||||||
|
"""Check whether tail overlaps the previous body segment."""
|
||||||
if len(body) < 2:
|
if len(body) < 2:
|
||||||
return False
|
return False
|
||||||
return body[-1]["x"] == body[-2]["x"] and body[-1]["y"] == body[-2]["y"]
|
return body[-1]["x"] == body[-2]["x"] and body[-1]["y"] == body[-2]["y"]
|
||||||
|
|
||||||
def _enemy_can_grow_this_turn(self, snake, food_set):
|
def _enemy_can_grow_this_turn(self, snake:SnakeState, food_set:set[Point]) -> bool:
|
||||||
|
"""Return True if an enemy can eat food in one move."""
|
||||||
head = snake["head"]
|
head = snake["head"]
|
||||||
for dx, dy in self.DIRECTIONS.values():
|
for dx, dy in self.DIRECTIONS.values():
|
||||||
if (head["x"] + dx, head["y"] + dy) in food_set:
|
if (head["x"] + dx, head["y"] + dy) in food_set:
|
||||||
return True
|
return True
|
||||||
return False
|
return False
|
||||||
|
|
||||||
def _nearest_food_distance(self, start, foods, blocked, width, height):
|
def _hazard_damage_per_turn(self, game_data:dict) -> int:
|
||||||
if not foods:
|
"""Read royale hazard damage from ruleset settings.
|
||||||
return None
|
|
||||||
|
|
||||||
targets = {(food["x"], food["y"]) for food in foods}
|
Docs: https://docs.battlesnake.com/maps/royale
|
||||||
|
"""
|
||||||
|
ruleset = {}
|
||||||
|
if hasattr(game_data, "get_ruleset"):
|
||||||
|
ruleset = game_data.get_ruleset() or {}
|
||||||
|
elif hasattr(game_data, "ruleset"):
|
||||||
|
ruleset = game_data.ruleset or {}
|
||||||
|
settings = ruleset.get("settings", {}) if isinstance(ruleset, dict) else {}
|
||||||
|
return int(settings.get("hazardDamagePerTurn", 15))
|
||||||
|
|
||||||
|
def _hazard_is_active(self, point:Point, ate_food:bool, hazard_set:set[Point], previous_hazard_set:set[Point]) -> bool:
|
||||||
|
"""Apply royale hazard grace and food-exception behavior.
|
||||||
|
|
||||||
|
Docs: https://docs.battlesnake.com/maps/royale
|
||||||
|
"""
|
||||||
|
if point not in hazard_set:
|
||||||
|
return False
|
||||||
|
if ate_food:
|
||||||
|
return False
|
||||||
|
return point in previous_hazard_set
|
||||||
|
|
||||||
|
def _time_exceeded(self, deadline:float|None) -> bool:
|
||||||
|
"""Return True when the move-calculation time budget is exhausted."""
|
||||||
|
if deadline is None:
|
||||||
|
return False
|
||||||
|
return perf_counter() >= deadline
|
||||||
|
|
||||||
|
def _nearest_food_distance(self, start:Point, food_set:set[Point], blocked:set[Point], width:int, height:int) -> int|None:
|
||||||
|
"""Compute shortest reachable distance to any food using BFS."""
|
||||||
|
if not food_set:
|
||||||
|
return None
|
||||||
queue = deque([(start, 0)])
|
queue = deque([(start, 0)])
|
||||||
seen = {start}
|
seen = {start}
|
||||||
|
|
||||||
while queue:
|
while queue:
|
||||||
point, distance = queue.popleft()
|
point, distance = queue.popleft()
|
||||||
if point in targets:
|
if point in food_set:
|
||||||
return distance
|
return distance
|
||||||
|
|
||||||
for neighbor in self._neighbors(point):
|
for neighbor in self._neighbors(point):
|
||||||
@@ -735,14 +854,15 @@ class BestBattleSnake(TemplateSnake):
|
|||||||
continue
|
continue
|
||||||
if not self._in_bounds(neighbor, width, height):
|
if not self._in_bounds(neighbor, width, height):
|
||||||
continue
|
continue
|
||||||
if neighbor in blocked and neighbor not in targets:
|
if neighbor in blocked and neighbor not in food_set:
|
||||||
continue
|
continue
|
||||||
seen.add(neighbor)
|
seen.add(neighbor)
|
||||||
queue.append((neighbor, distance + 1))
|
queue.append((neighbor, distance + 1))
|
||||||
|
|
||||||
return None
|
return None
|
||||||
|
|
||||||
def _path_distance(self, start, goal, blocked, width, height):
|
def _path_distance( self, start:Point, goal:Point, blocked:set[Point], width:int, height:int) -> int|None:
|
||||||
|
"""Compute shortest path distance between two cells."""
|
||||||
queue = deque([(start, 0)])
|
queue = deque([(start, 0)])
|
||||||
seen = {start}
|
seen = {start}
|
||||||
|
|
||||||
@@ -763,7 +883,8 @@ class BestBattleSnake(TemplateSnake):
|
|||||||
|
|
||||||
return None
|
return None
|
||||||
|
|
||||||
def _flood_fill_count(self, start, blocked, width, height):
|
def _flood_fill_count(self, start:Point, blocked:set[Point], width:int, height:int) -> int:
|
||||||
|
"""Count reachable cells from `start` using flood fill."""
|
||||||
queue = deque([start])
|
queue = deque([start])
|
||||||
seen = {start}
|
seen = {start}
|
||||||
|
|
||||||
@@ -781,7 +902,8 @@ class BestBattleSnake(TemplateSnake):
|
|||||||
|
|
||||||
return len(seen)
|
return len(seen)
|
||||||
|
|
||||||
def _open_neighbor_count(self, start, blocked, width, height):
|
def _open_neighbor_count(self, start:Point, blocked:set[Point], width:int, height:int) -> int:
|
||||||
|
"""Count walkable orthogonal neighbors around `start`."""
|
||||||
count = 0
|
count = 0
|
||||||
for neighbor in self._neighbors(start):
|
for neighbor in self._neighbors(start):
|
||||||
if not self._in_bounds(neighbor, width, height):
|
if not self._in_bounds(neighbor, width, height):
|
||||||
@@ -791,14 +913,15 @@ class BestBattleSnake(TemplateSnake):
|
|||||||
count += 1
|
count += 1
|
||||||
return count
|
return count
|
||||||
|
|
||||||
def _next_turn_option_count(self, future_body, blocked, width, height):
|
def _next_turn_option_count(self, future_body:list[Coord], blocked:set[Point], width:int, height:int) -> int:
|
||||||
|
"""Estimate options available after the next simulated turn."""
|
||||||
if not future_body:
|
if not future_body:
|
||||||
return 0
|
return 0
|
||||||
|
|
||||||
next_head = future_body[0]
|
next_head = future_body[0]
|
||||||
count = 0
|
count = 0
|
||||||
for pos in self.get_possible_moves(next_head).values():
|
for dx, dy in self.DIRECTIONS.values():
|
||||||
point = (pos["x"], pos["y"])
|
point = (next_head["x"] + dx, next_head["y"] + dy)
|
||||||
if not self._in_bounds(point, width, height):
|
if not self._in_bounds(point, width, height):
|
||||||
continue
|
continue
|
||||||
if point in blocked:
|
if point in blocked:
|
||||||
@@ -806,7 +929,10 @@ class BestBattleSnake(TemplateSnake):
|
|||||||
count += 1
|
count += 1
|
||||||
return count
|
return count
|
||||||
|
|
||||||
def _revisit_penalty(self, point):
|
def _revisit_penalty(self, point:Point) -> float:
|
||||||
|
"""Return penalty for revisiting recent head positions."""
|
||||||
|
if not self.recent_heads:
|
||||||
|
return 0.0
|
||||||
penalty = 0.0
|
penalty = 0.0
|
||||||
for index, old_point in enumerate(reversed(self.recent_heads), start=1):
|
for index, old_point in enumerate(reversed(self.recent_heads), start=1):
|
||||||
if old_point != point:
|
if old_point != point:
|
||||||
@@ -814,7 +940,8 @@ class BestBattleSnake(TemplateSnake):
|
|||||||
penalty += max(0.0, 18.0 - index * 2.0)
|
penalty += max(0.0, 18.0 - index * 2.0)
|
||||||
return penalty
|
return penalty
|
||||||
|
|
||||||
def _territory_control_score(self, my_start, enemy_starts, blocked, width, height):
|
def _territory_control_score(self, my_start:Point, enemy_starts:list[Point], blocked:set[Point], width:int, height:int) -> int:
|
||||||
|
"""Estimate territorial advantage versus enemy start positions."""
|
||||||
if not enemy_starts:
|
if not enemy_starts:
|
||||||
return 0
|
return 0
|
||||||
|
|
||||||
@@ -849,7 +976,8 @@ class BestBattleSnake(TemplateSnake):
|
|||||||
|
|
||||||
return score
|
return score
|
||||||
|
|
||||||
def _distance_map(self, start, blocked, width, height):
|
def _distance_map(self, start:Point, blocked:set[Point], width:int, height:int) -> dict[Point, int]:
|
||||||
|
"""Build a BFS distance map from the given start cell."""
|
||||||
queue = deque([(start, 0)])
|
queue = deque([(start, 0)])
|
||||||
distances = {start: 0}
|
distances = {start: 0}
|
||||||
|
|
||||||
@@ -867,19 +995,60 @@ class BestBattleSnake(TemplateSnake):
|
|||||||
|
|
||||||
return distances
|
return distances
|
||||||
|
|
||||||
def _neighbors(self, point):
|
def _enemy_confinement_metrics(self, enemy_head:Point, blocked:set[Point], width:int, height:int) -> tuple[int, int]:
|
||||||
|
"""Return enemy reachable space and immediate exit count."""
|
||||||
|
enemy_blocked = set(blocked)
|
||||||
|
enemy_blocked.discard(enemy_head)
|
||||||
|
enemy_space = self._flood_fill_count(enemy_head, enemy_blocked, width, height)
|
||||||
|
enemy_options = self._open_neighbor_count(
|
||||||
|
enemy_head, enemy_blocked, width, height
|
||||||
|
)
|
||||||
|
return enemy_space, enemy_options
|
||||||
|
|
||||||
|
def _enemy_constrictor_projection(self, other_snakes:list[SnakeState], blocked:set[Point], width:int, height: int) -> tuple[int, int]:
|
||||||
|
"""Estimate enemy best-space and total options after our candidate move."""
|
||||||
|
best_enemy_space = 0
|
||||||
|
total_enemy_options = 0
|
||||||
|
|
||||||
|
for enemy in other_snakes:
|
||||||
|
enemy_head = (enemy["head"]["x"], enemy["head"]["y"])
|
||||||
|
enemy_best_for_snake = 0
|
||||||
|
|
||||||
|
for neighbor in self._neighbors(enemy_head):
|
||||||
|
if not self._in_bounds(neighbor, width, height):
|
||||||
|
continue
|
||||||
|
if neighbor in blocked:
|
||||||
|
continue
|
||||||
|
|
||||||
|
total_enemy_options += 1
|
||||||
|
enemy_blocked = set(blocked)
|
||||||
|
enemy_blocked.add(neighbor)
|
||||||
|
enemy_space = self._flood_fill_count(
|
||||||
|
neighbor, enemy_blocked, width, height
|
||||||
|
)
|
||||||
|
enemy_best_for_snake = max(enemy_best_for_snake, enemy_space)
|
||||||
|
|
||||||
|
best_enemy_space = max(best_enemy_space, enemy_best_for_snake)
|
||||||
|
|
||||||
|
return best_enemy_space, total_enemy_options
|
||||||
|
|
||||||
|
def _neighbors(self, point:Point) -> Iterator[Point]:
|
||||||
|
"""Yield orthogonal neighbor coordinates for a point."""
|
||||||
for dx, dy in self.DIRECTIONS.values():
|
for dx, dy in self.DIRECTIONS.values():
|
||||||
yield (point[0] + dx, point[1] + dy)
|
yield (point[0] + dx, point[1] + dy)
|
||||||
|
|
||||||
def _manhattan(self, a, b):
|
def _manhattan(self, a:Point, b:Point) -> int:
|
||||||
|
"""Return Manhattan distance between two points."""
|
||||||
return abs(a[0] - b[0]) + abs(a[1] - b[1])
|
return abs(a[0] - b[0]) + abs(a[1] - b[1])
|
||||||
|
|
||||||
def _in_bounds(self, point, width, height):
|
def _in_bounds(self, point:Point, width:int, height:int) -> bool:
|
||||||
|
"""Return True when a point is inside board boundaries."""
|
||||||
return 0 <= point[0] < width and 0 <= point[1] < height
|
return 0 <= point[0] < width and 0 <= point[1] < height
|
||||||
|
|
||||||
def _fallback_move(self, head, width, height):
|
def _fallback_move(self, head:Coord, width:int, height:int) -> str:
|
||||||
for move, pos in self.get_possible_moves(head).items():
|
"""Pick the first in-bounds move as emergency fallback."""
|
||||||
point = (pos["x"], pos["y"])
|
for move, (dx, dy) in self.DIRECTIONS.items():
|
||||||
|
point = (head["x"] + dx, head["y"] + dy)
|
||||||
if self._in_bounds(point, width, height):
|
if self._in_bounds(point, width, height):
|
||||||
return move
|
return move
|
||||||
return "up"
|
return "up"
|
||||||
|
|||||||
@@ -3,9 +3,12 @@ from server.GameBoard import GameBoard
|
|||||||
from collections import deque
|
from collections import deque
|
||||||
|
|
||||||
class BetterMasterSnake(TemplateSnake):
|
class BetterMasterSnake(TemplateSnake):
|
||||||
|
VERSION = "1.3.0"
|
||||||
|
|
||||||
def __init__(self):
|
def __init__(self):
|
||||||
super().__init__()
|
super().__init__()
|
||||||
self.name = "BetterMasterSnake"
|
self.name = "BetterMasterSnake"
|
||||||
|
self.version = self.VERSION
|
||||||
# Definiere die möglichen Bewegungsrichtungen
|
# Definiere die möglichen Bewegungsrichtungen
|
||||||
self.min_safe_area = 2
|
self.min_safe_area = 2
|
||||||
|
|
||||||
|
|||||||
@@ -3,6 +3,8 @@ from snakes.TemplateSnake import TemplateSnake
|
|||||||
import random
|
import random
|
||||||
|
|
||||||
class DummSnake(TemplateSnake):
|
class DummSnake(TemplateSnake):
|
||||||
|
VERSION = "1.0.0"
|
||||||
|
|
||||||
def choose_move(self, data: dict) -> str:
|
def choose_move(self, data: dict) -> str:
|
||||||
is_move_safe = {"up": True, "down": True, "left": True, "right": True}
|
is_move_safe = {"up": True, "down": True, "left": True, "right": True}
|
||||||
|
|
||||||
|
|||||||
@@ -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.
|
||||||
|
|||||||
@@ -1,9 +1,12 @@
|
|||||||
from snakes.TemplateSnake import TemplateSnake
|
from snakes.TemplateSnake import TemplateSnake
|
||||||
|
|
||||||
class MasterSnake(TemplateSnake):
|
class MasterSnake(TemplateSnake):
|
||||||
|
VERSION = "1.2.0"
|
||||||
|
|
||||||
def __init__(self):
|
def __init__(self):
|
||||||
super().__init__()
|
super().__init__()
|
||||||
self.name = "MasterSnake"
|
self.name = "MasterSnake"
|
||||||
|
self.version = self.VERSION
|
||||||
self.disabled_find_near_by_food = True
|
self.disabled_find_near_by_food = True
|
||||||
|
|
||||||
def is_food_nearby(self, head, food_positions):
|
def is_food_nearby(self, head, food_positions):
|
||||||
|
|||||||
@@ -2,9 +2,13 @@ from server.GameBoard import GameBoard
|
|||||||
import random
|
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.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 = []
|
||||||
|
|||||||
@@ -0,0 +1,33 @@
|
|||||||
|
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",
|
||||||
|
}
|
||||||
|
|
||||||
|
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)
|
||||||
|
|||||||
@@ -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()
|
||||||
@@ -218,6 +218,146 @@ class TestBestBattleSnake(unittest.TestCase):
|
|||||||
move = make_board(game_state).snake_neat_make_a_move()
|
move = make_board(game_state).snake_neat_make_a_move()
|
||||||
self.assertNotEqual(move, "right")
|
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):
|
def test_does_not_step_into_stacked_tail(self):
|
||||||
game_state = {
|
game_state = {
|
||||||
"game": {
|
"game": {
|
||||||
@@ -328,6 +468,84 @@ class TestBestBattleSnake(unittest.TestCase):
|
|||||||
move = make_board(game_state).snake_neat_make_a_move()
|
move = make_board(game_state).snake_neat_make_a_move()
|
||||||
self.assertNotEqual(move, "up")
|
self.assertNotEqual(move, "up")
|
||||||
|
|
||||||
|
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):
|
def test_constrictor_avoids_growth_dead_end(self):
|
||||||
game_state = {
|
game_state = {
|
||||||
"game": {
|
"game": {
|
||||||
@@ -393,6 +611,145 @@ class TestBestBattleSnake(unittest.TestCase):
|
|||||||
move = make_board(game_state).snake_neat_make_a_move()
|
move = make_board(game_state).snake_neat_make_a_move()
|
||||||
self.assertEqual(move, "up")
|
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__":
|
if __name__ == "__main__":
|
||||||
unittest.main()
|
unittest.main()
|
||||||
|
|||||||
@@ -11,6 +11,12 @@ 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" },
|
{ 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]]
|
[[package]]
|
||||||
name = "blinker"
|
name = "blinker"
|
||||||
version = "1.9.0"
|
version = "1.9.0"
|
||||||
@@ -265,6 +271,7 @@ name = "snake-python"
|
|||||||
version = "0.1.0"
|
version = "0.1.0"
|
||||||
source = { virtual = "." }
|
source = { virtual = "." }
|
||||||
dependencies = [
|
dependencies = [
|
||||||
|
{ name = "aiologger" },
|
||||||
{ name = "dotenv" },
|
{ name = "dotenv" },
|
||||||
{ name = "gel" },
|
{ name = "gel" },
|
||||||
{ name = "quart" },
|
{ name = "quart" },
|
||||||
@@ -272,6 +279,7 @@ dependencies = [
|
|||||||
|
|
||||||
[package.metadata]
|
[package.metadata]
|
||||||
requires-dist = [
|
requires-dist = [
|
||||||
|
{ name = "aiologger", specifier = ">=0.7.0" },
|
||||||
{ name = "dotenv", specifier = ">=0.9.9" },
|
{ name = "dotenv", specifier = ">=0.9.9" },
|
||||||
{ name = "gel", specifier = ">=3.1.0" },
|
{ name = "gel", specifier = ">=3.1.0" },
|
||||||
{ name = "quart", specifier = ">=0.20.0" },
|
{ name = "quart", specifier = ">=0.20.0" },
|
||||||
|
|||||||
Reference in New Issue
Block a user