Compare commits

...

49 Commits

Author SHA1 Message Date
f0156ccec4 add multithreading for seed cracking
All checks were successful
Build / build (push) Successful in 1m55s
2025-06-24 20:59:32 +02:00
2c2bfd3489 fix fast validation
All checks were successful
Build / build (push) Successful in 1m51s
2025-06-24 20:49:56 +02:00
263b0642f4 calculate less
All checks were successful
Build / build (push) Successful in 2m38s
Speed up validation by precalculating some stuff and toing a fast return
wherever possible
2025-06-24 20:07:25 +02:00
081c41b753 try some seedcracking
All checks were successful
Build / build (push) Successful in 3m55s
2025-06-24 17:28:11 +02:00
549d4fe36d modularize simulation 2025-06-24 17:27:56 +02:00
6f54282c9a improve xtask 2025-06-24 17:27:29 +02:00
6f3a1d138a ignore assets and games 2025-06-24 17:27:13 +02:00
0876f1ed3c explicitly select rust toolchain 2025-06-24 17:27:01 +02:00
87fc6cccd2 update dependencies
All checks were successful
Build / build (push) Successful in 1m12s
2025-06-07 21:17:38 +02:00
2f87e2aa60 improve log output
All checks were successful
Build / build (push) Successful in 1m7s
2025-06-06 21:38:34 +02:00
5f1d3dfc4f build local snakes in release
All checks were successful
Build / build (push) Successful in 1m10s
2025-06-06 21:29:59 +02:00
d44538b749 make number of compute threads configurable
All checks were successful
Build / build (push) Successful in 1m15s
2025-06-06 21:24:18 +02:00
b4b332bdbb reduce regression parallelism
All checks were successful
Build / build (push) Successful in 2m52s
2025-06-06 21:16:22 +02:00
b97d7c895a add multithreading 2025-06-06 21:15:26 +02:00
e5600fe038 use faster rng
All checks were successful
Build / build (push) Successful in 1m54s
2025-04-25 19:55:42 +02:00
15d90357ec remove unused import
All checks were successful
Build / build (push) Successful in 2m6s
2025-04-25 15:04:09 +02:00
99acd4ad1f improve score condition
Some checks failed
Build / build (push) Has been cancelled
2025-04-25 14:59:21 +02:00
bad4d916b8 make battlesnake the default
All checks were successful
Build / build (push) Successful in 3m44s
2025-04-24 21:22:12 +02:00
caa6eed783 improve progress bar 2025-04-24 21:22:04 +02:00
9333f6c6fb reduce regression parallelism 2025-04-22 19:48:38 +02:00
1d527a89cd make simulation faster
All checks were successful
Build / build (push) Successful in 2m43s
2025-04-21 21:48:11 +02:00
c5097ec417 update
All checks were successful
Build / build (push) Successful in 3m51s
2025-04-21 20:56:18 +02:00
879f99e23f multi agent mcts
All checks were successful
Build / build (push) Successful in 2m10s
2025-01-26 19:29:45 +01:00
302f5cac50 fix regression test 2025-01-26 19:29:24 +01:00
d715aa47b3 allow changing the port
All checks were successful
Build / build (push) Successful in 2m31s
2025-01-25 23:55:56 +01:00
6f04d7cb7f single agent mcts
All checks were successful
Build / build (push) Successful in 2m30s
2025-01-25 23:49:05 +01:00
3f91660583 improve scoring system
All checks were successful
Build / build (push) Successful in 1m59s
2025-01-22 01:33:45 +01:00
32883b2a1b spawn blocking task for simulations
All checks were successful
Build / build (push) Successful in 2m2s
2025-01-22 01:17:11 +01:00
c26da8869c use full tokio features 2025-01-22 01:16:00 +01:00
d3abaf61a7 use division remainder as second criterion
All checks were successful
Build / build (push) Successful in 1m59s
2025-01-22 01:00:29 +01:00
d46e2d8163 correct food spawning algorithm 2025-01-22 00:59:55 +01:00
5b440bc7db simple monte carlo simulation
All checks were successful
Build / build (push) Successful in 1m58s
2025-01-22 00:43:07 +01:00
d858d88e76 fix health reset on feeding 2025-01-22 00:42:55 +01:00
3a163fd6e7 save u8 to string id mapping
All checks were successful
Build / build (push) Successful in 1m59s
2025-01-21 23:20:43 +01:00
108aeaa49d skip calculating index from id when index already present
All checks were successful
Build / build (push) Successful in 1m59s
2025-01-21 22:40:01 +01:00
ea96a0eb0d put small field bitfields on the stack
All checks were successful
Build / build (push) Successful in 2m1s
2025-01-21 20:25:54 +01:00
47f75563ae add clone benchmark 2025-01-21 20:21:23 +01:00
5bb7476af6 use VecDeque in intended direction
All checks were successful
Build / build (push) Successful in 2m2s
2025-01-21 19:26:43 +01:00
2f2b7ac11e add simulation benchmarks
All checks were successful
Build / build (push) Successful in 2m7s
2025-01-21 19:04:30 +01:00
1410602c6c bump rust version
All checks were successful
Build / build (push) Successful in 1m53s
2025-01-17 00:36:38 +01:00
5e81a7952f correct simulation
Some checks failed
Build / build (push) Failing after 1m54s
2025-01-17 00:33:54 +01:00
9c76df1f69 calculate valid moves
Some checks failed
Build / build (push) Failing after 1m52s
2025-01-16 21:06:49 +01:00
d91d0e0a82 remove rocket artefact 2025-01-16 20:33:17 +01:00
f9e34d119a fix docker lint
All checks were successful
Build / build (push) Successful in 1m56s
2025-01-16 20:18:02 +01:00
d9ee6ae2f7 create simple simulation datastructures 2025-01-16 20:17:40 +01:00
f3eba2ba75 add simple ci 2025-01-16 20:17:40 +01:00
932023451a accept battlesnake requests 2025-01-16 17:59:35 +01:00
7c79c718d0 rename parameter 2024-11-03 20:17:33 +01:00
923b661583 update dependencies 2024-11-03 20:17:27 +01:00
27 changed files with 5079 additions and 1289 deletions

View File

@ -1,5 +1,2 @@
[alias]
xtask = "run --package xtask --"
[build]
rustflags = "-Ctarget-cpu=core-avx2"

17
.github/workflows/build_docker.yaml vendored Normal file
View File

@ -0,0 +1,17 @@
name: Build
run-name: ${{ gitea.actor }} is runs ci pipeline
on: [push]
jobs:
build:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Set up Docker Buildx
uses: docker/setup-buildx-action@v3
- name: Build Docker image
uses: docker/build-push-action@v6
with:
context: .
file: ./Dockerfile
push: false

2
.gitignore vendored
View File

@ -1 +1,3 @@
target
assets
games

2462
Cargo.lock generated

File diff suppressed because it is too large Load Diff

View File

@ -1,4 +1,9 @@
[workspace]
members = ["battlesnake", "xtask"]
resolver = "3"
resolver = "2"
default-members = ["battlesnake"]
[profile.release]
lto = "fat"
codegen-units = 1

View File

@ -1,11 +1,11 @@
FROM rust:1.81-bookworm as build
FROM rust:1.86-bullseye AS build
COPY battlesnake/ /usr/app
WORKDIR /usr/app
RUN cargo install --path .
FROM debian:bookworm
FROM debian:bullseye-slim
COPY --from=build /usr/local/cargo/bin/battlesnake /bin/battlesnake
CMD ["battlesnake"]

View File

@ -1,8 +1,9 @@
[package]
authors = ["Max Känner"]
name = "battlesnake"
version = "1.0.0"
edition = "2021"
version = "2.0.0"
edition = "2024"
rust-version = "1.86"
readme = "README.md"
repository = "https://git.mkaenner.de/max/battlesnake"
@ -10,30 +11,55 @@ keywords = ["battlesnake"]
description = """
A simple Battlesnake written in Rust
"""
default-run = "battlesnake"
[lints.clippy]
pedantic = "warn"
nursery = "warn"
[dependencies]
rocket = { version = "0.5.0", features = ["json"] }
serde = { version = "1.0.117", features = ["derive"] }
serde_json = "1.0.59"
log = "0.4.0"
env_logger = "0.11.5"
rand = "0.8.4"
enum-iterator = "2.1"
iter_tools = "0.21"
ordered-float = "4.3.0"
dashmap = "6.1.0"
[[bin]]
name = "battlesnake"
battlesnake-game-types = "0.17.0"
[[bin]]
name = "seed-cracker"
[[bin]]
name = "generate"
[dependencies]
# server
tokio = { version = "1.43", features = ["full"] }
axum = { version = "0.8", features = ["http2", "multipart", "ws"] }
serde = { version = "1.0", features = ["derive", "rc"] }
# logging
log = "0.4"
env_logger = "0.11"
# other
bitvec = "1.0"
enum-iterator = "2.1"
rand = "0.9"
float-ord = "0.3"
futures-util = "0.3.31"
az = "1.2.1"
blanket = "0.4.0"
hashbrown = "0.15.4"
serde_json = "1.0.140"
clap = { version = "4.5.39", features = ["derive"] }
sqlx = { version = "0.8.6", features = ["runtime-tokio", "sqlite"] }
enum_dispatch = "0.3.13"
lru = "0.14.0"
lfu_cache = "1.3.0"
memmap2 = "0.9.5"
bytemuck = "1.23.1"
flame = "0.2.2"
flamer = "0.5.0"
rayon = "1.10.0"
[dev-dependencies]
# criterion = { version = "0.5.1", features = ["html_reports"] }
criterion2 = "1.1.1"
criterion = "0.5"
[profile.release]
lto = "fat"
codegen-units = 1
panic = "abort"
[[bench]]
name = "simulation"
harness = false

