Move in random actions (#225)

This commit is contained in:
Gregor Zeitlinger 2025-04-23 10:41:03 +02:00 • committed by GitHub
commit 62a7630d3d
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
26 changed files with 1960 additions and 1569 deletions

22
.github/workflows/bench.yml vendored Normal file
View file

@ -0,0 +1,22 @@
name: Performance Benchmark
on:
workflow_dispatch:
# still hangs
#
# push:
# branches: [ "main" ]
# pull_request:
# branches: [ "main" ]
jobs:
check:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: jdx/mise-action@v2
with:
experimental: 'true' # to get lock file support
- name: Random actions test
run: mise run random-actions

19
.github/workflows/check-client.yml vendored Normal file
View file

@ -0,0 +1,19 @@
name: Check Client
on:
push:
branches: [ "main" ]
pull_request:
branches: [ "main" ]
jobs:
check:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: jdx/mise-action@v2
with:
experimental: 'true' # to get lock file support
- name: Check all
run: mise run ci-client

19
.github/workflows/check-server.yml vendored Normal file
View file

@ -0,0 +1,19 @@
name: Check Server
on:
push:
branches: [ "main" ]
pull_request:
branches: [ "main" ]
jobs:
check:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: jdx/mise-action@v2
with:
experimental: 'true' # to get lock file support
- name: Check all
run: mise run ci-server

View file

@ -1,53 +0,0 @@
name: Check All
on:
push:
branches: [ "main" ]
pull_request:
branches: [ "main" ]
env:
RUSTFLAGS: "-Dwarnings" # Make sure CI fails on all warnings, including Clippy lints
CARGO_TERM_COLOR: always
jobs:
build:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: jdx/mise-action@v2
with:
experimental: 'true' # to get lock file support
- name: Install dependencies
uses: awalsh128/cache-apt-pkgs-action@latest
with:
packages: pkg-config libx11-dev libxi-dev libgl1-mesa-dev libasound2-dev
version: 1.0
- name: Build server
working-directory: ./server
run: |
cargo build
- name: Run tests server
working-directory: ./server
run: cargo test
- name: Run clippy server
working-directory: ./server
run: cargo clippy
- name: Format server
working-directory: ./server
run: cargo fmt --check
- name: Build client
working-directory: ./client
run: cargo build
- name: Run tests client
working-directory: ./client
run: cargo test
- name: Run clippy client
working-directory: ./client
run: cargo clippy
- name: Format client
working-directory: ./client
run: cargo fmt --check

1330
client/Cargo.lock generated

File diff suppressed because it is too large Load diff

View file

@ -22,18 +22,9 @@ serde_json = "1.0.140"
server = { path = "../server", version = "0.1.0" }
wasm-bindgen = "0.2.95"
wasm-bindgen-futures = "0.4.50"
lazy_static = "1.4.0"
log = "0.4.27"
async-std = "1.13.1"
serde-wasm-bindgen = "0.6.5"
console_error_panic_hook = "0.1.7"
web-sys = { version = "0.3.72", features = ["Window"] }
js-sys = "0.3.72"
pyroscope = { version = "0.5.8", optional = true }
pyroscope_pprofrs = { version = "0.2.8", optional = true }
[features]
profiling = ["dep:pyroscope", "dep:pyroscope_pprofrs"]
[[bin]]
name = "local_client"

View file

@ -15,6 +15,7 @@ use server::game_setup::setup_game;
use server::map::Terrain;
use server::player::add_unit;
use server::position::Position;
use server::profiling::start_profiling;
use server::resource_pile::ResourcePile;
use server::unit::{UnitType, set_unit_position};
use server::utils::remove_element;
@ -59,28 +60,6 @@ async fn main() {
run(game, &mut features).await;
}
#[cfg(not(feature = "profiling"))]
fn start_profiling() {
// do nothing
}
#[cfg(feature = "profiling")]
fn start_profiling() {
println!("start profiling");
use pyroscope::PyroscopeAgent;
use pyroscope_pprofrs::{PprofConfig, pprof_backend};
let pprof_config = PprofConfig::new().sample_rate(100);
let backend_impl = pprof_backend(pprof_config);
let agent = PyroscopeAgent::builder("http://localhost:4040", "clash")
.backend(backend_impl)
.build()
.expect("Failed to initialize pyroscope");
let _ = agent.start().unwrap();
}
fn get_modes(args: &[String]) -> Vec<Mode> {
match args.get(1) {
Some(arg) => match arg.as_str() {

View file

@ -1,9 +1,11 @@
[env]
RUST_BACKTRACE = '1'
RUSTFLAGS = '-Dwarnings' # Make sure CI fails on all warnings, including Clippy lints
CARGO_TERM_COLOR = 'always'
[tasks.random-actions]
description = "Run server tests"
run = 'cargo nextest run --nocapture random_actions'
run = 'cargo nextest run --release --nocapture test_random_actions -Pbench'
dir = "server"
[tasks.test]
@ -36,11 +38,35 @@ dir = "client"
[tasks.format-and-lint]
depends = ["server-format-and-lint", "client-format-and-lint"]
[tasks.ci-server]
description = "Run CI tasks server"
dir = "server"
run = [
"cargo build",
"cargo fmt --check",
"cargo clippy",
"cargo nextest run"
]
[tasks.ci-client]
description = "Run CI tasks server"
dir = "client"
run = [
"cargo build",
"cargo fmt --check",
"cargo clippy",
]
[tasks.profile]
description = "Run AI client with profiling"
run = ["cargo run --release --package client --features profiling --bin local_client -- ai"]
dir = "client"
[tasks.profile-random-actions]
description = "Run AI random actions test with profiling"
run = ["cargo test --release --features profiling random_actions"]
dir = "server"
[tools]
"cargo:cargo-nextest" = "latest"
rust = { version = "latest", components = "clippy,rustfmt" }

View file

@ -0,0 +1,5 @@
[profile.default]
default-filter = 'not test(test_random_actions)'
[profile.bench]
default-filter = 'all()'

1435
server/Cargo.lock generated

File diff suppressed because it is too large Load diff

View file

@ -7,9 +7,6 @@ repository = "git@github.com:boardgamers/clash.git"
homepage = "https://www.boardgamers.space/"
description = "A server for Clash of Cultures"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[lib]
name = "server"
crate-type = ["cdylib", "rlib"]
@ -32,3 +29,9 @@ num_cpus = "1.16.0"
readonly = "0.2.13"
enumset = { version = "1.1.5" }
rustc-hash = "2.1.1"
pyroscope = { version = "0.5.8", optional = true }
pyroscope_pprofrs = { version = "0.2.8", optional = true }
chrono = "0.4.40"
[features]
profiling = ["dep:pyroscope", "dep:pyroscope_pprofrs"]

View file

@ -99,14 +99,25 @@ pub enum ActionType {
/// Panics if the action is illegal
#[must_use]
pub fn execute_action(mut game: Game, action: Action, player_index: usize) -> Game {
assert_eq!(player_index, game.active_player(), "Not your turn");
if !game.supports_undo {
return execute_without_undo(game, action, player_index)
.expect("action should be executed");
execute_without_undo(&mut game, action, player_index).expect("action should be executed");
return game;
}
if let Action::Undo = action {
assert!(
game.can_undo(),
"actions revealing new information can't be undone"
);
return undo(game).expect("cannot undo");
}
let add_undo = !matches!(&action, Action::Undo);
let old = to_serde_value(&game);
let old_player = game.active_player();
game = execute_without_undo(game, action, player_index).expect("action should be executed");
execute_without_undo(&mut game, action, player_index).expect("action should be executed");
let new = to_serde_value(&game);
let new_player = game.active_player();
let patch = json_patch::diff(&new, &old);
@ -119,42 +130,36 @@ pub fn execute_action(mut game: Game, action: Action, player_index: usize) -> Ga
game
}
fn execute_without_undo(
mut game: Game,
///
/// # Errors
///
/// Returns an error if the action is not valid
pub fn execute_without_undo(
game: &mut Game,
action: Action,
player_index: usize,
) -> Result<Game, String> {
if player_index != game.active_player() {
return Err("Not your turn".to_string());
}
if let Action::Undo = action {
if !game.can_undo() {
return Err("actions revealing new information can't be undone".to_string());
}
return undo(game);
}
) -> Result<(), String> {
if matches!(action, Action::Redo) {
if !game.can_redo() {
return Err("action can't be redone".to_string());
}
redo(&mut game, player_index)?;
return Ok(game);
redo(game, player_index)?;
return Ok(());
}
add_log_item_from_action(&mut game, &action);
add_action_log_item(&mut game, action.clone());
add_log_item_from_action(game, &action);
add_action_log_item(game, action.clone());
match game.current_event_handler_mut() {
Some(s) => {
s.response = action.response();
let details = game.current_event().event_type.clone();
execute_custom_phase_action(&mut game, player_index, details)
execute_custom_phase_action(game, player_index, details)
}
_ => execute_regular_action(&mut game, action, player_index),
_ => execute_regular_action(game, action, player_index),
}?;
check_for_waste(&mut game);
update_stats(&mut game);
check_for_waste(game);
update_stats(game);
if game
.player(player_index)
@ -164,10 +169,10 @@ fn execute_without_undo(
.count()
>= 4
{
present_objective_cards(&mut game, player_index, vec!["Terror Regime".to_string()]);
present_objective_cards(game, player_index, vec!["Terror Regime".to_string()]);
}
Ok(game)
Ok(())
}
pub(crate) fn execute_custom_phase_action(

View file

@ -263,7 +263,11 @@ fn payment_with_action(
.expect("expected payment")
}
fn try_payment(ai_actions: &mut AiActions, o: &PaymentOptions, p: &Player) -> Option<ResourcePile> {
pub fn try_payment(
ai_actions: &mut AiActions,
o: &PaymentOptions,
p: &Player,
) -> Option<ResourcePile> {
let sum = o.default.amount();
let mut max = p.resources.clone();

View file

@ -121,7 +121,7 @@ pub(crate) fn invalidate_collect_cache() -> Builtin {
|event| &mut event.found_city,
1,
|game, player, _, p| {
reset_collect_within_range(game.player_mut(player), *p);
reset_collect_within_range(player, *p, game);
},
)
.add_simple_persistent_event_listener(
@ -134,9 +134,14 @@ pub(crate) fn invalidate_collect_cache() -> Builtin {
.build()
}
pub(crate) fn reset_collect_within_range(p: &mut Player, position: Position) {
let has_husbandry = p.has_advance(Advance::Husbandry);
let range = if has_husbandry { 2 } else { 1 };
pub(crate) fn reset_collect_within_range(player: usize, position: Position, game: &mut Game) {
let is_land = game.map.is_land(position);
let p = game.player_mut(player);
let range = if is_land && p.has_advance(Advance::Husbandry) {
2
} else {
1
};
for c in &mut p.cities {
if c.position.distance(position) <= range {
c.possible_collections.clear();
@ -145,8 +150,8 @@ pub(crate) fn reset_collect_within_range(p: &mut Player, position: Position) {
}
pub(crate) fn reset_collect_within_range_for_all(game: &mut Game, pos: Position) {
for p in &mut game.players {
reset_collect_within_range(p, pos);
for p in 0..game.human_players_count() {
reset_collect_within_range(p, pos, game);
}
}
@ -155,11 +160,11 @@ pub(crate) fn reset_collect_within_range_for_all_except(
pos: Position,
player: usize,
) {
for p in &mut game.players {
if p.index == player {
for p in 0..game.human_players_count() {
if p == player {
continue;
}
reset_collect_within_range(p, pos);
reset_collect_within_range(p, pos, game);
}
}

View file

@ -1,5 +1,6 @@
use serde::{Deserialize, Serialize};
use crate::city::City;
use Building::*;
use num::Zero;
@ -88,18 +89,6 @@ impl CityPieces {
}
}
pub fn remove_building(&mut self, building: Building) {
match building {
Academy => self.academy = None,
Market => self.market = None,
Obelisk => self.obelisk = None,
Observatory => self.observatory = None,
Fortress => self.fortress = None,
Port => self.port = None,
Temple => self.temple = None,
}
}
#[must_use]
pub fn amount(&self) -> usize {
self.buildings(None).len() + self.wonders.len()
@ -147,6 +136,20 @@ impl CityPieces {
}
}
pub fn remove_building(city: &mut City, building: Building) {
let pieces = &mut city.pieces;
match building {
Academy => pieces.academy = None,
Market => pieces.market = None,
Obelisk => pieces.obelisk = None,
Observatory => pieces.observatory = None,
Fortress => pieces.fortress = None,
Port => pieces.port = None,
Temple => pieces.temple = None,
}
city.possible_collections.clear();
}
#[derive(Serialize, Deserialize, Clone, PartialEq, Default)]
pub struct CityPiecesData {
#[serde(skip_serializing_if = "Option::is_none")]

View file

@ -89,8 +89,8 @@ pub fn get_total_collection(
let option = i.choices.get(&c.position);
if option.is_none_or(|options| !options.contains(&c.pile)) {
return Err(format!(
"You can only collect {:?} from {:?}",
option, c.position
"You can only collect {:?} from {:?} - all options are {:?}",
option, c.position, i.choices
));
}
}

View file

@ -1,6 +1,6 @@
use crate::city::City;
use crate::city::MoodState::Angry;
use crate::city_pieces::Building;
use crate::city_pieces::{Building, remove_building};
use crate::combat_listeners::{
Casualties, CombatEventPhase, CombatResult, CombatRoundEnd, CombatRoundStart, CombatStrength,
combat_round_end, combat_round_start,
@ -364,7 +364,7 @@ pub(crate) fn conquer_city(
if game.players[new_player_index].is_building_available(building, game) {
city.pieces.set_building(building, new_player_index);
} else {
city.pieces.remove_building(building);
remove_building(&mut city, building);
game.players[new_player_index].gain_resources(ResourcePile::gold(1));
}
}

View file

@ -1,6 +1,6 @@
use crate::ability_initializer::SelectedChoice;
use crate::city::{City, MoodState};
use crate::city_pieces::Building;
use crate::city_pieces::{Building, remove_building};
use crate::consts::WONDER_VICTORY_POINTS;
use crate::content::persistent_events::{
PositionRequest, SelectedStructure, Structure, StructuresRequest, is_selected_structures_valid,
@ -197,10 +197,7 @@ fn destroy_building(game: &mut Game, b: Building, position: Position) {
let o = game.player_mut(owner);
o.event_victory_points += 2.0;
o.destroyed_structures.add_building(b);
game.player_mut(city_owner)
.get_city_mut(position)
.pieces
.remove_building(b);
remove_building(game.player_mut(city_owner).get_city_mut(position), b);
game.add_info_log_item(&format!(
"{} gained 2 points for the {:?} at {}",
game.player_name(owner),
@ -216,10 +213,9 @@ fn destroy_wonder(game: &mut Game, position: Position, name: &str) {
let a = WONDER_VICTORY_POINTS / 2.0;
let p = game.player_mut(owner);
p.get_city_mut(position)
.pieces
.wonders
.retain(|w| w != name);
let city = p.get_city_mut(position);
city.pieces.wonders.retain(|w| w != name);
city.possible_collections.clear();
p.event_victory_points += a;
game.add_info_log_item(&format!(
"{} gained {} points for the {} at {}",

View file

@ -12,7 +12,8 @@ use crate::log::current_player_turn_log;
use crate::payment::PaymentOptions;
use crate::player_events::ActionInfo;
use crate::playing_actions::{
PlayingAction, PlayingActionType, base_or_custom_available, roll_boost_cost,
PlayingAction, PlayingActionType, base_or_custom_available, remaining_resources_for_action,
roll_boost_cost,
};
use crate::position::Position;
use crate::resource_pile::ResourcePile;
@ -96,11 +97,9 @@ pub(crate) fn influence_culture_attempt(
game: &mut Game,
player_index: usize,
c: &SelectedStructure,
action_type: &PlayingActionType,
) {
) -> Result<(), String> {
let target_city_position = c.position;
let info = influence_culture_boost_cost(game, player_index, c, action_type)
.expect("this should be a valid action");
let info = influence_culture_boost_cost(game, player_index, c, None)?;
let self_influence = info.starting_city_position == target_city_position;
// currently, there is no way to have different costs for this
@ -111,14 +110,14 @@ pub(crate) fn influence_culture_attempt(
game.add_to_last_log_item(&format!(" and succeeded (rolled {roll})"));
info.info.execute(game);
influence_culture(game, player_index, c);
return;
return Ok(());
}
if self_influence || info.prevent_boost {
game.add_to_last_log_item(&format!(" and failed (rolled {roll})"));
info.info.execute(game);
attempt_failed(game, player_index, target_city_position);
return;
return Ok(());
}
if let Some(roll_boost_cost) = PaymentOptions::resources(roll_boost_cost(roll))
.first_valid_payment(&game.players[player_index].resources)
@ -134,6 +133,7 @@ pub(crate) fn influence_culture_attempt(
info.info.execute(game);
attempt_failed(game, player_index, target_city_position);
}
Ok(())
}
pub(crate) fn ask_for_cultural_influence_payment(
@ -232,7 +232,7 @@ pub fn influence_culture_boost_cost(
game: &Game,
player_index: usize,
selected: &SelectedStructure,
action_type: &PlayingActionType,
action_type: Option<&PlayingActionType>,
) -> Result<InfluenceCultureInfo, String> {
let target_city_position = selected.position;
let structure = &selected.structure;
@ -314,7 +314,7 @@ pub fn available_influence_culture(
.into_iter()
.map(|s| {
let result =
influence_culture_boost_cost(game, player, &s, action_type);
influence_culture_boost_cost(game, player, &s, Some(action_type));
(s, result)
})
.collect_vec()
@ -378,13 +378,13 @@ fn affordable_start_city(
game: &Game,
player_index: usize,
target_city: &City,
action_type: &PlayingActionType,
action_type: Option<&PlayingActionType>,
) -> Result<(Position, u8), String> {
if target_city.player_index == player_index {
Ok((target_city.position, 0))
} else {
let player = game.player(player_index);
let available = action_type.remaining_resources(player, game);
let available = remaining_resources_for_action(game, action_type, player);
player
.cities
@ -403,8 +403,8 @@ fn affordable_start_city(
return None;
}
let boost_cost = influence_distance(game, c.position, target_city.position)
.saturating_sub(c.size() as u8);
let distance = influence_distance(game, c.position, target_city.position);
let boost_cost = distance.saturating_sub(c.size() as u8);
if boost_cost > available.culture_tokens {
return None;
}
@ -425,7 +425,7 @@ pub(crate) fn format_cultural_influence_attempt_log_item(
let target_city_position = s.position;
let target_city = game.get_any_city(target_city_position);
let target_player_index = target_city.player_index;
let info = influence_culture_boost_cost(game, player_index, s, &i.action_type)
let info = influence_culture_boost_cost(game, player_index, s, Some(&i.action_type))
.expect("this should be a valid action");
let player = if target_player_index == game.active_player() {

View file

@ -225,8 +225,10 @@ impl Game {
}
pub(crate) fn lock_undo(&mut self) {
self.undo_limit = self.action_log_index;
current_player_turn_log_mut(self).clear_undo();
if self.supports_undo {
self.undo_limit = self.action_log_index;
current_player_turn_log_mut(self).clear_undo();
}
}
///

View file

@ -52,6 +52,7 @@ pub mod player;
pub mod player_events;
pub mod playing_actions;
pub mod position;
pub mod profiling;
pub mod recruit;
pub mod resource;
pub mod resource_pile;

View file

@ -436,6 +436,11 @@ fn reachable_with_roads(player: &Player, units: &[u32], game: &Game) -> Vec<Move
.into_group_map_by(|&(p, _)| p)
.into_iter()
.filter_map(|(destination, stack_sizes_used)| {
if destination.distance(start) == 1 {
// can go directly without using roads
return None;
}
// but can stop on enemy units
if map.is_land(destination)
&& (
@ -546,7 +551,8 @@ pub(crate) fn has_movable_units(game: &Game, player: &Player) -> bool {
})
}
fn can_embark(game: &Game, player: &Player, unit: &Unit) -> bool {
#[must_use]
pub fn can_embark(game: &Game, player: &Player, unit: &Unit) -> bool {
unit.unit_type.is_land_based()
&& player.units.iter().any(|u| {
u.unit_type.is_ship()

View file

@ -700,6 +700,7 @@ impl Player {
if let Some(port_position) = port_position {
city.port_position = Some(port_position);
}
city.possible_collections.clear();
}
#[must_use]
@ -800,6 +801,13 @@ pub fn add_unit(player: usize, position: Position, unit_type: UnitType, game: &m
p.units.push(unit);
p.next_unit_id += 1;
reset_collect_within_range_for_all_except(game, position, player);
if game.player(player).civilization.is_pirates() {
for n in position.neighbors() {
if game.map.is_sea(n) {
reset_collect_within_range_for_all_except(game, n, player);
}
}
}
}
#[derive(Serialize, Deserialize, PartialEq)]

View file

@ -288,12 +288,7 @@ impl PlayingAction {
increase_happiness(game, player_index, &i.happiness_increases, Some(i.payment));
}
InfluenceCultureAttempt(c) => {
influence_culture_attempt(
game,
player_index,
&c.selected_structure,
&c.action_type,
);
influence_culture_attempt(game, player_index, &c.selected_structure)?;
}
ActionCard(a) => play_action_card(game, player_index, a),
WonderCard(name) => {
@ -455,3 +450,16 @@ fn any_angry(player: &Player) -> bool {
.iter()
.any(|city| city.mood_state == MoodState::Angry)
}
// None if the action cost has been paid
#[must_use]
pub fn remaining_resources_for_action(
game: &Game,
action_type: Option<&PlayingActionType>,
player: &Player,
) -> ResourcePile {
action_type.map_or_else(
|| player.resources.clone(),
|action_type| action_type.remaining_resources(player, game),
)
}

21
server/src/profiling.rs Normal file
View file

@ -0,0 +1,21 @@
#[cfg(not(feature = "profiling"))]
pub fn start_profiling() {
// do nothing
}
#[cfg(feature = "profiling")]
pub fn start_profiling() {
println!("start profiling");
use pyroscope::PyroscopeAgent;
use pyroscope_pprofrs::{PprofConfig, pprof_backend};
let pprof_config = PprofConfig::new().sample_rate(100);
let backend_impl = pprof_backend(pprof_config);
let agent = PyroscopeAgent::builder("http://localhost:4040", "clash")
.backend(backend_impl)
.build()
.expect("Failed to initialize pyroscope");
let _ = agent.start().unwrap();
}

View file

@ -1,8 +1,14 @@
use async_std::task;
use crate::common::{GamePath, to_json, write_result};
use itertools::Itertools;
use server::action::ActionType;
use server::ai_actions::AiActions;
use server::game::Game;
use server::movement::{MoveUnits, MovementAction, move_units_destinations};
use server::playing_actions::PlayingActionType;
use server::profiling::start_profiling;
use server::{
action::{self, Action},
ai_actions,
game::GameState,
game_setup,
playing_actions::PlayingAction,
@ -13,24 +19,20 @@ mod common;
const ITERATIONS: usize = 100;
#[tokio::test]
async fn test_random_actions() {
let num_cores = num_cpus::get();
//is too slow if not in release mode
#[test]
fn test_random_actions() {
start_profiling();
let mut rng = Rng::new();
let mut iterations = 0;
loop {
let mut handles = Vec::new();
for _ in 0..num_cores {
rng.seed = rng.seed.wrapping_add(1);
rng.next_seed();
let thread_rng = rng.clone();
let handle = task::spawn(async move { random_actions_iterations(thread_rng) });
handles.push(handle);
}
for handle in handles {
handle.await;
}
iterations += num_cores;
rng.seed = rng.seed.wrapping_add(1);
rng.next_seed();
random_actions_iterations(rng.clone());
iterations += 1;
println!("Iterations: {}", iterations);
if iterations >= ITERATIONS {
break;
}
@ -41,40 +43,96 @@ fn random_actions_iterations(mut rng: Rng) {
let seed = rng.range(0, 10_usize.pow(15)).to_string();
let mut game = game_setup::setup_game(2, seed, true);
game.supports_undo = false;
build_adjacent_cities(&mut game);
let mut ai_actions = AiActions::new();
loop {
if matches!(game.state, GameState::Finished) {
break;
}
let player_index = game.active_player();
//todo: include movement action
let actions = ai_actions.get_available_actions(&game);
let mut actions = ai_actions.get_available_actions(&game);
actions.extend(get_movement_actions(&mut ai_actions, &game));
let actions = actions
.into_iter()
.flat_map(|(_, actions)| actions)
.collect::<Vec<Action>>();
let action = actions
.take_random_element(&mut rng)
.unwrap_or(Action::Playing(PlayingAction::EndTurn));
.unwrap_or_else(|| no_action_available(&game));
game = action::execute_action(game.clone(), action.clone(), player_index)
match action::execute_without_undo(&mut game, action.clone(), player_index) {
Ok(_) => {}
Err(e) => {
use chrono::Utc;
let rfc_format = Utc::now().to_rfc3339();
let file = format!("failure{rfc_format}");
write_result(&to_json(&game), &GamePath::new(".", &file));
panic!(
"player {player_index} action {action:?}\nresult stored in {file}.json: {e:?}"
)
}
}
}
}
fn build_adjacent_cities(_game: &mut Game) {
// only until move works
// this way we can test constructing buildings
// todo makes it too slow
// for i in game.human_players(0) {
// let city = &game.player(i).cities[0];
// let pos = city
// .position
// .neighbors()
// .into_iter()
// .find(|p| game.map.get(*p) == Some(&Terrain::Barren))
// .expect("no barren space");
// game.player_mut(i).cities.push(City::new(i, pos));
// }
fn no_action_available(game: &Game) -> Action {
if matches!(game.state, GameState::Movement(_)) {
return Action::Movement(MovementAction::Stop);
}
Action::Playing(PlayingAction::EndTurn)
}
pub fn get_movement_actions(
ai_actions: &mut AiActions,
game: &Game,
) -> Vec<(ActionType, Vec<Action>)> {
if PlayingActionType::MoveUnits
.is_available(game, game.current_player_index)
.is_err()
{
return vec![];
}
let p = game.player(game.current_player_index);
// always move entire stacks as a simplification
let actions = p
.units
.iter()
.chunk_by(|u| u.position)
.into_iter()
.flat_map(|(pos, units)| {
let unit_ids = units.into_iter().map(|u| u.id).collect_vec();
let destinations = move_units_destinations(p, game, &unit_ids, pos, None);
destinations
.map(|d| {
d.iter()
.filter_map(|route| {
ai_actions::try_payment(ai_actions, &route.cost, p).map({
let value = unit_ids.clone();
move |pay| {
Action::Movement(MovementAction::Move(MoveUnits::new(
value,
route.destination,
None,
pay,
)))
}
})
})
.collect_vec()
})
.unwrap_or_default()
})
.collect_vec();
if actions.is_empty() {
return vec![];
}
vec![(ActionType::Playing(PlayingActionType::MoveUnits), actions)]
// todo embark
// || can_embark(game, p, unit)
}