diff --git a/.github/workflows/check.yml b/.github/workflows/check.yml index 7ffbf39a..f641f045 100644 --- a/.github/workflows/check.yml +++ b/.github/workflows/check.yml @@ -29,10 +29,6 @@ jobs: - name: Build server working-directory: ./server run: | - sed -i '1 i\#![allow(clippy::all)]' src/ai.rs # todo remove when AI is done - sed -i '1 i\#![allow(clippy::pedantic)]' src/ai.rs # todo remove when AI is done - sed -i '1 i\#![allow(unused_variables)]' src/ai.rs # todo remove when AI is done - sed -i '1 i\#![allow(dead_code)]' src/ai.rs # todo remove when AI is done cargo build - name: Run tests server working-directory: ./server diff --git a/client/src/client.rs b/client/src/client.rs index 3b8c35ee..d700c73a 100644 --- a/client/src/client.rs +++ b/client/src/client.rs @@ -3,7 +3,6 @@ use macroquad::prelude::clear_background; use macroquad::prelude::*; use server::action::Action; -use server::ai::AI; use server::game::Game; use server::position::Position; @@ -238,7 +237,7 @@ fn controlling_player_click(rc: &RenderContext, mouse_pos: Vec2, pos: Position) pub struct Features { pub import_export: bool, pub assets_url: String, - pub ai: Option, + pub ai: bool, } impl Features { diff --git a/client/src/client_state.rs b/client/src/client_state.rs index 0d31b6bf..4360ab46 100644 --- a/client/src/client_state.rs +++ b/client/src/client_state.rs @@ -19,6 +19,7 @@ use crate::status_phase_ui::ChooseAdditionalAdvances; use macroquad::prelude::*; use server::action::Action; use server::advance::Advance; +use server::ai::AI; use server::card::HandCard; use server::city::{City, MoodState}; use server::content::persistent_events::{ @@ -395,6 +396,7 @@ pub struct State { pub show_permanent_effects: bool, pub ai_autoplay: bool, pub pan_map: bool, + pub ai_players: Vec, } pub const ZOOM: f32 = 0.001; @@ -422,6 +424,7 @@ impl State { pan_map: false, show_permanent_effects: false, ai_autoplay: false, + ai_players: vec![], } } diff --git a/client/src/local_client/bin/main.rs b/client/src/local_client/bin/main.rs index e2103558..53bd55c9 100644 --- a/client/src/local_client/bin/main.rs +++ b/client/src/local_client/bin/main.rs @@ -2,6 +2,7 @@ use client::client::{Features, GameSyncRequest, GameSyncResult, init, render_and_update}; use client::client_state::State; +use itertools::Itertools; use macroquad::miniquad::window::set_window_size; use macroquad::prelude::{next_frame, screen_width, vec2}; use macroquad::window::screen_height; @@ -41,9 +42,7 @@ async fn main() { let mut features = Features { import_export: true, assets_url: "assets/".to_string(), - ai: modes - .contains(&Mode::AI) - .then(|| AI::new(1., Duration::from_secs(5), false)), + ai: modes.contains(&Mode::AI), }; let game = if modes.contains(&Mode::Test) { @@ -98,6 +97,14 @@ fn get_modes(args: &[String]) -> Vec { async fn run(mut game: Game, features: &mut Features) { let mut state = init(features).await; + if features.ai { + state.ai_players = game + .human_players(0) + .into_iter() + .map(|p| AI::new(1., Duration::from_secs(5), false, &game, p)) + .collect_vec() + } + let mut sync_result = GameSyncResult::None; state.show_player = game.active_player(); loop { @@ -134,10 +141,12 @@ async fn run(mut game: Game, features: &mut Features) { } fn ai_autoplay(mut game: Game, f: &mut Features, state: &mut State) -> Game { - if let Some(ai) = &mut f.ai { + if f.ai { while state.ai_autoplay && game.state != GameState::Finished { // todo does this block the ui? // state.ai_autoplay = false; + let active_player = game.active_player(); + let ai = &mut state.ai_players[active_player]; let action = ai.next_action(&game); let player_index = game.active_player(); game = execute_action(game, action, player_index); diff --git a/client/src/player_ui.rs b/client/src/player_ui.rs index 12d8b52d..092b7751 100644 --- a/client/src/player_ui.rs +++ b/client/src/player_ui.rs @@ -351,7 +351,7 @@ pub fn show_global_controls(rc: &RenderContext, features: &Features) -> StateUpd } } - if features.ai.is_some() { + if features.ai { let tooltip = if rc.state.ai_autoplay { "Pause AI autoplay" } else { diff --git a/client/src/remote_client/bin/main.rs b/client/src/remote_client/bin/main.rs index 2a0aaa23..f10e5e0c 100644 --- a/client/src/remote_client/bin/main.rs +++ b/client/src/remote_client/bin/main.rs @@ -83,7 +83,7 @@ impl RemoteClient { let features = Features { import_export: false, assets_url: control.assets_url(), - ai: None, + ai: false, }; let state = init(&features).await; diff --git a/server/Cargo.lock b/server/Cargo.lock index fb5619d7..b06e0abf 100644 --- a/server/Cargo.lock +++ b/server/Cargo.lock @@ -747,9 +747,9 @@ dependencies = [ [[package]] name = "proc-macro2" -version = "1.0.94" +version = "1.0.95" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a31971752e70b8b2686d7e46ec17fb38dad4051d94024c88df49b667caea9c84" +checksum = "02b3e5e68a3a1a02aad3ec490a98007cbc13c37cbe84a3cd7b8e406d76e7f778" dependencies = [ "unicode-ident", ] diff --git a/server/src/ai.rs b/server/src/ai.rs index ae883133..95d11b0f 100644 --- a/server/src/ai.rs +++ b/server/src/ai.rs @@ -1,26 +1,29 @@ -extern crate num_cpus; +use core::panic; use std::time::Duration; +use itertools::Itertools; +use num_cpus; use tokio::runtime::Runtime; use crate::ai_actions::AiActions; use crate::{ action::{self, Action, ActionType}, + ai_missions::ActiveMissions, game::{Game, GameData, GameState}, - playing_actions::PlayingAction, - position::Position, + playing_actions::{PlayingAction, PlayingActionType}, utils::{self, Rng}, }; -const ACTION_SCORE_WEIGHTING: f64 = 1.0; +pub const ACTION_SCORE_WEIGHTING: f64 = 0.0; const ADAPTIVE_DIFFICULTY_SCORE_THRESHOLD: f64 = 10.0; +const ALLOCATE_UNITS_EVALUATION_TIME: f64 = 0.1; pub struct AI { rng: Rng, pub difficulty: f64, pub thinking_time: Duration, pub adaptive_difficulty: bool, - active_missions: Vec, + active_missions: ActiveMissions, pub ai_actions: AiActions, } @@ -36,15 +39,34 @@ impl AI { /// /// Panics if the difficulty is not between 0 and 1 #[must_use] - pub fn new(difficulty: f64, thinking_time: Duration, adaptive_difficulty: bool) -> Self { + pub fn new( + difficulty: f64, + thinking_time: Duration, + adaptive_difficulty: bool, + starting_game: &Game, + player_index: usize, + ) -> Self { assert!((0.0..=1.0).contains(&difficulty)); let rng = Rng::new(); + let mut missions_rng = rng.clone(); + missions_rng.seed = missions_rng.seed.wrapping_add(1); + missions_rng.next_seed(); + let starting_units = starting_game.players[player_index].units.len(); + AI { rng, difficulty, thinking_time, adaptive_difficulty, - active_missions: Vec::new(), + active_missions: ActiveMissions::new( + starting_game, + player_index, + &mut missions_rng, + Some(( + thinking_time.mul_f64(ALLOCATE_UNITS_EVALUATION_TIME) * starting_units as u32, + difficulty, + )), + ), ai_actions: AiActions::new(), } } @@ -58,19 +80,24 @@ impl AI { /// /// # Panics /// - /// May panic if the game is in an invalid state or if `ai_actions` provides an invalid action. + /// Panics if it's not the AI's turn pub fn next_action(&mut self, game: &Game) -> Action { - //todo: handle movement phase actions - let actions = self.ai_actions.get_available_actions(game); - let actions = actions - .into_iter() - .flat_map(|(action_group, actions)| { - actions - .into_iter() - .map(|action| (action_group.clone(), action)) - .collect::>() - }) - .collect::>(); + assert_eq!(game.current_player_index, self.active_missions.player_index); + let start_time = std::time::Instant::now(); + + if can_move(game, self.active_missions.player_index) { + let idle_units = self.active_missions.idle_units.len(); + self.active_missions.update( + game, + &mut self.rng, + Some(( + self.thinking_time.mul_f64(ALLOCATE_UNITS_EVALUATION_TIME) * idle_units as u32, + self.difficulty, + )), + ); + } + + let actions = get_actions(&mut self.ai_actions, game, &self.active_missions); if actions.is_empty() { return Action::Playing(PlayingAction::EndTurn); } @@ -81,26 +108,16 @@ impl AI { .expect("there should be 1 available action") .1; } - if actions.len() == 1 { - return actions - .into_iter() - .next() - .expect("there should be 1 available action") - .1; - } let runtime = Runtime::new().expect("failed to create runtime"); + let time_remaining = self.thinking_time - start_time.elapsed(); + let thinking_time_per_action = time_remaining / actions.len() as u32; + //todo: multiple iterations with pruning - //todo: dynamic thinking time - let thinking_time_per_action = self.thinking_time / actions.len() as u32; - - //todo: handle going into movement phase - - let difficulty_factor = if self.difficulty >= 1.0 - f64::EPSILON { - 1.0 - } else { - self.difficulty / (1.0 - self.difficulty) - }; + let players_active_missions = self + .active_missions + .get_players_active_missions(game, &mut self.rng); + let difficulty_factor = difficulty_factor(self.difficulty); let evaluations = actions .iter() .map(|(action_group, action)| { @@ -111,12 +128,13 @@ impl AI { action_group, &mut self.rng, &thinking_time_per_action, + &players_active_missions, )) .powf(difficulty_factor) }) .collect::>(); - let index = if self.difficulty >= 1.0 - f64::EPSILON { + let chosen_action = if self.difficulty >= 1.0 - f64::EPSILON { evaluations .iter() .enumerate() @@ -130,7 +148,7 @@ impl AI { if self.difficulty > 0.0 + f64::EPSILON { let final_evaluation = evaluations .into_iter() - .nth(index) + .nth(chosen_action) .expect("there are no possible actions") .powf(1.0 / difficulty_factor); println!("average final relative score: {final_evaluation}"); @@ -149,7 +167,7 @@ impl AI { actions .into_iter() - .nth(index) + .nth(chosen_action) .expect("there are no possible actions") .1 } @@ -181,48 +199,83 @@ async fn evaluate_action( action_group: &ActionType, rng: &mut Rng, thinking_time: &Duration, + players_active_missions: &[ActiveMissions], ) -> f64 { - let action_score = get_action_score(game, action); - let action_group_score = get_action_group_score(game, action_group); let player_index = game.active_player(); + let action_score = get_action_score(game, action, &players_active_missions[player_index]); + let action_group_score = + get_action_group_score(game, action_group, &players_active_missions[player_index]); let mut game = game.clone(); game.supports_undo = false; let game = action::execute_action(game, action.clone(), player_index); + let score = get_average_score( + game, + player_index, + rng, + thinking_time, + players_active_missions, + ) + .await; + println!( + " -> Monte Carlo score: {score}, action score: {action_score}, action group score: {action_group_score}" + ); + score * action_score * action_group_score +} + +/// Simulates the current game multiple times to the end and returns the average score for the given player relative the best opponent. +/// +/// # Panics +/// +/// Panics if the game is in an invalid state or if the player index is out of bounds. +pub async fn get_average_score( + game: Game, + player_index: usize, + rng: &mut Rng, + evaluation_time: &Duration, + players_active_missions: &[ActiveMissions], +) -> f64 { let mut iterations = 0; let start_time = std::time::Instant::now(); let mut score = 0.0; + let num_cores = num_cpus::get(); loop { let mut handles = Vec::new(); - let num_cores = num_cpus::get(); for _ in 0..num_cores { rng.seed = rng.seed.wrapping_add(1); rng.next_seed(); let thread_rng = rng.clone(); let new_game = game.cloned_data(); - let handle = - tokio::spawn(async move { monte_carlo_score(thread_rng, player_index, new_game) }); + let new_active_missions = players_active_missions.to_vec(); + let handle = tokio::spawn(async move { + monte_carlo_score(thread_rng, player_index, new_game, new_active_missions) + }); handles.push(handle); } for handle in handles { score += handle.await.expect("multi-threading error"); } iterations += num_cores; - if start_time.elapsed() >= *thinking_time { + if start_time.elapsed() >= *evaluation_time { break; } } - println!( - "Monte Carlo iterations: {iterations}. Score: {}, {action_score}, {action_group_score}", - score / iterations as f64 - ); - (score / iterations as f64) * action_score * action_group_score + println!("Monte Carlo iterations: {iterations}"); + score / iterations as f64 } -fn monte_carlo_score(mut rng: Rng, player_index: usize, game_data: GameData) -> f64 { +fn monte_carlo_score( + mut rng: Rng, + player_index: usize, + game_data: GameData, + players_active_missions: Vec, +) -> f64 { let mut ai = AiActions::new(); - let mut game = Game::from_data(game_data); - game.supports_undo = false; - let new_game = monte_carlo_run(&mut ai, game, &mut rng); + let new_game = monte_carlo_run( + &mut ai, + Game::from_data(game_data), + &mut rng, + players_active_missions, + ); let ai_score = new_game.players[player_index].victory_points(&new_game) as f64; let mut max_opponent_score = 0.0; for (i, player) in new_game.players.iter().enumerate() { @@ -236,18 +289,32 @@ fn monte_carlo_score(mut rng: Rng, player_index: usize, game_data: GameData) -> ai_score - max_opponent_score } -fn monte_carlo_run(ai: &mut AiActions, mut game: Game, rng: &mut Rng) -> Game { +fn monte_carlo_run( + ai: &mut AiActions, + mut game: Game, + rng: &mut Rng, + mut players_active_missions: Vec, +) -> Game { loop { if matches!(game.state, GameState::Finished) { return game; } let current_player = game.active_player(); - let action = choose_monte_carlo_action(ai, &game, rng); + if can_move(&game, current_player) { + players_active_missions[current_player].update(&game, rng, None); + } + let action = + choose_monte_carlo_action(ai, &game, rng, &players_active_missions[current_player]); game = action::execute_action(game, action, current_player); } } -fn choose_monte_carlo_action(ai: &mut AiActions, game: &Game, rng: &mut Rng) -> Action { +fn choose_monte_carlo_action( + ai: &mut AiActions, + game: &Game, + rng: &mut Rng, + active_missions: &ActiveMissions, +) -> Action { let action_groups = ai.get_available_actions(game); if action_groups.is_empty() { return Action::Playing(PlayingAction::EndTurn); @@ -264,7 +331,7 @@ fn choose_monte_carlo_action(ai: &mut AiActions, game: &Game, rng: &mut Rng) -> } let group_evaluations = action_groups .iter() - .map(|(action_group, _)| get_action_group_score(game, action_group)) + .map(|(action_group, _)| get_action_group_score(game, action_group, active_missions)) .collect::>(); let group_index = utils::weighted_random_selection(&group_evaluations, rng); let action_group = action_groups @@ -274,7 +341,7 @@ fn choose_monte_carlo_action(ai: &mut AiActions, game: &Game, rng: &mut Rng) -> .1; let action_evaluations = action_group .iter() - .map(|action| get_action_score(game, action)) + .map(|action| get_action_score(game, action, active_missions)) .collect::>(); let action_index = utils::weighted_random_selection(&action_evaluations, rng); action_group @@ -283,75 +350,102 @@ fn choose_monte_carlo_action(ai: &mut AiActions, game: &Game, rng: &mut Rng) -> .expect("index out of bounds") } -fn get_action_score(game: &Game, action: &Action) -> f64 { - 1_f64.powf(ACTION_SCORE_WEIGHTING) +fn get_actions( + ai_actions: &mut AiActions, + game: &Game, + active_missions: &ActiveMissions, +) -> Vec<(ActionType, Action)> { + let mut actions = ai_actions.get_available_actions(game); + if can_move(game, active_missions.player_index) { + actions.push(( + ActionType::Movement, + active_missions + .missions + .clone() + .into_iter() + .filter_map(|mission| mission.next_action) + .map(Action::Movement) + .collect(), + )); + } + + actions + .into_iter() + .flat_map(|(action_group, actions)| { + actions + .into_iter() + .map(|action| (action_group.clone(), action)) + .collect::>() + }) + .collect::>() } -fn get_action_group_score(game: &Game, action_group: &ActionType) -> f64 { - 1_f64.powf(ACTION_SCORE_WEIGHTING) +fn can_move(game: &Game, player_index: usize) -> bool { + PlayingActionType::MoveUnits + .is_available(game, player_index) + .is_ok() } -struct Mission { - units_under_management: Vec, - target: Position, - mission_type: MissionType, +#[must_use] +pub fn difficulty_factor(difficulty: f64) -> f64 { + if difficulty >= 1.0 - f64::EPSILON { + 1.0 + } else { + difficulty / (1.0 - difficulty) + } } -impl Mission { - fn new( - units_under_management: Vec, - target: Position, - mission_type: MissionType, - ) -> Self { - Self { - units_under_management, - target, - mission_type, +fn get_action_score(game: &Game, action: &Action, active_missions: &ActiveMissions) -> f64 { + match action { + Action::Playing(_action) => 1.0, //todo + Action::Movement(action) => { + let mission = active_missions + .missions + .iter() + .find(|mission| { + mission + .next_action + .as_ref() + .is_some_and(|mission_action| mission_action == action) + }) + .expect("movement action is not part of any active mission"); + mission.priority(game, active_missions) } + Action::Response(_action) => 1.0, + _ => panic!("invalid ai action"), } - - fn priority(&self, game: &Game) -> f64 { - match self.mission_type { - MissionType::Explore => 0.5, - MissionType::DefendCity => 1.0, - MissionType::FoundCity => 1.5, - MissionType::CapturePlayerCity => 1.0, - MissionType::CaptureBarbarianCamp => 1.0, - MissionType::FightPlayerForces { .. } => 1.0, - MissionType::FightBarbarians { .. } => 1.0, - MissionType::FightPirates { .. } => 1.0, - MissionType::Transport => 1.0, - } - } - - fn update(&mut self, game: &Game) {} - - fn is_complete(&self, game: &Game) -> bool { - false - } - - fn next_movement(&self, game: &Game) -> Position { - todo!() - } + .powf(ACTION_SCORE_WEIGHTING) } -enum MissionType { - Explore, - DefendCity, - FoundCity, - CapturePlayerCity, - CaptureBarbarianCamp, - FightPlayerForces { - player_index: usize, - units: Vec, - }, - FightBarbarians { - units: Vec, - }, - FightPirates { - units: Vec, - }, - Transport, +fn get_action_group_score( + game: &Game, + action_group: &ActionType, + active_missions: &ActiveMissions, +) -> f64 { + match action_group { + ActionType::Playing(_action) => 1.0, //todo + ActionType::Movement => { + let skip = if active_missions.missions.len() <= 3 { + 0 + } else { + active_missions.missions.len() - 3 + }; + active_missions + .missions + .iter() + .sorted_by(|a, b| { + a.priority(game, active_missions) + .total_cmp(&b.priority(game, active_missions)) + }) + .rev() + .skip(skip) + .fold(0.0, |acc, mission| { + acc + mission.priority(game, active_missions) + }) + } + _ => 1.0, + } + .powf(ACTION_SCORE_WEIGHTING) } /// Returns the win probability of each player in the game in the order listed in the game. @@ -360,26 +454,36 @@ enum MissionType { /// /// Panics if the game is in an invalid state. #[must_use] -pub fn evaluate_position(ai: &mut AiActions, game: &Game, evaluation_time: Duration) -> Vec { +pub async fn evaluate_position(game: &Game, evaluation_time: Duration) -> Vec { let mut rng = Rng::new(); let start_time = std::time::Instant::now(); + let players_active_missions = game + .players + .iter() + .map(|player| ActiveMissions::new(game, player.index, &mut rng, None)) + .collect::>(); let mut wins = vec![0; game.players.len()]; + let num_cores = num_cpus::get(); let mut iterations = 0; loop { - let new_game = monte_carlo_run(ai, game.clone(), &mut rng); - let max_score = new_game - .players - .iter() - .map(|player| player.victory_points(&new_game) as f64) - .max_by(|a, b| a.partial_cmp(b).expect("floating point error")) - .expect("there are no players"); - for (i, player) in new_game.players.iter().enumerate() { - let score = player.victory_points(&new_game) as f64; - if (score - max_score).abs() < f64::EPSILON { - wins[i] += 1; - } + 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 new_game = game.cloned_data(); + let new_active_missions = players_active_missions.clone(); + let handle = + tokio::spawn( + async move { simulate_game(new_game, thread_rng, new_active_missions) }, + ); + handles.push(handle); } - iterations += 1; + for handle in handles { + let winner = handle.await.expect("multi-threading error"); + wins[winner] += 1; + } + iterations += num_cores; if start_time.elapsed() >= evaluation_time { return wins .iter() @@ -389,6 +493,32 @@ pub fn evaluate_position(ai: &mut AiActions, game: &Game, evaluation_time: Durat } } +fn simulate_game( + game: GameData, + mut rng: Rng, + players_active_missions: Vec, +) -> usize { + let new_game = monte_carlo_run( + &mut AiActions::new(), + Game::from_data(game), + &mut rng, + players_active_missions, + ); + let max_score = new_game + .players + .iter() + .map(|player| player.victory_points(&new_game) as f64) + .max_by(|a, b| a.partial_cmp(b).expect("floating point error")) + .expect("there are no players"); + for (i, player) in new_game.players.iter().enumerate() { + let score = player.victory_points(&new_game) as f64; + if (score - max_score).abs() < f64::EPSILON { + return i; + } + } + unreachable!("there should be a winner"); +} + /// Returns a score between 0 and 1 for the given action. with 0 being the worst possible action and 1 being the best. /// /// # Panics @@ -414,6 +544,11 @@ pub fn rate_action(ai: &mut AI, game: &Game, action: &Action, evaluation_time: D .position(|(_, a)| a == action) .expect("action not found in available actions"); let mut rng = Rng::new(); + let players_active_missions = game + .players + .iter() + .map(|player| ActiveMissions::new(game, player.index, &mut rng, None)) + .collect::>(); let runtime = Runtime::new().expect("failed to create runtime"); let thinking_time_per_action = evaluation_time / all_actions.len() as u32; let evaluations = all_actions @@ -425,6 +560,7 @@ pub fn rate_action(ai: &mut AI, game: &Game, action: &Action, evaluation_time: D action_group, &mut rng, &thinking_time_per_action, + &players_active_missions, )) }) .collect::>(); diff --git a/server/src/ai_missions.rs b/server/src/ai_missions.rs new file mode 100644 index 00000000..1b1913b5 --- /dev/null +++ b/server/src/ai_missions.rs @@ -0,0 +1,772 @@ +use std::{mem, time::Duration, vec}; + +use tokio::runtime::Runtime; + +use crate::advance::Advance; +use crate::{ + ai::{self, ACTION_SCORE_WEIGHTING}, + barbarians, + game::Game, + map::Terrain, + movement::{self, MoveUnits, MovementAction}, + payment::PaymentOptions, + pirates, + position::Position, + unit::UnitType, + utils::{self, Rng}, +}; + +#[derive(Clone)] +pub struct ActiveMissions { + pub missions: Vec, + pub player_index: usize, + pub idle_units: Vec, +} + +impl ActiveMissions { + pub fn new( + game: &Game, + player_index: usize, + rng: &mut Rng, + monte_carlo_evaluation: Option<(Duration, f64)>, + ) -> Self { + let mut missions = Self { + missions: Vec::new(), + player_index, + idle_units: Vec::new(), + }; + missions + .idle_units + .extend(game.players[player_index].units.iter().map(|unit| unit.id)); + missions.allocate_units(game, rng, monte_carlo_evaluation); + missions + } + + pub fn update( + &mut self, + game: &Game, + rng: &mut Rng, + monte_carlo_evaluation: Option<(Duration, f64)>, + ) { + let cloned_missions = self.clone(); + for mission in &mut self.missions { + mission.update(game, &cloned_missions); + } + for mission in &mut self.missions { + if mission.is_complete(game) { + let new_idle_units = mem::take(&mut mission.units); + self.idle_units.extend(new_idle_units); + } + } + self.missions.retain(|mission| !mission.is_complete(game)); + self.allocate_units(game, rng, monte_carlo_evaluation); + } + + fn allocate_units( + &mut self, + game: &Game, + rng: &mut Rng, + monte_carlo_evaluation: Option<(Duration, f64)>, + ) { + let mut new_missions = Vec::new(); + for unit in &self.idle_units { + let missions = self.missions_for_unit(game, *unit); + if missions.is_empty() { + continue; + } + if missions.len() == 1 { + new_missions.push( + missions + .into_iter() + .next() + .expect("there should be 1 mission"), + ); + continue; + } + let mission = if let Some((evaluation_time, difficulty)) = monte_carlo_evaluation { + let runtime = Runtime::new().expect("failed to create runtime"); + runtime.block_on(self.decide_mission( + game, + difficulty, + missions, + rng, + evaluation_time, + )) + } else { + let weightings = missions + .iter() + .map(|mission| mission.priority(game, self).powf(ACTION_SCORE_WEIGHTING)) + .collect::>(); + let mission_index = utils::weighted_random_selection(&weightings, rng); + missions + .into_iter() + .nth(mission_index) + .expect("index out of bounds") + }; + new_missions.push(mission); + } + new_missions + .chunk_by_mut(|a, b| { + a.mission_type == b.mission_type + && a.target == b.target + && a.current_location == b.current_location + }) + .map(|missions| { + let mut units = Vec::new(); + for mission in missions.iter_mut() { + units.append(&mut mission.units); + } + Mission::new( + units, + missions[0].target, + missions[0].mission_type.clone(), + game, + self.player_index, + ) + }) + .for_each(|mission| { + self.missions.push(mission); + }); + } + + fn missions_for_unit(&self, game: &Game, unit: u32) -> Vec { + let unit = game.players[self.player_index].get_unit(unit); + let explore_target = decide_scouting_position(game, self.player_index, unit.position, self); + if matches!(unit.unit_type, UnitType::Settler) { + return self.get_settler_missions(game, unit, explore_target); + } + if matches!(unit.unit_type, UnitType::Ship) { + return self.get_ship_missions(game, unit.id); + } + self.get_combat_unit_missions(game, explore_target, unit.id) + } + + #[allow(clippy::too_many_lines)] + fn get_combat_unit_missions( + &self, + game: &Game, + explore_target: Option, + unit: u32, + ) -> Vec { + let defend_city_targets = game.players[self.player_index] + .cities + .iter() + .map(|city| city.position) + .filter(|city_position| { + city_threat_score(game, self.player_index, *city_position) > 0.1 + }) + .collect::>(); + let capture_player_city_targets = game + .players + .iter() + .filter(|player| player.is_human() && player.index != self.player_index) + .flat_map(|player| { + player + .cities + .iter() + .map(|city| (player.index, city.position)) + }) + .collect::>(); + let capture_barbarian_camp_targets = barbarians::get_barbarians_player(game) + .cities + .iter() + .map(|city| city.position) + .collect::>(); + let fight_player_forces_targets = game + .players + .iter() + .filter(|player| player.is_human() && player.index != self.player_index) + .flat_map(|player| { + player + .units + .iter() + .map(|unit| unit.position) + .map(|position| { + ( + player.index, + position, + player + .get_units(position) + .iter() + .map(|unit| unit.id) + .collect::>(), + ) + }) + }) + .collect::)>>(); + let fight_barbarians_targets = barbarians::get_barbarians_player(game) + .units + .iter() + .map(|unit| unit.position) + .map(|position| { + ( + position, + barbarians::get_barbarians_player(game) + .get_units(position) + .iter() + .map(|unit| unit.id) + .collect::>(), + ) + }) + .collect::)>>(); + let mut missions = Vec::new(); + missions.extend(explore_target.map(|target| { + Mission::new( + vec![unit], + target, + MissionType::Explore, + game, + self.player_index, + ) + })); + missions.extend(defend_city_targets.into_iter().map(|target| { + Mission::new( + vec![unit], + target, + MissionType::DefendCity, + game, + self.player_index, + ) + })); + missions.extend( + capture_player_city_targets + .into_iter() + .map(|(player_index, target)| { + Mission::new( + vec![unit], + target, + MissionType::CapturePlayerCity { player_index }, + game, + self.player_index, + ) + }), + ); + missions.extend(capture_barbarian_camp_targets.into_iter().map(|target| { + Mission::new( + vec![unit], + target, + MissionType::CaptureBarbarianCamp, + game, + self.player_index, + ) + })); + missions.extend(fight_player_forces_targets.into_iter().map( + |(player_index, target, units)| { + Mission::new( + vec![unit], + target, + MissionType::FightPlayerForces { + player_index, + units, + }, + game, + self.player_index, + ) + }, + )); + missions.extend(fight_barbarians_targets.into_iter().map(|(target, units)| { + Mission::new( + vec![unit], + target, + MissionType::FightBarbarians { units }, + game, + self.player_index, + ) + })); + missions + } + + fn get_settler_missions( + &self, + game: &Game, + unit: &crate::unit::Unit, + explore_target: Option, + ) -> Vec { + let found_city_target = + decide_settling_position(game, self.player_index, unit.position, self); + let mut missions = vec![Mission::new( + vec![unit.id], + found_city_target, + MissionType::FoundCity, + game, + self.player_index, + )]; + missions.extend(explore_target.map(|target| { + Mission::new( + vec![unit.id], + target, + MissionType::Explore, + game, + self.player_index, + ) + })); + missions + } + + fn get_ship_missions(&self, game: &Game, unit: u32) -> Vec { + let fight_pirates_targets = pirates::get_pirates_player(game) + .units + .iter() + .map(|unit| unit.position) + .map(|position| { + ( + position, + pirates::get_pirates_player(game) + .get_units(position) + .iter() + .map(|unit| unit.id) + .collect::>(), + ) + }) + .collect::)>>(); + let transport_targets = Vec::::new(); + //todo + let cartography_targets = Vec::::new(); + //todo + let mut missions = Vec::new(); + missions.extend(fight_pirates_targets.into_iter().map(|(target, units)| { + Mission::new( + vec![unit], + target, + MissionType::FightPirates { units }, + game, + self.player_index, + ) + })); + missions.extend(transport_targets.into_iter().map(|target| { + Mission::new( + vec![unit], + target, + MissionType::Transport, + game, + self.player_index, + ) + })); + missions.extend(cartography_targets.into_iter().map(|target| { + Mission::new( + vec![unit], + target, + MissionType::Cartography, + game, + self.player_index, + ) + })); + missions + } + + async fn decide_mission( + &self, + game: &Game, + difficulty: f64, + missions: Vec, + rng: &mut Rng, + evaluation_time: Duration, + ) -> Mission { + let time_per_mission = evaluation_time / missions.len() as u32; + let mut scores = Vec::new(); + let players_active_missions = self.get_players_active_missions(game, rng); + let difficulty_factor = ai::difficulty_factor(difficulty); + for mission in &missions { + let mut game = game.clone(); + game.supports_undo = false; + let mut players_active_missions = players_active_missions.clone(); + players_active_missions[self.player_index] + .missions + .push(mission.clone()); + let score = ai::get_average_score( + game, + self.player_index, + rng, + &time_per_mission, + &players_active_missions, + ) + .await + .powf(difficulty_factor); + scores.push(score); + } + let chosen_mission = if difficulty >= 1.0 - f64::EPSILON { + scores + .iter() + .enumerate() + .max_by(|a, b| a.1.partial_cmp(b.1).expect("floating point error")) + .expect("there are no possible actions") + .0 + } else { + utils::weighted_random_selection(&scores, rng) + }; + missions + .into_iter() + .nth(chosen_mission) + .expect("index out of bounds") + } + + fn missions_of_type(&self, mission_type: &MissionType) -> usize { + self.missions + .iter() + .filter(|mission| mission.mission_type == *mission_type) + .count() + } + + fn targets_of_type(&self, mission_type: &MissionType) -> Vec { + self.missions + .iter() + .filter(|mission| mission.mission_type == *mission_type) + .map(|mission| mission.target) + .collect() + } + + pub fn get_players_active_missions(&self, game: &Game, rng: &mut Rng) -> Vec { + let mut players_active_missions = Vec::new(); + for player in &game.players { + if player.index == self.player_index { + players_active_missions.push(self.clone()); + continue; + } + players_active_missions.push(ActiveMissions::new(game, player.index, rng, None)); + } + players_active_missions + } +} + +#[derive(Clone)] +pub struct Mission { + units: Vec, + player_index: usize, + mission_type: MissionType, + target: Position, + current_location: Position, + pub next_action: Option, +} + +impl Mission { + fn new( + units: Vec, + target: Position, + mission_type: MissionType, + game: &Game, + player_index: usize, + ) -> Self { + let current_location = game.players[player_index].get_unit(units[0]).position; + let mut mission = Self { + units, + player_index, + target, + mission_type, + current_location, + next_action: None, + }; + mission.next_action = mission.next_movement(game); + mission + } + + /// Returns the priority of the mission. + /// + /// # Panics + /// + /// Panics if the game or the mission is invalid. + #[must_use] + #[allow(clippy::only_used_in_recursion)] + pub fn priority(&self, _game: &Game, _active_missions: &ActiveMissions) -> f64 { + 1.0 //todo + } + + fn update(&mut self, game: &Game, active_missions: &ActiveMissions) { + self.units.retain(|unit| { + game.players[self.player_index] + .try_get_unit(*unit) + .is_some() + }); + if self.units.is_empty() { + return; + } + self.current_location = game.players[self.player_index] + .get_unit(self.units[0]) + .position; + self.units.retain(|unit| { + game.players[self.player_index].get_unit(*unit).position == self.current_location + }); + self.next_action = self.next_movement(game); + match &mut self.mission_type { + MissionType::FoundCity => { + if game.players.iter().any(|player| { + player + .cities + .iter() + .any(|city| city.position.distance(self.target) < 3) + }) { + self.target = decide_settling_position( + game, + self.player_index, + self.current_location, + active_missions, + ); + } + } + MissionType::FightPlayerForces { + player_index: enemy_player, + units, + } => { + units.retain(|unit| game.players[*enemy_player].try_get_unit(*unit).is_some()); + if !units.is_empty() { + self.target = game.players[*enemy_player].get_unit(units[0]).position; + } + if units + .iter() + .any(|unit| game.players[*enemy_player].get_unit(*unit).position != self.target) + { + self.units.clear(); + } + } + MissionType::FightBarbarians { units } => { + units.retain(|unit| { + barbarians::get_barbarians_player(game) + .try_get_unit(*unit) + .is_some() + }); + if !units.is_empty() { + self.target = barbarians::get_barbarians_player(game) + .get_unit(units[0]) + .position; + } + } + MissionType::FightPirates { units } => { + units.retain(|unit| { + pirates::get_pirates_player(game) + .try_get_unit(*unit) + .is_some() + }); + if !units.is_empty() { + self.target = pirates::get_pirates_player(game) + .get_unit(units[0]) + .position; + } + } + _ => (), + } + } + + fn is_complete(&self, game: &Game) -> bool { + self.current_location == self.target + || self.units.is_empty() + || match &self.mission_type { + MissionType::Explore => !game.map.is_unexplored(self.target), + MissionType::DefendCity => game.players[self.player_index] + .try_get_city(self.target) + .is_none(), + MissionType::CapturePlayerCity { + player_index: enemy_player, + } => game.players[*enemy_player] + .try_get_city(self.target) + .is_none(), //todo: abort mission if defenses get too strong + MissionType::CaptureBarbarianCamp => barbarians::get_barbarians_player(game) + .try_get_city(self.target) + .is_none(), + MissionType::FightPlayerForces { + player_index: _, + units, + } + | MissionType::FightBarbarians { units } + | MissionType::FightPirates { units } => units.is_empty(), + _ => false, + } + } + + fn next_movement(&self, game: &Game) -> Option { + //todo: settlers and scouts should avoid stronger enemies in their path + let next_position = self + .current_location + .next_position_in_path(&self.target) + .expect("missions is at it's target location"); + let carrier = self.carrier(game); + let cost = self.movement_cost(game); + if !game.players[self.player_index].can_afford(&cost) { + return None; + } + //todo: handle roads + Some(MovementAction::Move(MoveUnits::new( + self.units.clone(), + next_position, + carrier, + cost.default_payment(), + ))) + } + + fn carrier(&self, game: &Game) -> Option { + let carrier = game.players[self.player_index] + .get_unit(self.units[0]) + .carrier_id; + carrier + } + + fn movement_cost(&self, game: &Game) -> PaymentOptions { + movement::move_units_destinations( + game.player(self.player_index), + game, + &self.units, + self.current_location, + self.carrier(game), + ) + .expect("units in mission can't move") + .into_iter() + .find(|destination| destination.destination == self.target) + .expect("mission can't move to target") + .cost + } +} + +#[derive(Clone, PartialEq)] +enum MissionType { + Explore, + DefendCity, + FoundCity, + CapturePlayerCity { + player_index: usize, + }, + CaptureBarbarianCamp, + FightPlayerForces { + player_index: usize, + units: Vec, + }, + FightBarbarians { + units: Vec, + }, + FightPirates { + units: Vec, + }, + Transport, + Cartography, +} + +fn decide_settling_position( + game: &Game, + player_index: usize, + settler_position: Position, + missions: &ActiveMissions, +) -> Position { + let mut blocked_positions = game + .players + .iter() + .flat_map(|player| &player.cities) + .map(|city| city.position) + .collect::>(); + blocked_positions.extend(missions.targets_of_type(&MissionType::FoundCity)); + + game.map + .tiles + .clone() + .into_keys() + .filter(|position| !blocked_positions.contains(position)) + .map(|position| { + ( + position, + settling_score(game, player_index, position, missions, &blocked_positions) + / settler_position.distance(position) as f64, + ) + }) + .max_by(|(_, a), (_, b)| a.total_cmp(b)) + .expect("empty map") + .0 +} + +fn settling_score( + game: &Game, + player_index: usize, + city_position: Position, + missions: &ActiveMissions, + blocked_positions: &[Position], +) -> f64 { + let mut score = 0.0; + let neighbors = city_position + .neighbors() + .into_iter() + .filter(|position| !blocked_positions.contains(position)) + .filter_map(|position| game.map.get(position)) + .collect::>(); + if neighbors.contains(&&Terrain::Mountain) { + score += 1.0; + } + if neighbors.contains(&&Terrain::Forest) { + score += 1.0; + } + if neighbors.contains(&&Terrain::Fertile) + || (neighbors.contains(&&Terrain::Barren) + && game.players[player_index].has_advance(Advance::Irrigation)) + || neighbors.contains(&&Terrain::Water) + && game.players[player_index].has_advance(Advance::Fishing) + { + score += 1.0; + } + if neighbors.contains(&&Terrain::Water) { + score += 0.25; + if game.players[player_index].cities.len() + + missions.missions_of_type(&MissionType::FoundCity) + == 1 + { + score += 0.75; + } + if game.players[player_index].has_advance(Advance::Fishing) { + score += 0.25; + } + } + score -= city_threat_score(game, player_index, city_position) * 3.0; + score +} + +fn city_threat_score(game: &Game, player_index: usize, city_position: Position) -> f64 { + game.players + .iter() + .filter(|player| player.index != player_index) + .flat_map(|player| { + let mut player_threats = player + .units + .iter() + .map(|unit| unit.position) + .collect::>(); + player_threats.extend(player.cities.iter().map(|city| city.position)); + player_threats + }) + .fold(0.0, |acc, position| { + acc + 1.0 / position.distance(city_position).pow(2) as f64 + }) +} + +fn decide_scouting_position( + game: &Game, + player_index: usize, + scout_position: Position, + missions: &ActiveMissions, +) -> Option { + let scout_targets = missions.targets_of_type(&MissionType::Explore); + game.map + .tiles + .clone() + .into_keys() + .filter(|position| game.map.is_unexplored(*position) && !scout_targets.contains(position)) + .map(|position| { + ( + position, + scout_score(game, player_index, position, &scout_targets) + / scout_position.distance(position) as f64, + ) + }) + .max_by(|(_, a), (_, b)| a.total_cmp(b)) + .map(|(position, _)| position) +} + +fn scout_score( + game: &Game, + player_index: usize, + position: Position, + scout_targets: &[Position], +) -> f64 { + let capital_city_position = game.players[player_index].cities[0].position; + let mut score = 1.0; + for target in scout_targets { + let distance = position.distance(*target); + if distance < 4 { + score /= 4.0 - distance as f64; + } + } + score /= position.distance(capital_city_position) as f64; + score +} diff --git a/server/src/lib.rs b/server/src/lib.rs index bb8ca890..83ede3bd 100644 --- a/server/src/lib.rs +++ b/server/src/lib.rs @@ -8,6 +8,7 @@ #![allow(clippy::cast_precision_loss)] #![allow(clippy::cast_possible_wrap)] #![allow(clippy::implicit_hasher)] +#![allow(clippy::struct_field_names)] pub mod ability_initializer; pub mod action; @@ -16,6 +17,7 @@ pub mod advance; pub mod ai; pub mod ai_actions; pub mod ai_collect; +pub mod ai_missions; mod barbarians; pub mod cache; pub mod card; diff --git a/server/src/position.rs b/server/src/position.rs index feb290ae..7f5a49e9 100644 --- a/server/src/position.rs +++ b/server/src/position.rs @@ -58,20 +58,26 @@ impl Position { } pub fn neighbors(&self) -> Vec { - /* vec![ - Position::new(self.q, self.r - 1), - Position::new(self.q + 1, self.r), - Position::new(self.q + 1, self.r + 1), - Position::new(self.q, self.r + 1), - Position::new(self.q - 1, self.r + 1), - Position::new(self.q - 1, self.r), - ] */ self.coordinate() .neighbors() .into_iter() .map(Position::from_coordinate) .collect() } + + #[must_use] + pub fn next_position_in_path(&self, target: &Self) -> Option { + if self == target { + return None; + } + let mut neighbors = self.neighbors(); + neighbors.sort_by_key(|a| a.distance(*target)); + if neighbors.is_empty() { + None + } else { + Some(neighbors[0]) + } + } } impl Display for Position { diff --git a/server/src/utils.rs b/server/src/utils.rs index 13ed7546..ce8c6646 100644 --- a/server/src/utils.rs +++ b/server/src/utils.rs @@ -87,9 +87,7 @@ pub fn ordinal_number(value: u32) -> String { fn get_current_time() -> Duration { let start = SystemTime::now(); - start - .duration_since(UNIX_EPOCH) - .expect("Time went backwards") + start.duration_since(UNIX_EPOCH).expect("unix time error") } #[derive(Clone, Default)] diff --git a/server/tests/random_actions.rs b/server/tests/random_actions.rs index e31c7e1a..7922e67e 100644 --- a/server/tests/random_actions.rs +++ b/server/tests/random_actions.rs @@ -11,7 +11,7 @@ use server::{ mod common; -const ITERATIONS: usize = 96; +const ITERATIONS: usize = 100; #[tokio::test] async fn test_random_actions() { diff --git a/server/update.cmd b/server/update.cmd index 16fa551f..f8149aaa 100644 --- a/server/update.cmd +++ b/server/update.cmd @@ -1,11 +1,13 @@ cargo update rustup update cargo update +cargo clean cargo fmt cd ..\client cargo update rustup update cargo update +cargo clean cargo fmt cd .. git stash