Skip to content

Commit

Permalink
The hauling + fixes update.
Browse files Browse the repository at this point in the history
- Made builders use the new "Offer" system.
- Offer type for containers in haulers, makes it easy to get energy
- Changed the behavior of creep counting to rely on the Heap instead of memory.
- Each creep should check if its alive BEFORE it runs, not the room.
  • Loading branch information
InfinityDevTech committed May 27, 2024
1 parent 753aada commit 9afa852
Show file tree
Hide file tree
Showing 22 changed files with 481 additions and 207 deletions.
2 changes: 1 addition & 1 deletion screeps.toml
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ prefix = "ptr"
# Linux Laptop
#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"
destination = "/home/jwjoh/.config/Screeps/scripts/botarena_screepspl_us___21025"

branch = "default"
[copy.build]
Expand Down
44 changes: 11 additions & 33 deletions src/memory.rs
Original file line number Diff line number Diff line change
@@ -1,26 +1,29 @@
use std::{cmp, collections::HashMap};

use log::error;
use screeps::{game, ObjectId, RawObjectId, ResourceType, RoomName, Source, StructureLink};
use screeps::{game, look::{self, LookResult}, Creep, HasPosition, ObjectId, Part, RawObjectId, ResourceType, Room, RoomName, Source, StructureLink, Terrain};
use serde::{Deserialize, Serialize};

use js_sys::JsString;

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

pub const ALLIES: [&str; 2] = ["MarvinTMB", "Tigga"];

#[derive(Clone, Serialize, Deserialize, Debug, PartialEq, Hash, Eq, Copy)]
// The roles listed in creep memory
// The order of this also is the order in which
// Traffic Priority is handled.
pub enum Role {
// Mining industry
Miner,
Hauler,
Miner = 0,
Hauler = 1,

// Construction industry
Upgrader,
Builder,
Upgrader = 2,
Builder = 3,

Scout,
Scout = 10,
}

structstruck::strike! {
Expand Down Expand Up @@ -76,17 +79,7 @@ pub struct RoomMemory{
pub name: String,
pub rcl: u8,
pub id: u128,
// Mining stuffs
pub sources: Vec<pub struct ScoutedSource {
#[serde(rename = "0")]
pub id: ObjectId<Source>,
#[serde(rename = "1")]
pub assigned_creeps: u8,
#[serde(rename = "2")]
pub max_creeps: u8,
#[serde(rename = "3")]
pub work_parts: u8,
}>,
pub planned: bool,
// Creeps by role
pub creeps: Vec<String>,
}
Expand Down Expand Up @@ -154,19 +147,4 @@ impl ScreepsMemory {
object
);
}
}

impl ScoutedSource {
pub fn parts_needed(&self) -> u8 {
let source: Source = game::get_object_by_id_typed(&self.id).unwrap();
let max_energy = source.energy_capacity();

// Each work part equates to 2 energy per tick
// Each source refills energy every 300 ticks.
let max_work_needed = (max_energy / 300) + 2;

let work_parts_needed = max_work_needed - self.work_parts as u32;

cmp::max(work_parts_needed, 0) as u8
}
}
2 changes: 2 additions & 0 deletions src/movement/move_target.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
use std::str::FromStr;

