xtask for 2-player local game

This commit is contained in:
Max Känner 2024-09-02 18:06:41 +02:00
parent bed2b1be81
commit 548b7ff7a6

View File

@ -2,7 +2,7 @@ use std::{
env,
net::TcpStream,
path::{Path, PathBuf},
process::Command,
process::{Child, Command},
thread::sleep,
time::Duration,
};
@ -20,6 +20,7 @@ fn try_main() -> Result<(), DynError> {
let task = env::args().nth(1);
match task.as_deref() {
Some("local") => local()?,
Some("local2") => local2()?,
_ => print_help(),
}
Ok(())
@ -30,51 +31,93 @@ fn print_help() {
"Tasks:
local runs the snake on a local game
local2 runs the snake twice on a local game
"
)
}
fn local() -> Result<(), DynError> {
let cargo = env::var("CARGO").unwrap_or_else(|_| "cargo".to_string());
let mut snake = run_snake(8000)?;
let game = Command::new("./battlesnake-cli")
.current_dir(project_root())
.args([
"play",
"-W",
"11",
"-H",
"11",
"--name",
"local test",
"--url",
"http://localhost:8000",
"-g",
"solo",
"--browser",
])
.status();
game.and(snake.kill())?;
Ok(())
}
fn local2() -> Result<(), DynError> {
let mut snake1 = run_snake(8000)?;
let mut snake2 = match run_snake(8001) {
Ok(snake) => snake,
Err(e) => {
let _ = snake1.kill();
return Err(e);
}
};
let game = Command::new("./battlesnake-cli")
.current_dir(project_root())
.args([
"play",
"-W",
"11",
"-H",
"11",
"--name",
"local test1",
"--url",
"http://localhost:8000",
"--name",
"local test2",
"--url",
"http://localhost:8001",
"-g",
"duel",
"--browser",
])
.status();
game.and(snake1.kill()).and(snake2.kill())?;
Ok(())
}
fn run_snake(port: u16) -> Result<Child, DynError> {
let cargo = env::var("CARGO").unwrap_or_else(|_| "cargo".to_string());
let mut snake = Command::new(cargo)
.current_dir(project_root())
.env("PORT", port.to_string())
.args(
["run", "--bin", "battlesnake"]
.map(str::to_string)
.into_iter()
.chain(env::args().skip(1)),
.chain(env::args().skip(2)),
)
.spawn()?;
while snake.try_wait()?.is_none() {
// check if port 8000 has been opened. Only then the game can be started
if TcpStream::connect(("127.0.0.1", 8000)).is_ok() {
let _game = Command::new("./battlesnake-cli")
.current_dir(project_root())
.args([
"play",
"-W",
"11",
"-H",
"11",
"--name",
"local test",
"--url",
"http://localhost:8000",
"-g",
"solo",
"--browser",
])
.status();
break;
} else {
sleep(Duration::from_secs(1));
loop {
if let Some(status) = snake.try_wait()? {
Err(format!("{status}"))?;
}
if TcpStream::connect(("127.0.0.1", port)).is_ok() {
break Ok(snake);
}
sleep(Duration::from_secs(1));
}
snake.kill()?;
Ok(())
}
fn project_root() -> PathBuf {