Skip to content

Commit

Permalink
Idk breh. A lot.
Browse files Browse the repository at this point in the history
  • Loading branch information
InfinityDevTech committed May 29, 2024
1 parent 9afa852 commit c275654
Show file tree
Hide file tree
Showing 13 changed files with 257 additions and 85 deletions.
12 changes: 8 additions & 4 deletions javascript/main.js
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,11 @@ global.suicide_all = function() {
}
}

global.reset_ivm = function() {
console.log("Resetting IVM...");
Game.cpu.halt();
}

function run_loop() {
if (ERROR) {
// Stops memory leak present in WASM if rust were to error out.
Expand All @@ -75,10 +80,8 @@ function run_loop() {

console.error = console_error
try {

if (!EXECUTION_PAUSED) {
wasm_module.loop();
}
wasm_module.loop();

if (RED_BUTTON) {
wasm_module.red_button();
global.wipe_memory();
Expand All @@ -98,6 +101,7 @@ function run_loop() {
let wasm_module;

module.exports.loop = function () {
if (EXECUTION_PAUSED) {console.log("Execution is paused, not running..."); return;}
// Fixes a memory corruption issue.
if (!global.Memory) {
global.RawMemory._parsed = {}; global.Memory = {}; global.Memory.rooms = {}
Expand Down
4 changes: 3 additions & 1 deletion screeps.toml
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,9 @@ prefix = "ptr"
# Linux Laptop
#destination = "/home/jwjoh/.config/Screeps/scripts/127_0_0_1___21025"
# Bot arena
destination = "/home/jwjoh/.config/Screeps/scripts/botarena_screepspl_us___21025"
#destination = "/home/jwjoh/.config/Screeps/scripts/botarena_screepspl_us___21025"
# Botarematch
destination = "/home/jwjoh/.config/Screeps/scripts/screeps_infinity_dev_xyz___21025"

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

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

use js_sys::JsString;
use js_sys::{JsString, Object};

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

Expand Down Expand Up @@ -37,8 +37,8 @@ pub struct CreepMemory{
#[serde(rename = "1")]
pub path: Option<String>,
// Career
#[serde(rename = "2")]
pub role: Role,
//#[serde(rename = "2")]
//pub role: Role,
// Needs Energy?
#[serde(skip_serializing_if = "Option::is_none")]
#[serde(rename = "3")]
Expand Down
9 changes: 6 additions & 3 deletions src/room/cache/creeps.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ use std::collections::HashMap;

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

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

#[derive(Debug, Clone)]
pub struct CreepCache {
Expand Down Expand Up @@ -40,10 +40,13 @@ impl CreepCache {

let creep_memory = creep_memory.unwrap();

if let Some(role_vec) = self.creeps_of_role.get_mut(&creep_memory.role) {
let role = utils::name_to_role(&creep.name());
if role.is_none() { continue; }

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

self.creeps.insert(creep.name(), creep);
Expand Down
35 changes: 23 additions & 12 deletions src/room/cache/hauling.rs
Original file line number Diff line number Diff line change
@@ -1,11 +1,13 @@
use std::{cmp::Ordering, collections::HashMap};

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

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

use super::structures::RoomStructureCache;

#[derive(Serialize, Deserialize, Debug, Clone, Copy, PartialEq, PartialOrd, Eq, Ord)]
pub enum HaulingPriority {
Combat = 0,
Expand Down Expand Up @@ -70,26 +72,18 @@ impl HaulingCache {
self.new_orders.insert(id, order);
}

pub fn find_new_order(&mut self, creep: &Creep, memory: &mut ScreepsMemory, resource: Option<ResourceType>, order_type: Option<HaulingType>) -> Option<CreepHaulTask> {
pub fn find_new_order(&mut self, creep: &Creep, memory: &mut ScreepsMemory, resource: Option<ResourceType>, order_type: Vec<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);
}
orders.retain(|x| order_type.contains(&x.haul_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_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);
}

if let Some(order) = orders.into_iter().next() {
let id = order.id;
let order = self.new_orders.get_mut(&id).unwrap();
Expand All @@ -109,6 +103,23 @@ impl HaulingCache {
}
None
}

pub fn haul_ruins(&mut self, structures: &RoomStructureCache) {
let ruins = &structures.ruins;

for ruin in ruins.values() {
if ruin.store().get_used_capacity(Some(ResourceType::Energy)) > 0 {
self.create_order(
ruin.raw_id(),
ResourceType::Energy,
ruin.store().get_used_capacity(Some(ResourceType::Energy)),
HaulingPriority::Energy,
HaulingType::Offer
);
return;
}
}
}
}

impl CreepHaulTask {
Expand Down
80 changes: 75 additions & 5 deletions src/room/cache/structures.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
use std::{cmp, collections::HashMap};

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 log::info;
use screeps::{find, game, look::{self, LookResult}, ConstructionSite, Creep, HasId, HasPosition, LocalCostMatrix, LocalRoomTerrain, ObjectId, OwnedStructureProperties, Part, Resource, ResourceType, Room, Ruin, Source, Structure, StructureContainer, StructureController, StructureExtension, StructureLink, StructureObject, StructureRoad, StructureSpawn, StructureTower, Terrain};

use crate::memory::ScreepsMemory;

Expand All @@ -9,7 +10,12 @@ use super::hauling::{HaulingCache, HaulingPriority, HaulingType};
#[derive(Debug, Clone)]
pub struct CachedSource {
pub id: ObjectId<Source>,
pub creeps: Vec<ObjectId<Creep>>
pub creeps: Vec<ObjectId<Creep>>,

pub link: Option<ObjectId<StructureLink>>,
pub container: Option<ObjectId<StructureContainer>>,

pub csites: Vec<ConstructionSite>,
}

#[derive(Debug, Clone)]
Expand All @@ -18,6 +24,7 @@ pub struct RoomStructureCache {
pub construction_sites: Vec<ConstructionSite>,

pub sources: Vec<CachedSource>,
pub ruins: HashMap<ObjectId<Ruin>, Ruin>,
pub spawns: HashMap<ObjectId<StructureSpawn>, StructureSpawn>,
pub extensions: HashMap<ObjectId<StructureExtension>, StructureExtension>,
pub containers: HashMap<ObjectId<StructureContainer>, StructureContainer>,
Expand All @@ -38,6 +45,7 @@ impl RoomStructureCache {
construction_sites: Vec::new(),

sources: Vec::new(),
ruins: HashMap::new(),
towers: HashMap::new(),
spawns: HashMap::new(),
containers: HashMap::new(),
Expand All @@ -59,6 +67,7 @@ impl RoomStructureCache {
cache.refresh_structure_cache(room);
cache.refresh_spawn_cache(room);
cache.refresh_construction_cache(room);
cache.refresh_ruin_cache(room);
cache
}

Expand Down Expand Up @@ -89,6 +98,21 @@ impl RoomStructureCache {
let used_capacity = container.store().get_used_capacity(Some(ResourceType::Energy));
let max_capacity = container.store().get_capacity(Some(ResourceType::Energy));

let mut i = 0;
let mut matching = false;
loop {
if self.sources.len() <= i { break }
if matching { break }

if let Some(source_container) = self.sources[i].get_container() {
if container.id() == source_container.id() {
matching = true;
}
}

i += 1;
}

hauling.create_order(
container.raw_id(),
ResourceType::Energy,
Expand All @@ -97,7 +121,7 @@ impl RoomStructureCache {
HaulingType::Offer
);

if (used_capacity as f32) < (max_capacity as f32 * 0.5) {
if !matching && (used_capacity as f32) <= (max_capacity as f32 * 0.5) {
hauling.create_order(
container.raw_id(),
ResourceType::Energy,
Expand All @@ -109,21 +133,36 @@ impl RoomStructureCache {
}
}

pub fn refresh_ruin_cache(&mut self, room: &Room) {
//if game::time() % 100 != 0 {
// return;
//}

let ruins = room.find(find::RUINS, None).into_iter();

for ruin in ruins {
self.ruins.insert(ruin.id(), ruin);
}
}

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

for structure in structures {

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

match structure {
StructureObject::StructureTower(tower) => {
if !tower.my() {continue;}
self.towers.insert(tower.id(), tower);
}
StructureObject::StructureExtension(extension) => {
if !extension.my() {continue;}
self.extensions.insert(extension.id(), extension);
}
StructureObject::StructureLink(link) => {
if !link.my() {continue;}
self.links.insert(link.id(), link);
}
StructureObject::StructureRoad(road) => {
Expand All @@ -146,9 +185,15 @@ impl RoomStructureCache {
pub fn refresh_source_cache(&mut self, room: &Room) {
let sources = room.find(find::SOURCES, None);
for source in sources {
let csites = source.pos().find_in_range(find::CONSTRUCTION_SITES, 1);

let constructed_source = CachedSource {
id: source.id(),
creeps: Vec::new()
creeps: Vec::new(),

link: None,
container: None,
csites,
};

self.sources.push(constructed_source);
Expand All @@ -157,6 +202,31 @@ impl RoomStructureCache {
}

impl CachedSource {
pub fn get_container(&mut self) -> Option<StructureContainer> {
if let Some(container_id) = self.container {
return Some(game::get_object_by_id_typed(&container_id).unwrap());
}

let source = game::get_object_by_id_typed(&self.id).unwrap();
let pos = source.pos();

let mut find = pos.find_in_range(find::STRUCTURES, 1);
find.retain(|c| {
matches!(c, StructureObject::StructureContainer(_))
});

if !find.is_empty() {
let container = find[0].clone();
if let StructureObject::StructureContainer(container) = container {
self.container = Some(container.id());
return Some(container);
}
return None;
}

None
}

pub fn parts_needed(&self) -> u8 {
let source: Source = game::get_object_by_id_typed(&self.id).unwrap();
let max_energy = source.energy_capacity();
Expand Down
6 changes: 3 additions & 3 deletions src/room/creeps/local/builder.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ pub fn run_creep(creep: &Creep, memory: &mut ScreepsMemory, cache: &mut RoomCach
}

if needs_energy || creep.store().get_used_capacity(Some(ResourceType::Energy)) == 0 {
let _ = creep.say("🌩️", false);
let _ = creep.say("📋", false);
find_energy(creep, memory, cache);
} else {
build(creep, creep_memory, cache)
Expand All @@ -28,7 +28,7 @@ pub fn build(creep: &Creep, creepmem: &mut CreepMemory, cache: &mut RoomCache) {
if !sites.is_empty() {
let site = sites.first().unwrap();
if site.pos().get_range_to(creep.pos()) > 1 {
let _ = creep.say("🚶", false);
let _ = creep.say("🚚", false);
creep.better_move_to(creepmem, site.pos(), 1);
} else {
let _ = creep.say("🔨", false);
Expand All @@ -52,8 +52,8 @@ pub fn find_energy(creep: &Creep, memory: &mut ScreepsMemory, cache: &mut RoomCa
execute_order(creep, creepmem_mut, task);

} else {
let new_order = cache.hauling.find_new_order(creep, memory, Some(ResourceType::Energy), vec![HaulingType::Offer, HaulingType::Pickup]);

let new_order = cache.hauling.find_new_order(creep, memory, Some(ResourceType::Energy), Some(HaulingType::Offer));
if let Some(order) = new_order {
execute_order(creep, memory.creeps.get_mut(&creep.name()).unwrap(), &order);
}
Expand Down
Loading

0 comments on commit c275654

Please sign in to comment.