View File

@ -1,4 +0,0 @@
[default]
address = "0.0.0.0"
port = 8000
keep_alive = 0

View File

@ -0,0 +1,229 @@
use std::{
hint::black_box,
sync::{
Arc,
atomic::{AtomicU32, Ordering},
},
};
use criterion::{Bencher, BenchmarkId, Criterion, criterion_group, criterion_main};
use battlesnake::types::{
Coord,
simulation::Game as Board,
wire::{Battlesnake, Board as WireBoard, Game, Request, RoyaleSettings, Ruleset, Settings},
};
use rand::{SeedableRng, rngs::SmallRng};
fn create_start_snake(coord: Coord) -> Battlesnake {
let id: Arc<str> = format!("{coord:?}").into();
Battlesnake {
id: id.clone(),
name: id.clone(),
health: 100,
body: vec![coord; 3],
latency: "0".into(),
head: coord,
length: 3,
shout: None,
squad: id,
}
}
fn create_standard_start_request(starts: [Coord; 4]) -> Request {
Request {
game: Game {
id: "test".into(),
ruleset: Ruleset {
name: "standard".into(),
version: "0".into(),
settings: Settings {
food_spawn_chance: 15,
minimum_food: 1,
hazard_damage_per_turn: 30,
royale: RoyaleSettings {
shrink_every_n_turns: 20,
},
},
},
map: "standard".into(),
timeout: 500,
source: "other".into(),
},
turn: 0,
board: WireBoard {
height: 11,
width: 11,
food: vec![Coord { x: 5, y: 5 }],
hazards: vec![],
snakes: vec![
create_start_snake(starts[0]),
create_start_snake(starts[1]),
create_start_snake(starts[2]),
create_start_snake(starts[3]),
],
},
you: create_start_snake(starts[0]),
}
}
fn standard(c: &mut Criterion) {
let turns_min = AtomicU32::new(u32::MAX);
let turns_max = AtomicU32::new(u32::MIN);
let turns_sum = AtomicU32::new(0);
let turns_total = AtomicU32::new(0);
let mut group = c.benchmark_group("standard");
group.sample_size(10000);
let benchmark = |b: &mut Bencher, board: &Board| {
b.iter(|| {
let mut board = board.clone();
board.simulate_random(&mut SmallRng::from_os_rng());
let turn = board.board.turn();
if turn < turns_min.load(Ordering::Relaxed) {
turns_min.store(turn, Ordering::Relaxed);
}
if turn > turns_max.load(Ordering::Relaxed) {
turns_max.store(turn, Ordering::Relaxed);
}
turns_sum.fetch_add(turn, Ordering::Relaxed);
turns_total.fetch_add(1, Ordering::Relaxed);
});
};
let request = create_standard_start_request([
Coord { x: 1, y: 1 },
Coord { x: 9, y: 1 },
Coord { x: 1, y: 9 },
Coord { x: 9, y: 9 },
]);
let board = Board::from(&request);
group.bench_with_input(
BenchmarkId::from_parameter("start x"),
black_box(&board),
benchmark,
);
{
let max = turns_max.load(Ordering::Relaxed);
let min = turns_min.load(Ordering::Relaxed);
let sum = turns_sum.load(Ordering::Relaxed);
let total = turns_total.load(Ordering::Relaxed);
let avg = sum / total;
println!("turns: [{min}, {max}] avg {avg} @ {total} samples");
turns_max.store(u32::MIN, Ordering::Relaxed);
turns_min.store(u32::MAX, Ordering::Relaxed);
turns_sum.store(0, Ordering::Relaxed);
turns_total.store(0, Ordering::Relaxed);
}
let request = create_standard_start_request([
Coord { x: 5, y: 1 },
Coord { x: 1, y: 5 },
Coord { x: 5, y: 9 },
Coord { x: 9, y: 5 },
]);
let board = Board::from(&request);
group.bench_with_input(
BenchmarkId::from_parameter("start +"),
black_box(&board),
benchmark,
);
{
let max = turns_max.load(Ordering::Relaxed);
let min = turns_min.load(Ordering::Relaxed);
let sum = turns_sum.load(Ordering::Relaxed);
let total = turns_total.load(Ordering::Relaxed);
let avg = sum / total;
println!("turns: [{min}, {max}] avg {avg} @ {total} samples");
}
}
fn constrictor(c: &mut Criterion) {
let turns_min = AtomicU32::new(u32::MAX);
let turns_max = AtomicU32::new(u32::MIN);
let turns_sum = AtomicU32::new(0);
let turns_total = AtomicU32::new(0);
let mut group = c.benchmark_group("constrictor");
group.sample_size(10000);
let benchmark = |b: &mut Bencher, board: &Board| {
b.iter(|| {
let mut board = board.clone();
board.simulate_random(&mut SmallRng::from_os_rng());
let turn = board.board.turn();
if turn < turns_min.load(Ordering::Relaxed) {
turns_min.store(turn, Ordering::Relaxed);
}
if turn > turns_max.load(Ordering::Relaxed) {
turns_max.store(turn, Ordering::Relaxed);
}
turns_sum.fetch_add(turn, Ordering::Relaxed);
turns_total.fetch_add(1, Ordering::Relaxed);
});
};
let mut request = create_standard_start_request([
Coord { x: 1, y: 1 },
Coord { x: 9, y: 1 },
Coord { x: 1, y: 9 },
Coord { x: 9, y: 9 },
]);
request.game.ruleset.name = "constrictor".into();
let board = Board::from(&request);
group.bench_with_input(
BenchmarkId::from_parameter("start x"),
black_box(&board),
benchmark,
);
{
let max = turns_max.load(Ordering::Relaxed);
let min = turns_min.load(Ordering::Relaxed);
let sum = turns_sum.load(Ordering::Relaxed);
let total = turns_total.load(Ordering::Relaxed);
let avg = sum / total;
println!("turns: [{min}, {max}] avg {avg} @ {total} samples");
turns_max.store(u32::MIN, Ordering::Relaxed);
turns_min.store(u32::MAX, Ordering::Relaxed);
turns_sum.store(0, Ordering::Relaxed);
turns_total.store(0, Ordering::Relaxed);
}
let mut request = create_standard_start_request([
Coord { x: 5, y: 1 },
Coord { x: 1, y: 5 },
Coord { x: 5, y: 9 },
Coord { x: 9, y: 5 },
]);
request.game.ruleset.name = "constrictor".into();
let board = Board::from(&request);
group.bench_with_input(
BenchmarkId::from_parameter("start +"),
black_box(&board),
benchmark,
);
{
let max = turns_max.load(Ordering::Relaxed);
let min = turns_min.load(Ordering::Relaxed);
let sum = turns_sum.load(Ordering::Relaxed);
let total = turns_total.load(Ordering::Relaxed);
let avg = sum / total;
println!("turns: [{min}, {max}] avg {avg} @ {total} samples");
}
}
fn clone(c: &mut Criterion) {
let request = create_standard_start_request([
Coord { x: 1, y: 1 },
Coord { x: 9, y: 1 },
Coord { x: 1, y: 9 },
Coord { x: 9, y: 9 },
]);
let board = Board::from(&request);
c.bench_function("clone", |b| b.iter(|| board.clone()));
}
criterion_group!(benches, standard, constrictor, clone);
criterion_main!(benches);

View File

@ -0,0 +1,47 @@
use std::{
fs::File,
io::{self, BufWriter, Write},
};
use az::Az;
use bytemuck::cast_slice;
fn main() -> Result<(), io::Error> {
let mut chain = BufWriter::new(File::create("assets/chain")?);
let mut indices = vec![0u32; (i32::MAX - 1).az::<usize>()];
let mut x = 1;
let mut count = 0;
loop {
if count % 1_000_000 == 0 {
println!("current: {count:0>10}");
}
let next = seedrand(x);
indices[x.az::<usize>() - 1] = count;
chain.write_all(&next.to_ne_bytes())?;
x = next;
count += 1;
if x == 1 {
break;
}
}
File::create("assets/table")?.write_all(cast_slice(&indices))?;
Ok(())
}
const fn seedrand(x: i32) -> i32 {
const A: i32 = 48_271;
const Q: i32 = 44_488;
const R: i32 = 3_399;
let hi = x / Q;
let lo = x % Q;
let x = A * lo - R * hi;
if x < 0 { x + i32::MAX } else { x }
}

File diff suppressed because it is too large Load Diff

View File

@ -1,24 +1 @@
use battlesnake_game_types::types::Move;
use serde::{Deserialize, Serialize};
pub mod logic;
#[derive(Debug, Deserialize, Serialize)]
pub struct Response {
/// In which direction the snake should move
r#move: &'static str,
}
impl Response {
#[must_use]
pub const fn new(r#move: Move) -> Self {
Self {
r#move: match r#move {
Move::Left => "left",
Move::Down => "down",
Move::Up => "up",
Move::Right => "right",
},
}
}
}
pub mod types;

View File