use log::warn;
use screeps::{
pathfinder::{self, MultiRoomCostResult, SearchOptions}, HasPosition, LocalCostMatrix, OwnedStructureProperties, Position,
Expand Down
19 changes: 13 additions & 6 deletions src/room/cache/hauling.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
use std::collections::HashMap;
use std::{cmp::Ordering, collections::HashMap};

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

use crate::memory::{CreepHaulTask, ScreepsMemory};
Expand All @@ -17,7 +17,7 @@ pub enum HaulingPriority {

#[derive(Serialize, Deserialize, Debug, Clone, Copy, PartialEq, PartialOrd, Eq, Ord)]
pub enum HaulingType {
Deposit = 0,
Offer = 0,
Withdraw = 1,
Pickup = 2,
Transfer = 3
Expand Down Expand Up @@ -70,14 +70,21 @@ impl HaulingCache {
self.new_orders.insert(id, order);
}

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

if let Some(order_type) = order_type {
orders.retain(|x| x.haul_type == order_type);
}
if let Some(resource_type) = resource {
orders.retain(|rsc| rsc.resource == resource_type);
}

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);
if creep.store().get_used_capacity(Some(ResourceType::Energy)) > 0 {
orders.retain(|x| 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);
Expand Down
2 changes: 1 addition & 1 deletion src/room/cache/resources.rs
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ impl RoomResourceCache {
cache
}

pub fn create_haul_request_for_dropped_energy(&self, hauling: &mut HaulingCache) {
pub fn haul_dropped_resources(&self, hauling: &mut HaulingCache) {
for resource in &self.dropped_energy {
hauling.create_order(resource.id().into(), resource.resource_type(), resource.amount(), HaulingPriority::Energy, HaulingType::Pickup);
}
Expand Down
146 changes: 141 additions & 5 deletions src/room/cache/structures.rs
Original file line number Diff line number Diff line change
@@ -1,30 +1,52 @@
use std::collections::HashMap;
use std::{cmp, collections::HashMap};

use screeps::{find, HasId, ObjectId, Room, Source, StructureController, StructureExtension, StructureLink, StructureObject, StructureSpawn, StructureTower};
use screeps::{find, game, look::{self, LookResult}, ConstructionSite, Creep, HasId, HasPosition, LocalCostMatrix, LocalRoomTerrain, ObjectId, Part, Resource, ResourceType, Room, Source, Structure, StructureContainer, StructureController, StructureExtension, StructureLink, StructureObject, StructureRoad, StructureSpawn, StructureTower, Terrain};

use crate::memory::ScreepsMemory;

use super::hauling::{HaulingCache, HaulingPriority, HaulingType};

#[derive(Debug, Clone)]
pub struct CachedSource {
pub id: ObjectId<Source>,
pub creeps: Vec<ObjectId<Creep>>
}

#[derive(Debug, Clone)]
pub struct RoomStructureCache {
pub sources: HashMap<ObjectId<Source>, Source>,
pub all_structures: Vec<StructureObject>,
pub construction_sites: Vec<ConstructionSite>,

pub sources: Vec<CachedSource>,
pub spawns: HashMap<ObjectId<StructureSpawn>, StructureSpawn>,
pub extensions: HashMap<ObjectId<StructureExtension>, StructureExtension>,
pub containers: HashMap<ObjectId<StructureContainer>, StructureContainer>,

pub controller: Option<StructureController>,

pub terrain: LocalRoomTerrain,
pub roads: HashMap<ObjectId<StructureRoad>, StructureRoad>,

pub links: HashMap<ObjectId<StructureLink>, StructureLink>,
pub towers: HashMap<ObjectId<StructureTower>, StructureTower>,
}

impl RoomStructureCache {
pub fn new_from_room(room: &Room, _memory: &mut ScreepsMemory) -> RoomStructureCache {
let mut cache = RoomStructureCache {
sources: HashMap::new(),
all_structures: Vec::new(),
construction_sites: Vec::new(),

sources: Vec::new(),
towers: HashMap::new(),
spawns: HashMap::new(),
containers: HashMap::new(),

controller: None,

terrain: LocalRoomTerrain::from(room.get_terrain()),
roads: HashMap::new(),

links: HashMap::new(),
extensions: HashMap::new(),
};
Expand All @@ -36,6 +58,7 @@ impl RoomStructureCache {
cache.refresh_source_cache(room);
cache.refresh_structure_cache(room);
cache.refresh_spawn_cache(room);
cache.refresh_construction_cache(room);
cache
}

Expand All @@ -47,10 +70,52 @@ impl RoomStructureCache {
}
}

pub fn temp(&mut self, hauling: &mut HaulingCache) {
for source in self.extensions.values() {
if source.store().get_free_capacity(Some(ResourceType::Energy)) > 0 {
hauling.create_order(
source.raw_id(),
ResourceType::Energy,
source.store().get_free_capacity(Some(ResourceType::Energy)).try_into().unwrap(),
HaulingPriority::Energy,
HaulingType::Transfer
);
}
}
}

pub fn check_containers(&mut self, hauling: &mut HaulingCache) {
for container in self.containers.values() {
let used_capacity = container.store().get_used_capacity(Some(ResourceType::Energy));
let max_capacity = container.store().get_capacity(Some(ResourceType::Energy));

hauling.create_order(
container.raw_id(),
ResourceType::Energy,
used_capacity,
HaulingPriority::Energy,
HaulingType::Offer
);

if (used_capacity as f32) < (max_capacity as f32 * 0.5) {
hauling.create_order(
container.raw_id(),
ResourceType::Energy,
container.store().get_free_capacity(Some(ResourceType::Energy)).try_into().unwrap(),
HaulingPriority::Energy,
HaulingType::Transfer
);
}
}
}

pub fn refresh_structure_cache(&mut self, room: &Room) {
let structures = room.find(find::MY_STRUCTURES, None).into_iter();

for structure in structures {

self.all_structures.push(structure.clone());

match structure {
StructureObject::StructureTower(tower) => {
self.towers.insert(tower.id(), tower);
Expand All @@ -61,15 +126,86 @@ impl RoomStructureCache {
StructureObject::StructureLink(link) => {
self.links.insert(link.id(), link);
}
StructureObject::StructureRoad(road) => {
self.roads.insert(road.id(), road);
}
StructureObject::StructureContainer(container) => {
self.containers.insert(container.id(), container);
}
_ => {}
}
}
}

pub fn refresh_construction_cache(&mut self, room: &Room) {
let mut construction_sites = room.find(find::CONSTRUCTION_SITES, None);

self.construction_sites.append(&mut construction_sites);
}

pub fn refresh_source_cache(&mut self, room: &Room) {
let sources = room.find(find::SOURCES, None);
for source in sources {
self.sources.insert(source.id(), source);
let constructed_source = CachedSource {
id: source.id(),
creeps: Vec::new()
};

self.sources.push(constructed_source);
}
}
}

impl CachedSource {
pub fn parts_needed(&self) -> u8 {
let source: Source = game::get_object_by_id_typed(&self.id).unwrap();
let max_energy = source.energy_capacity();

// Each work part equates to 2 energy per tick
// Each source refills energy every 300 ticks.
let max_work_needed = (max_energy / 300) + 2;

let work_parts_needed = max_work_needed - self.calculate_work_parts() as u32;

cmp::max(work_parts_needed, 0) as u8
}

pub fn calculate_mining_spots(&self, room: &Room) -> u8 {
let source = game::get_object_by_id_typed(&self.id).unwrap();

let x = source.pos().x().u8();
let y = source.pos().y().u8();

let areas = room.look_for_at_area(look::TERRAIN, y - 1, x - 1, y + 1, x + 1);
let mut available_spots = 0;

for area in areas {
match area.look_result {
LookResult::Terrain(Terrain::Plain) => available_spots += 1,
LookResult::Terrain(Terrain::Swamp) => available_spots += 1,
_ => {}

}
}

available_spots
}

pub fn calculate_work_parts(&self) -> u8 {
let creeps = &self.creeps;

let mut work_parts: u8 = 0;

for creep in creeps {
let creep = game::get_object_by_id_typed(creep);
if creep.is_none() { continue; }

let mut body = creep.unwrap().body();
body.retain(|part| part.part() == Part::Work);

work_parts += body.len() as u8
}

work_parts
}
}
Loading

0 comments on commit 9afa852

Please sign in to comment.