Compare commits
19 Commits
3d7f92e20f
...
8f938ce3fe
| 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__/
|
||||
data/
|
||||
.env
|
||||
.tools/
|
||||
|
||||
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
|
||||
```
|
||||
|
||||
Curate a high-quality training subset (single file):
|
||||
|
||||
```sh
|
||||
python -m server.DatasetCurator --input good_moves-2026-04-03.jsonl --output data/dataset/best_moves.jsonl
|
||||
```
|
||||
|
||||
Curate from multiple JSONL sources (repeat `--input`):
|
||||
|
||||
```sh
|
||||
python -m server.DatasetCurator \
|
||||
--input good_moves-2026-04-03.jsonl \
|
||||
--input good_moves-2026-04-04.jsonl \
|
||||
--output data/dataset/best_moves.jsonl
|
||||
```
|
||||
|
||||
Curate from folder or glob:
|
||||
|
||||
```sh
|
||||
python -m server.DatasetCurator --input data/dataset --output data/dataset/best_moves.jsonl
|
||||
python -m server.DatasetCurator --input "good_moves-*.jsonl" --output data/dataset/best_moves.jsonl
|
||||
```
|
||||
|
||||
Append mode (keeps existing curated rows and deduplicates against them):
|
||||
|
||||
```sh
|
||||
python -m server.DatasetCurator --input "good_moves-*.jsonl" --output data/dataset/best_moves.jsonl --append
|
||||
```
|
||||
|
||||
Archive processed input files after curation:
|
||||
|
||||
```sh
|
||||
python -m server.DatasetCurator --input "good_moves-*.jsonl" --output data/dataset/best_moves.jsonl --append --archive-input
|
||||
python -m server.DatasetCurator --input "good_moves-*.jsonl" --output data/dataset/best_moves.jsonl --append --archive-input --archive-dir data/dataset/archive
|
||||
```
|
||||
|
||||
Or with `just`:
|
||||
|
||||
```sh
|
||||
just curate-dataset
|
||||
just curate-dataset append=true
|
||||
just curate-dataset append=true archive=true archive_dir=data/dataset/archive
|
||||
```
|
||||
|
||||
Analyze dataset quality overall and by day (best game overall/day included):
|
||||
|
||||
```sh
|
||||
python -m server.DatasetStats --input "good_moves-*.jsonl"
|
||||
python -m server.DatasetStats --input data/dataset --output data/dataset/stats-report.json
|
||||
```
|
||||
|
||||
The stats report now includes both:
|
||||
- `best_game` (survival/length focused)
|
||||
- `best_pressure_game` (high-pressure quality focused: fewer safe options + strong survival)
|
||||
|
||||
Or with `just`:
|
||||
|
||||
```sh
|
||||
just analyze-dataset
|
||||
just analyze-dataset input=data/dataset output=data/dataset/stats-report.json
|
||||
```
|
||||
|
||||
To store compact dataset-only records (JSONL) and skip full per-game JSON files:
|
||||
|
||||
```sh
|
||||
|
||||
@@ -1,16 +1,5 @@
|
||||
from server.Server import Server
|
||||
import os
|
||||
from server.bootstrap import build_server_from_env
|
||||
|
||||
server = Server(
|
||||
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()
|
||||
server = build_server_from_env(default_snake_type="TemplateSnake")
|
||||
|
||||
app = server.app
|
||||
|
||||
@@ -1,661 +0,0 @@
|
||||
GNU AFFERO GENERAL PUBLIC LICENSE
|
||||
Version 3, 19 November 2007
|
||||
|
||||
Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
|
||||
Everyone is permitted to copy and distribute verbatim copies
|
||||
of this license document, but changing it is not allowed.
|
||||
|
||||
Preamble
|
||||
|
||||
The GNU Affero General Public License is a free, copyleft license for
|
||||
software and other kinds of works, specifically designed to ensure
|
||||
cooperation with the community in the case of network server software.
|
||||
|
||||
The licenses for most software and other practical works are designed
|
||||
to take away your freedom to share and change the works. By contrast,
|
||||
our General Public Licenses are intended to guarantee your freedom to
|
||||
share and change all versions of a program--to make sure it remains free
|
||||
software for all its users.
|
||||
|
||||
When we speak of free software, we are referring to freedom, not
|
||||
price. Our General Public Licenses are designed to make sure that you
|
||||
have the freedom to distribute copies of free software (and charge for
|
||||
them if you wish), that you receive source code or can get it if you
|
||||
want it, that you can change the software or use pieces of it in new
|
||||
free programs, and that you know you can do these things.
|
||||
|
||||
Developers that use our General Public Licenses protect your rights
|
||||
with two steps: (1) assert copyright on the software, and (2) offer
|
||||
you this License which gives you legal permission to copy, distribute
|
||||
and/or modify the software.
|
||||
|
||||
A secondary benefit of defending all users' freedom is that
|
||||
improvements made in alternate versions of the program, if they
|
||||
receive widespread use, become available for other developers to
|
||||
incorporate. Many developers of free software are heartened and
|
||||
encouraged by the resulting cooperation. However, in the case of
|
||||
software used on network servers, this result may fail to come about.
|
||||
The GNU General Public License permits making a modified version and
|
||||
letting the public access it on a server without ever releasing its
|
||||
source code to the public.
|
||||
|
||||
The GNU Affero General Public License is designed specifically to
|
||||
ensure that, in such cases, the modified source code becomes available
|
||||
to the community. It requires the operator of a network server to
|
||||
provide the source code of the modified version running there to the
|
||||
users of that server. Therefore, public use of a modified version, on
|
||||
a publicly accessible server, gives the public access to the source
|
||||
code of the modified version.
|
||||
|
||||
An older license, called the Affero General Public License and
|
||||
published by Affero, was designed to accomplish similar goals. This is
|
||||
a different license, not a version of the Affero GPL, but Affero has
|
||||
released a new version of the Affero GPL which permits relicensing under
|
||||
this license.
|
||||
|
||||
The precise terms and conditions for copying, distribution and
|
||||
modification follow.
|
||||
|
||||
TERMS AND CONDITIONS
|
||||
|
||||
0. Definitions.
|
||||
|
||||
"This License" refers to version 3 of the GNU Affero General Public License.
|
||||
|
||||
"Copyright" also means copyright-like laws that apply to other kinds of
|
||||
works, such as semiconductor masks.
|
||||
|
||||
"The Program" refers to any copyrightable work licensed under this
|
||||
License. Each licensee is addressed as "you". "Licensees" and
|
||||
"recipients" may be individuals or organizations.
|
||||
|
||||
To "modify" a work means to copy from or adapt all or part of the work
|
||||
in a fashion requiring copyright permission, other than the making of an
|
||||
exact copy. The resulting work is called a "modified version" of the
|
||||
earlier work or a work "based on" the earlier work.
|
||||
|
||||
A "covered work" means either the unmodified Program or a work based
|
||||
on the Program.
|
||||
|
||||
To "propagate" a work means to do anything with it that, without
|
||||
permission, would make you directly or secondarily liable for
|
||||
infringement under applicable copyright law, except executing it on a
|
||||
computer or modifying a private copy. Propagation includes copying,
|
||||
distribution (with or without modification), making available to the
|
||||
public, and in some countries other activities as well.
|
||||
|
||||
To "convey" a work means any kind of propagation that enables other
|
||||
parties to make or receive copies. Mere interaction with a user through
|
||||
a computer network, with no transfer of a copy, is not conveying.
|
||||
|
||||
An interactive user interface displays "Appropriate Legal Notices"
|
||||
to the extent that it includes a convenient and prominently visible
|
||||
feature that (1) displays an appropriate copyright notice, and (2)
|
||||
tells the user that there is no warranty for the work (except to the
|
||||
extent that warranties are provided), that licensees may convey the
|
||||
work under this License, and how to view a copy of this License. If
|
||||
the interface presents a list of user commands or options, such as a
|
||||
menu, a prominent item in the list meets this criterion.
|
||||
|
||||
1. Source Code.
|
||||
|
||||
The "source code" for a work means the preferred form of the work
|
||||
for making modifications to it. "Object code" means any non-source
|
||||
form of a work.
|
||||
|
||||
A "Standard Interface" means an interface that either is an official
|
||||
standard defined by a recognized standards body, or, in the case of
|
||||
interfaces specified for a particular programming language, one that
|
||||
is widely used among developers working in that language.
|
||||
|
||||
The "System Libraries" of an executable work include anything, other
|
||||
than the work as a whole, that (a) is included in the normal form of
|
||||
packaging a Major Component, but which is not part of that Major
|
||||
Component, and (b) serves only to enable use of the work with that
|
||||
Major Component, or to implement a Standard Interface for which an
|
||||
implementation is available to the public in source code form. A
|
||||
"Major Component", in this context, means a major essential component
|
||||
(kernel, window system, and so on) of the specific operating system
|
||||
(if any) on which the executable work runs, or a compiler used to
|
||||
produce the work, or an object code interpreter used to run it.
|
||||
|
||||
The "Corresponding Source" for a work in object code form means all
|
||||
the source code needed to generate, install, and (for an executable
|
||||
work) run the object code and to modify the work, including scripts to
|
||||
control those activities. However, it does not include the work's
|
||||
System Libraries, or general-purpose tools or generally available free
|
||||
programs which are used unmodified in performing those activities but
|
||||
which are not part of the work. For example, Corresponding Source
|
||||
includes interface definition files associated with source files for
|
||||
the work, and the source code for shared libraries and dynamically
|
||||
linked subprograms that the work is specifically designed to require,
|
||||
such as by intimate data communication or control flow between those
|
||||
subprograms and other parts of the work.
|
||||
|
||||
The Corresponding Source need not include anything that users
|
||||
can regenerate automatically from other parts of the Corresponding
|
||||
Source.
|
||||
|
||||
The Corresponding Source for a work in source code form is that
|
||||
same work.
|
||||
|
||||
2. Basic Permissions.
|
||||
|
||||
All rights granted under this License are granted for the term of
|
||||
copyright on the Program, and are irrevocable provided the stated
|
||||
conditions are met. This License explicitly affirms your unlimited
|
||||
permission to run the unmodified Program. The output from running a
|
||||
covered work is covered by this License only if the output, given its
|
||||
content, constitutes a covered work. This License acknowledges your
|
||||
rights of fair use or other equivalent, as provided by copyright law.
|
||||
|
||||
You may make, run and propagate covered works that you do not
|
||||
convey, without conditions so long as your license otherwise remains
|
||||
in force. You may convey covered works to others for the sole purpose
|
||||
of having them make modifications exclusively for you, or provide you
|
||||
with facilities for running those works, provided that you comply with
|
||||
the terms of this License in conveying all material for which you do
|
||||
not control copyright. Those thus making or running the covered works
|
||||
for you must do so exclusively on your behalf, under your direction
|
||||
and control, on terms that prohibit them from making any copies of
|
||||
your copyrighted material outside their relationship with you.
|
||||
|
||||
Conveying under any other circumstances is permitted solely under
|
||||
the conditions stated below. Sublicensing is not allowed; section 10
|
||||
makes it unnecessary.
|
||||
|
||||
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
|
||||
|
||||
No covered work shall be deemed part of an effective technological
|
||||
measure under any applicable law fulfilling obligations under article
|
||||
11 of the WIPO copyright treaty adopted on 20 December 1996, or
|
||||
similar laws prohibiting or restricting circumvention of such
|
||||
measures.
|
||||
|
||||
When you convey a covered work, you waive any legal power to forbid
|
||||
circumvention of technological measures to the extent such circumvention
|
||||
is effected by exercising rights under this License with respect to
|
||||
the covered work, and you disclaim any intention to limit operation or
|
||||
modification of the work as a means of enforcing, against the work's
|
||||
users, your or third parties' legal rights to forbid circumvention of
|
||||
technological measures.
|
||||
|
||||
4. Conveying Verbatim Copies.
|
||||
|
||||
You may convey verbatim copies of the Program's source code as you
|
||||
receive it, in any medium, provided that you conspicuously and
|
||||
appropriately publish on each copy an appropriate copyright notice;
|
||||
keep intact all notices stating that this License and any
|
||||
non-permissive terms added in accord with section 7 apply to the code;
|
||||
keep intact all notices of the absence of any warranty; and give all
|
||||
recipients a copy of this License along with the Program.
|
||||
|
||||
You may charge any price or no price for each copy that you convey,
|
||||
and you may offer support or warranty protection for a fee.
|
||||
|
||||
5. Conveying Modified Source Versions.
|
||||
|
||||
You may convey a work based on the Program, or the modifications to
|
||||
produce it from the Program, in the form of source code under the
|
||||
terms of section 4, provided that you also meet all of these conditions:
|
||||
|
||||
a) The work must carry prominent notices stating that you modified
|
||||
it, and giving a relevant date.
|
||||
|
||||
b) The work must carry prominent notices stating that it is
|
||||
released under this License and any conditions added under section
|
||||
7. This requirement modifies the requirement in section 4 to
|
||||
"keep intact all notices".
|
||||
|
||||
c) You must license the entire work, as a whole, under this
|
||||
License to anyone who comes into possession of a copy. This
|
||||
License will therefore apply, along with any applicable section 7
|
||||
additional terms, to the whole of the work, and all its parts,
|
||||
regardless of how they are packaged. This License gives no
|
||||
permission to license the work in any other way, but it does not
|
||||
invalidate such permission if you have separately received it.
|
||||
|
||||
d) If the work has interactive user interfaces, each must display
|
||||
Appropriate Legal Notices; however, if the Program has interactive
|
||||
interfaces that do not display Appropriate Legal Notices, your
|
||||
work need not make them do so.
|
||||
|
||||
A compilation of a covered work with other separate and independent
|
||||
works, which are not by their nature extensions of the covered work,
|
||||
and which are not combined with it such as to form a larger program,
|
||||
in or on a volume of a storage or distribution medium, is called an
|
||||
"aggregate" if the compilation and its resulting copyright are not
|
||||
used to limit the access or legal rights of the compilation's users
|
||||
beyond what the individual works permit. Inclusion of a covered work
|
||||
in an aggregate does not cause this License to apply to the other
|
||||
parts of the aggregate.
|
||||
|
||||
6. Conveying Non-Source Forms.
|
||||
|
||||
You may convey a covered work in object code form under the terms
|
||||
of sections 4 and 5, provided that you also convey the
|
||||
machine-readable Corresponding Source under the terms of this License,
|
||||
in one of these ways:
|
||||
|
||||
a) Convey the object code in, or embodied in, a physical product
|
||||
(including a physical distribution medium), accompanied by the
|
||||
Corresponding Source fixed on a durable physical medium
|
||||
customarily used for software interchange.
|
||||
|
||||
b) Convey the object code in, or embodied in, a physical product
|
||||
(including a physical distribution medium), accompanied by a
|
||||
written offer, valid for at least three years and valid for as
|
||||
long as you offer spare parts or customer support for that product
|
||||
model, to give anyone who possesses the object code either (1) a
|
||||
copy of the Corresponding Source for all the software in the
|
||||
product that is covered by this License, on a durable physical
|
||||
medium customarily used for software interchange, for a price no
|
||||
more than your reasonable cost of physically performing this
|
||||
conveying of source, or (2) access to copy the
|
||||
Corresponding Source from a network server at no charge.
|
||||
|
||||
c) Convey individual copies of the object code with a copy of the
|
||||
written offer to provide the Corresponding Source. This
|
||||
alternative is allowed only occasionally and noncommercially, and
|
||||
only if you received the object code with such an offer, in accord
|
||||
with subsection 6b.
|
||||
|
||||
d) Convey the object code by offering access from a designated
|
||||
place (gratis or for a charge), and offer equivalent access to the
|
||||
Corresponding Source in the same way through the same place at no
|
||||
further charge. You need not require recipients to copy the
|
||||
Corresponding Source along with the object code. If the place to
|
||||
copy the object code is a network server, the Corresponding Source
|
||||
may be on a different server (operated by you or a third party)
|
||||
that supports equivalent copying facilities, provided you maintain
|
||||
clear directions next to the object code saying where to find the
|
||||
Corresponding Source. Regardless of what server hosts the
|
||||
Corresponding Source, you remain obligated to ensure that it is
|
||||
available for as long as needed to satisfy these requirements.
|
||||
|
||||
e) Convey the object code using peer-to-peer transmission, provided
|
||||
you inform other peers where the object code and Corresponding
|
||||
Source of the work are being offered to the general public at no
|
||||
charge under subsection 6d.
|
||||
|
||||
A separable portion of the object code, whose source code is excluded
|
||||
from the Corresponding Source as a System Library, need not be
|
||||
included in conveying the object code work.
|
||||
|
||||
A "User Product" is either (1) a "consumer product", which means any
|
||||
tangible personal property which is normally used for personal, family,
|
||||
or household purposes, or (2) anything designed or sold for incorporation
|
||||
into a dwelling. In determining whether a product is a consumer product,
|
||||
doubtful cases shall be resolved in favor of coverage. For a particular
|
||||
product received by a particular user, "normally used" refers to a
|
||||
typical or common use of that class of product, regardless of the status
|
||||
of the particular user or of the way in which the particular user
|
||||
actually uses, or expects or is expected to use, the product. A product
|
||||
is a consumer product regardless of whether the product has substantial
|
||||
commercial, industrial or non-consumer uses, unless such uses represent
|
||||
the only significant mode of use of the product.
|
||||
|
||||
"Installation Information" for a User Product means any methods,
|
||||
procedures, authorization keys, or other information required to install
|
||||
and execute modified versions of a covered work in that User Product from
|
||||
a modified version of its Corresponding Source. The information must
|
||||
suffice to ensure that the continued functioning of the modified object
|
||||
code is in no case prevented or interfered with solely because
|
||||
modification has been made.
|
||||
|
||||
If you convey an object code work under this section in, or with, or
|
||||
specifically for use in, a User Product, and the conveying occurs as
|
||||
part of a transaction in which the right of possession and use of the
|
||||
User Product is transferred to the recipient in perpetuity or for a
|
||||
fixed term (regardless of how the transaction is characterized), the
|
||||
Corresponding Source conveyed under this section must be accompanied
|
||||
by the Installation Information. But this requirement does not apply
|
||||
if neither you nor any third party retains the ability to install
|
||||
modified object code on the User Product (for example, the work has
|
||||
been installed in ROM).
|
||||
|
||||
The requirement to provide Installation Information does not include a
|
||||
requirement to continue to provide support service, warranty, or updates
|
||||
for a work that has been modified or installed by the recipient, or for
|
||||
the User Product in which it has been modified or installed. Access to a
|
||||
network may be denied when the modification itself materially and
|
||||
adversely affects the operation of the network or violates the rules and
|
||||
protocols for communication across the network.
|
||||
|
||||
Corresponding Source conveyed, and Installation Information provided,
|
||||
in accord with this section must be in a format that is publicly
|
||||
documented (and with an implementation available to the public in
|
||||
source code form), and must require no special password or key for
|
||||
unpacking, reading or copying.
|
||||
|
||||
7. Additional Terms.
|
||||
|
||||
"Additional permissions" are terms that supplement the terms of this
|
||||
License by making exceptions from one or more of its conditions.
|
||||
Additional permissions that are applicable to the entire Program shall
|
||||
be treated as though they were included in this License, to the extent
|
||||
that they are valid under applicable law. If additional permissions
|
||||
apply only to part of the Program, that part may be used separately
|
||||
under those permissions, but the entire Program remains governed by
|
||||
this License without regard to the additional permissions.
|
||||
|
||||
When you convey a copy of a covered work, you may at your option
|
||||
remove any additional permissions from that copy, or from any part of
|
||||
it. (Additional permissions may be written to require their own
|
||||
removal in certain cases when you modify the work.) You may place
|
||||
additional permissions on material, added by you to a covered work,
|
||||
for which you have or can give appropriate copyright permission.
|
||||
|
||||
Notwithstanding any other provision of this License, for material you
|
||||
add to a covered work, you may (if authorized by the copyright holders of
|
||||
that material) supplement the terms of this License with terms:
|
||||
|
||||
a) Disclaiming warranty or limiting liability differently from the
|
||||
terms of sections 15 and 16 of this License; or
|
||||
|
||||
b) Requiring preservation of specified reasonable legal notices or
|
||||
author attributions in that material or in the Appropriate Legal
|
||||
Notices displayed by works containing it; or
|
||||
|
||||
c) Prohibiting misrepresentation of the origin of that material, or
|
||||
requiring that modified versions of such material be marked in
|
||||
reasonable ways as different from the original version; or
|
||||
|
||||
d) Limiting the use for publicity purposes of names of licensors or
|
||||
authors of the material; or
|
||||
|
||||
e) Declining to grant rights under trademark law for use of some
|
||||
trade names, trademarks, or service marks; or
|
||||
|
||||
f) Requiring indemnification of licensors and authors of that
|
||||
material by anyone who conveys the material (or modified versions of
|
||||
it) with contractual assumptions of liability to the recipient, for
|
||||
any liability that these contractual assumptions directly impose on
|
||||
those licensors and authors.
|
||||
|
||||
All other non-permissive additional terms are considered "further
|
||||
restrictions" within the meaning of section 10. If the Program as you
|
||||
received it, or any part of it, contains a notice stating that it is
|
||||
governed by this License along with a term that is a further
|
||||
restriction, you may remove that term. If a license document contains
|
||||
a further restriction but permits relicensing or conveying under this
|
||||
License, you may add to a covered work material governed by the terms
|
||||
of that license document, provided that the further restriction does
|
||||
not survive such relicensing or conveying.
|
||||
|
||||
If you add terms to a covered work in accord with this section, you
|
||||
must place, in the relevant source files, a statement of the
|
||||
additional terms that apply to those files, or a notice indicating
|
||||
where to find the applicable terms.
|
||||
|
||||
Additional terms, permissive or non-permissive, may be stated in the
|
||||
form of a separately written license, or stated as exceptions;
|
||||
the above requirements apply either way.
|
||||
|
||||
8. Termination.
|
||||
|
||||
You may not propagate or modify a covered work except as expressly
|
||||
provided under this License. Any attempt otherwise to propagate or
|
||||
modify it is void, and will automatically terminate your rights under
|
||||
this License (including any patent licenses granted under the third
|
||||
paragraph of section 11).
|
||||
|
||||
However, if you cease all violation of this License, then your
|
||||
license from a particular copyright holder is reinstated (a)
|
||||
provisionally, unless and until the copyright holder explicitly and
|
||||
finally terminates your license, and (b) permanently, if the copyright
|
||||
holder fails to notify you of the violation by some reasonable means
|
||||
prior to 60 days after the cessation.
|
||||
|
||||
Moreover, your license from a particular copyright holder is
|
||||
reinstated permanently if the copyright holder notifies you of the
|
||||
violation by some reasonable means, this is the first time you have
|
||||
received notice of violation of this License (for any work) from that
|
||||
copyright holder, and you cure the violation prior to 30 days after
|
||||
your receipt of the notice.
|
||||
|
||||
Termination of your rights under this section does not terminate the
|
||||
licenses of parties who have received copies or rights from you under
|
||||
this License. If your rights have been terminated and not permanently
|
||||
reinstated, you do not qualify to receive new licenses for the same
|
||||
material under section 10.
|
||||
|
||||
9. Acceptance Not Required for Having Copies.
|
||||
|
||||
You are not required to accept this License in order to receive or
|
||||
run a copy of the Program. Ancillary propagation of a covered work
|
||||
occurring solely as a consequence of using peer-to-peer transmission
|
||||
to receive a copy likewise does not require acceptance. However,
|
||||
nothing other than this License grants you permission to propagate or
|
||||
modify any covered work. These actions infringe copyright if you do
|
||||
not accept this License. Therefore, by modifying or propagating a
|
||||
covered work, you indicate your acceptance of this License to do so.
|
||||
|
||||
10. Automatic Licensing of Downstream Recipients.
|
||||
|
||||
Each time you convey a covered work, the recipient automatically
|
||||
receives a license from the original licensors, to run, modify and
|
||||
propagate that work, subject to this License. You are not responsible
|
||||
for enforcing compliance by third parties with this License.
|
||||
|
||||
An "entity transaction" is a transaction transferring control of an
|
||||
organization, or substantially all assets of one, or subdividing an
|
||||
organization, or merging organizations. If propagation of a covered
|
||||
work results from an entity transaction, each party to that
|
||||
transaction who receives a copy of the work also receives whatever
|
||||
licenses to the work the party's predecessor in interest had or could
|
||||
give under the previous paragraph, plus a right to possession of the
|
||||
Corresponding Source of the work from the predecessor in interest, if
|
||||
the predecessor has it or can get it with reasonable efforts.
|
||||
|
||||
You may not impose any further restrictions on the exercise of the
|
||||
rights granted or affirmed under this License. For example, you may
|
||||
not impose a license fee, royalty, or other charge for exercise of
|
||||
rights granted under this License, and you may not initiate litigation
|
||||
(including a cross-claim or counterclaim in a lawsuit) alleging that
|
||||
any patent claim is infringed by making, using, selling, offering for
|
||||
sale, or importing the Program or any portion of it.
|
||||
|
||||
11. Patents.
|
||||
|
||||
A "contributor" is a copyright holder who authorizes use under this
|
||||
License of the Program or a work on which the Program is based. The
|
||||
work thus licensed is called the contributor's "contributor version".
|
||||
|
||||
A contributor's "essential patent claims" are all patent claims
|
||||
owned or controlled by the contributor, whether already acquired or
|
||||
hereafter acquired, that would be infringed by some manner, permitted
|
||||
by this License, of making, using, or selling its contributor version,
|
||||
but do not include claims that would be infringed only as a
|
||||
consequence of further modification of the contributor version. For
|
||||
purposes of this definition, "control" includes the right to grant
|
||||
patent sublicenses in a manner consistent with the requirements of
|
||||
this License.
|
||||
|
||||
Each contributor grants you a non-exclusive, worldwide, royalty-free
|
||||
patent license under the contributor's essential patent claims, to
|
||||
make, use, sell, offer for sale, import and otherwise run, modify and
|
||||
propagate the contents of its contributor version.
|
||||
|
||||
In the following three paragraphs, a "patent license" is any express
|
||||
agreement or commitment, however denominated, not to enforce a patent
|
||||
(such as an express permission to practice a patent or covenant not to
|
||||
sue for patent infringement). To "grant" such a patent license to a
|
||||
party means to make such an agreement or commitment not to enforce a
|
||||
patent against the party.
|
||||
|
||||
If you convey a covered work, knowingly relying on a patent license,
|
||||
and the Corresponding Source of the work is not available for anyone
|
||||
to copy, free of charge and under the terms of this License, through a
|
||||
publicly available network server or other readily accessible means,
|
||||
then you must either (1) cause the Corresponding Source to be so
|
||||
available, or (2) arrange to deprive yourself of the benefit of the
|
||||
patent license for this particular work, or (3) arrange, in a manner
|
||||
consistent with the requirements of this License, to extend the patent
|
||||
license to downstream recipients. "Knowingly relying" means you have
|
||||
actual knowledge that, but for the patent license, your conveying the
|
||||
covered work in a country, or your recipient's use of the covered work
|
||||
in a country, would infringe one or more identifiable patents in that
|
||||
country that you have reason to believe are valid.
|
||||
|
||||
If, pursuant to or in connection with a single transaction or
|
||||
arrangement, you convey, or propagate by procuring conveyance of, a
|
||||
covered work, and grant a patent license to some of the parties
|
||||
receiving the covered work authorizing them to use, propagate, modify
|
||||
or convey a specific copy of the covered work, then the patent license
|
||||
you grant is automatically extended to all recipients of the covered
|
||||
work and works based on it.
|
||||
|
||||
A patent license is "discriminatory" if it does not include within
|
||||
the scope of its coverage, prohibits the exercise of, or is
|
||||
conditioned on the non-exercise of one or more of the rights that are
|
||||
specifically granted under this License. You may not convey a covered
|
||||
work if you are a party to an arrangement with a third party that is
|
||||
in the business of distributing software, under which you make payment
|
||||
to the third party based on the extent of your activity of conveying
|
||||
the work, and under which the third party grants, to any of the
|
||||
parties who would receive the covered work from you, a discriminatory
|
||||
patent license (a) in connection with copies of the covered work
|
||||
conveyed by you (or copies made from those copies), or (b) primarily
|
||||
for and in connection with specific products or compilations that
|
||||
contain the covered work, unless you entered into that arrangement,
|
||||
or that patent license was granted, prior to 28 March 2007.
|
||||
|
||||
Nothing in this License shall be construed as excluding or limiting
|
||||
any implied license or other defenses to infringement that may
|
||||
otherwise be available to you under applicable patent law.
|
||||
|
||||
12. No Surrender of Others' Freedom.
|
||||
|
||||
If conditions are imposed on you (whether by court order, agreement or
|
||||
otherwise) that contradict the conditions of this License, they do not
|
||||
excuse you from the conditions of this License. If you cannot convey a
|
||||
covered work so as to satisfy simultaneously your obligations under this
|
||||
License and any other pertinent obligations, then as a consequence you may
|
||||
not convey it at all. For example, if you agree to terms that obligate you
|
||||
to collect a royalty for further conveying from those to whom you convey
|
||||
the Program, the only way you could satisfy both those terms and this
|
||||
License would be to refrain entirely from conveying the Program.
|
||||
|
||||
13. Remote Network Interaction; Use with the GNU General Public License.
|
||||
|
||||
Notwithstanding any other provision of this License, if you modify the
|
||||
Program, your modified version must prominently offer all users
|
||||
interacting with it remotely through a computer network (if your version
|
||||
supports such interaction) an opportunity to receive the Corresponding
|
||||
Source of your version by providing access to the Corresponding Source
|
||||
from a network server at no charge, through some standard or customary
|
||||
means of facilitating copying of software. This Corresponding Source
|
||||
shall include the Corresponding Source for any work covered by version 3
|
||||
of the GNU General Public License that is incorporated pursuant to the
|
||||
following paragraph.
|
||||
|
||||
Notwithstanding any other provision of this License, you have
|
||||
permission to link or combine any covered work with a work licensed
|
||||
under version 3 of the GNU General Public License into a single
|
||||
combined work, and to convey the resulting work. The terms of this
|
||||
License will continue to apply to the part which is the covered work,
|
||||
but the work with which it is combined will remain governed by version
|
||||
3 of the GNU General Public License.
|
||||
|
||||
14. Revised Versions of this License.
|
||||
|
||||
The Free Software Foundation may publish revised and/or new versions of
|
||||
the GNU Affero General Public License from time to time. Such new versions
|
||||
will be similar in spirit to the present version, but may differ in detail to
|
||||
address new problems or concerns.
|
||||
|
||||
Each version is given a distinguishing version number. If the
|
||||
Program specifies that a certain numbered version of the GNU Affero General
|
||||
Public License "or any later version" applies to it, you have the
|
||||
option of following the terms and conditions either of that numbered
|
||||
version or of any later version published by the Free Software
|
||||
Foundation. If the Program does not specify a version number of the
|
||||
GNU Affero General Public License, you may choose any version ever published
|
||||
by the Free Software Foundation.
|
||||
|
||||
If the Program specifies that a proxy can decide which future
|
||||
versions of the GNU Affero General Public License can be used, that proxy's
|
||||
public statement of acceptance of a version permanently authorizes you
|
||||
to choose that version for the Program.
|
||||
|
||||
Later license versions may give you additional or different
|
||||
permissions. However, no additional obligations are imposed on any
|
||||
author or copyright holder as a result of your choosing to follow a
|
||||
later version.
|
||||
|
||||
15. Disclaimer of Warranty.
|
||||
|
||||
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
|
||||
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
|
||||
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
|
||||
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
|
||||
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
|
||||
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
|
||||
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
|
||||
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
|
||||
|
||||
16. Limitation of Liability.
|
||||
|
||||
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
|
||||
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
|
||||
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
|
||||
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
|
||||
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
|
||||
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
|
||||
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
|
||||
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
|
||||
SUCH DAMAGES.
|
||||
|
||||
17. Interpretation of Sections 15 and 16.
|
||||
|
||||
If the disclaimer of warranty and limitation of liability provided
|
||||
above cannot be given local legal effect according to their terms,
|
||||
reviewing courts shall apply local law that most closely approximates
|
||||
an absolute waiver of all civil liability in connection with the
|
||||
Program, unless a warranty or assumption of liability accompanies a
|
||||
copy of the Program in return for a fee.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
How to Apply These Terms to Your New Programs
|
||||
|
||||
If you develop a new program, and you want it to be of the greatest
|
||||
possible use to the public, the best way to achieve this is to make it
|
||||
free software which everyone can redistribute and change under these terms.
|
||||
|
||||
To do so, attach the following notices to the program. It is safest
|
||||
to attach them to the start of each source file to most effectively
|
||||
state the exclusion of warranty; and each file should have at least
|
||||
the "copyright" line and a pointer to where the full notice is found.
|
||||
|
||||
<one line to give the program's name and a brief idea of what it does.>
|
||||
Copyright (C) <year> <name of author>
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU Affero General Public License as published
|
||||
by the Free Software Foundation, either version 3 of the License, or
|
||||
(at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU Affero General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU Affero General Public License
|
||||
along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
Also add information on how to contact you by electronic and paper mail.
|
||||
|
||||
If your software can interact with users remotely through a computer
|
||||
network, you should also make sure that it provides a way for users to
|
||||
get its source. For example, if your program is a web application, its
|
||||
interface could display a "Source" link that leads users to an archive
|
||||
of the code. There are many ways you could offer source, and different
|
||||
solutions will be better for different programs; see section 13 for the
|
||||
specific requirements.
|
||||
|
||||
You should also get your employer (if you work as a programmer) or school,
|
||||
if any, to sign a "copyright disclaimer" for the program, if necessary.
|
||||
For more information on this, and how to apply and follow the GNU AGPL, see
|
||||
<http://www.gnu.org/licenses/>.
|
||||
@@ -1,53 +0,0 @@
|
||||
# BattlesnakeOfficial/rules
|
||||
|
||||
[](https://codecov.io/gh/BattlesnakeOfficial/rules)
|
||||
|
||||
[Battlesnake](https://play.battlesnake.com) rules and game logic, implemented as a Go module. This code is used in production at [play.battlesnake.com](https://play.battlesnake.com). Issues and contributions welcome!
|
||||
|
||||
|
||||
## CLI for Running Battlesnake Games Locally
|
||||
|
||||
This repo provides a simple CLI tool to run games locally against your dev environment.
|
||||
|
||||
### Installation
|
||||
|
||||
Download precompiled binaries here: <br>
|
||||
[https://github.com/BattlesnakeOfficial/rules/releases](https://github.com/BattlesnakeOfficial/rules/releases)
|
||||
|
||||
Install as a Go package. Requires Go 1.18 or higher. [[Download](https://golang.org/dl/)]
|
||||
```
|
||||
go install github.com/BattlesnakeOfficial/rules/cli/battlesnake@latest
|
||||
```
|
||||
|
||||
Compile from source. Also requires Go 1.18 or higher.
|
||||
```
|
||||
git clone git@github.com:BattlesnakeOfficial/rules.git
|
||||
cd rules
|
||||
go build -o battlesnake ./cli/battlesnake/main.go
|
||||
```
|
||||
|
||||
### Usage
|
||||
|
||||
Example command to run a game locally:
|
||||
```
|
||||
battlesnake play -W 11 -H 11 --name <SNAKE_NAME> --url <SNAKE_URL> -g solo -v
|
||||
```
|
||||
|
||||
For more details, see the [CLI README](cli/README.md).
|
||||
|
||||
|
||||
## FAQ
|
||||
|
||||
### Can I run games locally?
|
||||
|
||||
Yes! [See the included CLI](cli/README.md).
|
||||
|
||||
### How is this different from the old Battlesnake engine?
|
||||
|
||||
The [old game engine](https://github.com/battlesnakeio/engine) was re-written in early 2020 to handle a higher volume of concurrent games. As part of that rebuild we moved the game logic into a separate Go module that gets compiled into the production engine.
|
||||
|
||||
This provides two benefits: it makes it much simpler/easier to build new game modes, and it allows the community to get more involved in game development (without the maintenance overhead of the entire game engine).
|
||||
|
||||
### Feedback
|
||||
|
||||
* **Do you have an issue or suggestions for this repository?** Head over to our [Feedback Repository](https://play.battlesnake.com/feedback) today and let us know!
|
||||
Binary file not shown.
@@ -12,6 +12,9 @@ set dotenv-required := true
|
||||
# Use zsh
|
||||
set shell := ["bash", "-cu"]
|
||||
|
||||
BATTLESNAKE_CLI_DIR := ".tools/battlesnake-cli"
|
||||
BATTLESNAKE_CLI_BIN := ".tools/battlesnake-cli/battlesnake"
|
||||
|
||||
# ------------------------------------------------------------------------------
|
||||
# Default
|
||||
# ------------------------------------------------------------------------------
|
||||
@@ -28,23 +31,132 @@ default:
|
||||
run:
|
||||
"{{justfile_directory()}}/main.py"
|
||||
|
||||
run-snake port="8000" snake="BestBattleSnake":
|
||||
HOST="127.0.0.1" PORT="{{port}}" SNAKE="{{snake}}" DEBUG="false" DEBUG_SERVER="false" "{{justfile_directory()}}/main.py"
|
||||
|
||||
run-4-snakes base_port="9101" snake="BestBattleSnake":
|
||||
#!/usr/bin/env bash
|
||||
set -euo pipefail
|
||||
|
||||
pids=()
|
||||
for i in 0 1 2 3; do
|
||||
port="$(({{base_port}} + i))"
|
||||
echo "Starting snake on :$port"
|
||||
HOST="127.0.0.1" PORT="$port" SNAKE="{{snake}}" DEBUG="false" DEBUG_SERVER="false" "{{justfile_directory()}}/main.py" &
|
||||
pids[$i]="$!"
|
||||
done
|
||||
|
||||
cleanup() {
|
||||
for pid in "${pids[@]}"; do
|
||||
kill "$pid" 2>/dev/null || true
|
||||
done
|
||||
wait || true
|
||||
}
|
||||
trap cleanup EXIT INT TERM
|
||||
|
||||
wait
|
||||
|
||||
bench-best-snake iterations="1000":
|
||||
#!/usr/bin/env bash
|
||||
set -euo pipefail
|
||||
|
||||
PYTHONPATH="{{justfile_directory()}}" python "{{justfile_directory()}}/tests/bench_best_battle_snake.py" --iterations "{{iterations}}"
|
||||
|
||||
build-battlesnake-cli:
|
||||
#!/usr/bin/env bash
|
||||
set -euo pipefail
|
||||
|
||||
install_dir="{{justfile_directory()}}/{{BATTLESNAKE_CLI_DIR}}"
|
||||
bin_path="{{justfile_directory()}}/{{BATTLESNAKE_CLI_BIN}}"
|
||||
mkdir -p "$install_dir"
|
||||
|
||||
if [ ! -f "{{justfile_directory()}}/local-client/go.mod" ]; then
|
||||
echo "Missing local-client source. Run: git submodule update --init --recursive"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
(
|
||||
cd "{{justfile_directory()}}/local-client"
|
||||
go build -o "$bin_path" ./cli/battlesnake/main.go
|
||||
)
|
||||
|
||||
"$bin_path" --help > /dev/null
|
||||
echo "Built Battlesnake CLI at $bin_path"
|
||||
|
||||
battlesnake-cli-version:
|
||||
#!/usr/bin/env bash
|
||||
set -euo pipefail
|
||||
|
||||
"{{justfile_directory()}}/{{BATTLESNAKE_CLI_BIN}}" --help
|
||||
|
||||
# ------------------------------------------------------------------------------
|
||||
# Testing helpers
|
||||
# ------------------------------------------------------------------------------
|
||||
|
||||
test-constrictor:
|
||||
test-constrictor: build-battlesnake-cli
|
||||
#!/usr/bin/env bash
|
||||
set -euo pipefail
|
||||
|
||||
BATTLESNAKE_CLI=battlesnake_cli_1.2.3_Linux_x86_64/battlesnake
|
||||
$BATTLESNAKE_CLI play -W 11 -H 11 --name 'Python Starter Project' --url http://localhost:8000 -g constrictor --browser --minimumFood 0
|
||||
BATTLESNAKE_CLI="{{justfile_directory()}}/{{BATTLESNAKE_CLI_BIN}}"
|
||||
"$BATTLESNAKE_CLI" play -W 11 -H 11 --name 'Python Starter Project' --url http://localhost:8000 -g constrictor --browser --minimumFood 0
|
||||
|
||||
test-seed:
|
||||
test-seed: build-battlesnake-cli
|
||||
#!/usr/bin/env bash
|
||||
set -euo pipefail
|
||||
|
||||
BATTLESNAKE_CLI=battlesnake_cli_1.2.3_Linux_x86_64/battlesnake
|
||||
$BATTLESNAKE_CLI play -W 11 -H 11 --name 'Python Starter Project' --url http://localhost:8000 -g solo --browser --seed 1713099635738952360
|
||||
BATTLESNAKE_CLI="{{justfile_directory()}}/{{BATTLESNAKE_CLI_BIN}}"
|
||||
"$BATTLESNAKE_CLI" play -W 11 -H 11 --name 'Python Starter Project' --url http://localhost:8000 -g solo --browser --seed 1713099635738952360
|
||||
|
||||
test-local-4 mode="standard" map="standard" base_port="9101" snake="BestBattleSnake" seed="1713099635738952360" browser="true": build-battlesnake-cli
|
||||
#!/usr/bin/env bash
|
||||
set -euo pipefail
|
||||
|
||||
BATTLESNAKE_CLI="{{justfile_directory()}}/{{BATTLESNAKE_CLI_BIN}}"
|
||||
LOG_DIR="{{justfile_directory()}}/.tools/snake-logs"
|
||||
mkdir -p "$LOG_DIR"
|
||||
|
||||
pids=()
|
||||
for i in 0 1 2 3; do
|
||||
port="$(({{base_port}} + i))"
|
||||
log_file="$LOG_DIR/snake-$((i+1)).log"
|
||||
echo "Starting snake-$((i+1)) on :$port (log: $log_file)"
|
||||
HOST="127.0.0.1" PORT="$port" SNAKE="{{snake}}" DEBUG="false" DEBUG_SERVER="false" "{{justfile_directory()}}/main.py" > >(tee "$log_file") 2>&1 &
|
||||
pids[$i]="$!"
|
||||
done
|
||||
|
||||
cleanup() {
|
||||
for pid in "${pids[@]}"; do
|
||||
kill "$pid" 2>/dev/null || true
|
||||
done
|
||||
wait || true
|
||||
}
|
||||
trap cleanup EXIT INT TERM
|
||||
|
||||
for i in 0 1 2 3; do
|
||||
port="$(({{base_port}} + i))"
|
||||
for _ in $(seq 1 30); do
|
||||
if curl -fsS "http://127.0.0.1:$port" >/dev/null 2>&1; then
|
||||
break
|
||||
fi
|
||||
sleep 0.2
|
||||
done
|
||||
if ! curl -fsS "http://127.0.0.1:$port" >/dev/null 2>&1; then
|
||||
echo "Snake on :$port did not start correctly. Check logs in $LOG_DIR"
|
||||
exit 1
|
||||
fi
|
||||
done
|
||||
|
||||
BROWSER_FLAG=""
|
||||
if [ "{{browser}}" = "true" ]; then
|
||||
BROWSER_FLAG="--browser"
|
||||
fi
|
||||
|
||||
"$BATTLESNAKE_CLI" play -W 11 -H 11 \
|
||||
--name "Snake 1" --url "http://127.0.0.1:{{base_port}}" \
|
||||
--name "Snake 2" --url "http://127.0.0.1:$(({{base_port}} + 1))" \
|
||||
--name "Snake 3" --url "http://127.0.0.1:$(({{base_port}} + 2))" \
|
||||
--name "Snake 4" --url "http://127.0.0.1:$(({{base_port}} + 3))" \
|
||||
-g "{{mode}}" --map "{{map}}" --seed "{{seed}}" $BROWSER_FLAG
|
||||
|
||||
# ------------------------------------------------------------------------------
|
||||
# Fataset helpers
|
||||
@@ -52,3 +164,9 @@ test-seed:
|
||||
|
||||
export-dataset input="data" output="data/dataset/good_moves.jsonl":
|
||||
python -m server.DatasetExporter --input "{{input}}" --output "{{output}}"
|
||||
|
||||
curate-dataset input="good_moves-*.jsonl" output="data/dataset/best_moves.jsonl" min_turn="6" late_turn="20" max_safe_options="2" min_score="3" append="false" archive="false" archive_dir="":
|
||||
FLAGS=""; if [ "{{append}}" = "true" ]; then FLAGS="$FLAGS --append"; fi; if [ "{{archive}}" = "true" ]; then FLAGS="$FLAGS --archive-input"; fi; if [ -n "{{archive_dir}}" ]; then FLAGS="$FLAGS --archive-dir {{archive_dir}}"; fi; python -m server.DatasetCurator --input "{{input}}" --output "{{output}}" --min-turn "{{min_turn}}" --late-turn "{{late_turn}}" --max-safe-options "{{max_safe_options}}" --min-score "{{min_score}}" $FLAGS
|
||||
|
||||
analyze-dataset input="good_moves-*.jsonl" output="":
|
||||
if [ -n "{{output}}" ]; then python -m server.DatasetStats --input "{{input}}" --output "{{output}}"; else python -m server.DatasetStats --input "{{input}}"; fi
|
||||
|
||||
Submodule
+1
Submodule local-client added at 87e094e2e1
@@ -13,8 +13,9 @@
|
||||
# For more info see docs.battlesnake.com
|
||||
|
||||
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
|
||||
|
||||
# Start server when `python main.py` is run
|
||||
@@ -24,23 +25,7 @@ if __name__ == "__main__":
|
||||
"STORE_GAME_HISTORY": True,
|
||||
"DEBUG": True,
|
||||
"SNAKE": "TemplateSnake",
|
||||
"STORE_IF_WIN_AND_MOVES_ARE_BIGGER_AS": 10,
|
||||
})
|
||||
|
||||
server = Server(
|
||||
data_path=os.path.dirname(__file__),
|
||||
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)),
|
||||
)
|
||||
server = build_server_from_env(default_snake_type="TemplateSnake")
|
||||
asyncio.run(server.run(**build_run_config()))
|
||||
|
||||
@@ -5,6 +5,7 @@ description = "Add your description here"
|
||||
readme = "README.md"
|
||||
requires-python = ">=3.13"
|
||||
dependencies = [
|
||||
"aiologger>=0.7.0",
|
||||
"dotenv>=0.9.9",
|
||||
"gel>=3.1.0",
|
||||
"quart>=0.20.0",
|
||||
|
||||
Submodule
+1
Submodule quart_common added at 823560fdcd
@@ -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")
|
||||
+14
-3
@@ -16,12 +16,13 @@ class GameBoard:
|
||||
self.ruleset = ruleset
|
||||
self.map = map
|
||||
self.url = self._get_game_url(True if ruleset["version"] == "cli" else False)
|
||||
self.timeout = 500
|
||||
|
||||
# Setter Functions
|
||||
def _set_snakes(self, snakes:list[dict]):
|
||||
self.other_snakes = [ x for x in snakes if x["id"] != self.my_snake["id"] ]
|
||||
|
||||
def _set_my_snake(self, my_snake:str):
|
||||
def _set_my_snake(self, my_snake:dict):
|
||||
self.my_snake = my_snake
|
||||
|
||||
def _set_food(self, food:list[dict]):
|
||||
@@ -61,6 +62,15 @@ class GameBoard:
|
||||
def get_type(self):
|
||||
return self.type
|
||||
|
||||
def get_map(self):
|
||||
return self.map
|
||||
|
||||
def get_ruleset(self):
|
||||
return self.ruleset
|
||||
|
||||
def get_timeout(self):
|
||||
return self.timeout
|
||||
|
||||
def get_my_snake_head(self):
|
||||
return self.my_snake["head"]
|
||||
|
||||
@@ -79,8 +89,8 @@ class GameBoard:
|
||||
"width": self.width,
|
||||
"snakes": snakes,
|
||||
"food": self.food,
|
||||
"hazards": self.hazards
|
||||
}
|
||||
"hazards": self.hazards,
|
||||
}
|
||||
|
||||
# Game Functions
|
||||
def read_game_data(self, game_data:dict):
|
||||
@@ -91,6 +101,7 @@ class GameBoard:
|
||||
self._set_snakes(game_data['board']['snakes'])
|
||||
|
||||
self._set_turn(game_data["turn"])
|
||||
self.timeout = int(game_data.get('game', {}).get('timeout', 500))
|
||||
|
||||
async def start_game(self, game_data:dict):
|
||||
self.init_snakes = len(game_data['board']['snakes'])
|
||||
|
||||
+173
-40
@@ -1,6 +1,9 @@
|
||||
from server.Files import read_file
|
||||
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
|
||||
|
||||
@@ -8,9 +11,16 @@ from quart import Quart, request, jsonify
|
||||
import logging, json, os, re
|
||||
|
||||
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.snake_type = snake_type
|
||||
self.storage_type = storage_type
|
||||
@@ -20,124 +30,179 @@ class Server:
|
||||
self.check_tls_security = check_tls_security
|
||||
|
||||
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.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
|
||||
# and controls your Battlesnake's appearance
|
||||
# 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():
|
||||
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
|
||||
|
||||
# start is called when your Battlesnake begins a game
|
||||
@self.app.post("/start")
|
||||
@self.app.post('/start')
|
||||
async def on_start():
|
||||
game_state = await request.get_json()
|
||||
await self._create_game_board(game_state)
|
||||
print("GAME START:", game_state["game"])
|
||||
return "ok"
|
||||
await await_log(self.logger.info(f'GAME START: {game_state['game']}'))
|
||||
return 'ok'
|
||||
|
||||
# move is called when your Battlesnake game is running game
|
||||
@self.app.post("/move")
|
||||
@self.app.post('/move')
|
||||
async def on_move():
|
||||
game_state = await request.get_json()
|
||||
game_board = await self._get_game_board(game_state)
|
||||
next_move = game_board.snake_neat_make_a_move()
|
||||
|
||||
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
|
||||
@self.app.post("/end")
|
||||
@self.app.post('/end')
|
||||
async def on_end():
|
||||
game_state = await request.get_json()
|
||||
if self.store_game_state:
|
||||
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:
|
||||
await game_board.save(
|
||||
StorageLoader.build(self.storage_type),
|
||||
file_path=os.path.join(self.data_path, 'data'),
|
||||
database=os.getenv("EDGEDB_DATABASE", None),
|
||||
database=os.getenv('EDGEDB_DATABASE', None),
|
||||
tls_security=None
|
||||
)
|
||||
else:
|
||||
await game_board.save(
|
||||
StorageLoader.build(self.storage_type),
|
||||
file_path=os.path.join(self.data_path, 'data'),
|
||||
database=os.getenv("EDGEDB_DATABASE", None),
|
||||
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)
|
||||
return "ok"
|
||||
return 'ok'
|
||||
|
||||
@self.app.after_request
|
||||
async def identify_server(response):
|
||||
response.headers.set(
|
||||
"server", "battlesnake/gitea/snake-python"
|
||||
)
|
||||
response.headers.set('server', 'battlesnake/gitea/snake-python')
|
||||
return response
|
||||
|
||||
@self.app.get("/cleanup")
|
||||
@self.app.get('/cleanup')
|
||||
async def cleanup():
|
||||
results = self._cleanup_database()
|
||||
return jsonify(data=json.loads(results), status=200)
|
||||
|
||||
def run(self, host:str="0.0.0.0", port:str="8000", debug:bool=False):
|
||||
logging.getLogger("werkzeug").setLevel(logging.ERROR)
|
||||
@self.app.get('/metrics')
|
||||
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.run(host=host, port=port, debug=debug)
|
||||
@self.app.get('/metrics/prometheus')
|
||||
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):
|
||||
snake_config = await read_file(self.config_file, json.load)
|
||||
async def run(self, host:str='0.0.0.0', port:int=8000, debug:bool=False):
|
||||
logging.getLogger('werkzeug').setLevel(logging.ERROR)
|
||||
|
||||
await await_log(self.logger.info(f'Running Battlesnake at http://{host}:{port} with the {" ".join(re.findall("[A-Z][^A-Z]*", self.snake_type))}'))
|
||||
await self.app.run_task(host=host, port=port, debug=debug)
|
||||
|
||||
async def _read_json_config_or_create(self) -> dict[str, str]:
|
||||
snake_config = cast(dict[str, str]|None, await read_file(self.config_file, json.load))
|
||||
if not snake_config:
|
||||
return await self._override_snake_config_with_environment_variables(self.default_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]:
|
||||
for key in ("author", "color", "head", "tail"):
|
||||
value = os.environ.get(f"SNAKE_{key.upper()}")
|
||||
async def _override_snake_config_with_environment_variables(self, config:dict[str, str]) -> dict[str, str]:
|
||||
config['version'] = self.snake_version
|
||||
|
||||
for key in ('author', 'color', 'head', 'tail'):
|
||||
value = os.environ.get(f'SNAKE_{key.upper()}')
|
||||
if value is not None:
|
||||
config[key] = value
|
||||
|
||||
version_override = os.environ.get('SNAKE_VERSION')
|
||||
if version_override is not None:
|
||||
config['version'] = version_override
|
||||
|
||||
return config
|
||||
|
||||
def _get_snake_version(self) -> str:
|
||||
configured_version = SnakeBuilder.get_version(self.snake_type)
|
||||
if configured_version:
|
||||
return configured_version
|
||||
|
||||
try:
|
||||
snake = SnakeBuilder.build(self.snake_type)
|
||||
except Exception:
|
||||
return self.default_snake_config['version']
|
||||
|
||||
version = getattr(snake, 'version', None)
|
||||
if version is None:
|
||||
version = getattr(snake, 'VERSION', None)
|
||||
if not version:
|
||||
return self.default_snake_config['version']
|
||||
return str(version)
|
||||
|
||||
async def _create_game_board(self, game_state:dict):
|
||||
game_id = game_state['game']['id']
|
||||
new_game_board = GameBoard(
|
||||
game_id=game_state["game"]["id"],
|
||||
game_id=game_id,
|
||||
width=game_state['board']['width'],
|
||||
height=game_state['board']['height'],
|
||||
ruleset=game_state['game']["ruleset"],
|
||||
ruleset=game_state['game']['ruleset'],
|
||||
source=game_state['game']['source'],
|
||||
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)
|
||||
|
||||
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
|
||||
|
||||
def _delete_game_board(self, game_state):
|
||||
del self.running_games[game_state["game"]["id"]]
|
||||
def _delete_game_board(self, game_state:dict):
|
||||
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:
|
||||
game_board = self.running_games[game_state["game"]["id"]]
|
||||
game_board = self.running_games[game_id]
|
||||
except KeyError:
|
||||
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)
|
||||
if end:
|
||||
self._record_game_end(game_state)
|
||||
game_board.end_game(game_state)
|
||||
|
||||
return game_board
|
||||
@@ -148,3 +213,71 @@ class Server:
|
||||
def _cleanup_database(self):
|
||||
storage = StorageLoader.build(self.storage_type)()
|
||||
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 typing import Any, cast
|
||||
import random
|
||||
import os
|
||||
import random, os
|
||||
from time import perf_counter
|
||||
|
||||
from snakes.TemplateSnake import 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 = {
|
||||
"up": (0, 1),
|
||||
"down": (0, -1),
|
||||
@@ -23,12 +31,16 @@ class BestBattleSnake(TemplateSnake):
|
||||
def __init__(self):
|
||||
super().__init__()
|
||||
self.name = "BestBattleSnake"
|
||||
self.version = self.VERSION
|
||||
self.recent_heads = deque(maxlen=14)
|
||||
self.last_move = None
|
||||
self.last_game_id = None
|
||||
self.previous_hazards = set()
|
||||
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")
|
||||
if value is None:
|
||||
value = os.getenv("DUEL_STYLE", "balanced")
|
||||
@@ -38,7 +50,8 @@ class BestBattleSnake(TemplateSnake):
|
||||
return "balanced"
|
||||
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":
|
||||
return {
|
||||
"head_pressure": 0.65,
|
||||
@@ -57,16 +70,32 @@ class BestBattleSnake(TemplateSnake):
|
||||
"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.calculations = []
|
||||
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)
|
||||
turn = game_data.get_turn()
|
||||
if game_id != self.last_game_id or turn <= 1:
|
||||
self.recent_heads.clear()
|
||||
self.last_move = None
|
||||
self.previous_hazards = set()
|
||||
self.last_game_id = game_id
|
||||
|
||||
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}
|
||||
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"])
|
||||
|
||||
safe_moves = self._legal_moves(
|
||||
@@ -110,6 +149,7 @@ class BestBattleSnake(TemplateSnake):
|
||||
"reason": "no_safe_moves",
|
||||
}
|
||||
)
|
||||
self.previous_hazards = set(hazard_set)
|
||||
return fallback
|
||||
|
||||
enemy_attack_map = self._build_enemy_attack_map(
|
||||
@@ -119,6 +159,7 @@ class BestBattleSnake(TemplateSnake):
|
||||
is_constrictor=is_constrictor,
|
||||
width=width,
|
||||
height=height,
|
||||
enemy_can_grow_cache=enemy_can_grow_cache,
|
||||
)
|
||||
|
||||
if is_constrictor:
|
||||
@@ -129,12 +170,16 @@ class BestBattleSnake(TemplateSnake):
|
||||
other_snakes=other_snakes,
|
||||
food_set=food_set,
|
||||
enemy_attack_map=enemy_attack_map,
|
||||
enemy_heads=enemy_heads,
|
||||
enemy_can_grow_cache=enemy_can_grow_cache,
|
||||
width=width,
|
||||
height=height,
|
||||
deadline=deadline,
|
||||
)
|
||||
self.recent_heads.append(current_head_point)
|
||||
self.last_move = best_move
|
||||
self.add_to_history({"turn": turn, "move": best_move, "scores": scores})
|
||||
self.previous_hazards = set(hazard_set)
|
||||
return best_move
|
||||
|
||||
if len(other_snakes) == 1:
|
||||
@@ -143,23 +188,28 @@ class BestBattleSnake(TemplateSnake):
|
||||
my_body=my_body,
|
||||
my_len=my_len,
|
||||
my_health=my_health,
|
||||
foods=foods,
|
||||
food_set=food_set,
|
||||
hazards=hazards,
|
||||
hazard_set=hazard_set,
|
||||
other_snakes=other_snakes,
|
||||
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,
|
||||
height=height,
|
||||
deadline=deadline,
|
||||
)
|
||||
self.recent_heads.append(current_head_point)
|
||||
self.last_move = best_move
|
||||
self.add_to_history({"turn": turn, "move": best_move, "scores": scores})
|
||||
self.previous_hazards = set(hazard_set)
|
||||
return best_move
|
||||
|
||||
scores: dict[str, float] = {}
|
||||
move_safety: dict[str, dict[str, Any]] = {}
|
||||
scores:dict[str, float] = {}
|
||||
move_safety:dict[str, dict[str, Any]] = {}
|
||||
for move, pos in safe_moves.items():
|
||||
if self._time_exceeded(deadline):
|
||||
break
|
||||
point = (pos["x"], pos["y"])
|
||||
ate_food = point in food_set
|
||||
|
||||
@@ -169,6 +219,7 @@ class BestBattleSnake(TemplateSnake):
|
||||
other_snakes=other_snakes,
|
||||
food_set=food_set,
|
||||
is_constrictor=is_constrictor,
|
||||
enemy_can_grow_cache=enemy_can_grow_cache,
|
||||
)
|
||||
blocked.discard(point)
|
||||
|
||||
@@ -180,17 +231,13 @@ class BestBattleSnake(TemplateSnake):
|
||||
)
|
||||
territory = self._territory_control_score(
|
||||
my_start=point,
|
||||
enemy_starts=[
|
||||
(snake["head"]["x"], snake["head"]["y"]) for snake in other_snakes
|
||||
],
|
||||
enemy_starts=enemy_heads,
|
||||
blocked=blocked,
|
||||
width=width,
|
||||
height=height,
|
||||
)
|
||||
|
||||
nearest_food_dist = self._nearest_food_distance(
|
||||
point, foods, blocked, width, height
|
||||
)
|
||||
nearest_food_dist = self._nearest_food_distance(point, food_set, blocked, width, height)
|
||||
future_tail = future_body[-1]
|
||||
tail_point = (future_tail["x"], future_tail["y"])
|
||||
tail_dist = self._path_distance(
|
||||
@@ -242,7 +289,9 @@ class BestBattleSnake(TemplateSnake):
|
||||
score -= 40.0
|
||||
|
||||
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)
|
||||
|
||||
@@ -256,8 +305,9 @@ class BestBattleSnake(TemplateSnake):
|
||||
score -= 20.0
|
||||
|
||||
health_after_move = 100 if ate_food else my_health - 1
|
||||
if point in hazard_set:
|
||||
health_after_move -= 15
|
||||
hazard_active = self._hazard_is_active(point, ate_food, hazard_set, previous_hazard_set)
|
||||
if hazard_active:
|
||||
health_after_move -= hazard_damage
|
||||
if health_after_move <= 0:
|
||||
score -= 10000.0
|
||||
|
||||
@@ -274,6 +324,18 @@ class BestBattleSnake(TemplateSnake):
|
||||
|
||||
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 = [
|
||||
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.last_move = best_move
|
||||
self.add_to_history({"turn": turn, "move": best_move, "scores": scores})
|
||||
self.previous_hazards = set(hazard_set)
|
||||
return best_move
|
||||
|
||||
def _choose_duel_move(
|
||||
self,
|
||||
safe_moves,
|
||||
my_body,
|
||||
my_len,
|
||||
my_health,
|
||||
foods,
|
||||
food_set,
|
||||
hazards,
|
||||
hazard_set,
|
||||
other_snakes,
|
||||
enemy_attack_map,
|
||||
width,
|
||||
height,
|
||||
):
|
||||
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]]:
|
||||
"""Score and select a move for one-vs-one games."""
|
||||
duel_weights = self._duel_weights(self.duel_style)
|
||||
enemy = other_snakes[0]
|
||||
enemy_head = (enemy["head"]["x"], enemy["head"]["y"])
|
||||
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] = {}
|
||||
move_safety: dict[str, dict[str, Any]] = {}
|
||||
scores:dict[str, float] = {}
|
||||
move_safety:dict[str, dict[str, Any]] = {}
|
||||
|
||||
for move, pos in safe_moves.items():
|
||||
if self._time_exceeded(deadline):
|
||||
break
|
||||
point = (pos["x"], pos["y"])
|
||||
ate_food = point in food_set
|
||||
|
||||
@@ -342,6 +396,7 @@ class BestBattleSnake(TemplateSnake):
|
||||
other_snakes=other_snakes,
|
||||
food_set=food_set,
|
||||
is_constrictor=False,
|
||||
enemy_can_grow_cache=enemy_can_grow_cache,
|
||||
)
|
||||
blocked.discard(point)
|
||||
|
||||
@@ -352,9 +407,7 @@ class BestBattleSnake(TemplateSnake):
|
||||
future_body, blocked, width, height
|
||||
)
|
||||
|
||||
nearest_food_dist = self._nearest_food_distance(
|
||||
point, foods, blocked, width, height
|
||||
)
|
||||
nearest_food_dist = self._nearest_food_distance(point, food_set, blocked, width, height)
|
||||
future_tail = future_body[-1]
|
||||
tail_point = (future_tail["x"], future_tail["y"])
|
||||
tail_dist = self._path_distance(
|
||||
@@ -380,6 +433,7 @@ class BestBattleSnake(TemplateSnake):
|
||||
enemy_attack_len is not None and enemy_attack_len >= my_len
|
||||
)
|
||||
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 += reachable_space * 2.8
|
||||
@@ -393,7 +447,16 @@ class BestBattleSnake(TemplateSnake):
|
||||
if losing_head_to_head:
|
||||
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:
|
||||
score += 220.0 * duel_weights["head_pressure"]
|
||||
elif direct_head_distance == 2:
|
||||
@@ -401,6 +464,8 @@ class BestBattleSnake(TemplateSnake):
|
||||
else:
|
||||
if direct_head_distance <= 2:
|
||||
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)
|
||||
if nearest_food_dist is not None:
|
||||
@@ -420,7 +485,9 @@ class BestBattleSnake(TemplateSnake):
|
||||
score -= 50.0
|
||||
|
||||
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)
|
||||
|
||||
@@ -434,8 +501,9 @@ class BestBattleSnake(TemplateSnake):
|
||||
score -= 20.0
|
||||
|
||||
health_after_move = 100 if ate_food else my_health - 1
|
||||
if point in hazard_set:
|
||||
health_after_move -= 15
|
||||
hazard_active = self._hazard_is_active(point, ate_food, hazard_set, previous_hazard_set)
|
||||
if hazard_active:
|
||||
health_after_move -= hazard_damage
|
||||
if health_after_move <= 0:
|
||||
score -= 10000.0
|
||||
|
||||
@@ -472,27 +540,23 @@ class BestBattleSnake(TemplateSnake):
|
||||
else:
|
||||
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)
|
||||
top_moves = [
|
||||
move for move in considered_moves if best_score - scores[move] <= 1.5
|
||||
]
|
||||
return random.choice(top_moves), scores
|
||||
|
||||
def _choose_constrictor_move(
|
||||
self,
|
||||
safe_moves,
|
||||
my_body,
|
||||
my_len,
|
||||
other_snakes,
|
||||
food_set,
|
||||
enemy_attack_map,
|
||||
width,
|
||||
height,
|
||||
):
|
||||
scores: dict[str, float] = {}
|
||||
move_safety: dict[str, dict[str, Any]] = {}
|
||||
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]]:
|
||||
"""Score and select a move for constrictor games."""
|
||||
scores:dict[str, float] = {}
|
||||
move_safety:dict[str, dict[str, Any]] = {}
|
||||
|
||||
for move, pos in safe_moves.items():
|
||||
if self._time_exceeded(deadline):
|
||||
break
|
||||
point = (pos["x"], pos["y"])
|
||||
future_body = self._future_body(
|
||||
my_body, pos, ate_food=False, is_constrictor=True
|
||||
@@ -502,6 +566,7 @@ class BestBattleSnake(TemplateSnake):
|
||||
other_snakes=other_snakes,
|
||||
food_set=food_set,
|
||||
is_constrictor=True,
|
||||
enemy_can_grow_cache=enemy_can_grow_cache,
|
||||
)
|
||||
blocked.discard(point)
|
||||
|
||||
@@ -513,9 +578,13 @@ class BestBattleSnake(TemplateSnake):
|
||||
)
|
||||
territory = self._territory_control_score(
|
||||
my_start=point,
|
||||
enemy_starts=[
|
||||
(snake["head"]["x"], snake["head"]["y"]) for snake in other_snakes
|
||||
],
|
||||
enemy_starts=enemy_heads,
|
||||
blocked=blocked,
|
||||
width=width,
|
||||
height=height,
|
||||
)
|
||||
enemy_best_space, enemy_total_options = self._enemy_constrictor_projection(
|
||||
other_snakes=other_snakes,
|
||||
blocked=blocked,
|
||||
width=width,
|
||||
height=height,
|
||||
@@ -533,6 +602,13 @@ class BestBattleSnake(TemplateSnake):
|
||||
score += liberties * 24.0
|
||||
score += next_options * 16.0
|
||||
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:
|
||||
score -= 2600.0
|
||||
@@ -577,22 +653,24 @@ class BestBattleSnake(TemplateSnake):
|
||||
else:
|
||||
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)
|
||||
top_moves = [
|
||||
move for move in considered_moves if best_score - scores[move] <= 2.0
|
||||
]
|
||||
return random.choice(top_moves), scores
|
||||
|
||||
def _legal_moves(
|
||||
self, my_head, my_body, other_snakes, food_set, is_constrictor, width, height
|
||||
):
|
||||
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:
|
||||
"""Return legal immediate moves after body, wall, and tail checks."""
|
||||
occupied = self._occupied_cells(my_body, other_snakes)
|
||||
own_tail = (my_body[-1]["x"], my_body[-1]["y"])
|
||||
own_tail_stacked = self._is_tail_stacked(my_body)
|
||||
|
||||
safe_moves = {}
|
||||
for move, pos in self.get_possible_moves(my_head).items():
|
||||
point = (pos["x"], pos["y"])
|
||||
for move, (dx, dy) in self.DIRECTIONS.items():
|
||||
point = (my_head["x"] + dx, my_head["y"] + dy)
|
||||
if not self._in_bounds(point, width, height):
|
||||
continue
|
||||
|
||||
@@ -608,17 +686,19 @@ class BestBattleSnake(TemplateSnake):
|
||||
if point in occupied and not can_step_on_tail:
|
||||
continue
|
||||
|
||||
safe_moves[move] = pos
|
||||
safe_moves[move] = {"x": point[0], "y": point[1]}
|
||||
|
||||
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}
|
||||
for snake in other_snakes:
|
||||
occupied |= {(segment["x"], segment["y"]) for segment in snake["body"]}
|
||||
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}
|
||||
|
||||
if not is_constrictor and not self._is_tail_stacked(future_body):
|
||||
@@ -632,7 +712,13 @@ class BestBattleSnake(TemplateSnake):
|
||||
if is_constrictor:
|
||||
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
|
||||
|
||||
if self._is_tail_stacked(snake["body"]):
|
||||
@@ -643,20 +729,26 @@ class BestBattleSnake(TemplateSnake):
|
||||
|
||||
return blocked
|
||||
|
||||
def _build_enemy_attack_map(
|
||||
self, my_snake, other_snakes, food_set, is_constrictor, width, height
|
||||
):
|
||||
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:
|
||||
"""Map cells enemies can contest next turn to their effective length."""
|
||||
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 = {}
|
||||
|
||||
for enemy in other_snakes:
|
||||
enemy_len = enemy.get("length", len(enemy["body"]))
|
||||
enemy_tail = (enemy["body"][-1]["x"], enemy["body"][-1]["y"])
|
||||
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():
|
||||
point = (pos["x"], pos["y"])
|
||||
enemy_head = enemy["head"]
|
||||
for dx, dy in self.DIRECTIONS.values():
|
||||
point = (enemy_head["x"] + dx, enemy_head["y"] + dy)
|
||||
if not self._in_bounds(point, width, height):
|
||||
continue
|
||||
|
||||
@@ -664,18 +756,14 @@ class BestBattleSnake(TemplateSnake):
|
||||
not is_constrictor
|
||||
and point == enemy_tail
|
||||
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:
|
||||
continue
|
||||
|
||||
# Do not consider impossible overlap directly into my own occupied body except head swap possibilities.
|
||||
if point in {
|
||||
(segment["x"], segment["y"])
|
||||
for segment in my_snake["body"]
|
||||
if my_snake["id"] == my_id
|
||||
}:
|
||||
if point in my_body_points:
|
||||
continue
|
||||
|
||||
previous = attack_map.get(point)
|
||||
@@ -684,7 +772,8 @@ class BestBattleSnake(TemplateSnake):
|
||||
|
||||
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.extend(current_body)
|
||||
|
||||
@@ -694,9 +783,8 @@ class BestBattleSnake(TemplateSnake):
|
||||
next_body.pop()
|
||||
return next_body
|
||||
|
||||
def _can_step_on_own_tail(
|
||||
self, point, own_tail, own_tail_is_stacked, ate_food, is_constrictor
|
||||
):
|
||||
def _can_step_on_own_tail(self, point:Point, own_tail:Point, own_tail_is_stacked:bool, ate_food:bool, is_constrictor:bool) -> bool:
|
||||
"""Return whether stepping onto our tail is allowed this turn."""
|
||||
if is_constrictor:
|
||||
return False
|
||||
if ate_food:
|
||||
@@ -705,29 +793,60 @@ class BestBattleSnake(TemplateSnake):
|
||||
return False
|
||||
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:
|
||||
return False
|
||||
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"]
|
||||
for dx, dy in self.DIRECTIONS.values():
|
||||
if (head["x"] + dx, head["y"] + dy) in food_set:
|
||||
return True
|
||||
return False
|
||||
|
||||
def _nearest_food_distance(self, start, foods, blocked, width, height):
|
||||
if not foods:
|
||||
return None
|
||||
def _hazard_damage_per_turn(self, game_data:dict) -> int:
|
||||
"""Read royale hazard damage from ruleset settings.
|
||||
|
||||
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)])
|
||||
seen = {start}
|
||||
|
||||
while queue:
|
||||
point, distance = queue.popleft()
|
||||
if point in targets:
|
||||
if point in food_set:
|
||||
return distance
|
||||
|
||||
for neighbor in self._neighbors(point):
|
||||
@@ -735,14 +854,15 @@ class BestBattleSnake(TemplateSnake):
|
||||
continue
|
||||
if not self._in_bounds(neighbor, width, height):
|
||||
continue
|
||||
if neighbor in blocked and neighbor not in targets:
|
||||
if neighbor in blocked and neighbor not in food_set:
|
||||
continue
|
||||
seen.add(neighbor)
|
||||
queue.append((neighbor, distance + 1))
|
||||
|
||||
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)])
|
||||
seen = {start}
|
||||
|
||||
@@ -763,7 +883,8 @@ class BestBattleSnake(TemplateSnake):
|
||||
|
||||
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])
|
||||
seen = {start}
|
||||
|
||||
@@ -781,7 +902,8 @@ class BestBattleSnake(TemplateSnake):
|
||||
|
||||
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
|
||||
for neighbor in self._neighbors(start):
|
||||
if not self._in_bounds(neighbor, width, height):
|
||||
@@ -791,14 +913,15 @@ class BestBattleSnake(TemplateSnake):
|
||||
count += 1
|
||||
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:
|
||||
return 0
|
||||
|
||||
next_head = future_body[0]
|
||||
count = 0
|
||||
for pos in self.get_possible_moves(next_head).values():
|
||||
point = (pos["x"], pos["y"])
|
||||
for dx, dy in self.DIRECTIONS.values():
|
||||
point = (next_head["x"] + dx, next_head["y"] + dy)
|
||||
if not self._in_bounds(point, width, height):
|
||||
continue
|
||||
if point in blocked:
|
||||
@@ -806,7 +929,10 @@ class BestBattleSnake(TemplateSnake):
|
||||
count += 1
|
||||
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
|
||||
for index, old_point in enumerate(reversed(self.recent_heads), start=1):
|
||||
if old_point != point:
|
||||
@@ -814,7 +940,8 @@ class BestBattleSnake(TemplateSnake):
|
||||
penalty += max(0.0, 18.0 - index * 2.0)
|
||||
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:
|
||||
return 0
|
||||
|
||||
@@ -849,7 +976,8 @@ class BestBattleSnake(TemplateSnake):
|
||||
|
||||
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)])
|
||||
distances = {start: 0}
|
||||
|
||||
@@ -867,19 +995,60 @@ class BestBattleSnake(TemplateSnake):
|
||||
|
||||
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():
|
||||
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])
|
||||
|
||||
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
|
||||
|
||||
def _fallback_move(self, head, width, height):
|
||||
for move, pos in self.get_possible_moves(head).items():
|
||||
point = (pos["x"], pos["y"])
|
||||
def _fallback_move(self, head:Coord, width:int, height:int) -> str:
|
||||
"""Pick the first in-bounds move as emergency fallback."""
|
||||
for move, (dx, dy) in self.DIRECTIONS.items():
|
||||
point = (head["x"] + dx, head["y"] + dy)
|
||||
if self._in_bounds(point, width, height):
|
||||
return move
|
||||
return "up"
|
||||
|
||||
+201
-198
@@ -3,219 +3,222 @@ from server.GameBoard import GameBoard
|
||||
from collections import deque
|
||||
|
||||
class BetterMasterSnake(TemplateSnake):
|
||||
def __init__(self):
|
||||
super().__init__()
|
||||
self.name = "BetterMasterSnake"
|
||||
# Definiere die möglichen Bewegungsrichtungen
|
||||
self.min_safe_area = 2
|
||||
VERSION = "1.3.0"
|
||||
|
||||
def choose_move(self, game_data:GameBoard):
|
||||
self.game_board = game_data
|
||||
self.calculations = []
|
||||
self.eat_the_snake_overwrite = False
|
||||
def __init__(self):
|
||||
super().__init__()
|
||||
self.name = "BetterMasterSnake"
|
||||
self.version = self.VERSION
|
||||
# Definiere die möglichen Bewegungsrichtungen
|
||||
self.min_safe_area = 2
|
||||
|
||||
self.safe_positions = self.find_safe_positions(add_to_calculations=True)
|
||||
if self.eat_the_snake_overwrite:
|
||||
return self.overwrite_eat_the_other_snake(game_data.get_turn())
|
||||
def choose_move(self, game_data:GameBoard):
|
||||
self.game_board = game_data
|
||||
self.calculations = []
|
||||
self.eat_the_snake_overwrite = False
|
||||
|
||||
if game_data.get_type() == "constrictor":
|
||||
move = self.selected_move_constrictor()
|
||||
self.safe_positions = self.find_safe_positions(add_to_calculations=True)
|
||||
if self.eat_the_snake_overwrite:
|
||||
return self.overwrite_eat_the_other_snake(game_data.get_turn())
|
||||
|
||||
if game_data.get_type() == "constrictor":
|
||||
move = self.selected_move_constrictor()
|
||||
else:
|
||||
move = self.selected_move_standard()
|
||||
|
||||
self.add_to_history({"turn": game_data.get_turn(), "data": self.calculations})
|
||||
return move if move else "up"
|
||||
|
||||
def overwrite_eat_the_other_snake(self, turn:int):
|
||||
self.add_calculations({"function": "eat_the_snake_overwrite", "my_head": self.game_board.get_my_snake_head(), "move": self.kill_the_snake, "safe_positions": self.safe_positions})
|
||||
self.add_to_history({"turn": turn, "data": self.calculations})
|
||||
return self.kill_the_snake
|
||||
|
||||
#TODO: How to Fill the Gameboard best?
|
||||
def selected_move_constrictor(self):
|
||||
move = self.move_close_to_body()
|
||||
self.add_calculations({"function": "move_close_to_body", "my_head": self.game_board.get_my_snake_head(), "move": move})
|
||||
move = self.ensure_escape_route(move)
|
||||
self.add_calculations({"function": "ensure_escape_route", "my_head": self.game_board.get_my_snake_head(), "move": move, "safe_positions": self.safe_positions})
|
||||
return move
|
||||
|
||||
def selected_move_standard(self, move=None):
|
||||
# Finde den besten Weg zur Nahrung
|
||||
path_to_food = self.find_path_to_food()
|
||||
if path_to_food:
|
||||
move = self.move_towards(path_to_food[0])
|
||||
self.add_calculations({"function": "move_towards", "my_head": self.game_board.get_my_snake_head(), "path_to_food": path_to_food, "move": move})
|
||||
|
||||
if not move or self.would_eating_the_food_kill_the_snake(move):
|
||||
move = self.move_close_to_body(move_close_to_tail=True)
|
||||
self.add_calculations({"function": "move_close_to_body", "my_head": self.game_board.get_my_snake_head(), "move": move})
|
||||
|
||||
# Überprfe, ob der Zug einen Ausweg lässt
|
||||
move = self.ensure_escape_route(move)
|
||||
self.add_calculations({"function": "ensure_escape_route", "my_head": self.game_board.get_my_snake_head(), "move": move, "safe_positions": self.safe_positions})
|
||||
return move
|
||||
|
||||
def find_path_to_food(self):
|
||||
# Exclude own snake's body from obstacles
|
||||
obstacles = set((part['x'], part['y']) for part in self.game_board.get_my_snake_body())
|
||||
|
||||
for snake in self.game_board.get_other_snakes():
|
||||
for part in snake['body']:
|
||||
obstacles.add((part['x'], part['y']))
|
||||
|
||||
other_snakes_other_snake_posible_moves_set = {(d['x'], d['y']) for d in self.other_snake_posible_moves}
|
||||
removed_elements_set = set([(elem['x'], elem['y']) for elem in self.game_board.get_food() if (elem['x'], elem['y']) in other_snakes_other_snake_posible_moves_set])
|
||||
obstacles |= removed_elements_set
|
||||
|
||||
self.food_positions = [elem for elem in self.game_board.get_food() if (elem['x'], elem['y']) not in other_snakes_other_snake_posible_moves_set]
|
||||
|
||||
if len(self.food_positions) > 0:
|
||||
# Choose the closest food source based on the heuristic
|
||||
closest_food = min(self.food_positions, key=lambda food: abs(food['x'] - self.game_board.get_my_snake_head()['x']) + abs(food['y'] - self.game_board.get_my_snake_head()['y']))
|
||||
self.set_target_food(closest_food)
|
||||
|
||||
# Use A* to search for a safe path
|
||||
return self.a_star_search(self.game_board.get_my_snake_head(), closest_food, obstacles)
|
||||
return None
|
||||
|
||||
def find_path_to_tail(self):
|
||||
# Exclude other snake's body from obstacles
|
||||
obstacles = set((part['x'], part['y']) for part in self.game_board.get_my_snake_body())
|
||||
for snake in self.game_board.get_other_snakes():
|
||||
for part in snake['body']:
|
||||
obstacles.add((part['x'], part['y']))
|
||||
|
||||
my_snake_tail = {"x": self.game_board.get_my_snake_tail()['x'], "y": self.game_board.get_my_snake_tail()['y']}
|
||||
|
||||
# Use A* to search for a safe path
|
||||
path = self.a_star_search(self.game_board.get_my_snake_head(), my_snake_tail, obstacles)
|
||||
return path
|
||||
|
||||
def move_towards(self, target):
|
||||
best_direction = None
|
||||
min_distance = float('inf')
|
||||
for direction, coords in self.safe_positions.items():
|
||||
distance = abs(target['x'] - coords['x']) + abs(target['y'] - coords['y'])
|
||||
if distance < min_distance:
|
||||
min_distance = distance
|
||||
best_direction = direction
|
||||
|
||||
return best_direction if best_direction else "up"
|
||||
|
||||
def move_close_to_body(self, move_close_to_tail=False):
|
||||
# Heuristik, um Positionen nahe dem eigenen Körper zu bevorzugen
|
||||
body_positions = set((part['x'], part['y']) for part in self.game_board.get_my_snake_body())
|
||||
tail_position = (self.game_board.get_my_snake_tail()['x'], self.game_board.get_my_snake_tail()['y'])
|
||||
|
||||
best_move = None
|
||||
max_distance = -1 # Initialize maximum distance
|
||||
for direction, pos in self.safe_positions.items():
|
||||
next_position = (pos['x'], pos['y'])
|
||||
if next_position in self.safe_positions:
|
||||
# Berechne die Distanz zum eigenen Körper
|
||||
distance_to_body = min(abs(next_position[0] - part[0]) + abs(next_position[1] - part[1]) for part in body_positions)
|
||||
# Berechne die Distanz zum eigenen Schwanz
|
||||
distance_to_tail = abs(next_position[0] - tail_position[0]) + abs(next_position[1] - tail_position[1])
|
||||
# Wähle die maximale Distanz (Körper oder Schwanz)
|
||||
if move_close_to_tail:
|
||||
distance = min(next_position, distance_to_tail)
|
||||
else:
|
||||
move = self.selected_move_standard()
|
||||
distance = max(next_position, distance_to_body)
|
||||
# Update max_distance if a larger distance is found
|
||||
if distance > max_distance:
|
||||
max_distance = distance
|
||||
best_move = direction
|
||||
return best_move if best_move else "up" # Standardbewegung, falls keine bessere gefunden wird
|
||||
|
||||
self.add_to_history({"turn": game_data.get_turn(), "data": self.calculations})
|
||||
return move if move else "up"
|
||||
#TODO: Neat to Implement Function to check if eating the food would kill the snake?
|
||||
def would_eating_the_food_kill_the_snake(self, move:str):
|
||||
return False
|
||||
|
||||
def overwrite_eat_the_other_snake(self, turn:int):
|
||||
self.add_calculations({"function": "eat_the_snake_overwrite", "my_head": self.game_board.get_my_snake_head(), "move": self.kill_the_snake, "safe_positions": self.safe_positions})
|
||||
self.add_to_history({"turn": turn, "data": self.calculations})
|
||||
return self.kill_the_snake
|
||||
def ensure_escape_route(self, move:str):
|
||||
try:
|
||||
future_position = self.safe_positions[move]
|
||||
except KeyError:
|
||||
for move, pos in self.safe_positions.items():
|
||||
if self.is_near_tail(pos, (self.game_board.get_my_snake_tail()['x'], self.game_board.get_my_snake_tail()['y'])):
|
||||
self.add_calculations({"function": "ensure_escape_route", "move": move, "is_near_tail": True})
|
||||
move = self.move_towards(pos)
|
||||
return move
|
||||
else:
|
||||
path_to_tail = self.find_path_to_tail()
|
||||
if path_to_tail:
|
||||
self.add_calculations({"function": "move_towards", "my_head": self.game_board.get_my_snake_head(), "path_to_tail": path_to_tail, "move": move})
|
||||
move = self.move_towards(path_to_tail[0])
|
||||
|
||||
#TODO: How to Fill the Gameboard best?
|
||||
def selected_move_constrictor(self):
|
||||
move = self.move_close_to_body()
|
||||
self.add_calculations({"function": "move_close_to_body", "my_head": self.game_board.get_my_snake_head(), "move": move})
|
||||
move = self.ensure_escape_route(move)
|
||||
self.add_calculations({"function": "ensure_escape_route", "my_head": self.game_board.get_my_snake_head(), "move": move, "safe_positions": self.safe_positions})
|
||||
return move
|
||||
self.add_calculations({"function": "ensure_escape_route", "move": move, "KeyError": "Snake Coild itself up"})
|
||||
#return move
|
||||
|
||||
def selected_move_standard(self, move=None):
|
||||
# Finde den besten Weg zur Nahrung
|
||||
path_to_food = self.find_path_to_food()
|
||||
if path_to_food:
|
||||
move = self.move_towards(path_to_food[0])
|
||||
self.add_calculations({"function": "move_towards", "my_head": self.game_board.get_my_snake_head(), "path_to_food": path_to_food, "move": move})
|
||||
# TODO: Fix - Snake Neat to find the best way - Close to the Tail and maybe fill most free cells as posible
|
||||
return move
|
||||
|
||||
if not move or self.would_eating_the_food_kill_the_snake(move):
|
||||
move = self.move_close_to_body(move_close_to_tail=True)
|
||||
self.add_calculations({"function": "move_close_to_body", "my_head": self.game_board.get_my_snake_head(), "move": move})
|
||||
def is_near_tail(self, position, tail):
|
||||
return abs(position["x"] - tail[0]) + abs(position["y"] - tail[1]) <= 2
|
||||
|
||||
# Überprfe, ob der Zug einen Ausweg lässt
|
||||
move = self.ensure_escape_route(move)
|
||||
self.add_calculations({"function": "ensure_escape_route", "my_head": self.game_board.get_my_snake_head(), "move": move, "safe_positions": self.safe_positions})
|
||||
return move
|
||||
def a_star_search(self, start, goal, obstacles):
|
||||
# Helper functions
|
||||
def is_position_safe(position):
|
||||
return 0 <= position['x'] < self.game_board.get_width() and 0 <= position['y'] < self.game_board.get_height() and (position['x'], position['y']) not in obstacles
|
||||
|
||||
def find_path_to_food(self):
|
||||
# Exclude own snake's body from obstacles
|
||||
obstacles = set((part['x'], part['y']) for part in self.game_board.get_my_snake_body())
|
||||
def get_neighbors(position):
|
||||
neighbors = []
|
||||
for dx, dy in [(-1, 0), (1, 0), (0, -1), (0, 1)]: # links, rechts, oben, unten
|
||||
neighbor = {'x': position['x'] + dx, 'y': position['y'] + dy}
|
||||
if is_position_safe(neighbor):
|
||||
neighbors.append(neighbor)
|
||||
return neighbors
|
||||
|
||||
for snake in self.game_board.get_other_snakes():
|
||||
for part in snake['body']:
|
||||
obstacles.add((part['x'], part['y']))
|
||||
def heuristic(position, goal):
|
||||
# Verwenden Sie eine Heuristik, die immer positiv ist, selbst wenn das Ziel in der Nähe ist
|
||||
return max(abs(position['x'] - goal['x']), abs(position['y'] - goal['y']))
|
||||
|
||||
other_snakes_other_snake_posible_moves_set = {(d['x'], d['y']) for d in self.other_snake_posible_moves}
|
||||
removed_elements_set = set([(elem['x'], elem['y']) for elem in self.game_board.get_food() if (elem['x'], elem['y']) in other_snakes_other_snake_posible_moves_set])
|
||||
obstacles |= removed_elements_set
|
||||
# Überprüfen, ob das Ziel direkt neben dem Startpunkt liegt
|
||||
if start == goal or (abs(start['x'] - goal['x']) <= 1 and abs(start['y'] - goal['y']) <= 1):
|
||||
# Wenn das Ziel neben dem Startpunkt liegt, ist der Pfad das Ziel selbst
|
||||
return [goal]
|
||||
|
||||
self.food_positions = [elem for elem in self.game_board.get_food() if (elem['x'], elem['y']) not in other_snakes_other_snake_posible_moves_set]
|
||||
# Initialize the open and closed list
|
||||
open_set = set([(start['x'], start['y'])])
|
||||
came_from = {}
|
||||
g_score = {(start['x'], start['y']): 0}
|
||||
f_score = {(start['x'], start['y']): heuristic(start, goal)}
|
||||
|
||||
if len(self.food_positions) > 0:
|
||||
# Choose the closest food source based on the heuristic
|
||||
closest_food = min(self.food_positions, key=lambda food: abs(food['x'] - self.game_board.get_my_snake_head()['x']) + abs(food['y'] - self.game_board.get_my_snake_head()['y']))
|
||||
self.set_target_food(closest_food)
|
||||
while open_set:
|
||||
current = min(open_set, key=lambda pos: f_score.get(pos, float('inf')))
|
||||
current_dict = {'x': current[0], 'y': current[1]}
|
||||
if current_dict == goal:
|
||||
# Reconstruct the path
|
||||
path = []
|
||||
while current in came_from:
|
||||
current = came_from[current]
|
||||
path.append({'x': current[0], 'y': current[1]})
|
||||
path.reverse()
|
||||
if path and path[0] == start:
|
||||
path.pop(0) # Entferne das erste Element, wenn es dem Start entspricht
|
||||
return path # Return the path as a list of dicts
|
||||
|
||||
# Use A* to search for a safe path
|
||||
return self.a_star_search(self.game_board.get_my_snake_head(), closest_food, obstacles)
|
||||
return None
|
||||
open_set.remove(current)
|
||||
for neighbor in get_neighbors(current_dict):
|
||||
neighbor_tuple = (neighbor['x'], neighbor['y'])
|
||||
tentative_g_score = g_score[current] + 1 # Distance between neighbors is always 1
|
||||
if tentative_g_score < g_score.get(neighbor_tuple, float('inf')):
|
||||
came_from[neighbor_tuple] = current
|
||||
g_score[neighbor_tuple] = tentative_g_score
|
||||
f_score[neighbor_tuple] = g_score[neighbor_tuple] + heuristic(neighbor, goal)
|
||||
if neighbor_tuple not in open_set:
|
||||
open_set.add(neighbor_tuple)
|
||||
|
||||
def find_path_to_tail(self):
|
||||
# Exclude other snake's body from obstacles
|
||||
obstacles = set((part['x'], part['y']) for part in self.game_board.get_my_snake_body())
|
||||
for snake in self.game_board.get_other_snakes():
|
||||
for part in snake['body']:
|
||||
obstacles.add((part['x'], part['y']))
|
||||
return None # Kein Pfad gefunden
|
||||
|
||||
my_snake_tail = {"x": self.game_board.get_my_snake_tail()['x'], "y": self.game_board.get_my_snake_tail()['y']}
|
||||
|
||||
# Use A* to search for a safe path
|
||||
path = self.a_star_search(self.game_board.get_my_snake_head(), my_snake_tail, obstacles)
|
||||
return path
|
||||
|
||||
def move_towards(self, target):
|
||||
best_direction = None
|
||||
min_distance = float('inf')
|
||||
for direction, coords in self.safe_positions.items():
|
||||
distance = abs(target['x'] - coords['x']) + abs(target['y'] - coords['y'])
|
||||
if distance < min_distance:
|
||||
min_distance = distance
|
||||
best_direction = direction
|
||||
|
||||
return best_direction if best_direction else "up"
|
||||
|
||||
def move_close_to_body(self, move_close_to_tail=False):
|
||||
# Heuristik, um Positionen nahe dem eigenen Körper zu bevorzugen
|
||||
body_positions = set((part['x'], part['y']) for part in self.game_board.get_my_snake_body())
|
||||
tail_position = (self.game_board.get_my_snake_tail()['x'], self.game_board.get_my_snake_tail()['y'])
|
||||
|
||||
best_move = None
|
||||
max_distance = -1 # Initialize maximum distance
|
||||
for direction, pos in self.safe_positions.items():
|
||||
next_position = (pos['x'], pos['y'])
|
||||
if next_position in self.safe_positions:
|
||||
# Berechne die Distanz zum eigenen Körper
|
||||
distance_to_body = min(abs(next_position[0] - part[0]) + abs(next_position[1] - part[1]) for part in body_positions)
|
||||
# Berechne die Distanz zum eigenen Schwanz
|
||||
distance_to_tail = abs(next_position[0] - tail_position[0]) + abs(next_position[1] - tail_position[1])
|
||||
# Wähle die maximale Distanz (Körper oder Schwanz)
|
||||
if move_close_to_tail:
|
||||
distance = min(next_position, distance_to_tail)
|
||||
else:
|
||||
distance = max(next_position, distance_to_body)
|
||||
# Update max_distance if a larger distance is found
|
||||
if distance > max_distance:
|
||||
max_distance = distance
|
||||
best_move = direction
|
||||
return best_move if best_move else "up" # Standardbewegung, falls keine bessere gefunden wird
|
||||
|
||||
#TODO: Neat to Implement Function to check if eating the food would kill the snake?
|
||||
def would_eating_the_food_kill_the_snake(self, move:str):
|
||||
return False
|
||||
|
||||
def ensure_escape_route(self, move:str):
|
||||
try:
|
||||
future_position = self.safe_positions[move]
|
||||
except KeyError:
|
||||
for move, pos in self.safe_positions.items():
|
||||
if self.is_near_tail(pos, (self.game_board.get_my_snake_tail()['x'], self.game_board.get_my_snake_tail()['y'])):
|
||||
self.add_calculations({"function": "ensure_escape_route", "move": move, "is_near_tail": True})
|
||||
move = self.move_towards(pos)
|
||||
return move
|
||||
else:
|
||||
path_to_tail = self.find_path_to_tail()
|
||||
if path_to_tail:
|
||||
self.add_calculations({"function": "move_towards", "my_head": self.game_board.get_my_snake_head(), "path_to_tail": path_to_tail, "move": move})
|
||||
move = self.move_towards(path_to_tail[0])
|
||||
|
||||
self.add_calculations({"function": "ensure_escape_route", "move": move, "KeyError": "Snake Coild itself up"})
|
||||
#return move
|
||||
|
||||
# TODO: Fix - Snake Neat to find the best way - Close to the Tail and maybe fill most free cells as posible
|
||||
return move
|
||||
|
||||
def is_near_tail(self, position, tail):
|
||||
return abs(position["x"] - tail[0]) + abs(position["y"] - tail[1]) <= 2
|
||||
|
||||
def a_star_search(self, start, goal, obstacles):
|
||||
# Helper functions
|
||||
def is_position_safe(position):
|
||||
return 0 <= position['x'] < self.game_board.get_width() and 0 <= position['y'] < self.game_board.get_height() and (position['x'], position['y']) not in obstacles
|
||||
|
||||
def get_neighbors(position):
|
||||
neighbors = []
|
||||
for dx, dy in [(-1, 0), (1, 0), (0, -1), (0, 1)]: # links, rechts, oben, unten
|
||||
neighbor = {'x': position['x'] + dx, 'y': position['y'] + dy}
|
||||
if is_position_safe(neighbor):
|
||||
neighbors.append(neighbor)
|
||||
return neighbors
|
||||
|
||||
def heuristic(position, goal):
|
||||
# Verwenden Sie eine Heuristik, die immer positiv ist, selbst wenn das Ziel in der Nähe ist
|
||||
return max(abs(position['x'] - goal['x']), abs(position['y'] - goal['y']))
|
||||
|
||||
# Überprüfen, ob das Ziel direkt neben dem Startpunkt liegt
|
||||
if start == goal or (abs(start['x'] - goal['x']) <= 1 and abs(start['y'] - goal['y']) <= 1):
|
||||
# Wenn das Ziel neben dem Startpunkt liegt, ist der Pfad das Ziel selbst
|
||||
return [goal]
|
||||
|
||||
# Initialize the open and closed list
|
||||
open_set = set([(start['x'], start['y'])])
|
||||
came_from = {}
|
||||
g_score = {(start['x'], start['y']): 0}
|
||||
f_score = {(start['x'], start['y']): heuristic(start, goal)}
|
||||
|
||||
while open_set:
|
||||
current = min(open_set, key=lambda pos: f_score.get(pos, float('inf')))
|
||||
current_dict = {'x': current[0], 'y': current[1]}
|
||||
if current_dict == goal:
|
||||
# Reconstruct the path
|
||||
path = []
|
||||
while current in came_from:
|
||||
current = came_from[current]
|
||||
path.append({'x': current[0], 'y': current[1]})
|
||||
path.reverse()
|
||||
if path and path[0] == start:
|
||||
path.pop(0) # Entferne das erste Element, wenn es dem Start entspricht
|
||||
return path # Return the path as a list of dicts
|
||||
|
||||
open_set.remove(current)
|
||||
for neighbor in get_neighbors(current_dict):
|
||||
neighbor_tuple = (neighbor['x'], neighbor['y'])
|
||||
tentative_g_score = g_score[current] + 1 # Distance between neighbors is always 1
|
||||
if tentative_g_score < g_score.get(neighbor_tuple, float('inf')):
|
||||
came_from[neighbor_tuple] = current
|
||||
g_score[neighbor_tuple] = tentative_g_score
|
||||
f_score[neighbor_tuple] = g_score[neighbor_tuple] + heuristic(neighbor, goal)
|
||||
if neighbor_tuple not in open_set:
|
||||
open_set.add(neighbor_tuple)
|
||||
|
||||
return None # Kein Pfad gefunden
|
||||
|
||||
def find_direction(self):
|
||||
# Beispielhafte Logik zur Auswahl einer Bewegungsrichtung
|
||||
for direction, pos in self.safe_positions.items():
|
||||
next_position = (pos['x'], pos['y'])
|
||||
# Konvertiere safe_positions in eine Liste von Tupeln für den Vergleich
|
||||
safe_positions_tuples = [(pos['x'], pos['y']) for pos in self.safe_positions.values()]
|
||||
if next_position in safe_positions_tuples:
|
||||
return direction
|
||||
return "up" # Standardbewegung, falls keine sichere Position gefunden wird
|
||||
def find_direction(self):
|
||||
# Beispielhafte Logik zur Auswahl einer Bewegungsrichtung
|
||||
for direction, pos in self.safe_positions.items():
|
||||
next_position = (pos['x'], pos['y'])
|
||||
# Konvertiere safe_positions in eine Liste von Tupeln für den Vergleich
|
||||
safe_positions_tuples = [(pos['x'], pos['y']) for pos in self.safe_positions.values()]
|
||||
if next_position in safe_positions_tuples:
|
||||
return direction
|
||||
return "up" # Standardbewegung, falls keine sichere Position gefunden wird
|
||||
|
||||
+38
-36
@@ -3,53 +3,55 @@ from snakes.TemplateSnake import TemplateSnake
|
||||
import random
|
||||
|
||||
class DummSnake(TemplateSnake):
|
||||
def choose_move(self, data: dict) -> str:
|
||||
is_move_safe = {"up": True, "down": True, "left": True, "right": True}
|
||||
VERSION = "1.0.0"
|
||||
|
||||
# We've included code to prevent your Battlesnake from moving backwards
|
||||
my_head = data["you"]["body"][0] # Coordinates of your head
|
||||
my_neck = data["you"]["body"][1] # Coordinates of your "neck"
|
||||
def choose_move(self, data: dict) -> str:
|
||||
is_move_safe = {"up": True, "down": True, "left": True, "right": True}
|
||||
|
||||
if my_neck["x"] < my_head["x"]: # Neck is left of head, don't move left
|
||||
is_move_safe["left"] = False
|
||||
# We've included code to prevent your Battlesnake from moving backwards
|
||||
my_head = data["you"]["body"][0] # Coordinates of your head
|
||||
my_neck = data["you"]["body"][1] # Coordinates of your "neck"
|
||||
|
||||
elif my_neck["x"] > my_head["x"]: # Neck is right of head, don't move right
|
||||
is_move_safe["right"] = False
|
||||
if my_neck["x"] < my_head["x"]: # Neck is left of head, don't move left
|
||||
is_move_safe["left"] = False
|
||||
|
||||
elif my_neck["y"] < my_head["y"]: # Neck is below head, don't move down
|
||||
is_move_safe["down"] = False
|
||||
elif my_neck["x"] > my_head["x"]: # Neck is right of head, don't move right
|
||||
is_move_safe["right"] = False
|
||||
|
||||
elif my_neck["y"] > my_head["y"]: # Neck is above head, don't move up
|
||||
is_move_safe["up"] = False
|
||||
elif my_neck["y"] < my_head["y"]: # Neck is below head, don't move down
|
||||
is_move_safe["down"] = False
|
||||
|
||||
# TODO: Step 1 - Prevent your Battlesnake from moving out of bounds
|
||||
# board_width = game_state['board']['width']
|
||||
# board_height = game_state['board']['height']
|
||||
elif my_neck["y"] > my_head["y"]: # Neck is above head, don't move up
|
||||
is_move_safe["up"] = False
|
||||
|
||||
# TODO: Step 2 - Prevent your Battlesnake from colliding with itself
|
||||
# my_body = game_state['you']['body']
|
||||
# TODO: Step 1 - Prevent your Battlesnake from moving out of bounds
|
||||
# board_width = game_state['board']['width']
|
||||
# board_height = game_state['board']['height']
|
||||
|
||||
# TODO: Step 3 - Prevent your Battlesnake from colliding with other Battlesnakes
|
||||
# opponents = game_state['board']['snakes']
|
||||
# TODO: Step 2 - Prevent your Battlesnake from colliding with itself
|
||||
# my_body = game_state['you']['body']
|
||||
|
||||
# Are there any safe moves left?
|
||||
safe_moves = []
|
||||
for move, isSafe in is_move_safe.items():
|
||||
if isSafe:
|
||||
safe_moves.append(move)
|
||||
# TODO: Step 3 - Prevent your Battlesnake from colliding with other Battlesnakes
|
||||
# opponents = game_state['board']['snakes']
|
||||
|
||||
if len(safe_moves) == 0:
|
||||
print(f"MOVE {data['turn']}: No safe moves detected! Moving down")
|
||||
self.add_to_history({"my_head": my_head, "my_neck": my_neck, "move": move, "safe_moves": safe_moves, "is_move_safe": is_move_safe})
|
||||
return {"move": "down"}
|
||||
# Are there any safe moves left?
|
||||
safe_moves = []
|
||||
for move, isSafe in is_move_safe.items():
|
||||
if isSafe:
|
||||
safe_moves.append(move)
|
||||
|
||||
# Choose a random move from the safe ones
|
||||
move = random.choice(safe_moves)
|
||||
if len(safe_moves) == 0:
|
||||
print(f"MOVE {data['turn']}: No safe moves detected! Moving down")
|
||||
self.add_to_history({"my_head": my_head, "my_neck": my_neck, "move": move, "safe_moves": safe_moves, "is_move_safe": is_move_safe})
|
||||
return {"move": "down"}
|
||||
|
||||
# TODO: Step 4 - Move towards food instead of random, to regain health and survive longer
|
||||
# food = game_state['board']['food']
|
||||
# Choose a random move from the safe ones
|
||||
move = random.choice(safe_moves)
|
||||
|
||||
self.add_to_history({"my_head": my_head, "my_neck": my_neck, "move": move, "safe_moves": safe_moves, "is_move_safe": is_move_safe})
|
||||
print(f"{data['game']['id']} MOVE {data['turn']}: {move} picked from all valid options in {is_move_safe}")
|
||||
# TODO: Step 4 - Move towards food instead of random, to regain health and survive longer
|
||||
# food = game_state['board']['food']
|
||||
|
||||
return move
|
||||
self.add_to_history({"my_head": my_head, "my_neck": my_neck, "move": move, "safe_moves": safe_moves, "is_move_safe": is_move_safe})
|
||||
print(f"{data['game']['id']} MOVE {data['turn']}: {move} picked from all valid options in {is_move_safe}")
|
||||
|
||||
return move
|
||||
|
||||
@@ -4,6 +4,8 @@ import random
|
||||
from scipy import spatial
|
||||
|
||||
class LogicSnake(TemplateSnake):
|
||||
VERSION = "1.1.0"
|
||||
|
||||
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.
|
||||
|
||||
+211
-208
@@ -1,246 +1,249 @@
|
||||
from snakes.TemplateSnake import TemplateSnake
|
||||
|
||||
class MasterSnake(TemplateSnake):
|
||||
def __init__(self):
|
||||
super().__init__()
|
||||
self.name = "MasterSnake"
|
||||
self.disabled_find_near_by_food = True
|
||||
VERSION = "1.2.0"
|
||||
|
||||
def is_food_nearby(self, head, food_positions):
|
||||
for food in food_positions:
|
||||
if abs(head['x'] - food['x']) <= 1 and abs(head['y'] - food['y']) <= 1:
|
||||
return True
|
||||
return False
|
||||
def __init__(self):
|
||||
super().__init__()
|
||||
self.name = "MasterSnake"
|
||||
self.version = self.VERSION
|
||||
self.disabled_find_near_by_food = True
|
||||
|
||||
def avoid_snake_body(self, snakes, board_width, board_height):
|
||||
# Konvertiere die Körperpositionen der Schlangen in ein Set von Tupeln für schnellen Zugriff
|
||||
body_positions = set()
|
||||
for snake in snakes:
|
||||
for part in snake['body']:
|
||||
body_positions.add((part['x'], part['y']))
|
||||
def is_food_nearby(self, head, food_positions):
|
||||
for food in food_positions:
|
||||
if abs(head['x'] - food['x']) <= 1 and abs(head['y'] - food['y']) <= 1:
|
||||
return True
|
||||
return False
|
||||
|
||||
# Implementiere die Logik, um Positionen zu finden, die nicht von Schlangenkörpern belegt sind
|
||||
safe_positions = self.find_safe_positions(body_positions, board_width, board_height)
|
||||
return safe_positions
|
||||
def avoid_snake_body(self, snakes, board_width, board_height):
|
||||
# Konvertiere die Körperpositionen der Schlangen in ein Set von Tupeln für schnellen Zugriff
|
||||
body_positions = set()
|
||||
for snake in snakes:
|
||||
for part in snake['body']:
|
||||
body_positions.add((part['x'], part['y']))
|
||||
|
||||
def find_safe_positions(self, body_positions, board_width, board_height):
|
||||
# Finde sichere Positionen basierend auf den Körperpositionen und der Größe des Spielbretts
|
||||
safe_positions = []
|
||||
for x in range(board_width): # Nutze die tatsächliche Breite des Spielbretts
|
||||
for y in range(board_height): # Nutze die tatsächliche Höhe des Spielbretts
|
||||
if (x, y) not in body_positions:
|
||||
safe_positions.append({'x': x, 'y': y})
|
||||
return safe_positions
|
||||
# Implementiere die Logik, um Positionen zu finden, die nicht von Schlangenkörpern belegt sind
|
||||
safe_positions = self.find_safe_positions(body_positions, board_width, board_height)
|
||||
return safe_positions
|
||||
|
||||
def choose_move(self, game_data):
|
||||
board_width = game_data['board']['width']
|
||||
board_height = game_data['board']['height']
|
||||
snakes = game_data['board']['snakes']
|
||||
my_snake = game_data['you']
|
||||
my_head = my_snake['head']
|
||||
def find_safe_positions(self, body_positions, board_width, board_height):
|
||||
# Finde sichere Positionen basierend auf den Körperpositionen und der Größe des Spielbretts
|
||||
safe_positions = []
|
||||
for x in range(board_width): # Nutze die tatsächliche Breite des Spielbretts
|
||||
for y in range(board_height): # Nutze die tatsächliche Höhe des Spielbretts
|
||||
if (x, y) not in body_positions:
|
||||
safe_positions.append({'x': x, 'y': y})
|
||||
return safe_positions
|
||||
|
||||
# Vermeide Schlangenkörper
|
||||
safe_positions = self.avoid_snake_body(snakes, board_width, board_height)
|
||||
def choose_move(self, game_data):
|
||||
board_width = game_data['board']['width']
|
||||
board_height = game_data['board']['height']
|
||||
snakes = game_data['board']['snakes']
|
||||
my_snake = game_data['you']
|
||||
my_head = my_snake['head']
|
||||
|
||||
# Finde die nächstgelegene Nahrungsquelle, wenn Nahrung vorhanden ist
|
||||
try:
|
||||
if self.is_food_nearby(my_head, game_data['board']['food']) or self.disabled_find_near_by_food:
|
||||
path_to_food = self.find_path_to_food(game_data)
|
||||
if path_to_food:
|
||||
# Implementiere Logik, um in Richtung der Nahrungsquelle zu bewegen, falls sicher
|
||||
move = self.move_towards(my_head, path_to_food[0], safe_positions)
|
||||
self.add_to_history({"my_head": my_head, "path_to_food": path_to_food, "move": move})
|
||||
else:
|
||||
# Einfache Logik, um eine Bewegungsrichtung zu wählen, wenn keine Nahrung vorhanden ist
|
||||
move = self.find_direction(my_head, safe_positions)
|
||||
self.add_to_history({"my_head": my_head, "move": move})
|
||||
else:
|
||||
# Wenn keine Nahrung in der Nähe ist, bewege dich in eine Richtung, die dich nahe an deinem eigenen Körper hält
|
||||
move = self.find_direction(my_head, safe_positions)
|
||||
self.add_to_history({"my_head": my_head, "move": move})
|
||||
except ValueError:
|
||||
move = self.find_direction(my_head, safe_positions)
|
||||
self.add_to_history({"my_head": my_head, "move": move})
|
||||
# Vermeide Schlangenkörper
|
||||
safe_positions = self.avoid_snake_body(snakes, board_width, board_height)
|
||||
|
||||
# Finde den größten sicheren Bereich
|
||||
max_area_start, max_area = self.flood_fill(my_head, safe_positions)
|
||||
# Wenn der Schwanz der Schlange im größten sicheren Bereich liegt, bewege dich in Richtung des Schwanzes
|
||||
my_tail = (my_snake['body'][-1]['x'], my_snake['body'][-1]['y']) # Convert to tuple
|
||||
if my_tail in max_area:
|
||||
move = self.move_towards(my_head, my_tail, safe_positions)
|
||||
|
||||
# Überprüfe zukünftige Bewegungen, um Sackgassen zu vermeiden
|
||||
move = self.avoid_dead_ends(my_head, move, safe_positions, snakes)
|
||||
# Finde die nächstgelegene Nahrungsquelle, wenn Nahrung vorhanden ist
|
||||
try:
|
||||
if self.is_food_nearby(my_head, game_data['board']['food']) or self.disabled_find_near_by_food:
|
||||
path_to_food = self.find_path_to_food(game_data)
|
||||
if path_to_food:
|
||||
# Implementiere Logik, um in Richtung der Nahrungsquelle zu bewegen, falls sicher
|
||||
move = self.move_towards(my_head, path_to_food[0], safe_positions)
|
||||
self.add_to_history({"my_head": my_head, "path_to_food": path_to_food, "move": move})
|
||||
else:
|
||||
# Einfache Logik, um eine Bewegungsrichtung zu wählen, wenn keine Nahrung vorhanden ist
|
||||
move = self.find_direction(my_head, safe_positions)
|
||||
self.add_to_history({"my_head": my_head, "move": move})
|
||||
else:
|
||||
# Wenn keine Nahrung in der Nähe ist, bewege dich in eine Richtung, die dich nahe an deinem eigenen Körper hält
|
||||
move = self.find_direction(my_head, safe_positions)
|
||||
self.add_to_history({"my_head": my_head, "move": move})
|
||||
except ValueError:
|
||||
move = self.find_direction(my_head, safe_positions)
|
||||
self.add_to_history({"my_head": my_head, "move": move})
|
||||
|
||||
return move
|
||||
# Finde den größten sicheren Bereich
|
||||
max_area_start, max_area = self.flood_fill(my_head, safe_positions)
|
||||
# Wenn der Schwanz der Schlange im größten sicheren Bereich liegt, bewege dich in Richtung des Schwanzes
|
||||
my_tail = (my_snake['body'][-1]['x'], my_snake['body'][-1]['y']) # Convert to tuple
|
||||
if my_tail in max_area:
|
||||
move = self.move_towards(my_head, my_tail, safe_positions)
|
||||
|
||||
def move_towards(self, head, target, safe_positions):
|
||||
directions = {'up': (0, 1), 'down': (0, -1), 'left': (-1, 0), 'right': (1, 0)}
|
||||
best_direction = None
|
||||
min_distance = float('inf')
|
||||
min_distance_to_body = float('inf')
|
||||
body_positions = set((pos['x'], pos['y']) for pos in safe_positions[:-1]) # Exclude the head from body positions
|
||||
# Überprüfe zukünftige Bewegungen, um Sackgassen zu vermeiden
|
||||
move = self.avoid_dead_ends(my_head, move, safe_positions, snakes)
|
||||
self.add_to_history({"my_head": my_head, "move": move})
|
||||
|
||||
for direction, (dx, dy) in directions.items():
|
||||
next_position = {'x': head['x'] + dx, 'y': head['y'] + dy}
|
||||
if next_position in safe_positions:
|
||||
distance = abs(target[0] - next_position['x']) + abs(target[1] - next_position['y'])
|
||||
distance_to_body = sum(abs(part[0] - next_position['x']) + abs(part[1] - next_position['y']) for part in body_positions)
|
||||
if distance < min_distance or (distance == min_distance and distance_to_body < min_distance_to_body):
|
||||
best_direction = direction
|
||||
min_distance = distance
|
||||
min_distance_to_body = distance_to_body
|
||||
return move
|
||||
|
||||
return best_direction if best_direction else "up" # Default to moving up if no safe direction found
|
||||
def move_towards(self, head, target, safe_positions):
|
||||
directions = {'up': (0, 1), 'down': (0, -1), 'left': (-1, 0), 'right': (1, 0)}
|
||||
best_direction = None
|
||||
min_distance = float('inf')
|
||||
min_distance_to_body = float('inf')
|
||||
body_positions = set((pos['x'], pos['y']) for pos in safe_positions[:-1]) # Exclude the head from body positions
|
||||
|
||||
def find_path_to_food(self, game_data):
|
||||
my_head = game_data['you']['head']
|
||||
food_positions = game_data['board']['food']
|
||||
snakes = game_data['board']['snakes']
|
||||
board_width = game_data['board']['width']
|
||||
board_height = game_data['board']['height']
|
||||
|
||||
# Exclude own snake's body from obstacles
|
||||
own_snake_body = game_data['you']['body']
|
||||
obstacles = set((part['x'], part['y']) for part in own_snake_body)
|
||||
|
||||
for snake in snakes:
|
||||
if snake['id'] != game_data['you']['id']:
|
||||
for part in snake['body']:
|
||||
obstacles.add((part['x'], part['y']))
|
||||
|
||||
# Choose the closest food source based on the heuristic
|
||||
closest_food = min(food_positions, key=lambda food: abs(food['x'] - my_head['x']) + abs(food['y'] - my_head['y']))
|
||||
|
||||
# Use A* to search for a safe path
|
||||
path = self.a_star_search(my_head, closest_food, obstacles, board_width, board_height)
|
||||
return path
|
||||
for direction, (dx, dy) in directions.items():
|
||||
next_position = {'x': head['x'] + dx, 'y': head['y'] + dy}
|
||||
if next_position in safe_positions:
|
||||
distance = abs(target[0] - next_position['x']) + abs(target[1] - next_position['y'])
|
||||
distance_to_body = sum(abs(part[0] - next_position['x']) + abs(part[1] - next_position['y']) for part in body_positions)
|
||||
if distance < min_distance or (distance == min_distance and distance_to_body < min_distance_to_body):
|
||||
best_direction = direction
|
||||
min_distance = distance
|
||||
min_distance_to_body = distance_to_body
|
||||
|
||||
def a_star_search(self, start, goal, obstacles, board_width, board_height):
|
||||
# Convert snake positions into a set of obstacles
|
||||
# Helper functions
|
||||
def is_position_safe(position):
|
||||
x, y = position
|
||||
return 0 <= x < board_width and 0 <= y < board_height and position not in obstacles
|
||||
return best_direction if best_direction else "up" # Default to moving up if no safe direction found
|
||||
|
||||
def get_neighbors(position):
|
||||
x, y = position
|
||||
return [(nx, ny) for nx, ny in [(x-1, y), (x+1, y), (x, y-1), (x, y+1)] if is_position_safe((nx, ny))]
|
||||
def find_path_to_food(self, game_data):
|
||||
my_head = game_data['you']['head']
|
||||
food_positions = game_data['board']['food']
|
||||
snakes = game_data['board']['snakes']
|
||||
board_width = game_data['board']['width']
|
||||
board_height = game_data['board']['height']
|
||||
|
||||
# Exclude own snake's body from obstacles
|
||||
own_snake_body = game_data['you']['body']
|
||||
obstacles = set((part['x'], part['y']) for part in own_snake_body)
|
||||
|
||||
for snake in snakes:
|
||||
if snake['id'] != game_data['you']['id']:
|
||||
for part in snake['body']:
|
||||
obstacles.add((part['x'], part['y']))
|
||||
|
||||
# Choose the closest food source based on the heuristic
|
||||
closest_food = min(food_positions, key=lambda food: abs(food['x'] - my_head['x']) + abs(food['y'] - my_head['y']))
|
||||
|
||||
# Use A* to search for a safe path
|
||||
path = self.a_star_search(my_head, closest_food, obstacles, board_width, board_height)
|
||||
return path
|
||||
|
||||
def heuristic(position, goal):
|
||||
return abs(position[0] - goal[0]) + abs(position[1] - goal[1])
|
||||
def a_star_search(self, start, goal, obstacles, board_width, board_height):
|
||||
# Convert snake positions into a set of obstacles
|
||||
# Helper functions
|
||||
def is_position_safe(position):
|
||||
x, y = position
|
||||
return 0 <= x < board_width and 0 <= y < board_height and position not in obstacles
|
||||
|
||||
# Initialize start and goal positions
|
||||
start = (start['x'], start['y'])
|
||||
goal = (goal['x'], goal['y'])
|
||||
def get_neighbors(position):
|
||||
x, y = position
|
||||
return [(nx, ny) for nx, ny in [(x-1, y), (x+1, y), (x, y-1), (x, y+1)] if is_position_safe((nx, ny))]
|
||||
|
||||
# Initialize the open and closed list
|
||||
open_set = set([start])
|
||||
came_from = {}
|
||||
g_score = {start: 0}
|
||||
f_score = {start: heuristic(start, goal)}
|
||||
def heuristic(position, goal):
|
||||
return abs(position[0] - goal[0]) + abs(position[1] - goal[1])
|
||||
|
||||
while open_set:
|
||||
current = min(open_set, key=lambda pos: f_score.get(pos, float('inf')))
|
||||
if current == goal:
|
||||
# Reconstruct the path
|
||||
path = []
|
||||
while current in came_from:
|
||||
path.append(current)
|
||||
current = came_from[current]
|
||||
path.reverse()
|
||||
return path # Return the path as a list of tuples
|
||||
# Initialize start and goal positions
|
||||
start = (start['x'], start['y'])
|
||||
goal = (goal['x'], goal['y'])
|
||||
|
||||
open_set.remove(current)
|
||||
for neighbor in get_neighbors(current):
|
||||
tentative_g_score = g_score[current] + 1 # Distance between neighbors is always 1
|
||||
if tentative_g_score < g_score.get(neighbor, float('inf')):
|
||||
came_from[neighbor] = current
|
||||
g_score[neighbor] = tentative_g_score
|
||||
f_score[neighbor] = g_score[neighbor] + heuristic(neighbor, goal)
|
||||
if neighbor not in open_set:
|
||||
open_set.add(neighbor)
|
||||
# Initialize the open and closed list
|
||||
open_set = set([start])
|
||||
came_from = {}
|
||||
g_score = {start: 0}
|
||||
f_score = {start: heuristic(start, goal)}
|
||||
|
||||
return None # Kein Pfad gefunden
|
||||
while open_set:
|
||||
current = min(open_set, key=lambda pos: f_score.get(pos, float('inf')))
|
||||
if current == goal:
|
||||
# Reconstruct the path
|
||||
path = []
|
||||
while current in came_from:
|
||||
path.append(current)
|
||||
current = came_from[current]
|
||||
path.reverse()
|
||||
return path # Return the path as a list of tuples
|
||||
|
||||
def find_direction(self, head, safe_positions):
|
||||
# Beispielhafte Logik zur Auswahl einer Bewegungsrichtung
|
||||
directions = {'up': (0, 1), 'down': (0, -1), 'left': (-1, 0), 'right': (1, 0)}
|
||||
for direction, (dx, dy) in directions.items():
|
||||
next_position = {'x': head['x'] + dx, 'y': head['y'] + dy}
|
||||
if next_position in safe_positions:
|
||||
return direction
|
||||
return "up" # Standardbewegung, falls keine sichere Position gefunden wird
|
||||
open_set.remove(current)
|
||||
for neighbor in get_neighbors(current):
|
||||
tentative_g_score = g_score[current] + 1 # Distance between neighbors is always 1
|
||||
if tentative_g_score < g_score.get(neighbor, float('inf')):
|
||||
came_from[neighbor] = current
|
||||
g_score[neighbor] = tentative_g_score
|
||||
f_score[neighbor] = g_score[neighbor] + heuristic(neighbor, goal)
|
||||
if neighbor not in open_set:
|
||||
open_set.add(neighbor)
|
||||
|
||||
def avoid_self_collision(self, future_head, body_positions):
|
||||
# Überprüft, ob die zukünftige Kopfposition im Körper der Schlange liegt
|
||||
return (future_head['x'], future_head['y']) not in body_positions
|
||||
return None # Kein Pfad gefunden
|
||||
|
||||
def avoid_dead_ends(self, head, move, safe_positions, snakes):
|
||||
directions = {'up': (0, 1), 'down': (0, -1), 'left': (-1, 0), 'right': (1, 0)}
|
||||
dx, dy = directions[move]
|
||||
future_head = {'x': head['x'] + dx, 'y': head['y'] + dy}
|
||||
body_positions = set((part['x'], part['y']) for part in snakes[0]['body'])
|
||||
def find_direction(self, head, safe_positions):
|
||||
# Beispielhafte Logik zur Auswahl einer Bewegungsrichtung
|
||||
directions = {'up': (0, 1), 'down': (0, -1), 'left': (-1, 0), 'right': (1, 0)}
|
||||
for direction, (dx, dy) in directions.items():
|
||||
next_position = {'x': head['x'] + dx, 'y': head['y'] + dy}
|
||||
if next_position in safe_positions:
|
||||
return direction
|
||||
return "up" # Standardbewegung, falls keine sichere Position gefunden wird
|
||||
|
||||
if not self.is_future_move_safe(future_head, safe_positions, snakes) or not self.avoid_self_collision(future_head, body_positions):
|
||||
for alternative_move in directions.keys():
|
||||
dx, dy = directions[alternative_move]
|
||||
alternative_future_head = {'x': head['x'] + dx, 'y': head['y'] + dy}
|
||||
if self.is_future_move_safe(alternative_future_head, safe_positions, snakes) and self.avoid_self_collision(alternative_future_head, body_positions):
|
||||
return alternative_move
|
||||
return move
|
||||
def avoid_self_collision(self, future_head, body_positions):
|
||||
# Überprüft, ob die zukünftige Kopfposition im Körper der Schlange liegt
|
||||
return (future_head['x'], future_head['y']) not in body_positions
|
||||
|
||||
def simulate_snake_movement(self, snakes):
|
||||
future_body_positions = set()
|
||||
for snake in snakes:
|
||||
# Beachte, dass dies nur ein Beispiel ist und angepasst werden muss, um deine spezifische Spiellogik zu berücksichtigen
|
||||
for part in snake['body'][:-1]: # Ignoriere den letzten Teil des Körpers, da er sich bewegt
|
||||
future_body_positions.add((part['x'], part['y']))
|
||||
return future_body_positions
|
||||
def avoid_dead_ends(self, head, move, safe_positions, snakes):
|
||||
directions = {'up': (0, 1), 'down': (0, -1), 'left': (-1, 0), 'right': (1, 0)}
|
||||
dx, dy = directions[move]
|
||||
future_head = {'x': head['x'] + dx, 'y': head['y'] + dy}
|
||||
body_positions = set((part['x'], part['y']) for part in snakes[0]['body'])
|
||||
|
||||
def is_future_move_safe(self, future_head, safe_positions, snakes):
|
||||
# Simuliere die Bewegung der Schlange und aktualisiere die Positionen des eigenen Körpers
|
||||
future_body_positions = self.simulate_snake_movement(snakes)
|
||||
# Konvertiere safe_positions in ein Set von Tupeln für den Flood Fill Algorithmus
|
||||
safe_positions_set = set((pos['x'], pos['y']) for pos in safe_positions)
|
||||
# Entferne die zukünftigen Körperpositionen aus den sicheren Positionen
|
||||
safe_positions_set = safe_positions_set - future_body_positions
|
||||
# Füge die zukünftige Kopfposition hinzu, um sie als Startpunkt zu verwenden
|
||||
safe_positions_set.add((future_head['x'], future_head['y']))
|
||||
# Berechne die Anzahl der erreichbaren sicheren Positionen von der zukünftigen Kopfposition aus
|
||||
reachable_positions = self.flood_fill((future_head['x'], future_head['y']), safe_positions_set)
|
||||
# Entscheide, ob die Bewegung sicher ist, basierend auf der Anzahl der erreichbaren Positionen
|
||||
if not self.is_future_move_safe(future_head, safe_positions, snakes) or not self.avoid_self_collision(future_head, body_positions):
|
||||
for alternative_move in directions.keys():
|
||||
dx, dy = directions[alternative_move]
|
||||
alternative_future_head = {'x': head['x'] + dx, 'y': head['y'] + dy}
|
||||
if self.is_future_move_safe(alternative_future_head, safe_positions, snakes) and self.avoid_self_collision(alternative_future_head, body_positions):
|
||||
return alternative_move
|
||||
return move
|
||||
|
||||
fill_bool = len(reachable_positions) > len(safe_positions_set) * 0.25
|
||||
if fill_bool:
|
||||
return fill_bool
|
||||
def simulate_snake_movement(self, snakes):
|
||||
future_body_positions = set()
|
||||
for snake in snakes:
|
||||
# Beachte, dass dies nur ein Beispiel ist und angepasst werden muss, um deine spezifische Spiellogik zu berücksichtigen
|
||||
for part in snake['body'][:-1]: # Ignoriere den letzten Teil des Körpers, da er sich bewegt
|
||||
future_body_positions.add((part['x'], part['y']))
|
||||
return future_body_positions
|
||||
|
||||
return len(safe_positions_set) >= len(snakes[0]['body'])
|
||||
def is_future_move_safe(self, future_head, safe_positions, snakes):
|
||||
# Simuliere die Bewegung der Schlange und aktualisiere die Positionen des eigenen Körpers
|
||||
future_body_positions = self.simulate_snake_movement(snakes)
|
||||
# Konvertiere safe_positions in ein Set von Tupeln für den Flood Fill Algorithmus
|
||||
safe_positions_set = set((pos['x'], pos['y']) for pos in safe_positions)
|
||||
# Entferne die zukünftigen Körperpositionen aus den sicheren Positionen
|
||||
safe_positions_set = safe_positions_set - future_body_positions
|
||||
# Füge die zukünftige Kopfposition hinzu, um sie als Startpunkt zu verwenden
|
||||
safe_positions_set.add((future_head['x'], future_head['y']))
|
||||
# Berechne die Anzahl der erreichbaren sicheren Positionen von der zukünftigen Kopfposition aus
|
||||
reachable_positions = self.flood_fill((future_head['x'], future_head['y']), safe_positions_set)
|
||||
# Entscheide, ob die Bewegung sicher ist, basierend auf der Anzahl der erreichbaren Positionen
|
||||
|
||||
def flood_fill(self, start, safe_positions):
|
||||
stack = [start]
|
||||
visited = set()
|
||||
max_area = 0
|
||||
max_area_start = None
|
||||
fill_bool = len(reachable_positions) > len(safe_positions_set) * 0.25
|
||||
if fill_bool:
|
||||
return fill_bool
|
||||
|
||||
while stack:
|
||||
position = stack.pop()
|
||||
if isinstance(position, dict):
|
||||
position = tuple(position.values())
|
||||
else:
|
||||
position = tuple(position)
|
||||
return len(safe_positions_set) >= len(snakes[0]['body'])
|
||||
|
||||
if position not in visited:
|
||||
visited.add(position)
|
||||
for dx, dy in [(-1, 0), (1, 0), (0, -1), (0, 1)]: # links, rechts, oben, unten
|
||||
next_position = tuple([position[0] + dx, position[1] + dy])
|
||||
if next_position in safe_positions:
|
||||
stack.append(next_position)
|
||||
def flood_fill(self, start, safe_positions):
|
||||
stack = [start]
|
||||
visited = set()
|
||||
max_area = 0
|
||||
max_area_start = None
|
||||
|
||||
# Überprüfe, ob der aktuelle Bereich größer ist als der bisher größte Bereich
|
||||
if len(visited) > max_area:
|
||||
max_area = len(visited)
|
||||
max_area_start = position
|
||||
while stack:
|
||||
position = stack.pop()
|
||||
if isinstance(position, dict):
|
||||
position = tuple(position.values())
|
||||
else:
|
||||
position = tuple(position)
|
||||
|
||||
return max_area_start, visited
|
||||
if position not in visited:
|
||||
visited.add(position)
|
||||
for dx, dy in [(-1, 0), (1, 0), (0, -1), (0, 1)]: # links, rechts, oben, unten
|
||||
next_position = tuple([position[0] + dx, position[1] + dy])
|
||||
if next_position in safe_positions:
|
||||
stack.append(next_position)
|
||||
|
||||
# Überprüfe, ob der aktuelle Bereich größer ist als der bisher größte Bereich
|
||||
if len(visited) > max_area:
|
||||
max_area = len(visited)
|
||||
max_area_start = position
|
||||
|
||||
return max_area_start, visited
|
||||
|
||||
@@ -2,9 +2,13 @@ from server.GameBoard import GameBoard
|
||||
import random
|
||||
|
||||
class TemplateSnake:
|
||||
VERSION = "1.0.0"
|
||||
|
||||
def __init__(self):
|
||||
self.history = []
|
||||
self.target_food = None
|
||||
self.name = self.__class__.__name__
|
||||
self.version = getattr(self, "VERSION", "1.0.0")
|
||||
|
||||
def clear_history(self):
|
||||
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()
|
||||
self.assertNotEqual(move, "right")
|
||||
|
||||
def test_duel_small_length_lead_does_not_head_hunt(self):
|
||||
game_state = {
|
||||
"game": {
|
||||
"id": "test-duel-small-no-head-hunt",
|
||||
"ruleset": {"name": "standard", "version": "v1.0.0"},
|
||||
"source": "custom",
|
||||
"map": "standard",
|
||||
},
|
||||
"turn": 20,
|
||||
"board": {
|
||||
"height": 11,
|
||||
"width": 11,
|
||||
"food": [{"x": 1, "y": 1}],
|
||||
"hazards": [],
|
||||
"snakes": [
|
||||
{
|
||||
"id": "me",
|
||||
"name": "me",
|
||||
"health": 90,
|
||||
"length": 7,
|
||||
"head": {"x": 5, "y": 5},
|
||||
"body": [
|
||||
{"x": 5, "y": 5},
|
||||
{"x": 5, "y": 4},
|
||||
{"x": 5, "y": 3},
|
||||
{"x": 4, "y": 3},
|
||||
{"x": 4, "y": 4},
|
||||
{"x": 4, "y": 5},
|
||||
{"x": 4, "y": 6},
|
||||
],
|
||||
},
|
||||
{
|
||||
"id": "enemy",
|
||||
"name": "enemy",
|
||||
"health": 90,
|
||||
"length": 6,
|
||||
"head": {"x": 7, "y": 5},
|
||||
"body": [
|
||||
{"x": 7, "y": 5},
|
||||
{"x": 7, "y": 4},
|
||||
{"x": 7, "y": 3},
|
||||
{"x": 7, "y": 2},
|
||||
{"x": 7, "y": 1},
|
||||
{"x": 6, "y": 1},
|
||||
],
|
||||
},
|
||||
],
|
||||
},
|
||||
"you": {
|
||||
"id": "me",
|
||||
"name": "me",
|
||||
"health": 90,
|
||||
"length": 7,
|
||||
"head": {"x": 5, "y": 5},
|
||||
"body": [
|
||||
{"x": 5, "y": 5},
|
||||
{"x": 5, "y": 4},
|
||||
{"x": 5, "y": 3},
|
||||
{"x": 4, "y": 3},
|
||||
{"x": 4, "y": 4},
|
||||
{"x": 4, "y": 5},
|
||||
{"x": 4, "y": 6},
|
||||
],
|
||||
},
|
||||
}
|
||||
|
||||
move = make_board(game_state).snake_neat_make_a_move()
|
||||
self.assertNotEqual(move, "right")
|
||||
|
||||
def test_duel_big_length_lead_can_head_hunt(self):
|
||||
game_state = {
|
||||
"game": {
|
||||
"id": "test-duel-big-head-hunt",
|
||||
"ruleset": {"name": "standard", "version": "v1.0.0"},
|
||||
"source": "custom",
|
||||
"map": "standard",
|
||||
},
|
||||
"turn": 20,
|
||||
"board": {
|
||||
"height": 11,
|
||||
"width": 11,
|
||||
"food": [{"x": 1, "y": 1}],
|
||||
"hazards": [],
|
||||
"snakes": [
|
||||
{
|
||||
"id": "me",
|
||||
"name": "me",
|
||||
"health": 90,
|
||||
"length": 8,
|
||||
"head": {"x": 5, "y": 5},
|
||||
"body": [
|
||||
{"x": 5, "y": 5},
|
||||
{"x": 5, "y": 4},
|
||||
{"x": 5, "y": 3},
|
||||
{"x": 4, "y": 3},
|
||||
{"x": 4, "y": 4},
|
||||
{"x": 4, "y": 5},
|
||||
{"x": 4, "y": 6},
|
||||
{"x": 5, "y": 6},
|
||||
],
|
||||
},
|
||||
{
|
||||
"id": "enemy",
|
||||
"name": "enemy",
|
||||
"health": 90,
|
||||
"length": 6,
|
||||
"head": {"x": 7, "y": 5},
|
||||
"body": [
|
||||
{"x": 7, "y": 5},
|
||||
{"x": 7, "y": 4},
|
||||
{"x": 7, "y": 3},
|
||||
{"x": 7, "y": 2},
|
||||
{"x": 7, "y": 1},
|
||||
{"x": 6, "y": 1},
|
||||
],
|
||||
},
|
||||
],
|
||||
},
|
||||
"you": {
|
||||
"id": "me",
|
||||
"name": "me",
|
||||
"health": 90,
|
||||
"length": 8,
|
||||
"head": {"x": 5, "y": 5},
|
||||
"body": [
|
||||
{"x": 5, "y": 5},
|
||||
{"x": 5, "y": 4},
|
||||
{"x": 5, "y": 3},
|
||||
{"x": 4, "y": 3},
|
||||
{"x": 4, "y": 4},
|
||||
{"x": 4, "y": 5},
|
||||
{"x": 4, "y": 6},
|
||||
{"x": 5, "y": 6},
|
||||
],
|
||||
},
|
||||
}
|
||||
|
||||
move = make_board(game_state).snake_neat_make_a_move()
|
||||
self.assertEqual(move, "right")
|
||||
|
||||
def test_does_not_step_into_stacked_tail(self):
|
||||
game_state = {
|
||||
"game": {
|
||||
@@ -328,6 +468,84 @@ class TestBestBattleSnake(unittest.TestCase):
|
||||
move = make_board(game_state).snake_neat_make_a_move()
|
||||
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):
|
||||
game_state = {
|
||||
"game": {
|
||||
@@ -393,6 +611,145 @@ class TestBestBattleSnake(unittest.TestCase):
|
||||
move = make_board(game_state).snake_neat_make_a_move()
|
||||
self.assertEqual(move, "up")
|
||||
|
||||
def test_duel_tightens_space_when_enemy_is_encased(self):
|
||||
game_state = {
|
||||
"game": {
|
||||
"id": "test-encase-tighten",
|
||||
"ruleset": {"name": "standard", "version": "v1.0.0"},
|
||||
"source": "custom",
|
||||
"map": "standard",
|
||||
},
|
||||
"turn": 40,
|
||||
"board": {
|
||||
"height": 7,
|
||||
"width": 7,
|
||||
"food": [{"x": 0, "y": 0}],
|
||||
"hazards": [],
|
||||
"snakes": [
|
||||
{
|
||||
"id": "me",
|
||||
"name": "me",
|
||||
"health": 92,
|
||||
"length": 8,
|
||||
"head": {"x": 2, "y": 3},
|
||||
"body": [
|
||||
{"x": 2, "y": 3},
|
||||
{"x": 2, "y": 2},
|
||||
{"x": 1, "y": 2},
|
||||
{"x": 1, "y": 3},
|
||||
{"x": 1, "y": 4},
|
||||
{"x": 2, "y": 4},
|
||||
{"x": 3, "y": 4},
|
||||
{"x": 3, "y": 5},
|
||||
],
|
||||
},
|
||||
{
|
||||
"id": "enemy",
|
||||
"name": "enemy",
|
||||
"health": 88,
|
||||
"length": 5,
|
||||
"head": {"x": 4, "y": 3},
|
||||
"body": [
|
||||
{"x": 4, "y": 3},
|
||||
{"x": 5, "y": 3},
|
||||
{"x": 5, "y": 2},
|
||||
{"x": 4, "y": 2},
|
||||
{"x": 4, "y": 1},
|
||||
],
|
||||
},
|
||||
],
|
||||
},
|
||||
"you": {
|
||||
"id": "me",
|
||||
"name": "me",
|
||||
"health": 92,
|
||||
"length": 8,
|
||||
"head": {"x": 2, "y": 3},
|
||||
"body": [
|
||||
{"x": 2, "y": 3},
|
||||
{"x": 2, "y": 2},
|
||||
{"x": 1, "y": 2},
|
||||
{"x": 1, "y": 3},
|
||||
{"x": 1, "y": 4},
|
||||
{"x": 2, "y": 4},
|
||||
{"x": 3, "y": 4},
|
||||
{"x": 3, "y": 5},
|
||||
],
|
||||
},
|
||||
}
|
||||
|
||||
move = make_board(game_state).snake_neat_make_a_move()
|
||||
self.assertEqual(move, "right")
|
||||
|
||||
def test_constrictor_prefers_choke_when_safe(self):
|
||||
game_state = {
|
||||
"game": {
|
||||
"id": "test-constrictor-choke",
|
||||
"ruleset": {"name": "constrictor", "version": "v1.0.0"},
|
||||
"source": "custom",
|
||||
"map": "standard",
|
||||
},
|
||||
"turn": 25,
|
||||
"board": {
|
||||
"height": 7,
|
||||
"width": 7,
|
||||
"food": [],
|
||||
"hazards": [],
|
||||
"snakes": [
|
||||
{
|
||||
"id": "me",
|
||||
"name": "me",
|
||||
"health": 100,
|
||||
"length": 7,
|
||||
"head": {"x": 2, "y": 3},
|
||||
"body": [
|
||||
{"x": 2, "y": 3},
|
||||
{"x": 2, "y": 2},
|
||||
{"x": 1, "y": 2},
|
||||
{"x": 1, "y": 3},
|
||||
{"x": 1, "y": 4},
|
||||
{"x": 2, "y": 4},
|
||||
{"x": 2, "y": 5},
|
||||
],
|
||||
},
|
||||
{
|
||||
"id": "enemy",
|
||||
"name": "enemy",
|
||||
"health": 100,
|
||||
"length": 7,
|
||||
"head": {"x": 4, "y": 3},
|
||||
"body": [
|
||||
{"x": 4, "y": 3},
|
||||
{"x": 5, "y": 3},
|
||||
{"x": 5, "y": 2},
|
||||
{"x": 4, "y": 2},
|
||||
{"x": 4, "y": 1},
|
||||
{"x": 5, "y": 1},
|
||||
{"x": 6, "y": 1},
|
||||
],
|
||||
},
|
||||
],
|
||||
},
|
||||
"you": {
|
||||
"id": "me",
|
||||
"name": "me",
|
||||
"health": 100,
|
||||
"length": 7,
|
||||
"head": {"x": 2, "y": 3},
|
||||
"body": [
|
||||
{"x": 2, "y": 3},
|
||||
{"x": 2, "y": 2},
|
||||
{"x": 1, "y": 2},
|
||||
{"x": 1, "y": 3},
|
||||
{"x": 1, "y": 4},
|
||||
{"x": 2, "y": 4},
|
||||
{"x": 2, "y": 5},
|
||||
],
|
||||
},
|
||||
}
|
||||
|
||||
move = make_board(game_state).snake_neat_make_a_move()
|
||||
self.assertEqual(move, "right")
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
|
||||
@@ -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" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "aiologger"
|
||||
version = "0.7.0"
|
||||
source = { registry = "https://pypi.org/simple" }
|
||||
sdist = { url = "https://files.pythonhosted.org/packages/76/a8/ca4c00b319b877d29aa792cdd4ae3fb2a9f57268d94708a637abe9ae58c5/aiologger-0.7.0.tar.gz", hash = "sha256:7a4d5c91b836b61e842a791071786a3d80d6b6fa46fb8fd8e73391253ecb72ac", size = 20485, upload-time = "2022-10-05T01:03:22.199Z" }
|
||||
|
||||
[[package]]
|
||||
name = "blinker"
|
||||
version = "1.9.0"
|
||||
@@ -265,6 +271,7 @@ name = "snake-python"
|
||||
version = "0.1.0"
|
||||
source = { virtual = "." }
|
||||
dependencies = [
|
||||
{ name = "aiologger" },
|
||||
{ name = "dotenv" },
|
||||
{ name = "gel" },
|
||||
{ name = "quart" },
|
||||
@@ -272,6 +279,7 @@ dependencies = [
|
||||
|
||||
[package.metadata]
|
||||
requires-dist = [
|
||||
{ name = "aiologger", specifier = ">=0.7.0" },
|
||||
{ name = "dotenv", specifier = ">=0.9.9" },
|
||||
{ name = "gel", specifier = ">=3.1.0" },
|
||||
{ name = "quart", specifier = ">=0.20.0" },
|
||||
|
||||
Reference in New Issue
Block a user