@ -1,359 +0,0 @@
// Welcome to
// __________ __ __ .__ __
// \______ \_____ _/ |__/ |_| | ____ ______ ____ _____ | | __ ____
// | | _/\__ \\ __\ __\ | _/ __ \ / ___// \\__ \ | |/ // __ \
// | | \ / __ \| | | | | |_\ ___/ \___ \| | \/ __ \| <\ ___/
// |________/(______/__| |__| |____/\_____>______>___|__(______/__|__\\_____>
//
// This file can be a nice home for your Battlesnake logic and helper functions.
//
// To get you started we've included code to prevent your Battlesnake from moving backwards.
// For more info see docs.battlesnake.com
use core::f64;
use std::{collections::HashMap, time::Instant};
use battlesnake_game_types::{
compact_representation::standard::CellBoard4Snakes11x11,
types::{
build_snake_id_map, LengthGettableGame, Move, RandomReasonableMovesGame,
ReasonableMovesGame, SimulableGame, SimulatorInstruments, SnakeIDMap, SnakeId,
VictorDeterminableGame, YouDeterminableGame,
},
wire_representation::Game,
};
use log::{error, info};
use ordered_float::OrderedFloat;
use rand::{prelude::*, thread_rng};
use rocket::time::{ext::NumericalDuration, Duration};
use serde_json::{json, Value};
// 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
#[must_use]
pub fn info() -> Value {
info!("INFO");
json!({
"apiversion": "1",
"author": "der-informatiker",
"color": "#00FFEE",
"head": "smart-caterpillar",
"tail": "mouse",
})
}
#[derive(Debug)]
pub struct GameState {
calculation_time: Duration,
snake_id_map: SnakeIDMap,
}
// start is called when your Battlesnake begins a game
#[must_use]
pub fn start(game: &Game) -> GameState {
info!("GAME START");
let snake_id_map = build_snake_id_map(game);
let calculation_time = (game.game.timeout / 2).milliseconds();
GameState {
calculation_time,
snake_id_map,
}
}
// end is called when your Battlesnake finishes a game
pub fn end(game: &Game, state: GameState) {
std::mem::drop(state);
info!("GAME OVER after {} turns", game.turn);
}
// move is called on every turn and returns your next move
// Valid moves are "up", "down", "left", or "right"
// See https://docs.battlesnake.com/api/example-move for available data
pub fn get_move(game: Game, state: &mut GameState, start: &Instant) -> Move {
let calc_start = Instant::now();
if calc_start - *start > 10.milliseconds() {
error!(
"The calculation was started long after the request ({}ms)",
(calc_start - *start).as_millis()
);
}
let deadline = *start + state.calculation_time;
let name = game.you.name.clone();
let turn = game.turn;
let solo = game.game.ruleset.name == "solo";
let Ok(board) = CellBoard4Snakes11x11::convert_from_game(game, &state.snake_id_map) else {
error!("Unable to fit board");
return Move::Down;
};
let mut tree = Node {
statistic: Statistics {
played: 0,
won: HashMap::new(),
},
child_statistics: HashMap::new(),
childs: HashMap::new(),
};
while Instant::now() < deadline {
if solo {
tree.monte_carlo_solo_step(&board);
} else {
tree.monte_carlo_step(&board);
}
}
let actions = tree.child_statistics.entry(*board.you_id()).or_default();
info!("actions {}: {actions:?}", name);
#[allow(clippy::cast_precision_loss)]
let chosen = actions
.iter()
.max_by_key(|(_, stat)| stat.played)
.map(|(direction, _)| *direction)
.or_else(|| {
board
.random_reasonable_move_for_each_snake(&mut thread_rng())
.find(|(snake_id, _)| snake_id == board.you_id())
.map(|(_, direction)| direction)
})
.unwrap_or(Move::Down);
info!(
"DIRECTION {turn}: {chosen:?} after {}ms ({name})",
start.elapsed().as_millis(),
);
chosen
}
#[derive(Debug, Clone, Copy)]
struct Instruments;
impl SimulatorInstruments for Instruments {
fn observe_simulation(&self, _duration: std::time::Duration) {}
}
#[derive(Debug, PartialEq, Eq, Clone, Default)]
struct Statistics {
/// Number of times this node was simulated
played: usize,
/// Number of times this node was simulated and the agent has won.
won: HashMap<SnakeId, usize>,
}
#[derive(Debug, PartialEq, Eq, Clone, Default)]
struct ActionStatistic {
played: usize,
won: usize,
}
#[derive(Debug, PartialEq, Eq, Clone, Default)]
struct Node {
statistic: Statistics,
child_statistics: HashMap<SnakeId, HashMap<Move, ActionStatistic>>,
childs: HashMap<[Option<(Move, u16)>; 4], Node>,
}
impl Node {
/// Performs one monte carlo simulation step
///
/// Returns the snake that has won the simulation
fn monte_carlo_step(&mut self, board: &CellBoard4Snakes11x11) -> Option<SnakeId> {
let stop_condition = CellBoard4Snakes11x11::is_over;
let winner = if stop_condition(board) {
board.get_winner()
} else if self.statistic.played == 0 {
// We didn't simulate a game for this node yet. Do that
let mut board = *board;
while !stop_condition(&board) {
let rng = &mut thread_rng();
let moves = board.random_reasonable_move_for_each_snake(rng);
let (_, new_board) = board
.simulate_with_moves(
&Instruments,
moves.map(|(snake_id, direction)| (snake_id, [direction])),
)
.next()
.unwrap();
board = new_board;
}
board.get_winner()
} else {
// select a node to simulate
let possible_actions = board.reasonable_moves_for_each_snake();
let actions = possible_actions
.filter_map(|(token, actions)| {
let statistics = self.child_statistics.entry(token).or_default();
let selected = actions.iter().copied().max_by_key(|direction| {
let statistics = statistics.entry(*direction).or_default();
if statistics.played == 0 {
return OrderedFloat(f64::INFINITY);
}
#[allow(clippy::cast_precision_loss)]
let exploitation = statistics.won as f64 / statistics.played as f64;
#[allow(clippy::cast_precision_loss)]
let exploration = f64::consts::SQRT_2
* f64::sqrt(
f64::ln(self.statistic.played as f64) / statistics.played as f64,
);
OrderedFloat(exploitation + exploration)
})?;
Some((token, [selected]))
})
.collect::<Vec<_>>();
let (_, board) = board
.simulate_with_moves(&Instruments, actions.iter().copied())
.next()
.unwrap();
let mut map_actions = [None; 4];
for (i, action) in map_actions.iter_mut().enumerate() {
*action = actions
.iter()
.find(|(snake_id, _)| snake_id.as_usize() == i)
.and_then(|(snake_id, moves)| {
Some((*moves.first()?, board.get_length(snake_id)))
});
}
let winner = self
.childs
.entry(map_actions)
.or_default()
.monte_carlo_step(&board);
// update child statistics
for (token, action) in &actions {
let entry = self
.child_statistics
.entry(*token)
.or_default()
.entry(action[0])
.or_default();
entry.played += 1;
if Some(*token) == winner {
entry.won += 1;
}
}
winner
};
self.statistic.played += 1;
if let Some(token) = winner {
self.statistic
.won
.entry(token)
.and_modify(|won| *won += 1)
.or_insert(1);
}
winner
}
/// Performs one monte carlo simulation step for a solo game
///
/// Returns the lengths before death
fn monte_carlo_solo_step(&mut self, board: &CellBoard4Snakes11x11) -> u16 {
let stop_condition = |board: &CellBoard4Snakes11x11| board.alive_snake_count() == 0;
let winner = if self.statistic.played == 0 {
// We didn't simulate a game for this node yet. Do that
let mut board = *board;
while !stop_condition(&board) {
let moves =
board
.reasonable_moves_for_each_snake()
.filter_map(|(snake_id, moves)| {
Some((snake_id, [*moves.choose(&mut thread_rng())?]))
});
let Some((_, new_board)) = board.simulate_with_moves(&Instruments, moves).next()
else {
break;
};
if stop_condition(&new_board) {
break;
}
board = new_board;
}
let winner = board.get_length(board.you_id());
winner
} else {
// select a node to simulate
let possible_actions = board.reasonable_moves_for_each_snake();
let actions = possible_actions
.filter_map(|(token, actions)| {
let statistics = self.child_statistics.entry(token).or_default();
let selected = actions.iter().copied().max_by_key(|direction| {
let statistics = statistics.entry(*direction).or_default();
if statistics.played == 0 {
return OrderedFloat(f64::INFINITY);
}
#[allow(clippy::cast_precision_loss)]
let exploitation = statistics.won as f64 / statistics.played as f64;
#[allow(clippy::cast_precision_loss)]
let exploration = f64::consts::SQRT_2
* f64::sqrt(
f64::ln(self.statistic.played as f64) / statistics.played as f64,
)
* 11.0
* 11.0;
OrderedFloat(exploitation + exploration)
})?;
Some((token, [selected]))
})
.collect::<Vec<_>>();
let (_, new_board) = board
.simulate_with_moves(&Instruments, actions.iter().copied())
.next()
.unwrap();
let mut map_actions = [None; 4];
for (i, action) in map_actions.iter_mut().enumerate() {
*action = actions
.iter()
.find(|(snake_id, _)| snake_id.as_usize() == i)
.and_then(|(snake_id, moves)| {
Some((*moves.first()?, new_board.get_length(snake_id)))
});
}
let winner = if stop_condition(&new_board) {
board.get_length(board.you_id())
} else {
self.childs
.entry(map_actions)
.or_default()
.monte_carlo_solo_step(&new_board)
};
// update child statistics
let entry = self
.child_statistics
.entry(*new_board.you_id())
.or_default()
.entry(
actions
.iter()
.find(|(snake_id, _)| snake_id == new_board.you_id())
.map(|(_, action)| action[0])
.unwrap(),
)
.or_default();
entry.played += 1;
entry.won += usize::from(winner);
winner
};
self.statistic.played += 1;
self.statistic
.won
.entry(*board.you_id())
.and_modify(|won| *won += usize::from(winner))
.or_insert_with(|| usize::from(winner));
winner
}
}

