Skip to content

Commit

Permalink
Haulers work.
Browse files Browse the repository at this point in the history
Upgraders work.
Haul queue works.
Bot *may* break.
  • Loading branch information
InfinityDevTech committed May 23, 2024
1 parent 6b46fd4 commit 0416520
Show file tree
Hide file tree
Showing 20 changed files with 566 additions and 377 deletions.
2 changes: 0 additions & 2 deletions javascript/main.js
Original file line number Diff line number Diff line change
Expand Up @@ -76,8 +76,6 @@ function run_loop() {
console.error = console_error
try {

console.log(wasm_module)

if (!EXECUTION_PAUSED) {
wasm_module.loop();
}
Expand Down
4 changes: 2 additions & 2 deletions screeps.toml
Original file line number Diff line number Diff line change
Expand Up @@ -17,9 +17,9 @@ prefix = "ptr"

[copy]
# Windows Desktop
#destination = "C:\\Users\\jwjoh\\AppData\\Local\\Screeps\\scripts\\127_0_0_1___21025"
destination = "C:\\Users\\jwjoh\\AppData\\Local\\Screeps\\scripts\\127_0_0_1___21025"
# Linux Laptop
destination = "/home/jwjoh/.config/Screeps/scripts/127_0_0_1___21025"
#destination = "/home/jwjoh/.config/Screeps/scripts/127_0_0_1___21025"
# Bot arena
#destination = "C:\\Users\\jwjoh\\AppData\\Local\\Screeps\\scripts\\botarena_screepspl_us___21025"

Expand Down
11 changes: 5 additions & 6 deletions src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
use std::{collections::HashMap, str::FromStr};
use std::collections::HashMap;

use log::*;
use screeps::{find, game, prelude::*, RoomName};
use screeps::{find, game, OwnedStructureProperties, StructureProperties};
use wasm_bindgen::prelude::*;

use crate::{memory::ScreepsMemory, room::planning::{self, room::plan_room}, traits::room::RoomExtensions};
Expand Down Expand Up @@ -43,11 +43,9 @@ pub fn game_loop() {
for room in game::rooms().keys() {
let room = game::rooms().get(room).unwrap();

let controller = room.controller().unwrap();

// If the planner says false on the first game tick, it doesnt have enough CPU to plan the room.
// So we can fill teh bucket and try again next tick.
if controller.my() && !planning::room::plan_room(&room, &mut memory) { return; }
if room.my() && !planning::room::plan_room(&room, &mut memory) { return; }
}
}

Expand All @@ -66,13 +64,14 @@ pub fn game_loop() {
memory.write_memory();

let heap = game::cpu::get_heap_statistics();
let used = (heap.total_heap_size() / heap.heap_size_limit()) * 100;

info!("[STATS] Statistics are as follows: ");
info!(" GCL {}. Next: {} / {}", game::gcl::level(), game::gcl::progress(), game::gcl::progress_total());
info!(" CPU Usage:");
info!(" Total: {}", game::cpu::get_used());
info!(" Bucket: {}", game::cpu::bucket());
info!(" Heap: {:.1}/{:.1}", (heap.total_heap_size() / 1000000), (heap.heap_size_limit() / 1000000));
info!(" Heap: {:.2}%", used);
}

#[wasm_bindgen(js_name = red_button)]
Expand Down
46 changes: 21 additions & 25 deletions src/memory.rs
Original file line number Diff line number Diff line change
@@ -1,15 +1,16 @@
use std::{cmp, collections::HashMap};

use log::error;
use qcell::QCell;
use screeps::{game, ObjectId, RawObjectId, Resource, ResourceType, RoomName, Source, Structure, StructureLink};
use screeps::{game, ObjectId, RawObjectId, ResourceType, RoomName, Source, StructureLink};
use serde::{Deserialize, Serialize};

use js_sys::JsString;

use crate::{room::hauling::{HaulPriorities, HaulType}, MEMORY_VERSION};
use crate::{room::cache::hauling::{HaulingPriority, HaulingType}, MEMORY_VERSION};

#[derive(Clone, Serialize, Deserialize, Debug, PartialEq)]
pub const ALLIES: [&str; 2] = ["MarvinTMB", "Tigga"];

#[derive(Clone, Serialize, Deserialize, Debug, PartialEq, Hash, Eq, Copy)]
pub enum Role {
// Mining industry
Miner,
Expand Down Expand Up @@ -44,13 +45,27 @@ pub struct CreepMemory{
// If it is, but the link isnt next to it, the miner will clear the link id. If it is, the miner will deposit resources into the link
#[serde(skip_serializing_if = "Option::is_none")]
#[serde(rename = "4")]
pub link_id: Option<u8>,
pub link_id: Option<ObjectId<StructureLink>>,
// This is a pointer that changes based on the role of the creep
// Hauler - A reference to the ID of the current haul orders
// Miner - A reference to the source in the vec of sources
#[serde(skip_serializing_if = "Option::is_none")]
#[serde(rename = "5")]
pub task_id: Option<u128>,
// The hauling task if a creep is a hauler.
#[serde(skip_serializing_if = "Option::is_none")]
#[serde(rename = "6")]
pub hauling_task: Option<pub struct CreepHaulTask {
#[serde(rename = "0")]
pub target_id: RawObjectId,
#[serde(rename = "1")]
pub haul_type: HaulingType,
#[serde(rename = "2")]
pub priority: HaulingPriority,
#[serde(rename = "3")]
pub resource: ResourceType,
#[serde(rename = "4")]
pub amount: u32,
}>,
}
}

Expand All @@ -67,25 +82,6 @@ pub struct RoomMemory{
pub max_creeps: u8,
pub work_parts: u8,
}>,

pub haul_orders: HashMap<u128, pub struct HaulOrder {
#[serde(rename = "0")]
pub id: u128,
#[serde(rename = "1")]
pub priority: HaulPriorities,
#[serde(rename = "2")]
pub target_id: RawObjectId,
#[serde(rename = "3")]
pub target_type: ResourceType,
#[serde(rename = "4")]
pub responder: Option<String>,
#[serde(rename = "5")]
pub haul_type: HaulType,
#[serde(rename = "6")]
pub amount: u32,
}>,
#[serde(skip_serializing_if = "Option::is_none")]
pub links: Option<Vec<ObjectId<StructureLink>>>,
// Creeps by role
pub creeps: Vec<String>,
pub creeps_manufactured: u128,
Expand Down
57 changes: 57 additions & 0 deletions src/room/cache/creeps.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
use std::collections::HashMap;

use screeps::{find, Creep, Room, SharedCreepProperties};

use crate::memory::{Role, ScreepsMemory, ALLIES};

#[derive(Debug, Clone)]
pub struct CreepCache {
pub creeps: HashMap<String, Creep>,
pub creeps_of_role: HashMap<Role, Vec<String>>,

pub enemy_creeps: Vec<Creep>,
pub allied_creeps: Vec<Creep>,
}

impl CreepCache {
pub fn new_from_room(room: &Room, memory: &mut ScreepsMemory) -> CreepCache {
let mut cache = CreepCache {
creeps: HashMap::new(),
creeps_of_role: HashMap::new(),

enemy_creeps: Vec::new(),
allied_creeps: Vec::new(),
};

cache.refresh_creep_cache(room, memory);
cache
}

pub fn refresh_creep_cache(&mut self, room: &Room, memory: &mut ScreepsMemory) {
let creeps = room.find(find::CREEPS, None);

for creep in creeps {
if creep.my() {
let creep_memory = memory.creeps.get(&creep.name());

if creep_memory.is_none() {
continue;
}

let creep_memory = creep_memory.unwrap();

if let Some(role_vec) = self.creeps_of_role.get_mut(&creep_memory.role) {
role_vec.push(creep.name());
} else {
self.creeps_of_role.insert(creep_memory.role, vec![creep.name()]);
}

self.creeps.insert(creep.name(), creep);
} else if ALLIES.contains(&creep.owner().username().as_str()) {
self.allied_creeps.push(creep);
} else {
self.enemy_creeps.push(creep);
}
}
}
}
115 changes: 115 additions & 0 deletions src/room/cache/hauling.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,115 @@
use std::collections::HashMap;

use log::info;
use screeps::{game, Creep, HasPosition, Position, RawObjectId, ResourceType, SharedCreepProperties};
use serde::{Deserialize, Serialize};

use crate::memory::{CreepHaulTask, ScreepsMemory};

#[derive(Serialize, Deserialize, Debug, Clone, Copy, PartialEq, PartialOrd, Eq, Ord)]
pub enum HaulingPriority {
Combat = 0,
Emergency = 1,
Energy = 2,
Minerals = 3,
Market = 4
}

#[derive(Serialize, Deserialize, Debug, Clone, Copy, PartialEq, PartialOrd, Eq, Ord)]
pub enum HaulingType {
Deposit = 0,
Withdraw = 1,
Pickup = 2,
Transfer = 3
}

#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct RoomHaulingOrder {
pub id: u32,
pub target: RawObjectId,
pub resource: ResourceType,
pub amount: u32,
pub priority: HaulingPriority,
pub haul_type: HaulingType,
}

pub struct HaulingCache {
pub new_orders: HashMap<u32, RoomHaulingOrder>,

pub current_id_index: u32,

pub haulers: Vec<String>,
}

impl HaulingCache {
pub fn new() -> HaulingCache {
HaulingCache {
new_orders: HashMap::new(),
current_id_index: game::time(),
haulers: Vec::new(),
}
}

pub fn get_unique_id(&mut self) -> u32 {
self.current_id_index += 1;
self.current_id_index
}

pub fn create_order(&mut self, target: RawObjectId, resource: ResourceType, amount: u32, priority: HaulingPriority, haul_type: HaulingType) {
let id = self.get_unique_id();

let order = RoomHaulingOrder {
id,
target,
resource,
amount,
priority,
haul_type,
};

self.new_orders.insert(id, order);
}

pub fn find_new_order(&mut self, creep: &Creep, memory: &mut ScreepsMemory) -> Option<CreepHaulTask> {
let unsorted_orders = self.new_orders.values().collect::<Vec<&RoomHaulingOrder>>();
let mut orders = unsorted_orders.clone();

orders.sort_by(|a, b| a.priority.cmp(&b.priority));

if creep.store().get_free_capacity(Some(ResourceType::Energy)) as u32 == 0 {
orders.retain(|x| x.haul_type == HaulingType::Deposit || x.haul_type == HaulingType::Transfer);
info!("Hauling: Deposit or Transfer {}", orders.len());
} else {
orders.retain(|x| x.haul_type == HaulingType::Withdraw || x.haul_type == HaulingType::Pickup);
}

if let Some(order) = orders.into_iter().next() {
let id = order.id;
let order = self.new_orders.get_mut(&id).unwrap();

let creep_memory = memory.creeps.get_mut(&creep.name()).unwrap();
let task = CreepHaulTask {
target_id: order.target,
resource: order.resource,
amount: order.amount,
priority: order.priority,
haul_type: order.haul_type,
};

self.new_orders.remove(&id);
creep_memory.hauling_task = Some(task);
return creep_memory.hauling_task.clone();
}
None
}
}

impl CreepHaulTask {
pub fn get_target_position(&self) -> Option<Position> {
let target = game::get_object_by_id_erased(&self.target_id);

target.as_ref()?;

Some(target.unwrap().pos())
}
}
42 changes: 42 additions & 0 deletions src/room/cache/mod.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
use screeps::Room;

use crate::memory::ScreepsMemory;

use self::{creeps::CreepCache, hauling::HaulingCache, resources::RoomResourceCache, structures::RoomStructureCache};

pub mod structures;
pub mod creeps;
pub mod hauling;
pub mod resources;

pub struct RoomCache {
pub structures: RoomStructureCache,
pub creeps: CreepCache,

pub resources: RoomResourceCache,

//pub hauling: RefCell<HaulingCache>,
pub hauling: HaulingCache,
}

impl RoomCache {
pub fn new_from_room(room: &Room, memory: &mut ScreepsMemory) -> RoomCache {
RoomCache {
structures: RoomStructureCache::new_from_room(room, memory),
creeps: CreepCache::new_from_room(room, memory),

resources: RoomResourceCache::new_from_room(room, memory),

hauling: HaulingCache::new(),
//hauling: RefCell::new(HaulingCache::new()),
}
}

pub fn _refresh_cache(&mut self, room: &Room, memory: &mut ScreepsMemory) {
self.structures.refresh_structure_cache(room);
self.structures.refresh_source_cache(room);
self.structures.refresh_spawn_cache(room);

self.creeps.refresh_creep_cache(room, memory);
}
}
Loading

0 comments on commit 0416520

Please sign in to comment.