Compare commits

..

10 Commits

Author SHA1 Message Date
321e3ebb76 improving, but still cannot pick a building location for non-pylons 2026-01-23 09:21:55 -07:00
c39f95b304 real messages from backend to frontend 2026-01-23 09:10:57 -07:00
30a169ed06 updated lock 2026-01-23 08:59:40 -07:00
6e082c24df got some webserver 2026-01-22 22:33:46 -07:00
28696b2358 rewrite 2026-01-22 22:26:26 -07:00
affbd3f82f mistakes were made 2026-01-22 22:25:56 -07:00
fbcbb8f882 removing bad webserver 2026-01-22 22:25:49 -07:00
eebba4d7bc updates 2026-01-22 21:12:34 -07:00
ce7ce427c6 runs, but not webserver 2026-01-22 17:57:52 -07:00
feda48b0a4 attempts 2026-01-21 22:17:23 -07:00
17 changed files with 749 additions and 321 deletions

1
.gitignore vendored
View File

@@ -56,3 +56,4 @@ result
result-* result-*
.direnv/ .direnv/
.envrc.cache .envrc.cache
target/

12
flake.lock generated
View File

@@ -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": {

View File

@@ -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());
// Check if the created unit is a building
if !unit.get_type().is_building() {
return;
}
let Ok(mut locked_state) = self.game_state.lock() else {
return;
};
build_manager::on_building_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,
}
} }
} }

View File

@@ -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(),
)
});
} }

View File

@@ -1,5 +1,5 @@
use std::collections::HashMap;
use rsbwapi::{Order, Position, Unit, UnitType, UpgradeType}; use rsbwapi::{Order, Position, Unit, UnitType, UpgradeType};
use std::collections::HashMap;
use crate::state::build_stages::BuildStage; use crate::state::build_stages::BuildStage;
@@ -9,9 +9,9 @@ pub struct GameState {
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 {
@@ -20,6 +20,7 @@ impl Default for GameState {
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(),
} }
} }
} }

View File

@@ -6,8 +6,9 @@ pub fn find_build_location(
building_type: UnitType, building_type: UnitType,
max_range: i32, max_range: i32,
) -> Option<TilePosition> { ) -> Option<TilePosition> {
let start_tile = builder.get_tile_position(); let start_tile = builder.get_tile_position();
let map_width = game.map_width();
let map_height = game.map_height();
for distance in 0..max_range { for distance in 0..max_range {
for dx in -distance..=distance { for dx in -distance..=distance {
@@ -21,6 +22,10 @@ pub fn find_build_location(
y: start_tile.y + dy, y: start_tile.y + dy,
}; };
if tile.x < 0 || tile.y < 0 || tile.x >= map_width || tile.y >= map_height {
continue;
}
if is_valid_build_location(game, building_type, tile, builder) { if is_valid_build_location(game, building_type, tile, builder) {
return Some(tile); return Some(tile);
} }
@@ -37,17 +42,7 @@ fn is_valid_build_location(
position: TilePosition, position: TilePosition,
builder: &Unit, builder: &Unit,
) -> bool { ) -> bool {
if !game.can_build_here(builder, position, building_type, false).unwrap_or(false) { game
return false; .can_build_here(builder, position, building_type, false)
} .unwrap_or(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
} }

View File

@@ -1,4 +1,4 @@
use rsbwapi::{Game, Order, Player, UnitType}; use rsbwapi::{Game, Order, Player, Unit, UnitType};
use crate::{ use crate::{
state::game_state::{BuildHistoryEntry, GameState, IntendedCommand}, state::game_state::{BuildHistoryEntry, GameState, IntendedCommand},
@@ -6,16 +6,64 @@ use crate::{
}; };
pub fn on_frame(game: &Game, player: &Player, state: &mut GameState) { pub fn on_frame(game: &Game, player: &Player, state: &mut GameState) {
cleanup_stale_commands(player, state);
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) {
if let Some(entry) = state
.unit_build_history
.iter()
.rev()
.find(|e| e.unit_type == Some(unit.get_type()))
{
if let Some(probe_id) = entry.assigned_unit_id {
// Remove the probe's intended command (PlaceBuilding order)
state.intended_commands.remove(&probe_id);
println!(
"Building {} started. Removed assignment for probe {}",
unit.get_type().name(),
probe_id
);
}
}
}
fn cleanup_stale_commands(player: &Player, state: &mut GameState) {
let unit_ids: Vec<usize> = player.get_units().iter().map(|u| u.get_id()).collect();
state.intended_commands.retain(|unit_id, cmd| {
// Remove if unit no longer exists
if !unit_ids.contains(unit_id) {
return false;
}
// Find the unit
if let Some(unit) = player.get_units().iter().find(|u| u.get_id() == *unit_id) {
// For PlaceBuilding orders, check if unit is actually constructing or idle
if cmd.order == Order::PlaceBuilding {
// Keep command only if unit is moving to build location or constructing
return unit.is_constructing() || unit.get_order() == Order::PlaceBuilding;
}
// For Train orders, check if the building is training
if cmd.order == Order::Train {
return unit.is_training();
}
}
false
});
}
fn try_start_next_build(game: &Game, player: &Player, state: &mut GameState) { fn try_start_next_build(game: &Game, player: &Player, state: &mut GameState) {
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) else { let Some(builder) = find_builder_for_unit(player, unit_type, state) else {
return; return;
}; };
@@ -40,13 +88,72 @@ fn try_start_next_build(game: &Game, player: &Player, state: &mut GameState) {
} }
} }
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 &current_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) { if let Some(pylon) = check_need_more_supply(game, player, state) {
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 &current_stage.desired_counts { for (unit_type, &desired_count) in &current_stage.desired_counts {
@@ -56,27 +163,18 @@ fn get_next_thing_to_build(game: &Game, player: &Player, state: &GameState) -> O
continue; continue;
} }
if !can_afford_unit(player, *unit_type) { let status = status_map.get(&unit_type.name().to_string());
continue; if status.is_some() && status.unwrap().starts_with("Ready to build") {
}
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.push(*unit_type);
} }
}
candidates.into_iter().max_by_key(|unit_type| { candidates
unit_type.mineral_price() + unit_type.gas_price() .into_iter()
}) .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();
@@ -91,8 +189,9 @@ fn check_need_more_supply(game: &Game, player: &Player) -> Option<UnitType> {
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) { if let Some(builder) = find_builder_for_unit(player, pylon_type, state) {
let build_location = build_location_utils::find_build_location(game, &builder, pylon_type, 20); let build_location =
build_location_utils::find_build_location(game, &builder, pylon_type, 25);
if build_location.is_some() { if build_location.is_some() {
return Some(pylon_type); return Some(pylon_type);
} }
@@ -103,23 +202,36 @@ fn check_need_more_supply(game: &Game, player: &Player) -> Option<UnitType> {
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())
&& !state.intended_commands.contains_key(&u.get_id())
}) })
.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,
builder: &rsbwapi::Unit,
unit_type: UnitType,
state: &mut GameState,
) -> bool {
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, builder, unit_type, 25);
if let Some(pos) = build_location { if let Some(pos) = build_location {
println!( println!(
@@ -180,8 +292,6 @@ fn count_units_of_type(player: &Player, _state: &GameState, unit_type: UnitType)
.filter(|u| u.get_type() == unit_type) .filter(|u| u.get_type() == unit_type)
.count() as i32; .count() as i32;
existing existing
} }

View File

@@ -10,49 +10,21 @@ pub fn assign_idle_workers_to_minerals(game: &Game, player: &Player, state: &mut
.cloned() .cloned()
.collect(); .collect();
// First, clean up workers that finished building // Assign idle workers to mining
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); assign_worker_to_mineral(game, &worker, state);
} }
} }
fn reassign_finished_builders(_game: &Game, workers: &[Unit], state: &mut GameState) {
for worker in workers {
let worker_id = worker.get_id();
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);
}
}
}
}
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
if let Some(cmd) = state.intended_commands.get(&worker_id) { if let Some(cmd) = state.intended_commands.get(&worker_id) {
if cmd.order != Order::MiningMinerals { if cmd.order != Order::MiningMinerals {
return; return;
} }
} }
// Only assign idle workers
if !worker.is_idle() { if !worker.is_idle() {
return; return;
} }