View File

@ -1,109 +1,399 @@
#![allow(clippy::needless_pass_by_value)]
use std::{env, sync::Arc, time::Instant};
use battlesnake::{
logic::{self, GameState},
Response,
use std::{
env,
sync::atomic::{AtomicUsize, Ordering},
};
use battlesnake_game_types::{types::Move, wire_representation::Game};
use dashmap::DashMap;
use log::{error, info};
use rocket::{
fairing::AdHoc, get, http::Status, launch, post, routes, serde::json::Json, tokio::task, State,
use axum::{
Router,
extract::{Json, State},
response,
routing::{get, post},
};
use battlesnake::types::{
Direction,
simulation::{Board, Game},
wire::{Request, Response},
};
use float_ord::FloatOrd;
use futures_util::future::join_all;
use hashbrown::HashMap;
use log::{debug, error, info, trace, warn};
use rand::prelude::*;
use serde::Serialize;
use tokio::{
fs::File,
io::AsyncWriteExt,
net::TcpListener,
sync::mpsc::{UnboundedSender, unbounded_channel},
time::{Duration, Instant},
};
use serde_json::Value;
type States = Arc<DashMap<(String, String), GameState>>;
#[get("/")]
fn handle_index() -> Json<Value> {
Json(logic::info())
}
#[post("/start", format = "json", data = "<game>")]
fn handle_start(state: &State<States>, game: Json<Game>) -> Status {
if state
.insert(
(game.game.id.clone(), game.you.id.clone()),
logic::start(&game),
)
.is_some()
{
error!("re-started game");
}
Status::Ok
}
#[post("/move", format = "json", data = "<game>")]
async fn handle_move(state: &State<States>, game: Json<Game>) -> Json<Response> {
let start = Instant::now();
let state = (*state).clone();
let action = task::spawn_blocking(move || {
let mut game_state = state.get_mut(&(game.game.id.clone(), game.you.id.clone()));
while game_state.is_none() {
error!("move request without previous start");
if state
.insert(
(game.game.id.clone(), game.you.id.clone()),
logic::start(&game),
)
.is_some()
{
error!("re-started game");
}
game_state = state.get_mut(&(game.game.id.clone(), game.you.id.clone()));
}
let Some(mut game_state) = game_state else {
std::mem::drop(game_state);
unreachable!()
};
logic::get_move(game.0, &mut game_state, &start)
})
.await
.unwrap_or(Move::Up);
Json(Response::new(action))
}
#[post("/end", format = "json", data = "<game>")]
fn handle_end(state: &State<States>, game: Json<Game>) -> Status {
if let Some((_key, game_state)) = state.remove(&(game.game.id.clone(), game.you.id.clone())) {
logic::end(&game, game_state);
} else {
error!("ended game without state");
}
Status::Ok
}
#[launch]
fn rocket() -> _ {
// Lots of web hosting services expect you to bind to the port specified by the `PORT`
// environment variable. However, Rocket looks at the `ROCKET_PORT` environment variable.
// If we find a value for `PORT`, we set `ROCKET_PORT` to that value.
if let Ok(port) = env::var("PORT") {
env::set_var("ROCKET_PORT", &port);
}
// We default to 'info' level logging. But if the `RUST_LOG` environment variable is set,
// we keep that value instead.
if env::var("RUST_LOG").is_err() {
env::set_var("RUST_LOG", "info");
}
static THREADS: AtomicUsize = AtomicUsize::new(1);
#[tokio::main]
async fn main() {
env_logger::init();
info!("Starting Battlesnake Server...");
let (sender, mut receiver) = unbounded_channel();
rocket::build()
.attach(AdHoc::on_response("Server ID Middleware", |_, res| {
Box::pin(async move {
res.set_raw_header("Server", "battlesnake/github/starter-snake-rust");
})
}))
.mount(
"/",
routes![handle_index, handle_start, handle_move, handle_end],
)
.manage(States::new(DashMap::new()))
debug!("Creating routes");
let app = Router::new()
.route("/", get(info))
.route("/start", post(start))
.route("/move", post(get_move))
.route("/end", post(end))
.with_state(sender);
let threads = env::var("THREADS")
.ok()
.and_then(|threads| {
threads
.parse()
.inspect_err(|err| error!("Unable to parse number of threads: {err}"))
.ok()
})
.unwrap_or(1);
THREADS.store(threads, Ordering::Relaxed);
debug!("Creating listener");
let port = env::var("PORT").unwrap_or_else(|_| "8000".into());
let listener = TcpListener::bind(format!("0.0.0.0:{port}")).await.unwrap();
debug!("Starting observer");
tokio::spawn(async move {
let mut games = HashMap::new();
while let Some((request_type, request)) = receiver.recv().await {
match request_type {
RequestType::Start => {
let game_id = request.game.id.clone();
info!("Got start request {game_id}");
if let Some(old_requests) = games.insert(game_id, vec![request]) {
warn!("evicted duplicate game: {old_requests:?}");
}
}
RequestType::GetMove => {
let game_id = request.game.id.clone();
info!("Got move request {game_id}");
games.entry(game_id).or_default().push(request);
}
RequestType::End => {
let game_id = request.game.id.clone();
info!("Got end request {game_id}");
if let Some(mut requests) = games.remove(&game_id) {
requests.push(request);
let json = match serde_json::to_vec_pretty(&requests) {
Ok(json) => json,
Err(e) => {
error!("Unable to serealize json: {e}");
continue;
}
};
match File::create_new(format!("games/{game_id}.json")).await {
Ok(mut file) => {
if let Err(e) = file.write_all(&json).await {
error!("Unable to write jsone: {e}");
}
}
Err(e) => error!("Unable to open file: {e}"),
}
} else {
warn!("end of game without game: {request:?}");
}
}
}
}
warn!("Observer stopped");
});
debug!("Starting server");
axum::serve(listener, app).await.unwrap();
}
async fn info() -> response::Json<Info> {
info!("got info request");
response::Json(Info {
apiversion: "1",
author: "der-informatiker",
color: "#00FFEE",
head: "smart-caterpillar",
tail: "mouse",
version: env!("CARGO_PKG_VERSION"),
})
}
#[derive(Debug, Clone, Serialize)]
struct Info {
apiversion: &'static str,
author: &'static str,
color: &'static str,
head: &'static str,
tail: &'static str,
version: &'static str,
}
#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Clone, Copy)]
enum RequestType {
Start,
GetMove,
End,
}
async fn start(
State(sender): State<UnboundedSender<(RequestType, Request)>>,
Json(request): Json<Request>,
) {
if let Err(e) = sender.send((RequestType::Start, request.clone())) {
warn!("Unable to observe request: {e}");
}
let board = Board::from(&request);
info!("got start request: {board}");
}
#[allow(clippy::too_many_lines)]
async fn get_move(
State(sender): State<UnboundedSender<(RequestType, Request)>>,
Json(request): Json<Request>,
) -> response::Json<Response> {
let start = Instant::now();
if let Err(e) = sender.send((RequestType::GetMove, request.clone())) {
warn!("Unable to observe request: {e}");
}
let board = Game::from(&request);
let timeout = Duration::from_millis(u64::from(request.game.timeout));
let id = board.board.get_id(&request.you.id).unwrap_or_else(|| {
error!("My id is not in the simulation board");
0
});
debug!("got move request: {}", board.board);
let actions = board.board.valid_actions(id).collect::<Vec<_>>();
if actions.len() <= 1 {
info!(
"only one possible action. Fast forwarding {:?}",
actions.first()
);
return response::Json(Response {
direction: actions.first().copied().unwrap_or(Direction::Up),
shout: None,
});
}
info!("valid actions: {actions:?}");
if start.elapsed() > Duration::from_millis(10) {
error!(
"The calculation started late ({}ms)",
start.elapsed().as_millis()
);
}
let score_fn: fn(&Board, u8) -> u32 = match &*request.game.ruleset.name {
"solo" => score_solo,
_ => score_standard,
};
let action_futures = (0..THREADS.load(Ordering::Relaxed)).map(|_| {
let request = request.clone();
let board = board.clone();
let mut rng = SmallRng::from_os_rng();
tokio::task::spawn_blocking(move || {
let mut mcts_managers: Vec<_> = (0..request.board.snakes.len())
.map(|id| MctsManager::new(u8::try_from(id).unwrap()))
.collect();
let c = f32::sqrt(2.0);
let mut mcts_actions = Vec::new();
while start.elapsed() < timeout * 4 / 5 {
let mut board = board.clone();
let mut game_over = false;
while !game_over {
mcts_actions.clear();
mcts_actions.extend(mcts_managers.iter_mut().filter_map(|mcts_manager| {
mcts_manager
.next_action(&board.board, c, &mut rng)
.map(|action| (mcts_manager.snake, action))
}));
game_over = board.next_turn_random(&mcts_actions, &mut rng);
if mcts_actions.is_empty() {
break;
}
}
if !game_over {
board.simulate_random(&mut rng);
}
for mcts_manager in &mut mcts_managers {
let id = mcts_manager.snake;
let score = score_fn(&board.board, id);
mcts_manager.apply_score(score);
}
}
let my_mcts_manager = mcts_managers.into_iter().nth(usize::from(id)).unwrap();
let actions = my_mcts_manager.base.next.map(|action| {
action.map_or(0.0, |action| action.score as f32 / action.played as f32)
});
(actions, my_mcts_manager.base.played)
})
});
let (scores, played) = join_all(action_futures).await.into_iter().fold(
([0.0; 4], 0),
|(mut total, mut games), actions| {
if let Ok((actions, new_games)) = actions {
for i in 0..total.len() {
total[i] += actions[i];
}
games += new_games;
}
(total, games)
},
);
for action in actions {
let score = scores[usize::from(action)];
info!("{action:?} -> {score}");
}
let action = scores
.into_iter()
.enumerate()
.max_by_key(|(_, score)| FloatOrd(*score))
.map(|(index, _)| match index {
0 => Direction::Up,
1 => Direction::Down,
2 => Direction::Left,
3 => Direction::Right,
_ => unreachable!(),
});
if let Some(action) = action {
info!("found action {action:?} after {played} simulations.",);
} else {
warn!("unable to find a valid action");
}
info!("chose {action:?}");
response::Json(Response {
direction: action.unwrap_or(Direction::Up),
shout: None,
})
}
const fn score_solo(board: &Board, _id: u8) -> u32 {
board.turn()
}
fn score_standard(board: &Board, id: u8) -> u32 {
if board.alive(id) {
1 + u32::from(board.max_length() == board.length(id))
} else {
0
}
}
async fn end(
State(sender): State<UnboundedSender<(RequestType, Request)>>,
Json(request): Json<Request>,
) {
if let Err(e) = sender.send((RequestType::End, request.clone())) {
warn!("Unable to observe request: {e}");
}
let board = Board::from(&request);
info!("got end request: {board}");
}
#[derive(Debug)]
struct ActionInfo {
score: u32,
played: u32,
next: Box<[Option<ActionInfo>; 4]>,
}
impl ActionInfo {
fn new() -> Self {
Self {
score: 0,
played: 0,
next: Box::new([None, None, None, None]),
}
}
fn uct(&self, c: f32) -> [Option<f32>; 4] {
let mut ucts = [None; 4];
for (action, uct) in self.next.iter().zip(ucts.iter_mut()) {
if let Some(action) = action {
let exploitation = action.score as f32 / action.played as f32;
let exploration = f32::sqrt(f32::ln(self.played as f32) / action.played as f32);
uct.replace(c.mul_add(exploration, exploitation));
}
}
ucts
}
}
#[derive(Debug)]
struct MctsManager {
base: ActionInfo,
actions: Vec<Direction>,
expanded: bool,
snake: u8,
}
impl MctsManager {
fn new(snake: u8) -> Self {
Self {
base: ActionInfo::new(),
actions: Vec::new(),
expanded: false,
snake,
}
}
fn apply_score(&mut self, score: u32) {
self.base.played += 1;
self.base.score += score;
let mut current = &mut self.base;
for action in &self.actions {
let Some(new_current) = &mut current.next[usize::from(*action)] else {
error!("got action without actioninfo");
break;
};
current = new_current;
current.played += 1;
current.score += score;
}
self.actions.clear();
self.expanded = false;
}
fn next_action(&mut self, board: &Board, c: f32, rng: &mut impl RngCore) -> Option<Direction> {
if self.expanded {
return None;
}
let mut current = &mut self.base;
for action in &self.actions {
let Some(new_current) = &mut current.next[usize::from(*action)] else {
error!("got action without actioninfo");
return None;
};
current = new_current;
}
let ucts = current.uct(c);
let valid_actions = board.valid_actions(self.snake);
let ucts: Vec<_> = valid_actions
.map(|action| (action, ucts[usize::from(action)]))
.collect();
trace!("got actions: {ucts:?}");
if ucts.iter().any(|(_, uct)| uct.is_none()) {
let action = ucts.iter().filter(|(_, uct)| uct.is_none()).choose(rng)?.0;
self.expanded = true;
current.next[usize::from(action)].replace(ActionInfo::new());
self.actions.push(action);
return Some(action);
}
let action = ucts
.iter()
.max_by_key(|(_, uct)| FloatOrd(uct.unwrap_or(f32::NEG_INFINITY)))
.map(|(action, _)| *action);
if let Some(action) = action {
self.actions.push(action);
}
action
}
}

View File

@ -0,0 +1,66 @@
use std::fmt::Display;
use enum_iterator::Sequence;
use serde::{Deserialize, Serialize};
pub mod simulation;
pub mod wire;
#[derive(Debug, PartialEq, Eq, Clone, Copy, Deserialize, Serialize)]
pub struct Coord {
pub x: u8,
pub y: u8,
}
impl Coord {
#[must_use]
pub fn apply(self, direction: Direction) -> Option<Self> {
match direction {
Direction::Up => self.y.checked_add(1).map(|y| Self { y, x: self.x }),
Direction::Down => self.y.checked_sub(1).map(|y| Self { y, x: self.x }),
Direction::Left => self.x.checked_sub(1).map(|x| Self { x, y: self.y }),
Direction::Right => self.x.checked_add(1).map(|x| Self { x, y: self.y }),
}
}
#[must_use]
pub const fn wrapping_apply(mut self, direction: Direction) -> Self {
match direction {
Direction::Up => self.y = self.y.wrapping_add(1),
Direction::Down => self.y = self.y.wrapping_sub(1),
Direction::Left => self.x = self.x.wrapping_sub(1),
Direction::Right => self.x = self.x.wrapping_add(1),
}
self
}
}
impl Display for Coord {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "({}, {})", self.x, self.y)
}
}
#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Clone, Copy, Serialize, Sequence)]
#[serde(rename_all = "lowercase")]
pub enum Direction {
/// Move in positive y direction
Up,
/// Move in negative y direction
Down,
/// Move in negative x direction
Left,
/// Move in positive x direction
Right,
}
impl From<Direction> for usize {
fn from(value: Direction) -> Self {
match value {
Direction::Up => 0,
Direction::Down => 1,
Direction::Left => 2,
Direction::Right => 3,
}
}
}

View File

@ -0,0 +1,43 @@
mod royale;
mod standard;
use blanket::blanket;
use enum_dispatch::enum_dispatch;
use rand::Rng;
use royale::Royale;
use standard::Standard;
use crate::types::wire::Game;
use super::Board;
#[blanket(derive(Ref, Arc, Mut, Box))]
#[enum_dispatch(Maps)]
pub trait Map {
/// Called before the board is updated
fn pre_update(&self, board: &mut Board, rng: &mut impl Rng);
/// Called after the board is updated
fn post_update(&self, board: &mut Board, rng: &mut impl Rng);
}
#[enum_dispatch]
#[derive(Debug, Clone, Copy)]
pub enum Maps {
Standard,
Royale,
}
pub trait MapId {
/// ID of the map for detection
const ID: &str;
}
impl From<&Game> for Maps {
fn from(value: &Game) -> Self {
match value.map.as_ref() {
Royale::ID => Royale::from(&value.ruleset.settings).into(),
_ => Standard::from(&value.ruleset.settings).into(),
}
}
}

View File

@ -0,0 +1,86 @@
use rand::{Rng, seq::IteratorRandom};
use crate::types::{Coord, Direction, simulation::Board, wire::Settings};
use super::{Map, MapId, standard::Standard};
#[derive(Debug, Clone, Copy)]
pub struct Royale {
standard: Standard,
shrink_every_n_turns: u8,
}
impl Map for Royale {
fn pre_update(&self, board: &mut Board, rng: &mut impl Rng) {
self.standard.pre_update(board, rng);
}
fn post_update(&self, board: &mut Board, rng: &mut impl Rng) {
self.standard.post_update(board, rng);
// Royale uses the current turn to generate hazards, not the previous turn that's in the
// board state
let turn = board.turn + 1;
if turn < u32::from(self.shrink_every_n_turns) {
return;
}
let side = enum_iterator::all::<Direction>()
.choose(rng)
.unwrap_or(Direction::Up);
match side {
Direction::Up => {
if let Some(i) = board.hazard.first_zero() {
let y = board.linear_to_coord(i).y;
for x in 0..board.width {
let i = board.coord_to_linear(Coord { x, y });
board.hazard.set(i, true);
}
}
}
Direction::Down => {
if let Some(i) = board.hazard.last_zero() {
let y = board.linear_to_coord(i).y;
for x in 0..board.width {
let i = board.coord_to_linear(Coord { x, y });
board.hazard.set(i, true);
}
}
}
Direction::Left => {
if let Some(i) = board.hazard.first_zero() {
let x = board.linear_to_coord(i).y;
for y in 0..board.height {
let i = board.coord_to_linear(Coord { x, y });
board.hazard.set(i, true);
}
}
}
Direction::Right => {
if let Some(i) = board.hazard.last_zero() {
let x = board.linear_to_coord(i).y;
for y in 0..board.height {
let i = board.coord_to_linear(Coord { x, y });
board.hazard.set(i, true);
}
}
}
}
}
}
impl MapId for Royale {
const ID: &str = "royale";
}
impl From<&Settings> for Royale {
fn from(value: &Settings) -> Self {
let standard = Standard::from(value);
let shrink_every_n_turns = value.royale.shrink_every_n_turns;
Self {
standard,
shrink_every_n_turns,
}
}
}

View File

@ -0,0 +1,78 @@
use az::SaturatingAs;
use rand::{Rng, seq::SliceRandom};
use crate::types::{Coord, simulation::Board, wire::Settings};
use super::{Map, MapId};
#[derive(Debug, Clone, Copy)]
pub struct Standard {
min_food: u16,
food_spawn_chance: u8,
}
impl Map for Standard {
fn pre_update(&self, _board: &mut Board, _rng: &mut impl Rng) {}
fn post_update(&self, board: &mut Board, rng: &mut impl Rng) {
let food_needed = self.check_food_needing_placement(board, rng);
if food_needed > 0 {
Self::place_food_randomly(board, rng, food_needed);
}
}
}
impl MapId for Standard {
const ID: &str = "standard";
}
impl From<&Settings> for Standard {
fn from(value: &Settings) -> Self {
let min_food = value.minimum_food;
let food_spawn_chance = value.food_spawn_chance;
Self {
min_food,
food_spawn_chance,
}
}
}
impl Standard {
fn check_food_needing_placement(self, board: &Board, rng: &mut impl rand::Rng) -> u16 {
let num_current_food: u16 = board.food.count_ones().saturating_as();
if num_current_food < self.min_food {
return self.min_food - num_current_food;
}
if self.food_spawn_chance > 0 && (100 - rng.random_range(0..100)) < self.food_spawn_chance {
return 1;
}
0
}
fn place_food_randomly(board: &mut Board, rng: &mut impl rand::Rng, food_needed: u16) {
let mut unoccupied_points: Vec<_> = board.get_unoccupied_points(false, false).collect();
Self::place_food_ramdomly_at_positions(
board,
rng,
food_needed,
unoccupied_points.as_mut_slice(),
);
}
fn place_food_ramdomly_at_positions(
board: &mut Board,
rng: &mut impl rand::Rng,
food_needed: u16,
positions: &mut [Coord],
) {
let food_needed = usize::from(food_needed).min(positions.len());
positions.shuffle(rng);
for tile in &positions[..food_needed] {
let i = board.coord_to_linear(*tile);
board.food.set(i, true);
}
}
}

View File

@ -0,0 +1,444 @@
mod maps;
mod rules;
use std::{
collections::VecDeque,
fmt::Display,
num::NonZeroUsize,
ops::{Deref, DerefMut},
sync::Arc,
};
use az::SaturatingAs;
use bitvec::prelude::*;
use log::{error, warn};
use maps::{Map, Maps};
use rand::prelude::*;
use rules::{Ruleset, Rulesets};
use super::{Coord, Direction, wire::Request};
#[derive(Debug, PartialEq, Eq, Clone)]
enum SmallBitBox {
Stack {
storage: BitArr!(for Self::STACK_BITS),
len: NonZeroUsize,
},
Heap(BitBox),
}
impl SmallBitBox {
const STACK_BITS: usize = usize::BITS as usize * 3;
fn new(initial: bool, len: usize) -> Self {
if let len @ 1..Self::STACK_BITS = len {
let Some(len) = NonZeroUsize::new(len) else {
unreachable!()
};
let mut storage = BitArray::ZERO;
storage.fill(initial);
Self::Stack { storage, len }
} else {
Self::Heap(bitbox![u8::from(initial); len])
}
}
}
impl Deref for SmallBitBox {
type Target = BitSlice;
fn deref(&self) -> &Self::Target {
match self {
Self::Stack { storage, len } => &storage[..len.get()],
Self::Heap(bit_box) => bit_box,
}
}
}
impl DerefMut for SmallBitBox {
fn deref_mut(&mut self) -> &mut Self::Target {
match self {
Self::Stack { storage, len } => &mut storage[..len.get()],
Self::Heap(bit_box) => bit_box,
}
}
}
#[derive(Clone)]
pub struct Game {
pub board: Board,
map: Maps,
ruleset: Rulesets,
}
impl From<&Request> for Game {
fn from(value: &Request) -> Self {
let board = value.into();
let map = (&value.game).into();
let ruleset = (&value.game.ruleset).into();
Self {
board,
map,
ruleset,
}
}
}
impl Game {
pub fn simulate_random(&mut self, rng: &mut impl Rng) {
loop {
let random_actions: Vec<_> = (0..self.board.snakes.len())
.filter_map(|i| {
self.board
.valid_actions_index(i)
.choose(rng)
.map(|direction| (i.saturating_as(), direction))
})
.collect();
if self.next_turn(&random_actions, rng) {
break;
}
}
}
pub fn next_turn_random(&mut self, actions: &[(u8, Direction)], rng: &mut impl Rng) -> bool {
let random_actions: Vec<_> = (0..self.board.snakes.len())
.filter_map(|i| {
actions
.iter()
.find(|(j, _)| i == usize::from(*j))
.copied()
.or_else(|| {
self.board
.valid_actions_index(i)
.choose(rng)
.map(|direction| (i.saturating_as(), direction))
})
})
.collect();
self.next_turn(&random_actions, rng)
}
pub fn next_turn(&mut self, actions: &[(u8, Direction)], rng: &mut impl Rng) -> bool {
self.map.pre_update(&mut self.board, rng);
let game_over = self.ruleset.execute(&mut self.board, actions);
self.map.post_update(&mut self.board, rng);
self.board.turn += 1;
game_over
}
}
#[derive(Debug, PartialEq, Eq, Clone)]
pub struct Board {
width: u8,
height: u8,
turn: u32,
food: SmallBitBox,
hazard: SmallBitBox,
free: SmallBitBox,
snakes: Vec<Snake>,
id_map: Arc<[(u8, Arc<str>)]>,
}
impl From<&Request> for Board {
fn from(value: &Request) -> Self {
let width = value.board.width;
let height = value.board.height;
let fields = usize::from(width) * usize::from(height);
let id_map = value
.board
.snakes
.iter()
.enumerate()
.filter_map(|(i, snake)| {
u8::try_from(i)
.inspect_err(|e| warn!("unable to convert id to u8: {e}"))
.ok()
.map(|i| (i, snake.id.clone()))
})
.collect::<Vec<_>>();
let mut board = Self {
width,
height,
turn: value.turn,
food: SmallBitBox::new(false, fields),
hazard: SmallBitBox::new(false, fields),
free: SmallBitBox::new(true, fields),
snakes: Vec::with_capacity(value.board.snakes.len()),
id_map: id_map.into(),
};
for &food in &value.board.food {
let index = board.coord_to_linear(food);
board.food.set(index, true);
}
for &hazard in &value.board.hazards {
let index = board.coord_to_linear(hazard);
board.hazard.set(index, true);
}
let constrictor = value.game.ruleset.name.as_ref() == "constrictor";
for (id, snake) in value.board.snakes.iter().enumerate() {
for &tile in snake
.body
.iter()
.take(snake.body.len() - usize::from(!constrictor))
{
let index = board.coord_to_linear(tile);
board.free.set(index, false);
}
let snake = Snake {
body: snake.body.iter().rev().copied().collect(),
id: u8::try_from(id).unwrap_or(u8::MAX),
health: snake.health,
};
board.snakes.push(snake);
}
board
}
}
impl Display for Board {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
writeln!(f, "{}x{} @ {}", self.width, self.height, self.turn)?;
for y in (0..self.height).rev() {
for x in 0..self.width {
let tile = Coord { x, y };
if self.snakes.iter().any(|snake| snake.head() == tile) {
write!(f, "H")?;
continue;
}
if self.snakes.iter().any(|snake| snake.tail() == tile) {
write!(f, "T")?;
continue;
}
let index = self.coord_to_linear(tile);
if !self.free[index] {
write!(f, "S")?;
continue;
}
if self.food[index] {
write!(f, "f")?;
continue;
}
if self.hazard[index] {
write!(f, "h")?;
continue;
}
write!(f, ".")?;
}
writeln!(f)?;
}
Ok(())
}
}
impl Board {
#[must_use]
pub fn get_id(&self, str_id: &str) -> Option<u8> {
self.id_map
.iter()
.find(|(_, str_id2)| *str_id == **str_id2)
.map(|(id, _)| *id)
}
#[must_use]
pub const fn turn(&self) -> u32 {
self.turn
}
#[must_use]
pub fn num_snakes(&self) -> usize {
self.snakes.len()
}
#[must_use]
pub fn alive(&self, id: u8) -> bool {
self.id_to_index(id).is_some()
}
#[must_use]
pub fn length(&self, id: u8) -> usize {
let Some(index) = self.id_to_index(id) else {
return 0;
};
self.snakes[index].body.len()
}
#[must_use]
pub fn max_length(&self) -> usize {
self.snakes
.iter()
.map(|snake| snake.body.len())
.max()
.unwrap_or(0)
}
#[must_use]
pub fn is_food(&self, tile: Coord) -> bool {
let index = self.coord_to_linear(tile);
self.food[index]
}
#[must_use]
pub fn is_hazard(&self, tile: Coord) -> bool {
let index = self.coord_to_linear(tile);
self.hazard[index]
}
#[must_use]
pub fn is_free(&self, tile: Coord) -> bool {
if !self.is_in_bounds(tile) {
return false;
}
let index = self.coord_to_linear(tile);
self.free[index]
}
pub fn valid_actions(&self, id: u8) -> impl Iterator<Item = Direction> + use<'_> {
let index = self.id_to_index(id);
index
.into_iter()
.flat_map(|index| self.valid_actions_index(index))
}
#[must_use]
pub fn random_action(&self, id: u8, rng: &mut impl RngCore) -> Direction {
let Some(index) = self.id_to_index(id) else {
return Direction::Up;
};
self.valid_actions_index(index)
.choose(rng)
.unwrap_or(Direction::Up)
}
pub fn random_actions<'a, R: RngCore>(
&self,
rng: &'a mut R,
) -> impl Iterator<Item = (u8, Direction)> + use<'_, 'a, R> {
(0..self.snakes.len()).map(|index| {
(
self.snakes[index].id,
self.valid_actions_index(index)
.choose(rng)
.unwrap_or(Direction::Up),
)
})
}
fn id_to_index(&self, id: u8) -> Option<usize> {
self.snakes.binary_search_by_key(&id, |snake| snake.id).ok()
}
fn valid_actions_index(&self, index: usize) -> impl Iterator<Item = Direction> + use<'_> {
let head = self.snakes[index].head();
enum_iterator::all::<Direction>()
.filter(move |direction| self.is_free(head.wrapping_apply(*direction)))
}
fn update_free_map(&mut self) {
// free tails
for snake in &self.snakes {
let tail = snake.tail();
let pre_tail = snake.body[snake.body.len() - 2];
if tail != pre_tail {
let tail_index = self.coord_to_linear(tail);
self.free.set(tail_index, true);
}
}
// block heads
for snake in &self.snakes {
let head = snake.head();
let head_index = self.coord_to_linear(head);
self.free.set(head_index, false);
}
}
fn get_unoccupied_points(
&self,
include_possible_moves: bool,
include_hazards: bool,
) -> impl Iterator<Item = Coord> + use<'_> {
let possible_moves: Vec<_> = if include_possible_moves {
Vec::new()
} else {
self.snakes
.iter()
.flat_map(|snake| {
let head = snake.head();
enum_iterator::all::<Direction>()
.map(move |direction| head.wrapping_apply(direction))
.filter(|tile| self.is_in_bounds(*tile))
.map(|tile| self.coord_to_linear(tile))
})
.collect()
};
self.free
.iter()
.zip(self.food.iter())
.zip(self.hazard.iter())
.enumerate()
.filter(move |(i, ((free, food), hazard))| {
**free
&& !**food
&& (include_hazards || !**hazard)
&& (include_possible_moves || !possible_moves.contains(i))
})
.map(|(i, _)| self.linear_to_coord(i))
}
fn coord_to_linear(&self, coord: Coord) -> usize {
usize::from(coord.x) + usize::from(coord.y) * usize::from(self.width)
}
fn linear_to_coord(&self, linear: usize) -> Coord {
let x = (linear % usize::from(self.width)).saturating_as();
let y = (linear / usize::from(self.width)).saturating_as();
Coord { x, y }
}
const fn is_in_bounds(&self, coord: Coord) -> bool {
coord.x < self.width && coord.y < self.height
}
}
#[derive(Debug, PartialEq, Eq, Clone)]
struct Snake {
id: u8,
health: u8,
body: VecDeque<Coord>,
}
impl Snake {
pub fn head(&self) -> Coord {
self.body.back().copied().unwrap_or_else(|| {
error!("Snake without a head: {self:?}");
Coord { x: 0, y: 0 }
})
}
pub fn tail(&self) -> Coord {
self.body.front().copied().unwrap_or_else(|| {
error!("Snake without a tail: {self:?}");
Coord { x: 0, y: 0 }
})
}
pub fn advance(&mut self, head: Coord) {
self.body.push_back(head);
self.body.pop_front();
}
pub fn feed(&mut self) {
if let Some(tail) = self.body.front() {
self.body.push_front(*tail);
self.health = 100;
}
}
}

