Something went wrong. Try again.
Star Gambit Computer Player SDK
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110use rand::seq::SliceRandom;use rand::Rng;
use sg_sdk::{apply, legal_actions, Com, Game};use stellar::model::Unit;
use stellar::GameEngine;
fn is_active(u: &Unit) -> bool { u.remaining_health() > 0}
/// Total remaining hit points of `me`'s opponent (ships *and* portal). The drop/// in this quantity is the damage an action deals.fn enemy_health(engine: &GameEngine, me: i32) -> i32 { let enemy = 1 - me; engine .units .iter() .filter(|u| is_active(u) && u.owner == enemy) .map(|u| u.remaining_health()) .sum()}
/// The damage the best available shot would deal right now (0 if no gun bears).fn best_immediate_damage(engine: &GameEngine, me: i32) -> i32 { let before = enemy_health(engine, me); legal_actions(engine) .iter() .filter(|a| a.contains('*')) .filter_map(|a| apply(engine, a).ok()) .map(|after| before - enemy_health(&after, me)) .max() .unwrap_or(0)}
/// A bot that always fires if it can.pub fn fire_com_turn<R: Rng>(engine: &GameEngine, me: i32, rng: &mut R) -> Vec<String> { let mut cur = engine.clone(); let mut out = Vec::new();
for _ in 0..(1000) { let cands = legal_actions(&cur); if cands.is_empty() { break; }
// 1. Fire the most damaging shot available. let before = enemy_health(&cur, me); let best_fire = cands .iter() .filter(|a| a.contains('*')) .filter_map(|a| { apply(&cur, a) .ok() .map(|next| (before - enemy_health(&next, me), a)) }) .max_by_key(|(dmg, _)| *dmg); if let Some((dmg, action)) = best_fire { if dmg > 0 { cur = apply(&cur, action).expect("fire was validated"); out.push(action.clone()); continue; } }
// 2. Move to set up the best shot reachable in one step. let best_move = cands .iter() .filter(|a| a.contains('+')) .filter_map(|a| { apply(&cur, a) .ok() .map(|next| (best_immediate_damage(&next, me), a)) }) .filter(|(dmg, _)| *dmg > 0) .max_by_key(|(dmg, _)| *dmg); if let Some((_, action)) = best_move { cur = apply(&cur, action).expect("move was validated"); out.push(action.clone()); continue; }
// 3. Nothing aggressive to do, so play a random legal action. let action = cands.choose(rng).cloned().unwrap(); match apply(&cur, &action) { Ok(next) => cur = next, Err(_) => break, } out.push(action.clone()); if action == "END" || cur.result.is_some() || cur.whos_turn != me { break; } }
if out.last().map_or(true, |a| a != "END") && legal_actions(&cur).iter().any(|c| c == "END") { out.push("END".to_string()); } out}
/// A trigger-happy skirmisher example com. See [`fire_com_turn`].pub struct FireCom;
impl Com for FireCom { fn act(&mut self, game: &Game) -> Vec<String> { fire_com_turn(game.engine(), game.me(), &mut rand::thread_rng()) }}