Compare commits
15 Commits
7da834de0b
...
terran
| Author | SHA1 | Date | |
|---|---|---|---|
| 810fc4a3d4 | |||
| 9956c930cd | |||
| dd24f686b3 | |||
| 997cbdb48e | |||
| 0dfdb6a6df | |||
| 321e3ebb76 | |||
| c39f95b304 | |||
| 30a169ed06 | |||
| 6e082c24df | |||
| 28696b2358 | |||
| affbd3f82f | |||
| fbcbb8f882 | |||
| eebba4d7bc | |||
| ce7ce427c6 | |||
| feda48b0a4 |
1
.gitignore
vendored
1
.gitignore
vendored
@@ -56,3 +56,4 @@ result
|
|||||||
result-*
|
result-*
|
||||||
.direnv/
|
.direnv/
|
||||||
.envrc.cache
|
.envrc.cache
|
||||||
|
target/
|
||||||
|
|||||||
12
flake.lock
generated
12
flake.lock
generated
@@ -20,11 +20,11 @@
|
|||||||
},
|
},
|
||||||
"nixpkgs": {
|
"nixpkgs": {
|
||||||
"locked": {
|
"locked": {
|
||||||
"lastModified": 1768886240,
|
"lastModified": 1769018530,
|
||||||
"narHash": "sha256-C2TjvwYZ2VDxYWeqvvJ5XPPp6U7H66zeJlRaErJKoEM=",
|
"narHash": "sha256-MJ27Cy2NtBEV5tsK+YraYr2g851f3Fl1LpNHDzDX15c=",
|
||||||
"owner": "NixOS",
|
"owner": "NixOS",
|
||||||
"repo": "nixpkgs",
|
"repo": "nixpkgs",
|
||||||
"rev": "80e4adbcf8992d3fd27ad4964fbb84907f9478b0",
|
"rev": "88d3861acdd3d2f0e361767018218e51810df8a1",
|
||||||
"type": "github"
|
"type": "github"
|
||||||
},
|
},
|
||||||
"original": {
|
"original": {
|
||||||
@@ -65,11 +65,11 @@
|
|||||||
]
|
]
|
||||||
},
|
},
|
||||||
"locked": {
|
"locked": {
|
||||||
"lastModified": 1769050281,
|
"lastModified": 1769136478,
|
||||||
"narHash": "sha256-1H8DN4UZgEUqPUA5ecHOufLZMscJ4IlcGaEftaPtpBY=",
|
"narHash": "sha256-8UNd5lmGf8phCr/aKxagJ4kNsF0pCHLish2G4ZKCFFY=",
|
||||||
"owner": "oxalica",
|
"owner": "oxalica",
|
||||||
"repo": "rust-overlay",
|
"repo": "rust-overlay",
|
||||||
"rev": "6deef0585c52d9e70f96b6121207e1496d4b0c49",
|
"rev": "470ee44393bb19887056b557ea2c03fc5230bd5a",
|
||||||
"type": "github"
|
"type": "github"
|
||||||
},
|
},
|
||||||
"original": {
|
"original": {
|
||||||
|
|||||||
@@ -1,6 +1,9 @@
|
|||||||
|
use crate::{
|
||||||
|
state::game_state::GameState,
|
||||||
|
utils::{build_manager, worker_management},
|
||||||
|
};
|
||||||
use rsbwapi::*;
|
use rsbwapi::*;
|
||||||
use std::sync::{Arc, Mutex};
|
use std::sync::{Arc, Mutex};
|
||||||
use crate::{state::game_state::GameState, utils::{build_manager, worker_management}};
|
|
||||||
|
|
||||||
fn draw_unit_ids(game: &Game) {
|
fn draw_unit_ids(game: &Game) {
|
||||||
for unit in game.get_all_units() {
|
for unit in game.get_all_units() {
|
||||||
@@ -35,9 +38,28 @@ impl AiModule for ProtosBot {
|
|||||||
return;
|
return;
|
||||||
};
|
};
|
||||||
|
|
||||||
|
// Apply desired game speed from shared state
|
||||||
|
let desired_speed = self.shared_speed.get();
|
||||||
|
unsafe {
|
||||||
|
let game_ptr = game as *const Game as *mut Game;
|
||||||
|
(*game_ptr).set_local_speed(desired_speed);
|
||||||
|
}
|
||||||
|
|
||||||
build_manager::on_frame(game, &player, &mut locked_state);
|
build_manager::on_frame(game, &player, &mut locked_state);
|
||||||
worker_management::assign_idle_workers_to_minerals(game, &player, &mut locked_state);
|
worker_management::assign_idle_workers_to_minerals(game, &player, &mut locked_state);
|
||||||
|
|
||||||
|
// Update web server with current build status
|
||||||
|
let stage_name = locked_state
|
||||||
|
.build_stages
|
||||||
|
.get(locked_state.current_stage_index)
|
||||||
|
.map(|s| s.name.clone())
|
||||||
|
.unwrap_or_else(|| "Unknown".to_string());
|
||||||
|
self.build_status.update(
|
||||||
|
stage_name,
|
||||||
|
locked_state.current_stage_index,
|
||||||
|
locked_state.stage_item_status.clone(),
|
||||||
|
);
|
||||||
|
|
||||||
build_manager::print_debug_build_status(game, &player, &locked_state);
|
build_manager::print_debug_build_status(game, &player, &locked_state);
|
||||||
draw_unit_ids(game);
|
draw_unit_ids(game);
|
||||||
}
|
}
|
||||||
@@ -47,6 +69,17 @@ impl AiModule for ProtosBot {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
println!("unit created: {:?}", unit.get_type());
|
println!("unit created: {:?}", unit.get_type());
|
||||||
|
|
||||||
|
// If the created unit is a building, handle building creation; otherwise handle unit creation (e.g., trained units).
|
||||||
|
let Ok(mut locked_state) = self.game_state.lock() else {
|
||||||
|
return;
|
||||||
|
};
|
||||||
|
|
||||||
|
if unit.get_type().is_building() {
|
||||||
|
build_manager::on_building_create(&unit, &mut locked_state);
|
||||||
|
} else {
|
||||||
|
build_manager::on_unit_create(&unit, &mut locked_state);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fn on_unit_morph(&mut self, _game: &Game, _unit: Unit) {}
|
fn on_unit_morph(&mut self, _game: &Game, _unit: Unit) {}
|
||||||
@@ -70,10 +103,20 @@ impl AiModule for ProtosBot {
|
|||||||
|
|
||||||
pub struct ProtosBot {
|
pub struct ProtosBot {
|
||||||
game_state: Arc<Mutex<GameState>>,
|
game_state: Arc<Mutex<GameState>>,
|
||||||
|
shared_speed: crate::web_server::SharedGameSpeed,
|
||||||
|
build_status: crate::web_server::SharedBuildStatus,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl ProtosBot {
|
impl ProtosBot {
|
||||||
pub fn new(game_state: Arc<Mutex<GameState>>) -> Self {
|
pub fn new(
|
||||||
Self { game_state }
|
game_state: Arc<Mutex<GameState>>,
|
||||||
|
shared_speed: crate::web_server::SharedGameSpeed,
|
||||||
|
build_status: crate::web_server::SharedBuildStatus,
|
||||||
|
) -> Self {
|
||||||
|
Self {
|
||||||
|
game_state,
|
||||||
|
shared_speed,
|
||||||
|
build_status,
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,16 +1,36 @@
|
|||||||
mod bot;
|
mod bot;
|
||||||
mod state;
|
mod state;
|
||||||
mod utils;
|
mod utils;
|
||||||
|
mod web_server;
|
||||||
|
|
||||||
use bot::ProtosBot;
|
use bot::ProtosBot;
|
||||||
use std::sync::{Arc, Mutex};
|
|
||||||
use state::game_state::GameState;
|
use state::game_state::GameState;
|
||||||
|
use std::sync::{Arc, Mutex};
|
||||||
|
use web_server::{SharedBuildStatus, SharedGameSpeed};
|
||||||
|
|
||||||
fn main() {
|
fn main() {
|
||||||
println!("Starting RustBot...");
|
println!("Starting RustBot...");
|
||||||
|
|
||||||
let game_state = Arc::new(Mutex::new(GameState::default()));
|
let game_state = Arc::new(Mutex::new(GameState::default()));
|
||||||
|
let shared_speed = SharedGameSpeed::new(42); // Default speed (slowest)
|
||||||
|
let build_status = SharedBuildStatus::new();
|
||||||
|
|
||||||
rsbwapi::start(move |_game| ProtosBot::new(game_state.clone() ));
|
// Start web server in a separate thread
|
||||||
|
let shared_speed_clone = shared_speed.clone();
|
||||||
|
let build_status_clone = build_status.clone();
|
||||||
|
std::thread::spawn(move || {
|
||||||
|
let runtime = tokio::runtime::Runtime::new().unwrap();
|
||||||
|
runtime.block_on(web_server::start_web_server(
|
||||||
|
shared_speed_clone,
|
||||||
|
build_status_clone,
|
||||||
|
));
|
||||||
|
});
|
||||||
|
|
||||||
|
rsbwapi::start(move |_game| {
|
||||||
|
ProtosBot::new(
|
||||||
|
game_state.clone(),
|
||||||
|
shared_speed.clone(),
|
||||||
|
build_status.clone(),
|
||||||
|
)
|
||||||
|
});
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -24,23 +24,26 @@ impl BuildStage {
|
|||||||
pub fn get_build_stages() -> Vec<BuildStage> {
|
pub fn get_build_stages() -> Vec<BuildStage> {
|
||||||
vec![
|
vec![
|
||||||
BuildStage::new("Start")
|
BuildStage::new("Start")
|
||||||
.with_unit(UnitType::Protoss_Probe, 10)
|
.with_unit(UnitType::Terran_SCV, 10)
|
||||||
.with_unit(UnitType::Protoss_Pylon, 1),
|
.with_unit(UnitType::Terran_Supply_Depot, 1),
|
||||||
|
|
||||||
BuildStage::new("Basic Production")
|
BuildStage::new("Basic Production")
|
||||||
.with_unit(UnitType::Protoss_Probe, 12)
|
.with_unit(UnitType::Terran_SCV, 12)
|
||||||
.with_unit(UnitType::Protoss_Pylon, 2)
|
.with_unit(UnitType::Terran_Supply_Depot, 2)
|
||||||
.with_unit(UnitType::Protoss_Gateway, 1)
|
.with_unit(UnitType::Terran_Barracks, 1)
|
||||||
.with_unit(UnitType::Protoss_Forge, 1),
|
.with_unit(UnitType::Terran_Refinery, 1),
|
||||||
|
BuildStage::new("Defense Bunker")
|
||||||
|
.with_unit(UnitType::Terran_SCV, 16)
|
||||||
|
.with_unit(UnitType::Terran_Supply_Depot, 3)
|
||||||
|
.with_unit(UnitType::Terran_Command_Center, 1)
|
||||||
|
.with_unit(UnitType::Terran_Barracks, 1)
|
||||||
|
.with_unit(UnitType::Terran_Refinery, 1),
|
||||||
|
|
||||||
|
BuildStage::new("Mid Game")
|
||||||
// Stage 2: Defense cannons
|
.with_unit(UnitType::Terran_SCV, 20)
|
||||||
BuildStage::new("Defense Cannons")
|
.with_unit(UnitType::Terran_Supply_Depot, 4)
|
||||||
.with_unit(UnitType::Protoss_Probe, 16)
|
.with_unit(UnitType::Terran_Command_Center, 2)
|
||||||
.with_unit(UnitType::Protoss_Pylon, 3)
|
.with_unit(UnitType::Terran_Barracks, 2)
|
||||||
.with_unit(UnitType::Protoss_Nexus, 1)
|
.with_unit(UnitType::Terran_Refinery, 2)
|
||||||
.with_unit(UnitType::Protoss_Gateway, 1)
|
.with_unit(UnitType::Terran_Missile_Turret, 2),
|
||||||
.with_unit(UnitType::Protoss_Forge, 1)
|
|
||||||
.with_unit(UnitType::Protoss_Photon_Cannon, 4),
|
|
||||||
]
|
]
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,36 +1,28 @@
|
|||||||
|
use rsbwapi::{UnitType, UpgradeType};
|
||||||
use std::collections::HashMap;
|
use std::collections::HashMap;
|
||||||
use rsbwapi::{Order, Position, Unit, UnitType, UpgradeType};
|
|
||||||
|
|
||||||
use crate::state::build_stages::BuildStage;
|
use crate::state::build_stages::BuildStage;
|
||||||
|
|
||||||
pub struct GameState {
|
pub struct GameState {
|
||||||
pub intended_commands: HashMap<usize, IntendedCommand>,
|
|
||||||
pub unit_build_history: Vec<BuildHistoryEntry>,
|
pub unit_build_history: Vec<BuildHistoryEntry>,
|
||||||
pub build_stages: Vec<BuildStage>,
|
pub build_stages: Vec<BuildStage>,
|
||||||
pub current_stage_index: usize,
|
pub current_stage_index: usize,
|
||||||
pub desired_game_speed: i32,
|
pub desired_game_speed: i32,
|
||||||
|
pub stage_item_status: HashMap<String, String>,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
impl Default for GameState {
|
impl Default for GameState {
|
||||||
fn default() -> Self {
|
fn default() -> Self {
|
||||||
Self {
|
Self {
|
||||||
intended_commands: HashMap::new(),
|
|
||||||
unit_build_history: Vec::new(),
|
unit_build_history: Vec::new(),
|
||||||
build_stages: crate::state::build_stages::get_build_stages(),
|
build_stages: crate::state::build_stages::get_build_stages(),
|
||||||
current_stage_index: 0,
|
current_stage_index: 0,
|
||||||
desired_game_speed: 20,
|
desired_game_speed: 20,
|
||||||
|
stage_item_status: HashMap::new(),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Clone, Debug)]
|
|
||||||
pub struct IntendedCommand {
|
|
||||||
pub order: Order,
|
|
||||||
pub target_position: Option<Position>,
|
|
||||||
pub target_unit: Option<Unit>,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Clone, Debug)]
|
#[derive(Clone, Debug)]
|
||||||
pub enum BuildStatus {
|
pub enum BuildStatus {
|
||||||
Assigned,
|
Assigned,
|
||||||
@@ -42,5 +34,6 @@ pub struct BuildHistoryEntry {
|
|||||||
pub unit_type: Option<UnitType>,
|
pub unit_type: Option<UnitType>,
|
||||||
pub upgrade_type: Option<UpgradeType>,
|
pub upgrade_type: Option<UpgradeType>,
|
||||||
pub assigned_unit_id: Option<usize>,
|
pub assigned_unit_id: Option<usize>,
|
||||||
|
pub tile_position: Option<rsbwapi::TilePosition>,
|
||||||
// pub status: BuildStatus,
|
// pub status: BuildStatus,
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,53 +1,46 @@
|
|||||||
use rsbwapi::{Game, TilePosition, Unit, UnitType};
|
use rsbwapi::{Game, Player, TilePosition, Unit, UnitType};
|
||||||
|
|
||||||
pub fn find_build_location(
|
pub fn find_build_location(
|
||||||
game: &Game,
|
game: &Game,
|
||||||
|
_player: &Player,
|
||||||
builder: &Unit,
|
builder: &Unit,
|
||||||
building_type: UnitType,
|
building_type: UnitType,
|
||||||
max_range: i32,
|
max_range: i32,
|
||||||
) -> Option<TilePosition> {
|
) -> Option<TilePosition> {
|
||||||
|
if building_type.is_refinery() {
|
||||||
|
for geyser in game.get_geysers() {
|
||||||
|
let tp = geyser.get_tile_position();
|
||||||
|
if let Ok(true) = game.can_build_here(Some(builder), tp, building_type, false) {
|
||||||
|
return Some(tp);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
|
||||||
let start_tile = builder.get_tile_position();
|
let start = builder.get_tile_position();
|
||||||
|
for radius in 0..=max_range {
|
||||||
for distance in 0..max_range {
|
for dx in -radius..=radius {
|
||||||
for dx in -distance..=distance {
|
let dy = radius - dx.abs();
|
||||||
for dy in -distance..=distance {
|
for &dy_sign in &[-1, 1] {
|
||||||
if dx.abs() != distance && dy.abs() != distance {
|
let cand = TilePosition {
|
||||||
|
x: start.x + dx,
|
||||||
|
y: start.y + dy * dy_sign,
|
||||||
|
};
|
||||||
|
if let Ok(true) = game.can_build_here(Some(builder), cand, building_type, false) {
|
||||||
|
return Some(cand);
|
||||||
|
}
|
||||||
|
if dy == 0 {
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
|
let cand2 = TilePosition {
|
||||||
let tile = TilePosition {
|
x: start.x + dx,
|
||||||
x: start_tile.x + dx,
|
y: start.y - dy * dy_sign,
|
||||||
y: start_tile.y + dy,
|
|
||||||
};
|
};
|
||||||
|
if let Ok(true) = game.can_build_here(Some(builder), cand2, building_type, false) {
|
||||||
if is_valid_build_location(game, building_type, tile, builder) {
|
return Some(cand2);
|
||||||
return Some(tile);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
None
|
None
|
||||||
}
|
}
|
||||||
|
|
||||||
fn is_valid_build_location(
|
|
||||||
game: &Game,
|
|
||||||
building_type: UnitType,
|
|
||||||
position: TilePosition,
|
|
||||||
builder: &Unit,
|
|
||||||
) -> bool {
|
|
||||||
if !game.can_build_here(builder, position, building_type, false).unwrap_or(false) {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
// if building_type.requires_psi() && !game.has_power(position, building_type) {
|
|
||||||
// return false;
|
|
||||||
// }
|
|
||||||
|
|
||||||
// if building_type.requires_creep() && !game.has_creep(position) {
|
|
||||||
// return false;
|
|
||||||
// }
|
|
||||||
|
|
||||||
true
|
|
||||||
}
|
|
||||||
|
|||||||
@@ -1,149 +1,237 @@
|
|||||||
use rsbwapi::{Game, Order, Player, UnitType};
|
use rsbwapi::{Game, Player, Unit, UnitType};
|
||||||
|
|
||||||
use crate::{
|
use crate::{
|
||||||
state::game_state::{BuildHistoryEntry, GameState, IntendedCommand},
|
state::game_state::{BuildHistoryEntry, GameState},
|
||||||
utils::build_location_utils,
|
utils::build_location_utils,
|
||||||
};
|
};
|
||||||
|
|
||||||
pub fn on_frame(game: &Game, player: &Player, state: &mut GameState) {
|
pub fn on_frame(game: &Game, player: &Player, state: &mut GameState) {
|
||||||
|
// No intended command tracking; directly manage builds and stages.
|
||||||
check_and_advance_stage(player, state);
|
check_and_advance_stage(player, state);
|
||||||
|
state.stage_item_status = get_status_for_stage_items(game, player, state);
|
||||||
try_start_next_build(game, player, state);
|
try_start_next_build(game, player, state);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
pub fn on_building_create(unit: &Unit, state: &mut GameState) {
|
||||||
|
// When a building is created, remove the corresponding build history entry so the next
|
||||||
|
// build can be started without waiting for the current one to finish.
|
||||||
|
if let Some(pos) = state.unit_build_history.iter().position(|entry| {
|
||||||
|
entry
|
||||||
|
.unit_type
|
||||||
|
.map(|ut| ut == unit.get_type())
|
||||||
|
.unwrap_or(false)
|
||||||
|
}) {
|
||||||
|
state.unit_build_history.remove(pos);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Called when a non‑building unit (e.g., a trained unit) is created.
|
||||||
|
/// This clears any pending assignment for the building that trained it.
|
||||||
|
pub fn on_unit_create(_unit: &Unit, _state: &mut GameState) {
|
||||||
|
// No intended command tracking needed for unit creation.
|
||||||
|
}
|
||||||
|
|
||||||
fn try_start_next_build(game: &Game, player: &Player, state: &mut GameState) {
|
fn try_start_next_build(game: &Game, player: &Player, state: &mut GameState) {
|
||||||
|
if !should_start_next_build(game, player, state) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
let Some(unit_type) = get_next_thing_to_build(game, player, state) else {
|
let Some(unit_type) = get_next_thing_to_build(game, player, state) else {
|
||||||
return;
|
return;
|
||||||
};
|
};
|
||||||
|
let Some(builder) = find_builder_for_unit(player, unit_type, state) else {
|
||||||
let Some(builder) = find_builder_for_unit(player, unit_type) else {
|
|
||||||
return;
|
return;
|
||||||
};
|
};
|
||||||
|
|
||||||
let builder_id = builder.get_id();
|
let builder_id = builder.get_id();
|
||||||
|
if let Some((success, tile_pos)) =
|
||||||
|
assign_builder_to_construct(game, player, &builder, unit_type, state)
|
||||||
|
{
|
||||||
|
if success {
|
||||||
|
let entry = BuildHistoryEntry {
|
||||||
|
unit_type: Some(unit_type),
|
||||||
|
upgrade_type: None,
|
||||||
|
assigned_unit_id: Some(builder_id),
|
||||||
|
tile_position: tile_pos,
|
||||||
|
};
|
||||||
|
state.unit_build_history.push(entry);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
if assign_builder_to_construct(game, &builder, unit_type, state) {
|
fn should_start_next_build(_game: &Game, player: &Player, state: &mut GameState) -> bool {
|
||||||
let entry = BuildHistoryEntry {
|
// Do not start a new build if there is a pending build (assigned but not yet constructing/training).
|
||||||
unit_type: Some(unit_type),
|
if pending_build_exists(state, player) {
|
||||||
upgrade_type: None,
|
return false;
|
||||||
assigned_unit_id: Some(builder_id),
|
}
|
||||||
};
|
// Ensure there is a builder available for the next thing to build.
|
||||||
|
if let Some(unit_type) = get_next_thing_to_build(_game, player, state) {
|
||||||
|
find_builder_for_unit(player, unit_type, state).is_some()
|
||||||
|
} else {
|
||||||
|
false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
state.unit_build_history.push(entry);
|
fn has_ongoing_constructions(state: &GameState, player: &Player) -> bool {
|
||||||
|
// Consider a construction ongoing if there is a build history entry with an assigned unit that
|
||||||
|
// is currently constructing or training. This covers the period after a build command is issued
|
||||||
|
// but before the unit starts the actual constructing state, preventing multiple workers from
|
||||||
|
// being assigned to the same build command.
|
||||||
|
state.unit_build_history.iter().any(|entry| {
|
||||||
|
if let Some(unit_id) = entry.assigned_unit_id {
|
||||||
|
if let Some(unit) = player.get_units().iter().find(|u| u.get_id() == unit_id) {
|
||||||
|
return unit.is_constructing() || unit.is_training();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
false
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
let current_stage = &state.build_stages[state.current_stage_index];
|
// Returns true if there is a build history entry with an assigned builder that has not yet started constructing or training.
|
||||||
println!(
|
fn pending_build_exists(state: &GameState, player: &Player) -> bool {
|
||||||
"Started building {} with unit {} (Stage: {})",
|
state.unit_build_history.iter().any(|entry| {
|
||||||
unit_type.name(),
|
if let Some(unit_id) = entry.assigned_unit_id {
|
||||||
builder_id,
|
if let Some(unit) = player.get_units().iter().find(|u| u.get_id() == unit_id) {
|
||||||
current_stage.name
|
return !(unit.is_constructing() || unit.is_training());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
false
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
fn get_status_for_stage_items(
|
||||||
|
_game: &Game,
|
||||||
|
player: &Player,
|
||||||
|
state: &GameState,
|
||||||
|
) -> std::collections::HashMap<String, String> {
|
||||||
|
let mut status_map = std::collections::HashMap::new();
|
||||||
|
let Some(current_stage) = state.build_stages.get(state.current_stage_index) else {
|
||||||
|
return status_map;
|
||||||
|
};
|
||||||
|
for (unit_type, &desired_count) in ¤t_stage.desired_counts {
|
||||||
|
let unit_name = unit_type.name().to_string();
|
||||||
|
let current_count = count_units_of_type(player, state, *unit_type);
|
||||||
|
if current_count >= desired_count {
|
||||||
|
status_map.insert(
|
||||||
|
unit_name,
|
||||||
|
format!("Complete ({}/{})", current_count, desired_count),
|
||||||
|
);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if !can_afford_unit(player, *unit_type) {
|
||||||
|
let minerals_short = unit_type.mineral_price() - player.minerals();
|
||||||
|
let gas_short = unit_type.gas_price() - player.gas();
|
||||||
|
status_map.insert(
|
||||||
|
unit_name,
|
||||||
|
format!(
|
||||||
|
"Need {} minerals, {} gas ({}/{})",
|
||||||
|
minerals_short.max(0),
|
||||||
|
gas_short.max(0),
|
||||||
|
current_count,
|
||||||
|
desired_count
|
||||||
|
),
|
||||||
|
);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if unit_type.is_building() {
|
||||||
|
if find_builder_for_unit(player, *unit_type, state).is_none() {
|
||||||
|
status_map.insert(
|
||||||
|
unit_name,
|
||||||
|
format!("No builder available ({}/{})", current_count, desired_count),
|
||||||
|
);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
status_map.insert(
|
||||||
|
unit_name,
|
||||||
|
format!("Ready to build ({}/{})", current_count, desired_count),
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
status_map
|
||||||
}
|
}
|
||||||
|
|
||||||
fn get_next_thing_to_build(game: &Game, player: &Player, state: &GameState) -> Option<UnitType> {
|
fn get_next_thing_to_build(game: &Game, player: &Player, state: &GameState) -> Option<UnitType> {
|
||||||
let current_stage = state.build_stages.get(state.current_stage_index)?;
|
let current_stage = state.build_stages.get(state.current_stage_index)?;
|
||||||
|
if let Some(pylon) = check_need_more_supply(game, player, state) {
|
||||||
if let Some(pylon) = check_need_more_supply(game, player) {
|
|
||||||
return Some(pylon);
|
return Some(pylon);
|
||||||
}
|
}
|
||||||
|
let status_map = get_status_for_stage_items(game, player, state);
|
||||||
let mut candidates = Vec::new();
|
let mut candidates = Vec::new();
|
||||||
|
|
||||||
for (unit_type, &desired_count) in ¤t_stage.desired_counts {
|
for (unit_type, &desired_count) in ¤t_stage.desired_counts {
|
||||||
let current_count = count_units_of_type(player, state, *unit_type);
|
let current_count = count_units_of_type(player, state, *unit_type);
|
||||||
|
|
||||||
if current_count >= desired_count {
|
if current_count >= desired_count {
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
|
let status = status_map.get(&unit_type.name().to_string());
|
||||||
if !can_afford_unit(player, *unit_type) {
|
if status.is_some() && status.unwrap().starts_with("Ready to build") {
|
||||||
continue;
|
candidates.push(*unit_type);
|
||||||
}
|
}
|
||||||
|
|
||||||
if unit_type.is_building() {
|
|
||||||
let builder = find_builder_for_unit(player, *unit_type)?;
|
|
||||||
let build_location = build_location_utils::find_build_location(game, &builder, *unit_type, 20);
|
|
||||||
if build_location.is_none() {
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
candidates.push(*unit_type);
|
|
||||||
}
|
}
|
||||||
|
candidates
|
||||||
candidates.into_iter().max_by_key(|unit_type| {
|
.into_iter()
|
||||||
unit_type.mineral_price() + unit_type.gas_price()
|
.max_by_key(|unit_type| unit_type.mineral_price() + unit_type.gas_price())
|
||||||
})
|
|
||||||
}
|
}
|
||||||
|
|
||||||
fn check_need_more_supply(game: &Game, player: &Player) -> Option<UnitType> {
|
fn check_need_more_supply(_game: &Game, player: &Player, _state: &GameState) -> Option<UnitType> {
|
||||||
let supply_used = player.supply_used();
|
let supply_used = player.supply_used();
|
||||||
let supply_total = player.supply_total();
|
let supply_total = player.supply_total();
|
||||||
|
|
||||||
if supply_total == 0 {
|
if supply_total == 0 {
|
||||||
return None;
|
return None;
|
||||||
}
|
}
|
||||||
|
|
||||||
let supply_remaining = supply_total - supply_used;
|
let supply_remaining = supply_total - supply_used;
|
||||||
let threshold = ((supply_total as f32) * 0.15).ceil() as i32;
|
let threshold = ((supply_total as f32) * 0.15).ceil() as i32;
|
||||||
|
|
||||||
if supply_remaining <= threshold && supply_total < 400 {
|
if supply_remaining <= threshold && supply_total < 400 {
|
||||||
let pylon_type = UnitType::Protoss_Pylon;
|
let pylon_type = UnitType::Protoss_Pylon;
|
||||||
|
|
||||||
if can_afford_unit(player, pylon_type) {
|
if can_afford_unit(player, pylon_type) {
|
||||||
if let Some(builder) = find_builder_for_unit(player, pylon_type) {
|
return Some(pylon_type);
|
||||||
let build_location = build_location_utils::find_build_location(game, &builder, pylon_type, 20);
|
|
||||||
if build_location.is_some() {
|
|
||||||
return Some(pylon_type);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
None
|
None
|
||||||
}
|
}
|
||||||
|
|
||||||
fn find_builder_for_unit(player: &Player, unit_type: UnitType) -> Option<rsbwapi::Unit> {
|
fn find_builder_for_unit(
|
||||||
|
player: &Player,
|
||||||
|
unit_type: UnitType,
|
||||||
|
_state: &GameState,
|
||||||
|
) -> Option<rsbwapi::Unit> {
|
||||||
let builder_type = unit_type.what_builds().0;
|
let builder_type = unit_type.what_builds().0;
|
||||||
|
|
||||||
player
|
player
|
||||||
.get_units()
|
.get_units()
|
||||||
.iter()
|
.iter()
|
||||||
.find(|u| {
|
.find(|u| {
|
||||||
u.get_type() == builder_type && !u.is_constructing() && !u.is_training() && u.is_idle()
|
u.get_type() == builder_type
|
||||||
|
&& !u.is_constructing()
|
||||||
|
&& !u.is_training()
|
||||||
|
&& (u.is_idle() || u.is_gathering_minerals() || u.is_gathering_gas())
|
||||||
})
|
})
|
||||||
.cloned()
|
.cloned()
|
||||||
}
|
}
|
||||||
|
|
||||||
fn assign_builder_to_construct(game: &Game, builder: &rsbwapi::Unit, unit_type: UnitType, state: &mut GameState) -> bool {
|
fn assign_builder_to_construct(
|
||||||
|
game: &Game,
|
||||||
|
player: &Player,
|
||||||
|
builder: &rsbwapi::Unit,
|
||||||
|
unit_type: UnitType,
|
||||||
|
state: &mut GameState,
|
||||||
|
) -> Option<(bool, Option<rsbwapi::TilePosition>)> {
|
||||||
let builder_id = builder.get_id();
|
let builder_id = builder.get_id();
|
||||||
|
|
||||||
if unit_type.is_building() {
|
if unit_type.is_building() {
|
||||||
let build_location = build_location_utils::find_build_location(game, builder, unit_type, 20);
|
let build_location =
|
||||||
|
build_location_utils::find_build_location(game, player, builder, unit_type, 42);
|
||||||
if let Some(pos) = build_location {
|
if let Some(pos) = build_location {
|
||||||
println!(
|
println!(
|
||||||
"Attempting to build {} at {:?} with worker {} (currently at {:?})",
|
"Attempting to build {} at {:?} with worker {}",
|
||||||
unit_type.name(),
|
unit_type.name(),
|
||||||
pos,
|
pos,
|
||||||
builder_id,
|
builder_id,
|
||||||
builder.get_position()
|
|
||||||
);
|
);
|
||||||
|
|
||||||
match builder.build(unit_type, pos) {
|
match builder.build(unit_type, pos) {
|
||||||
Ok(_) => {
|
Ok(_) => {
|
||||||
println!("Build command succeeded for {}", unit_type.name());
|
println!("Build command succeeded for {}", unit_type.name());
|
||||||
let intended_cmd = IntendedCommand {
|
// No intended command for building actions; the builder (worker) will be tracked via ongoing constructions.
|
||||||
order: Order::PlaceBuilding,
|
Some((true, Some(pos)))
|
||||||
target_position: Some(pos.to_position()),
|
|
||||||
target_unit: None,
|
|
||||||
};
|
|
||||||
state.intended_commands.insert(builder_id, intended_cmd);
|
|
||||||
true
|
|
||||||
}
|
}
|
||||||
Err(e) => {
|
Err(e) => {
|
||||||
println!("Build command FAILED for {}: {:?}", unit_type.name(), e);
|
println!("Build command FAILED for {}: {:?}", unit_type.name(), e);
|
||||||
false
|
Some((false, None))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
@@ -152,43 +240,33 @@ fn assign_builder_to_construct(game: &Game, builder: &rsbwapi::Unit, unit_type:
|
|||||||
unit_type.name(),
|
unit_type.name(),
|
||||||
builder.get_id()
|
builder.get_id()
|
||||||
);
|
);
|
||||||
false
|
Some((false, None))
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
match builder.train(unit_type) {
|
match builder.train(unit_type) {
|
||||||
Ok(_) => {
|
Ok(_) => {
|
||||||
let intended_cmd = IntendedCommand {
|
// No intended command for training; the building will be tracked via ongoing constructions.
|
||||||
order: Order::Train,
|
Some((true, None))
|
||||||
target_position: None,
|
|
||||||
target_unit: None,
|
|
||||||
};
|
|
||||||
state.intended_commands.insert(builder_id, intended_cmd);
|
|
||||||
true
|
|
||||||
}
|
}
|
||||||
Err(e) => {
|
Err(e) => {
|
||||||
println!("Train command FAILED for {}: {:?}", unit_type.name(), e);
|
println!("Train command FAILED for {}: {:?}", unit_type.name(), e);
|
||||||
false
|
Some((false, None))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fn count_units_of_type(player: &Player, _state: &GameState, unit_type: UnitType) -> i32 {
|
fn count_units_of_type(player: &Player, _state: &GameState, unit_type: UnitType) -> i32 {
|
||||||
let existing = player
|
player
|
||||||
.get_units()
|
.get_units()
|
||||||
.iter()
|
.iter()
|
||||||
.filter(|u| u.get_type() == unit_type)
|
.filter(|u| u.get_type() == unit_type)
|
||||||
.count() as i32;
|
.count() as i32
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
existing
|
|
||||||
}
|
}
|
||||||
|
|
||||||
fn can_afford_unit(player: &Player, unit_type: UnitType) -> bool {
|
fn can_afford_unit(player: &Player, unit_type: UnitType) -> bool {
|
||||||
let minerals = player.minerals();
|
let minerals = player.minerals();
|
||||||
let gas = player.gas();
|
let gas = player.gas();
|
||||||
|
|
||||||
minerals >= unit_type.mineral_price() && gas >= unit_type.gas_price()
|
minerals >= unit_type.mineral_price() && gas >= unit_type.gas_price()
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -196,7 +274,6 @@ fn check_and_advance_stage(player: &Player, state: &mut GameState) {
|
|||||||
let Some(current_stage) = state.build_stages.get(state.current_stage_index) else {
|
let Some(current_stage) = state.build_stages.get(state.current_stage_index) else {
|
||||||
return;
|
return;
|
||||||
};
|
};
|
||||||
|
|
||||||
let stage_complete = current_stage
|
let stage_complete = current_stage
|
||||||
.desired_counts
|
.desired_counts
|
||||||
.iter()
|
.iter()
|
||||||
@@ -204,10 +281,8 @@ fn check_and_advance_stage(player: &Player, state: &mut GameState) {
|
|||||||
let current_count = count_units_of_type(player, state, *unit_type);
|
let current_count = count_units_of_type(player, state, *unit_type);
|
||||||
current_count >= desired_count
|
current_count >= desired_count
|
||||||
});
|
});
|
||||||
|
|
||||||
if stage_complete {
|
if stage_complete {
|
||||||
let next_stage_index = state.current_stage_index + 1;
|
let next_stage_index = state.current_stage_index + 1;
|
||||||
|
|
||||||
if next_stage_index < state.build_stages.len() {
|
if next_stage_index < state.build_stages.len() {
|
||||||
println!(
|
println!(
|
||||||
"Stage '{}' complete! Advancing to stage {}",
|
"Stage '{}' complete! Advancing to stage {}",
|
||||||
@@ -221,7 +296,6 @@ fn check_and_advance_stage(player: &Player, state: &mut GameState) {
|
|||||||
pub fn print_debug_build_status(game: &Game, player: &Player, state: &GameState) {
|
pub fn print_debug_build_status(game: &Game, player: &Player, state: &GameState) {
|
||||||
let mut y = 10;
|
let mut y = 10;
|
||||||
let x = 3;
|
let x = 3;
|
||||||
|
|
||||||
if let Some(current_stage) = state.build_stages.get(state.current_stage_index) {
|
if let Some(current_stage) = state.build_stages.get(state.current_stage_index) {
|
||||||
let next_build = get_next_thing_to_build(game, player, state);
|
let next_build = get_next_thing_to_build(game, player, state);
|
||||||
let next_build_str = if let Some(unit_type) = next_build {
|
let next_build_str = if let Some(unit_type) = next_build {
|
||||||
@@ -238,7 +312,6 @@ pub fn print_debug_build_status(game: &Game, player: &Player, state: &GameState)
|
|||||||
};
|
};
|
||||||
game.draw_text_screen((x, y), &next_build_str);
|
game.draw_text_screen((x, y), &next_build_str);
|
||||||
y += 10;
|
y += 10;
|
||||||
|
|
||||||
if let Some(last_entry) = state.unit_build_history.last() {
|
if let Some(last_entry) = state.unit_build_history.last() {
|
||||||
let unit_name = if let Some(unit_type) = last_entry.unit_type {
|
let unit_name = if let Some(unit_type) = last_entry.unit_type {
|
||||||
unit_type.name()
|
unit_type.name()
|
||||||
@@ -252,10 +325,8 @@ pub fn print_debug_build_status(game: &Game, player: &Player, state: &GameState)
|
|||||||
game.draw_text_screen((x, y), "Last Built: None");
|
game.draw_text_screen((x, y), "Last Built: None");
|
||||||
}
|
}
|
||||||
y += 10;
|
y += 10;
|
||||||
|
|
||||||
game.draw_text_screen((x, y), "Stage Progress:");
|
game.draw_text_screen((x, y), "Stage Progress:");
|
||||||
y += 10;
|
y += 10;
|
||||||
|
|
||||||
for (unit_type, &desired_count) in ¤t_stage.desired_counts {
|
for (unit_type, &desired_count) in ¤t_stage.desired_counts {
|
||||||
let current_count = count_units_of_type(player, state, *unit_type);
|
let current_count = count_units_of_type(player, state, *unit_type);
|
||||||
game.draw_text_screen(
|
game.draw_text_screen(
|
||||||
|
|||||||
@@ -1,122 +1,71 @@
|
|||||||
use rsbwapi::{Game, Order, Player, Unit};
|
use rsbwapi::{Game, Player, Unit};
|
||||||
|
|
||||||
use crate::state::game_state::{GameState, IntendedCommand};
|
use crate::state::game_state::GameState;
|
||||||
|
|
||||||
pub fn assign_idle_workers_to_minerals(game: &Game, player: &Player, state: &mut GameState) {
|
pub fn assign_idle_workers_to_minerals(game: &Game, player: &Player, state: &mut GameState) {
|
||||||
let all_units = player.get_units();
|
let all_units = player.get_units();
|
||||||
let workers: Vec<Unit> = all_units
|
let workers: Vec<Unit> = all_units
|
||||||
.iter()
|
.iter()
|
||||||
.filter(|u| u.get_type().is_worker() && u.is_completed())
|
.filter(|u| {
|
||||||
|
// Worker must be a completed worker unit
|
||||||
|
u.get_type().is_worker() && u.is_completed()
|
||||||
|
})
|
||||||
.cloned()
|
.cloned()
|
||||||
.collect();
|
.collect();
|
||||||
|
|
||||||
// First, clean up workers that finished building
|
// Assign idle workers that are not already assigned in the build history
|
||||||
reassign_finished_builders(game, &workers, state);
|
|
||||||
|
|
||||||
// Then assign idle workers to mining
|
|
||||||
for worker in workers {
|
for worker in workers {
|
||||||
assign_worker_to_mineral(game, &worker, state);
|
// Skip if this worker is already recorded as assigned in any ongoing build history entry
|
||||||
}
|
let already_assigned = state.unit_build_history.iter().any(|entry| {
|
||||||
}
|
entry.assigned_unit_id == Some(worker.get_id())
|
||||||
|
&& entry.unit_type.map(|ut| ut.is_building()).unwrap_or(false)
|
||||||
fn reassign_finished_builders(_game: &Game, workers: &[Unit], state: &mut GameState) {
|
});
|
||||||
for worker in workers {
|
if already_assigned {
|
||||||
let worker_id = worker.get_id();
|
continue;
|
||||||
|
|
||||||
if let Some(cmd) = state.intended_commands.get(&worker_id) {
|
|
||||||
// For building commands, only remove if the worker was constructing and now is not
|
|
||||||
// This prevents premature removal when the worker is still moving to the build site
|
|
||||||
if cmd.order == Order::PlaceBuilding {
|
|
||||||
// Worker finished if it WAS constructing but no longer is and is idle
|
|
||||||
// We check the actual order to see if it's moved on from building
|
|
||||||
let current_order = worker.get_order();
|
|
||||||
if worker.is_idle() && current_order != Order::PlaceBuilding && current_order != Order::ConstructingBuilding {
|
|
||||||
println!("Worker {} finished building, reassigning to minerals", worker_id);
|
|
||||||
state.intended_commands.remove(&worker_id);
|
|
||||||
}
|
|
||||||
} else if cmd.order == Order::Train && worker.is_idle() && !worker.is_training() {
|
|
||||||
// For training, the original logic is fine
|
|
||||||
state.intended_commands.remove(&worker_id);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
assign_worker_to_mineral(game, &worker, state);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fn assign_worker_to_mineral(game: &Game, worker: &Unit, state: &mut GameState) {
|
fn assign_worker_to_mineral(game: &Game, worker: &Unit, state: &mut GameState) {
|
||||||
let worker_id = worker.get_id();
|
let worker_id = worker.get_id();
|
||||||
|
|
||||||
// Don't reassign workers that have a non-mining intended command
|
// Skip if the worker is currently assigned to an in‑progress building construction.
|
||||||
if let Some(cmd) = state.intended_commands.get(&worker_id) {
|
let has_in_progress_build = state.unit_build_history.iter().any(|entry| {
|
||||||
if cmd.order != Order::MiningMinerals {
|
entry.assigned_unit_id == Some(worker_id)
|
||||||
return;
|
&& entry.unit_type.map(|ut| ut.is_building()).unwrap_or(false)
|
||||||
}
|
});
|
||||||
}
|
if has_in_progress_build {
|
||||||
|
|
||||||
// Only assign idle workers
|
|
||||||
if !worker.is_idle() {
|
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
if worker.is_gathering_minerals() || worker.is_gathering_gas() {
|
// Worker must be idle and not already gathering resources.
|
||||||
|
if !worker.is_idle() || worker.is_gathering_minerals() || worker.is_gathering_gas() {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Find a mineral patch to assign.
|
||||||
let Some(mineral) = find_available_mineral(game, worker, state) else {
|
let Some(mineral) = find_available_mineral(game, worker, state) else {
|
||||||
return;
|
return;
|
||||||
};
|
};
|
||||||
|
|
||||||
let intended_cmd = IntendedCommand {
|
// Assign worker to gather minerals (ignore intended command tracking).
|
||||||
order: Order::MiningMinerals,
|
|
||||||
target_position: None,
|
|
||||||
target_unit: Some(mineral.clone()),
|
|
||||||
};
|
|
||||||
|
|
||||||
state.intended_commands.insert(worker_id, intended_cmd);
|
|
||||||
|
|
||||||
println!(
|
|
||||||
"Worker {} current order: {:?}, assigning to mine from mineral at {:?}",
|
|
||||||
worker_id,
|
|
||||||
worker.get_order(),
|
|
||||||
mineral.get_position()
|
|
||||||
);
|
|
||||||
|
|
||||||
if worker.gather(&mineral).is_ok() {
|
if worker.gather(&mineral).is_ok() {
|
||||||
println!(
|
println!("Assigned worker {} to mine from mineral", worker_id,);
|
||||||
"Assigned worker {} to mine from mineral at {:?}",
|
|
||||||
worker_id,
|
|
||||||
mineral.get_position()
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fn find_available_mineral(game: &Game, worker: &Unit, state: &GameState) -> Option<Unit> {
|
fn find_available_mineral(game: &Game, worker: &Unit, _state: &GameState) -> Option<Unit> {
|
||||||
let worker_pos = worker.get_position();
|
let worker_pos = worker.get_position();
|
||||||
let minerals = game.get_static_minerals();
|
let minerals = game.get_static_minerals();
|
||||||
let mut mineral_list: Vec<Unit> = minerals.iter().filter(|m| m.exists()).cloned().collect();
|
let mut mineral_list: Vec<Unit> = minerals.iter().filter(|m| m.exists()).cloned().collect();
|
||||||
|
|
||||||
|
// Sort minerals by distance to the worker.
|
||||||
mineral_list.sort_by_key(|m| {
|
mineral_list.sort_by_key(|m| {
|
||||||
let pos = m.get_position();
|
let pos = m.get_position();
|
||||||
((pos.x - worker_pos.x).pow(2) + (pos.y - worker_pos.y).pow(2)) as i32
|
((pos.x - worker_pos.x).pow(2) + (pos.y - worker_pos.y).pow(2)) as i32
|
||||||
});
|
});
|
||||||
|
|
||||||
for mineral in mineral_list.iter() {
|
// Return the closest mineral, ignoring any intended command tracking.
|
||||||
let mineral_id: usize = mineral.get_id();
|
|
||||||
|
|
||||||
let worker_count = state
|
|
||||||
.intended_commands
|
|
||||||
.values()
|
|
||||||
.filter(|cmd| {
|
|
||||||
if let Some(target) = &cmd.target_unit {
|
|
||||||
target.get_id() == mineral_id
|
|
||||||
} else {
|
|
||||||
false
|
|
||||||
}
|
|
||||||
})
|
|
||||||
.count();
|
|
||||||
|
|
||||||
if worker_count < 2 {
|
|
||||||
return Some(mineral.clone());
|
|
||||||
}
|
|
||||||
}
|
|
||||||
mineral_list.first().cloned()
|
mineral_list.first().cloned()
|
||||||
}
|
}
|
||||||
|
|||||||
173
protossbot/src/web_server.rs
Normal file
173
protossbot/src/web_server.rs
Normal file
@@ -0,0 +1,173 @@
|
|||||||
|
use axum::{
|
||||||
|
extract::State,
|
||||||
|
http::StatusCode,
|
||||||
|
response::{IntoResponse, Response},
|
||||||
|
routing::{get, post},
|
||||||
|
Json, Router,
|
||||||
|
};
|
||||||
|
use serde::{Deserialize, Serialize};
|
||||||
|
use std::collections::HashMap;
|
||||||
|
use std::sync::{Arc, Mutex};
|
||||||
|
use tower_http::{cors::CorsLayer, services::ServeDir};
|
||||||
|
|
||||||
|
#[derive(Clone)]
|
||||||
|
pub struct SharedGameSpeed {
|
||||||
|
speed: Arc<Mutex<i32>>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl SharedGameSpeed {
|
||||||
|
pub fn new(initial_speed: i32) -> Self {
|
||||||
|
Self {
|
||||||
|
speed: Arc::new(Mutex::new(initial_speed)),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn get(&self) -> i32 {
|
||||||
|
*self.speed.lock().unwrap()
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn set(&self, speed: i32) {
|
||||||
|
*self.speed.lock().unwrap() = speed;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone, Default)]
|
||||||
|
pub struct BuildStatusData {
|
||||||
|
pub stage_name: String,
|
||||||
|
pub stage_index: usize,
|
||||||
|
pub item_status: HashMap<String, String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone)]
|
||||||
|
pub struct SharedBuildStatus {
|
||||||
|
data: Arc<Mutex<BuildStatusData>>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl SharedBuildStatus {
|
||||||
|
pub fn new() -> Self {
|
||||||
|
Self {
|
||||||
|
data: Arc::new(Mutex::new(BuildStatusData::default())),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn update(
|
||||||
|
&self,
|
||||||
|
stage_name: String,
|
||||||
|
stage_index: usize,
|
||||||
|
item_status: HashMap<String, String>,
|
||||||
|
) {
|
||||||
|
let mut data = self.data.lock().unwrap();
|
||||||
|
data.stage_name = stage_name;
|
||||||
|
data.stage_index = stage_index;
|
||||||
|
data.item_status = item_status;
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn get(&self) -> BuildStatusData {
|
||||||
|
self.data.lock().unwrap().clone()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone)]
|
||||||
|
struct AppState {
|
||||||
|
game_speed: SharedGameSpeed,
|
||||||
|
build_status: SharedBuildStatus,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Serialize, Deserialize)]
|
||||||
|
pub struct GameSpeedResponse {
|
||||||
|
pub speed: i32,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Serialize, Deserialize)]
|
||||||
|
pub struct GameSpeedRequest {
|
||||||
|
pub speed: i32,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Serialize, Deserialize)]
|
||||||
|
pub struct BuildStatusResponse {
|
||||||
|
pub stage_name: String,
|
||||||
|
pub stage_index: usize,
|
||||||
|
pub items: Vec<BuildItemStatusInfo>,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Serialize, Deserialize)]
|
||||||
|
pub struct BuildItemStatusInfo {
|
||||||
|
pub unit_name: String,
|
||||||
|
pub status: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn get_game_speed(State(app_state): State<AppState>) -> Response {
|
||||||
|
let speed = app_state.game_speed.get();
|
||||||
|
(StatusCode::OK, Json(GameSpeedResponse { speed })).into_response()
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn set_game_speed(
|
||||||
|
State(app_state): State<AppState>,
|
||||||
|
Json(payload): Json<GameSpeedRequest>,
|
||||||
|
) -> Response {
|
||||||
|
if payload.speed < -1 || payload.speed > 1000 {
|
||||||
|
return (
|
||||||
|
StatusCode::BAD_REQUEST,
|
||||||
|
Json(GameSpeedResponse { speed: 0 }),
|
||||||
|
)
|
||||||
|
.into_response();
|
||||||
|
}
|
||||||
|
|
||||||
|
app_state.game_speed.set(payload.speed);
|
||||||
|
|
||||||
|
(
|
||||||
|
StatusCode::OK,
|
||||||
|
Json(GameSpeedResponse {
|
||||||
|
speed: payload.speed,
|
||||||
|
}),
|
||||||
|
)
|
||||||
|
.into_response()
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn get_build_status(State(app_state): State<AppState>) -> Response {
|
||||||
|
let data = app_state.build_status.get();
|
||||||
|
|
||||||
|
let items: Vec<BuildItemStatusInfo> = data
|
||||||
|
.item_status
|
||||||
|
.iter()
|
||||||
|
.map(|(unit_name, status)| BuildItemStatusInfo {
|
||||||
|
unit_name: unit_name.clone(),
|
||||||
|
status: status.clone(),
|
||||||
|
})
|
||||||
|
.collect();
|
||||||
|
|
||||||
|
let response = BuildStatusResponse {
|
||||||
|
stage_name: data.stage_name,
|
||||||
|
stage_index: data.stage_index,
|
||||||
|
items,
|
||||||
|
};
|
||||||
|
|
||||||
|
(StatusCode::OK, Json(response)).into_response()
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn start_web_server(shared_speed: SharedGameSpeed, build_status: SharedBuildStatus) {
|
||||||
|
let static_dir = std::env::current_dir().unwrap().join("static");
|
||||||
|
|
||||||
|
let cors = CorsLayer::very_permissive();
|
||||||
|
|
||||||
|
let app_state = AppState {
|
||||||
|
game_speed: shared_speed,
|
||||||
|
build_status,
|
||||||
|
};
|
||||||
|
|
||||||
|
let app = Router::new()
|
||||||
|
.route("/api/speed", get(get_game_speed))
|
||||||
|
.route("/api/speed", post(set_game_speed))
|
||||||
|
.route("/api/build-status", get(get_build_status))
|
||||||
|
.layer(cors)
|
||||||
|
.fallback_service(ServeDir::new(static_dir))
|
||||||
|
.with_state(app_state);
|
||||||
|
|
||||||
|
let addr = "127.0.0.1:3333";
|
||||||
|
|
||||||
|
let listener = tokio::net::TcpListener::bind(addr).await.unwrap();
|
||||||
|
|
||||||
|
println!("Web server running at http://{}", addr);
|
||||||
|
|
||||||
|
axum::serve(listener, app).await.unwrap();
|
||||||
|
}
|
||||||
353
protossbot/static/index.html
Normal file
353
protossbot/static/index.html
Normal file
@@ -0,0 +1,353 @@
|
|||||||
|
<!doctype html>
|
||||||
|
<html lang="en">
|
||||||
|
<head>
|
||||||
|
<meta charset="UTF-8" />
|
||||||
|
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||||
|
<title>Protoss Bot - Game Speed Control</title>
|
||||||
|
<style>
|
||||||
|
* {
|
||||||
|
margin: 0;
|
||||||
|
padding: 0;
|
||||||
|
box-sizing: border-box;
|
||||||
|
}
|
||||||
|
|
||||||
|
body {
|
||||||
|
font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
|
||||||
|
background: linear-gradient(135deg, #1a1a1a 0%, #2d2d2d 100%);
|
||||||
|
min-height: 100vh;
|
||||||
|
display: flex;
|
||||||
|
justify-content: center;
|
||||||
|
align-items: center;
|
||||||
|
padding: 20px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.container {
|
||||||
|
background: #1e1e1e;
|
||||||
|
border: 2px solid #d4af37;
|
||||||
|
border-radius: 20px;
|
||||||
|
box-shadow: 0 20px 60px rgba(212, 175, 55, 0.3);
|
||||||
|
padding: 40px;
|
||||||
|
max-width: 500px;
|
||||||
|
width: 100%;
|
||||||
|
}
|
||||||
|
|
||||||
|
.control-group {
|
||||||
|
margin-bottom: 30px;
|
||||||
|
}
|
||||||
|
|
||||||
|
label {
|
||||||
|
display: block;
|
||||||
|
color: #d4af37;
|
||||||
|
font-weight: 600;
|
||||||
|
margin-bottom: 10px;
|
||||||
|
font-size: 14px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.speed-display {
|
||||||
|
text-align: center;
|
||||||
|
margin-bottom: 20px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.speed-value {
|
||||||
|
font-size: 48px;
|
||||||
|
font-weight: bold;
|
||||||
|
color: #d4af37;
|
||||||
|
display: block;
|
||||||
|
transition: color 0.3s;
|
||||||
|
}
|
||||||
|
.speed-fast {
|
||||||
|
color: #4ade80; /* green */
|
||||||
|
}
|
||||||
|
.speed-slow {
|
||||||
|
color: #f87171; /* red */
|
||||||
|
}
|
||||||
|
|
||||||
|
.speed-label {
|
||||||
|
display: none; /* hide label for compact view */
|
||||||
|
}
|
||||||
|
|
||||||
|
.preset-buttons {
|
||||||
|
display: grid;
|
||||||
|
grid-template-columns: repeat(4, 1fr);
|
||||||
|
gap: 10px;
|
||||||
|
margin-bottom: 20px;
|
||||||
|
}
|
||||||
|
|
||||||
|
button {
|
||||||
|
padding: 20px 12px;
|
||||||
|
border: 2px solid #d4af37;
|
||||||
|
border-radius: 8px;
|
||||||
|
font-size: 18px;
|
||||||
|
font-weight: 600;
|
||||||
|
cursor: pointer;
|
||||||
|
transition: all 0.2s ease;
|
||||||
|
background: #2d2d2d;
|
||||||
|
color: #d4af37;
|
||||||
|
}
|
||||||
|
button.active {
|
||||||
|
background: #d4af37;
|
||||||
|
color: #1e1e1e;
|
||||||
|
}
|
||||||
|
|
||||||
|
button small {
|
||||||
|
display: block;
|
||||||
|
font-size: 11px;
|
||||||
|
font-weight: normal;
|
||||||
|
margin-top: 4px;
|
||||||
|
opacity: 0.7;
|
||||||
|
}
|
||||||
|
|
||||||
|
button:hover {
|
||||||
|
background: #d4af37;
|
||||||
|
color: #1e1e1e;
|
||||||
|
transform: translateY(-2px);
|
||||||
|
box-shadow: 0 4px 12px rgba(212, 175, 55, 0.4);
|
||||||
|
}
|
||||||
|
|
||||||
|
button:active {
|
||||||
|
transform: translateY(0);
|
||||||
|
}
|
||||||
|
|
||||||
|
.status {
|
||||||
|
padding: 12px;
|
||||||
|
border-radius: 8px;
|
||||||
|
text-align: center;
|
||||||
|
font-size: 13px;
|
||||||
|
margin-top: 20px;
|
||||||
|
opacity: 0;
|
||||||
|
transition: opacity 0.3s ease;
|
||||||
|
}
|
||||||
|
|
||||||
|
.status.visible {
|
||||||
|
opacity: 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
.status.success {
|
||||||
|
background: rgba(34, 197, 94, 0.2);
|
||||||
|
color: #4ade80;
|
||||||
|
border: 1px solid #22c55e;
|
||||||
|
}
|
||||||
|
|
||||||
|
.status.error {
|
||||||
|
background: rgba(239, 68, 68, 0.2);
|
||||||
|
color: #f87171;
|
||||||
|
border: 1px solid #ef4444;
|
||||||
|
}
|
||||||
|
|
||||||
|
.build-status-section {
|
||||||
|
margin-top: 30px;
|
||||||
|
padding-top: 30px;
|
||||||
|
border-top: 2px solid #333;
|
||||||
|
}
|
||||||
|
|
||||||
|
.build-status-section h2 {
|
||||||
|
color: #d4af37;
|
||||||
|
font-size: 20px;
|
||||||
|
margin-bottom: 20px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.stage-info {
|
||||||
|
background: #2d2d2d;
|
||||||
|
padding: 15px;
|
||||||
|
border-radius: 8px;
|
||||||
|
margin-bottom: 15px;
|
||||||
|
border: 1px solid #444;
|
||||||
|
}
|
||||||
|
|
||||||
|
.stage-name {
|
||||||
|
color: #d4af37;
|
||||||
|
font-size: 16px;
|
||||||
|
font-weight: bold;
|
||||||
|
margin-bottom: 10px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.build-items {
|
||||||
|
list-style: none;
|
||||||
|
}
|
||||||
|
|
||||||
|
.build-item {
|
||||||
|
padding: 8px 10px;
|
||||||
|
margin: 5px 0;
|
||||||
|
background: #1e1e1e;
|
||||||
|
border-radius: 4px;
|
||||||
|
border-left: 3px solid #d4af37;
|
||||||
|
display: flex;
|
||||||
|
justify-content: space-between;
|
||||||
|
align-items: center;
|
||||||
|
}
|
||||||
|
|
||||||
|
.build-item.ready {
|
||||||
|
border-left-color: #22c55e;
|
||||||
|
}
|
||||||
|
|
||||||
|
.build-item.complete {
|
||||||
|
border-left-color: #3b82f6;
|
||||||
|
opacity: 0.7;
|
||||||
|
}
|
||||||
|
|
||||||
|
.build-item.waiting {
|
||||||
|
border-left-color: #f59e0b;
|
||||||
|
}
|
||||||
|
|
||||||
|
.unit-name {
|
||||||
|
color: #d4af37;
|
||||||
|
font-weight: 600;
|
||||||
|
}
|
||||||
|
|
||||||
|
.unit-status {
|
||||||
|
color: #999;
|
||||||
|
font-size: 13px;
|
||||||
|
}
|
||||||
|
</style>
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
<div class="container">
|
||||||
|
|
||||||
|
|
||||||
|
<div class="control-group">
|
||||||
|
<div class="preset-buttons">
|
||||||
|
<button data-speed="42" onclick="setSpeed(42)">
|
||||||
|
42<br /><small>Slowest</small>
|
||||||
|
</button>
|
||||||
|
<button data-speed="1" onclick="setSpeed(1)">
|
||||||
|
1<br /><small>Fast</small>
|
||||||
|
</button>
|
||||||
|
<button data-speed="0" onclick="setSpeed(0)">
|
||||||
|
0<br /><small>Fastest</small>
|
||||||
|
</button>
|
||||||
|
<button data-speed="-1" onclick="setSpeed(-1)">
|
||||||
|
-1<br /><small>Max</small>
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div id="status" class="status"></div>
|
||||||
|
|
||||||
|
<div class="build-status-section">
|
||||||
|
<div class="stage-info">
|
||||||
|
<div class="stage-name" id="stageName">Loading...</div>
|
||||||
|
<ul class="build-items" id="buildItems">
|
||||||
|
<li class="build-item">Connecting to bot...</li>
|
||||||
|
</ul>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<script id="game-speed-script">
|
||||||
|
const presetButtons = document.querySelectorAll('.preset-buttons button');
|
||||||
|
const statusDiv = document.getElementById('status');
|
||||||
|
|
||||||
|
function highlightButton(speed) {
|
||||||
|
presetButtons.forEach(btn => {
|
||||||
|
if (Number(btn.dataset.speed) === speed) {
|
||||||
|
btn.classList.add('active');
|
||||||
|
} else {
|
||||||
|
btn.classList.remove('active');
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
async function fetchCurrentSpeed() {
|
||||||
|
const response = await fetch('http://127.0.0.1:3333/api/speed');
|
||||||
|
if (response.ok) {
|
||||||
|
const data = await response.json();
|
||||||
|
highlightButton(data.speed);
|
||||||
|
// Clear any previous error message
|
||||||
|
statusDiv.textContent = '';
|
||||||
|
statusDiv.className = 'status';
|
||||||
|
} else {
|
||||||
|
showStatus('Unable to connect to bot', 'error');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function setSpeed(speed) {
|
||||||
|
const response = await fetch('http://127.0.0.1:3333/api/speed', {
|
||||||
|
method: 'POST',
|
||||||
|
headers: {
|
||||||
|
'Content-Type': 'application/json',
|
||||||
|
},
|
||||||
|
body: JSON.stringify({ speed: speed }),
|
||||||
|
});
|
||||||
|
|
||||||
|
if (response.ok) {
|
||||||
|
const data = await response.json();
|
||||||
|
highlightButton(data.speed);
|
||||||
|
// Clear any previous status message on success
|
||||||
|
statusDiv.textContent = '';
|
||||||
|
statusDiv.className = 'status';
|
||||||
|
} else {
|
||||||
|
showStatus('Failed to update speed', 'error');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
function showStatus(message, type) {
|
||||||
|
statusDiv.textContent = message;
|
||||||
|
statusDiv.className = `status ${type} visible`;
|
||||||
|
setTimeout(() => {
|
||||||
|
statusDiv.classList.remove("visible");
|
||||||
|
}, 3000);
|
||||||
|
}
|
||||||
|
|
||||||
|
fetchCurrentSpeed();
|
||||||
|
setInterval(fetchCurrentSpeed, 1000);
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<script id="build-status-script">
|
||||||
|
const stageNameEl = document.getElementById("stageName");
|
||||||
|
const buildItemsEl = document.getElementById("buildItems");
|
||||||
|
|
||||||
|
async function fetchBuildStatus() {
|
||||||
|
try {
|
||||||
|
const response = await fetch(
|
||||||
|
"http://127.0.0.1:3333/api/build-status",
|
||||||
|
);
|
||||||
|
if (response.ok) {
|
||||||
|
const data = await response.json();
|
||||||
|
updateBuildStatus(data);
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
console.error("Failed to fetch build status:", error);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function updateBuildStatus(data) {
|
||||||
|
stageNameEl.textContent = `Stage ${data.stage_index + 1}: ${data.stage_name}`;
|
||||||
|
|
||||||
|
if (data.items.length === 0) {
|
||||||
|
buildItemsEl.innerHTML =
|
||||||
|
'<li class="build-item">No build items in current stage</li>';
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Sort items alphabetically by unit name
|
||||||
|
const sortedItems = [...data.items].sort((a, b) =>
|
||||||
|
a.unit_name.localeCompare(b.unit_name),
|
||||||
|
);
|
||||||
|
|
||||||
|
buildItemsEl.innerHTML = sortedItems
|
||||||
|
.map((item) => {
|
||||||
|
let itemClass = "build-item";
|
||||||
|
if (item.status.includes("Complete")) {
|
||||||
|
itemClass += " complete";
|
||||||
|
} else if (item.status.includes("Ready to build")) {
|
||||||
|
itemClass += " ready";
|
||||||
|
} else {
|
||||||
|
itemClass += " waiting";
|
||||||
|
}
|
||||||
|
|
||||||
|
return `
|
||||||
|
<li class="${itemClass}">
|
||||||
|
<span class="unit-name">${item.unit_name}</span>
|
||||||
|
<span class="unit-status">${item.status}</span>
|
||||||
|
</li>
|
||||||
|
`;
|
||||||
|
})
|
||||||
|
.join("");
|
||||||
|
}
|
||||||
|
|
||||||
|
fetchBuildStatus();
|
||||||
|
setInterval(fetchBuildStatus, 1000);
|
||||||
|
</script>
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
@@ -1,20 +0,0 @@
|
|||||||
[package]
|
|
||||||
name = "protoss-bot-web"
|
|
||||||
version = "0.1.0"
|
|
||||||
edition = "2021"
|
|
||||||
|
|
||||||
[dependencies]
|
|
||||||
leptos = { version = "0.6", features = ["csr"] }
|
|
||||||
leptos_axum = { version = "0.6" }
|
|
||||||
leptos_meta = { version = "0.6" }
|
|
||||||
leptos_router = { version = "0.6" }
|
|
||||||
axum = "0.7"
|
|
||||||
tokio = { version = "1", features = ["full"] }
|
|
||||||
tower = "0.4"
|
|
||||||
tower-http = { version = "0.5", features = ["fs"] }
|
|
||||||
serde = { version = "1", features = ["derive"] }
|
|
||||||
serde_json = "1"
|
|
||||||
lazy_static = "1.4"
|
|
||||||
|
|
||||||
[lib]
|
|
||||||
crate-type = ["cdylib", "rlib"]
|
|
||||||
@@ -1,20 +0,0 @@
|
|||||||
# Leptos configuration file
|
|
||||||
[package]
|
|
||||||
name = "protoss-bot-web"
|
|
||||||
version = "0.1.0"
|
|
||||||
|
|
||||||
[leptos]
|
|
||||||
output-name = "protoss-bot-web"
|
|
||||||
site-root = "target/site"
|
|
||||||
site-pkg-dir = "pkg"
|
|
||||||
style-file = "style/main.css"
|
|
||||||
assets-dir = "public"
|
|
||||||
site-addr = "127.0.0.1:3000"
|
|
||||||
reload-port = 3001
|
|
||||||
browserquery = "defaults"
|
|
||||||
watch = false
|
|
||||||
env = "DEV"
|
|
||||||
bin-features = ["ssr"]
|
|
||||||
bin-default-features = false
|
|
||||||
lib-features = ["hydrate"]
|
|
||||||
lib-default-features = false
|
|
||||||
@@ -1,32 +0,0 @@
|
|||||||
# Protoss Bot Web Control Panel
|
|
||||||
|
|
||||||
A Leptos web interface to control the Protoss bot in real-time.
|
|
||||||
|
|
||||||
## Setup
|
|
||||||
|
|
||||||
1. Install cargo-leptos:
|
|
||||||
```bash
|
|
||||||
cargo install cargo-leptos
|
|
||||||
```
|
|
||||||
|
|
||||||
2. Run the development server:
|
|
||||||
```bash
|
|
||||||
cd web
|
|
||||||
cargo leptos watch
|
|
||||||
```
|
|
||||||
|
|
||||||
3. Open your browser to `http://localhost:3000`
|
|
||||||
|
|
||||||
## Features
|
|
||||||
|
|
||||||
- **Game Speed Control**: Set the desired game speed with convenient buttons
|
|
||||||
- Real-time updates via server functions
|
|
||||||
- Dark theme matching StarCraft aesthetics
|
|
||||||
|
|
||||||
## Integration with Bot
|
|
||||||
|
|
||||||
The web server exposes a global `GAME_SPEED` variable that can be read by the bot. To integrate:
|
|
||||||
|
|
||||||
1. Add the web crate as a dependency in your bot's `Cargo.toml`
|
|
||||||
2. Read the speed value: `protoss_bot_web::GAME_SPEED.read().unwrap()`
|
|
||||||
3. Apply it to the game using BWAPI's setLocalSpeed() or setFrameSkip()
|
|
||||||
@@ -1,66 +0,0 @@
|
|||||||
use leptos::*;
|
|
||||||
use leptos_meta::*;
|
|
||||||
use leptos_router::*;
|
|
||||||
use std::sync::{Arc, RwLock};
|
|
||||||
|
|
||||||
// Global static for game speed (shared with the bot)
|
|
||||||
lazy_static::lazy_static! {
|
|
||||||
pub static ref GAME_SPEED: Arc<RwLock<i32>> = Arc::new(RwLock::new(20));
|
|
||||||
}
|
|
||||||
|
|
||||||
#[component]
|
|
||||||
pub fn App() -> impl IntoView {
|
|
||||||
provide_meta_context();
|
|
||||||
|
|
||||||
view! {
|
|
||||||
<Stylesheet id="leptos" href="/pkg/protoss-bot-web.css"/>
|
|
||||||
<Title text="Protoss Bot Control"/>
|
|
||||||
<Router>
|
|
||||||
<main>
|
|
||||||
<Routes>
|
|
||||||
<Route path="" view=HomePage/>
|
|
||||||
</Routes>
|
|
||||||
</main>
|
|
||||||
</Router>
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[component]
|
|
||||||
fn HomePage() -> impl IntoView {
|
|
||||||
let (game_speed, set_game_speed) = create_signal(20);
|
|
||||||
|
|
||||||
let set_speed = move |speed: i32| {
|
|
||||||
set_game_speed.set(speed);
|
|
||||||
spawn_local(async move {
|
|
||||||
let _ = set_game_speed_server(speed).await;
|
|
||||||
});
|
|
||||||
};
|
|
||||||
|
|
||||||
view! {
|
|
||||||
<div class="container">
|
|
||||||
<h1>"Protoss Bot Control Panel"</h1>
|
|
||||||
|
|
||||||
<div class="speed-control">
|
|
||||||
<h2>"Game Speed Control"</h2>
|
|
||||||
<p>"Current Speed: " {game_speed}</p>
|
|
||||||
|
|
||||||
<div class="button-group">
|
|
||||||
<button on:click=move |_| set_speed(0)>"Slowest (0)"</button>
|
|
||||||
<button on:click=move |_| set_speed(10)>"Slower (10)"</button>
|
|
||||||
<button on:click=move |_| set_speed(20)>"Normal (20)"</button>
|
|
||||||
<button on:click=move |_| set_speed(30)>"Fast (30)"</button>
|
|
||||||
<button on:click=move |_| set_speed(42)>"Fastest (42)"</button>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[server(SetGameSpeed, "/api")]
|
|
||||||
pub async fn set_game_speed_server(speed: i32) -> Result<(), ServerFnError> {
|
|
||||||
if let Ok(mut game_speed) = GAME_SPEED.write() {
|
|
||||||
*game_speed = speed;
|
|
||||||
println!("Game speed set to: {}", speed);
|
|
||||||
}
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
@@ -1,27 +0,0 @@
|
|||||||
use axum::{
|
|
||||||
routing::get,
|
|
||||||
Router,
|
|
||||||
};
|
|
||||||
use leptos::*;
|
|
||||||
use leptos_axum::{generate_route_list, LeptosRoutes};
|
|
||||||
use protoss_bot_web::App;
|
|
||||||
use tower_http::services::ServeDir;
|
|
||||||
|
|
||||||
#[tokio::main]
|
|
||||||
async fn main() {
|
|
||||||
let conf = get_configuration(None).await.unwrap();
|
|
||||||
let leptos_options = conf.leptos_options;
|
|
||||||
let addr = leptos_options.site_addr;
|
|
||||||
let routes = generate_route_list(App);
|
|
||||||
|
|
||||||
let app = Router::new()
|
|
||||||
.leptos_routes(&leptos_options, routes, App)
|
|
||||||
.fallback(leptos_axum::file_and_error_handler(App))
|
|
||||||
.with_state(leptos_options);
|
|
||||||
|
|
||||||
println!("Listening on http://{}", &addr);
|
|
||||||
let listener = tokio::net::TcpListener::bind(&addr).await.unwrap();
|
|
||||||
axum::serve(listener, app.into_make_service())
|
|
||||||
.await
|
|
||||||
.unwrap();
|
|
||||||
}
|
|
||||||
@@ -1,62 +0,0 @@
|
|||||||
body {
|
|
||||||
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, sans-serif;
|
|
||||||
margin: 0;
|
|
||||||
padding: 20px;
|
|
||||||
background-color: #1a1a1a;
|
|
||||||
color: #ffffff;
|
|
||||||
}
|
|
||||||
|
|
||||||
.container {
|
|
||||||
max-width: 800px;
|
|
||||||
margin: 0 auto;
|
|
||||||
padding: 20px;
|
|
||||||
}
|
|
||||||
|
|
||||||
h1 {
|
|
||||||
color: #4a9eff;
|
|
||||||
margin-bottom: 30px;
|
|
||||||
}
|
|
||||||
|
|
||||||
h2 {
|
|
||||||
color: #ffffff;
|
|
||||||
margin-bottom: 15px;
|
|
||||||
}
|
|
||||||
|
|
||||||
.speed-control {
|
|
||||||
background-color: #2a2a2a;
|
|
||||||
padding: 20px;
|
|
||||||
border-radius: 8px;
|
|
||||||
margin-bottom: 20px;
|
|
||||||
}
|
|
||||||
|
|
||||||
.button-group {
|
|
||||||
display: flex;
|
|
||||||
gap: 10px;
|
|
||||||
flex-wrap: wrap;
|
|
||||||
margin-top: 15px;
|
|
||||||
}
|
|
||||||
|
|
||||||
button {
|
|
||||||
background-color: #4a9eff;
|
|
||||||
color: white;
|
|
||||||
border: none;
|
|
||||||
padding: 12px 24px;
|
|
||||||
border-radius: 6px;
|
|
||||||
cursor: pointer;
|
|
||||||
font-size: 14px;
|
|
||||||
font-weight: 500;
|
|
||||||
transition: background-color 0.2s;
|
|
||||||
}
|
|
||||||
|
|
||||||
button:hover {
|
|
||||||
background-color: #357abd;
|
|
||||||
}
|
|
||||||
|
|
||||||
button:active {
|
|
||||||
background-color: #2a5f9a;
|
|
||||||
}
|
|
||||||
|
|
||||||
p {
|
|
||||||
color: #cccccc;
|
|
||||||
margin: 10px 0;
|
|
||||||
}
|
|
||||||
@@ -20,11 +20,6 @@ INSTALL_DIR="$PROJECT_DIR/starcraft"
|
|||||||
|
|
||||||
SC_WIN_PATH="$(winepath -w "$INSTALL_DIR" 2>/dev/null || echo "Z:${INSTALL_DIR}" | sed 's/\//\\\\/g')\\\\"
|
SC_WIN_PATH="$(winepath -w "$INSTALL_DIR" 2>/dev/null || echo "Z:${INSTALL_DIR}" | sed 's/\//\\\\/g')\\\\"
|
||||||
|
|
||||||
# if wine REG QUERY "HKEY_LOCAL_MACHINE\\SOFTWARE\\Blizzard Entertainment\\Starcraft" /v InstallPath >/dev/null 2>&1; then
|
|
||||||
# echo "Registry already configured, skipping..."
|
|
||||||
# exit 0
|
|
||||||
# fi
|
|
||||||
|
|
||||||
echo "Configuring registry..."
|
echo "Configuring registry..."
|
||||||
# Core registry entries
|
# Core registry entries
|
||||||
wine REG ADD "HKEY_LOCAL_MACHINE\\SOFTWARE\\Blizzard Entertainment\\Starcraft" \
|
wine REG ADD "HKEY_LOCAL_MACHINE\\SOFTWARE\\Blizzard Entertainment\\Starcraft" \
|
||||||
|
|||||||
@@ -9,8 +9,8 @@ map: maps/BroodWar/(4)CircuitBreaker.scx
|
|||||||
# map: maps/(2)Boxer.scm
|
# map: maps/(2)Boxer.scm
|
||||||
|
|
||||||
# player_race: Zerg
|
# player_race: Zerg
|
||||||
# player_race: Terran
|
player_race: Terran
|
||||||
player_race: Protoss
|
# player_race: Protoss
|
||||||
# player_race: Random
|
# player_race: Random
|
||||||
|
|
||||||
# enemy_count: 1
|
# enemy_count: 1
|
||||||
|
|||||||
Reference in New Issue
Block a user