View File

@ -0,0 +1,38 @@
use crate::types::{Direction, simulation::Board, wire};
use super::{
Ruleset,
standard::{DamageHazards, eliminate_snakes, game_over, move_snakes, reduce_snake_health},
};
#[derive(Debug, Clone, Copy)]
pub struct Constrictor {
damage_hazards: DamageHazards,
}
impl From<&wire::Ruleset> for Constrictor {
fn from(value: &wire::Ruleset) -> Self {
Self {
damage_hazards: (&value.settings).into(),
}
}
}
impl Ruleset for Constrictor {
fn execute(&self, board: &mut Board, actions: &[(u8, Direction)]) -> bool {
let game_over = game_over(board);
move_snakes(board, actions);
reduce_snake_health(board);
self.damage_hazards.execute(board);
eliminate_snakes(board);
grow_snakes(board);
board.update_free_map();
game_over
}
}
fn grow_snakes(board: &mut Board) {
for snake in &mut board.snakes {
snake.feed();
}
}

View File

@ -0,0 +1,37 @@
mod constrictor;
mod solo;
mod standard;
use constrictor::Constrictor;
use enum_dispatch::enum_dispatch;
use solo::Solo;
use standard::Standard;
use crate::types::{Direction, wire};
use super::Board;
#[enum_dispatch]
pub trait Ruleset {
/// executes one turn of the ruleset.
/// Returns true if the game is over
fn execute(&self, board: &mut Board, actions: &[(u8, Direction)]) -> bool;
}
#[enum_dispatch(Ruleset)]
#[derive(Debug, Clone, Copy)]
pub enum Rulesets {
Standard,
Constrictor,
Solo,
}
impl From<&wire::Ruleset> for Rulesets {
fn from(value: &wire::Ruleset) -> Self {
match value.name.as_ref() {
"solo" => Solo::from(value).into(),
"constrictor" => Constrictor::from(value).into(),
_ => Standard::from(value).into(),
}
}
}