View 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();
}

View File

@@ -0,0 +1,345 @@
<!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%;
}
h1 {
color: #d4af37;
margin-bottom: 30px;
font-size: 28px;
text-align: center;
}
.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;
}
.speed-label {
color: #999;
font-size: 12px;
text-transform: uppercase;
letter-spacing: 1px;
}
.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 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">
<h1>⚡ Game Speed Control</h1>
<div class="speed-display">
<span class="speed-value" id="currentSpeed">42</span>
<span class="speed-label">Current Speed</span>
</div>
<div class="control-group">
<label>Select Speed</label>
<div class="preset-buttons">
<button onclick="setSpeed(42)">42<br /><small>Slowest</small></button>
<button onclick="setSpeed(1)">1<br /><small>Fast</small></button>
<button onclick="setSpeed(0)">0<br /><small>Fastest</small></button>
<button onclick="setSpeed(-1)">-1<br /><small>Max</small></button>
</div>
</div>
<div id="status" class="status"></div>
<div class="build-status-section">
<h2>📋 Build Status</h2>
<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 currentSpeedDisplay = document.getElementById("currentSpeed");
const statusDiv = document.getElementById("status");
async function fetchCurrentSpeed() {
try {
const response = await fetch("http://127.0.0.1:3333/api/speed");
if (response.ok) {
const data = await response.json();
updateSpeedDisplay(data.speed);
}
} catch (error) {
showStatus("Unable to connect to bot", "error");
}
}
function updateSpeedDisplay(speed) {
currentSpeedDisplay.textContent = speed;
}
async function setSpeed(speed) {
try {
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();
updateSpeedDisplay(data.speed);
showStatus(`Speed set to ${data.speed}`, "success");
} else {
showStatus("Failed to update speed", "error");
}
} catch (error) {
showStatus("Connection error", "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>

View File

@@ -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"]

View File

@@ -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

View File

@@ -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()

View File

@@ -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(())
}

View File

@@ -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();
}

View File

@@ -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;
}

View File

@@ -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" \