View File

@ -0,0 +1,36 @@
use crate::types::{Direction, simulation::Board, wire};
use super::{
Ruleset,
standard::{DamageHazards, eliminate_snakes, feed_snakes, move_snakes, reduce_snake_health},
};
#[derive(Debug, Clone, Copy)]
pub struct Solo {
damage_hazards: DamageHazards,
}
impl From<&wire::Ruleset> for Solo {
fn from(value: &wire::Ruleset) -> Self {
Self {
damage_hazards: (&value.settings).into(),
}
}
}
impl Ruleset for Solo {
fn execute(&self, board: &mut Board, actions: &[(u8, Direction)]) -> bool {
let game_over = game_over(board);
move_snakes(board, actions);
reduce_snake_health(board);
self.damage_hazards.execute(board);
feed_snakes(board);
eliminate_snakes(board);
board.update_free_map();
game_over
}
}
pub fn game_over(board: &Board) -> bool {
board.num_snakes() == 0
}

View File

@ -0,0 +1,180 @@
use crate::types::{
Direction,
simulation::Board,
wire::{self, Settings},
};
use super::Ruleset;
#[derive(Debug, Clone, Copy)]
pub struct Standard {
damage_hazards: DamageHazards,
}
impl From<&wire::Ruleset> for Standard {
fn from(value: &wire::Ruleset) -> Self {
Self {
damage_hazards: (&value.settings).into(),
}
}
}
impl Ruleset for Standard {
fn execute(&self, board: &mut Board, actions: &[(u8, Direction)]) -> bool {
let game_over = game_over(board);
move_snakes(board, actions);
reduce_snake_health(board);
self.damage_hazards.execute(board);
feed_snakes(board);
eliminate_snakes(board);
board.update_free_map();
game_over
}
}
pub fn move_snakes(board: &mut Board, actions: &[(u8, Direction)]) {
for i in 0..board.snakes.len() {
let snake = &board.snakes[i];
let action = actions.iter().find(|(id, _)| *id == snake.id).map_or_else(
|| {
let head = snake.body[0];
let previous_head = snake.body[1];
let delta_x = i16::from(head.x) - i16::from(previous_head.x);
let delta_y = i16::from(head.y) - i16::from(previous_head.y);
if delta_x == 0 && delta_y == 0 {
Direction::Up
} else if delta_x.abs() > delta_y.abs() {
if delta_x < 0 {
Direction::Left
} else {
Direction::Right
}
} else if delta_y < 0 {
Direction::Down
} else {
Direction::Up
}
},
|(_, action)| *action,
);
let new_head = snake.head().wrapping_apply(action);
board.snakes[i].advance(new_head);
}
}
pub fn reduce_snake_health(board: &mut Board) {
for snake in &mut board.snakes {
snake.health = snake.health.saturating_sub(1);
}
}
#[derive(Debug, Clone, Copy)]
pub struct DamageHazards {
damage: u8,
}
impl DamageHazards {
pub fn execute(self, board: &mut Board) {
let mut i = 0;
while i < board.snakes.len() {
let head = board.snakes[i].head();
if board.is_in_bounds(head) {
let head_index = board.coord_to_linear(head);
if board.hazard[head_index] && !board.food[head_index] {
let health = &mut board.snakes[i].health;
*health = health.saturating_sub(self.damage);
if *health == 0 {
let snake = board.snakes.remove(i);
for tile in snake.body {
let index = board.coord_to_linear(tile);
board.free.set(index, true);
}
continue;
}
}
}
i += 1;
}
}
}
impl From<&Settings> for DamageHazards {
fn from(value: &Settings) -> Self {
let damage = value.hazard_damage_per_turn;
Self { damage }
}
}
pub fn eliminate_snakes(board: &mut Board) {
// eliminate out of health and out of bounds
let mut i = 0;
while i < board.snakes.len() {
let snake = &board.snakes[i];
if snake.health == 0 || !board.is_in_bounds(snake.head()) {
let snake = board.snakes.remove(i);
for tile in snake.body.iter().skip(1) {
if board.is_in_bounds(*tile) {
let index = board.coord_to_linear(*tile);
board.free.set(index, true);
}
}
continue;
}
i += 1;
}
// look for collisions
let mut collisions = vec![];
for snake in &board.snakes {
let head = snake.head();
let head_index = board.coord_to_linear(head);
if !board.free[head_index] {
collisions.push(snake.id);
continue;
}
for snake2 in &board.snakes {
if snake.id != snake2.id
&& snake.head() == snake2.head()
&& snake.body.len() <= snake2.body.len()
{
collisions.push(snake.id);
break;
}
}
}
// apply collisions
let mut i = 0;
while i < board.snakes.len() {
if collisions.contains(&board.snakes[i].id) {
let snake = board.snakes.remove(i);
for tile in snake.body {
let index = board.coord_to_linear(tile);
board.free.set(index, true);
}
continue;
}
i += 1;
}
}
pub fn feed_snakes(board: &mut Board) {
let mut eaten_food = vec![];
for i in 0..board.snakes.len() {
let head = board.snakes[i].head();
if board.is_in_bounds(head) {
let head_index = board.coord_to_linear(head);
if board.food[head_index] {
eaten_food.push(head_index);
board.snakes[i].feed();
}
}
}
for food_index in eaten_food {
board.food.set(food_index, false);
}
}
pub fn game_over(board: &Board) -> bool {
board.num_snakes() <= 1
}

View File

@ -0,0 +1,121 @@
use std::sync::Arc;
use serde::{Deserialize, Serialize};
use super::{Coord, Direction};
#[derive(Debug, PartialEq, Eq, Clone, Deserialize, Serialize)]
pub struct Request {
/// Game object describing the game being played.
pub game: Game,
/// Turn number for this move.
pub turn: u32,
/// Board object describing the initial state of the game board.
pub board: Board,
/// Battlesnake Object describing your Battlesnake.
pub you: Battlesnake,
}
#[derive(Debug, PartialEq, Eq, Clone, Deserialize, Serialize)]
pub struct Game {
/// A unique identifier for this Game.
pub id: Arc<str>,
/// Information about the ruleset being used to run this Game.
pub ruleset: Ruleset,
/// The name of the map being played on.
pub map: Arc<str>,
/// How much time your snake has to respond to requests for this Game.
pub timeout: u16,
/// The source of this Game.
/// One of:
/// - tournament
/// - league
/// - arena
/// - challenge
/// - custom
pub source: Arc<str>,
}
#[derive(Debug, PartialEq, Eq, Clone, Deserialize, Serialize)]
pub struct Ruleset {
/// Name of the ruleset being used to run this game.
pub name: Arc<str>,
/// The release version of the Rules module used in this game.
pub version: Arc<str>,
/// A collection of specific settings being used by the current game that control how the rules
/// are applied.
pub settings: Settings,
}
#[derive(Debug, PartialEq, Eq, Clone, Copy, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct Settings {
/// Percentage chance of spawning a new food every round.
pub food_spawn_chance: u8,
/// Minimum food to keep on the board every turn.
pub minimum_food: u16,
/// Health damage a snake will take when ending its turn in a hazard. This stacks on top of the
/// regular 1 damage a snake takes per turn.
pub hazard_damage_per_turn: u8,
/// Settings for the royale game mode
pub royale: RoyaleSettings,
}
#[derive(Debug, PartialEq, Eq, Clone, Copy, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct RoyaleSettings {
/// The number of turns between generating new hazards (shrinking the safe board space).
pub shrink_every_n_turns: u8,
}
#[derive(Debug, PartialEq, Eq, Clone, Deserialize, Serialize)]
pub struct Board {
/// The number of rows in the y-axis of the game board.
pub height: u8,
/// The number of rows in the x-axis of the game board.
pub width: u8,
/// Array of coordinates representing food locations on the game board.
pub food: Vec<Coord>,
/// Array of coordinates representing hazardous locations on the game board.
pub hazards: Vec<Coord>,
/// Array of Battlesnake objects representing all Battlesnakes remaining on the game board
/// (including yourself if you haven't been eliminated).
pub snakes: Vec<Battlesnake>,
}
#[derive(Debug, PartialEq, Eq, Clone, Deserialize, Serialize)]
pub struct Battlesnake {
/// Unique identifier for this Battlesnake in the context of the current Game.
pub id: Arc<str>,
/// Name given to this Battlesnake by its author
pub name: Arc<str>,
/// Health value of this Battlesnake, between 0 and 100
pub health: u8,
/// Array of coordinates representing the Battlesnake's location on the game board.
/// This array is ordered from head to tail.
pub body: Vec<Coord>,
/// The previous response time of this Battlesnake, in milliseconds.
/// If the Battlesnake timed out and failed to respond, the game timeout will be returned
pub latency: Arc<str>,
/// Coordinates for this Battlesnake's head.
/// Equivalent to the first element of the body array.
pub head: Coord,
/// Length of this Battlesnake from head to tail.
/// Equivalent to the length of the body array.
pub length: u16,
/// Message shouted by this Battlesnake on the previous turn
pub shout: Option<Arc<str>>,
/// The squad that the Battlesnake belongs to.
/// Used to identify squad members in Squad Mode games.
pub squad: Arc<str>,
}
#[derive(Debug, PartialEq, Eq, Clone, Serialize)]
pub struct Response {
/// Your Battlesnake's move for this turn.
#[serde(rename = "move")]
pub direction: Direction,
/// An optional message sent to all other Battlesnakes on the next turn.
/// Must be 256 characters or less.
pub shout: Option<String>,
}

2
rust-toolchain.toml Normal file
View File

@ -0,0 +1,2 @@
[toolchain]
channel = "stable"

View File

@ -1,7 +1,8 @@
[package]
name = "xtask"
version = "0.1.0"
edition = "2021"
edition = "2024"
[dependencies]
rayon = "1.10"
rich_progress_bar = "1.1"

View File

@ -4,11 +4,13 @@ use std::{
net::TcpStream,
path::{Path, PathBuf},
process::{Child, Command, Stdio},
sync::Mutex,
thread::sleep,
time::Duration,
};
use rayon::iter::{IntoParallelIterator, ParallelIterator};
use rich_progress_bar::{Colors, RichProgressBar};
type DynError = Box<dyn std::error::Error>;
@ -232,9 +234,13 @@ fn regression() -> Result<(), DynError> {
}
};
sleep(Duration::from_secs(1));
let res = try_regression();
snake.kill().and(prod.kill())?;
stop_local_docker()?;
stop_production()?;
let (won, draw, loose) = res?;
let games = won + draw + loose;
println!(
@ -261,22 +267,29 @@ fn try_regression() -> Result<(usize, usize, usize), DynError> {
const GAMES: usize = 100;
// limit the parallelism
rayon::ThreadPoolBuilder::new()
.num_threads(std::thread::available_parallelism()?.get() / 3)
.num_threads(std::thread::available_parallelism()?.get() / 4)
.build_global()
.unwrap();
let mut progress = RichProgressBar::new();
progress
.set_progress_character('=')
.set_color(Colors::BrightCyan)
.set_total(GAMES as u64);
let progress = Mutex::new(&mut progress);
let stats = (0..GAMES)
.into_par_iter()
.flat_map(|_| {
eprint!(".");
let game = Command::new("./battlesnake-cli")
.current_dir(project_root())
.args([
"play",
"-W",
"--width",
"11",
"-H",
"--height",
"11",
"--timeout",
"100",
"--name",
"local",
"--url",
@ -290,7 +303,7 @@ fn try_regression() -> Result<(usize, usize, usize), DynError> {
])
.output()
.ok()?;
if !game.status.success() {
let res = if !game.status.success() {
eprintln!("game output: {}", String::from_utf8(game.stderr).ok()?);
eprintln!("game status: {}", game.status);
None
@ -308,7 +321,11 @@ fn try_regression() -> Result<(usize, usize, usize), DynError> {
} else {
Some((0, 1, 0))
}
};
if let Ok(mut progress) = progress.lock() {
let _ = progress.inc();
}
res
})
.reduce(
|| (0, 0, 0),
@ -331,7 +348,7 @@ fn run_snake(port: u16, log: Option<&str>) -> Result<Child, DynError> {
}
let mut snake = snake
.args(
["run", "--bin", "battlesnake"]
["run", "--bin", "battlesnake", "--release"]
.map(str::to_string)
.into_iter()
.chain(env::args().skip(2)),
@ -366,7 +383,7 @@ fn run_local_docker(port: u16) -> Result<Child, DynError> {
"--env",
"RUST_LOG=error",
"--env",
format!("ROCKET_PORT={}", port).as_str(),
format!("PORT={}", port).as_str(),
"--network=host",
"--rm",
"local_snake",
@ -386,6 +403,13 @@ fn run_local_docker(port: u16) -> Result<Child, DynError> {
}
}
fn stop_local_docker() -> Result<(), DynError> {
Command::new("docker")
.args(["stop", "battlesnake-regression-local"])
.status()?;
Ok(())
}
fn run_production(port: u16) -> Result<Child, DynError> {
let mut snake = Command::new("docker")
.args([
@ -396,7 +420,7 @@ fn run_production(port: u16) -> Result<Child, DynError> {
"--env",
"RUST_LOG=error",
"--env",
format!("ROCKET_PORT={}", port).as_str(),
format!("PORT={}", port).as_str(),
"--network=host",
"--rm",
"docker.mkaenner.de/snake:latest",
@ -416,6 +440,13 @@ fn run_production(port: u16) -> Result<Child, DynError> {
}
}
fn stop_production() -> Result<(), DynError> {
Command::new("docker")
.args(["stop", "battlesnake-regression-production"])
.status()?;
Ok(())
}
fn docker() -> Result<(), DynError> {
if !Command::new("docker")
.current_dir(project_root())