Compare commits

24 Commits

Author SHA1 Message Date
douwe
6ee67eac47 Creeps extract memory completly 2025-08-22 03:11:44 +02:00
douwe
cd1464cc94 Added structure handling in engine as well. 2025-08-22 01:13:09 +02:00
douwe
0381ea6873 Fixed some bugs in harvester. 2025-08-22 00:13:32 +02:00
douwe
0c8da1d472 Finished revision harvester behaviour. Added Some metrics for every loop. 2025-08-21 23:35:00 +02:00
douwe
1ede4cce47 Improved harvester source detection. 2025-08-21 21:01:00 +02:00
douwe
1e9e696b1e Created a base engine class and let it handle all creeps. 2025-08-21 14:13:32 +02:00
douwe
c9ce09ba1a Updated screepsxx module to original url 2025-08-20 17:42:37 +02:00
Douwe Ravers
1a74743e4f Merge pull request #9 from DouweRavers/develop
Develop
2025-08-13 21:14:16 +02:00
douwe
fa5d75fca3 Update with gitignore 2025-08-13 21:12:38 +02:00
Douwe Ravers
b61743fa52 Create .gitignore 2025-08-13 21:11:09 +02:00
Douwe Ravers
009853665d Merge pull request #8 from DouweRavers/develop
Develop
2025-08-13 21:09:51 +02:00
douwe
257cf85695 Minor bug fixes 2025-08-13 21:08:26 +02:00
douwe
9a1682a857 First working version of colony.
Harversters and spawn work.
2025-08-13 20:43:26 +02:00
Douwe Ravers
8a39526580 Update README.md 2025-08-13 00:01:45 +02:00
douwe
5ed1329d2e Basic setup for Cpp based screeping. 2025-08-12 23:56:10 +02:00
unknown
7c1a84a5ca Changed miner search functions 2023-08-31 19:19:41 +02:00
unknown
bde8a2309f Changed miner movement; 2023-08-31 19:13:22 +02:00
unknown
8d67dcb8b8 Minor changes 2023-08-31 19:04:10 +02:00
unknown
29aa48dc3b Changed spawn checktime to 100 2023-08-30 23:57:38 +02:00
unknown
5cfea80b19 Changed update function of spawn to only check every 300 ticks. 2023-08-30 23:53:35 +02:00
unknown
eda20c2dce Removed the harvester. Introduced the cleaner (not active yet) spawners use full room capacity now. 2023-08-30 23:37:04 +02:00
unknown
112c3c3a97 Created supplier and builder functions 2023-08-29 20:43:10 +02:00
Douwe Ravers
523a2e0005 Merge pull request #2 from DouweRavers/develop
fixed wrong vacancy generation bug.
2023-08-26 21:32:06 +02:00
Douwe Ravers
cab2c3fd25 Merge pull request #1 from DouweRavers/develop
Develop
2023-08-26 20:49:17 +02:00
35 changed files with 792 additions and 393 deletions

1
.gitignore vendored Normal file
View File

@@ -0,0 +1 @@
build

6
.gitmodules vendored Normal file
View File

@@ -0,0 +1,6 @@
[submodule "emsdk"]
path = emsdk
url = git@github.com:emscripten-core/emsdk.git
[submodule "screepsxx"]
path = screepsxx
url = git@github.com:UltraCoderRU/screepsxx.git

116
.vscode/settings.json vendored
View File

@@ -1,7 +1,113 @@
{
"files.exclude": {
".*": true,
"LICENSE": true,
"*.md": true
}
"files.associations": {
"__hash_table": "cpp",
"__string": "cpp",
"algorithm": "cpp",
"functional": "cpp",
"locale": "cpp",
"utility": "cpp",
"mutex": "cpp",
"shared_mutex": "cpp",
"stop_token": "cpp",
"cassert": "cpp",
"vector": "cpp",
"optional": "cpp",
"*.inc": "cpp",
"thread": "cpp",
"atomic": "cpp",
"__config": "cpp",
"__debug": "cpp",
"__errc": "cpp",
"__functional_03": "cpp",
"__mutex_base": "cpp",
"__nullptr": "cpp",
"__split_buffer": "cpp",
"__tree": "cpp",
"any": "cpp",
"array": "cpp",
"bit": "cpp",
"bitset": "cpp",
"cctype": "cpp",
"charconv": "cpp",
"chrono": "cpp",
"clocale": "cpp",
"cmath": "cpp",
"codecvt": "cpp",
"compare": "cpp",
"complex": "cpp",
"condition_variable": "cpp",
"cstdarg": "cpp",
"cstddef": "cpp",
"cstdint": "cpp",
"cstdio": "cpp",
"cstdlib": "cpp",
"cstring": "cpp",
"ctime": "cpp",
"cwchar": "cpp",
"cwctype": "cpp",
"deque": "cpp",
"exception": "cpp",
"filesystem": "cpp",
"forward_list": "cpp",
"iterator": "cpp",
"list": "cpp",
"map": "cpp",
"memory_resource": "cpp",
"regex": "cpp",
"set": "cpp",
"string": "cpp",
"type_traits": "cpp",
"unordered_map": "cpp",
"unordered_set": "cpp",
"fstream": "cpp",
"future": "cpp",
"initializer_list": "cpp",
"iomanip": "cpp",
"ios": "cpp",
"iosfwd": "cpp",
"iostream": "cpp",
"istream": "cpp",
"limits": "cpp",
"memory": "cpp",
"new": "cpp",
"numeric": "cpp",
"ostream": "cpp",
"queue": "cpp",
"random": "cpp",
"ratio": "cpp",
"span": "cpp",
"sstream": "cpp",
"stack": "cpp",
"stdexcept": "cpp",
"streambuf": "cpp",
"string_view": "cpp",
"strstream": "cpp",
"system_error": "cpp",
"tuple": "cpp",
"typeinfo": "cpp",
"valarray": "cpp",
"variant": "cpp",
"cerrno": "cpp",
"cfloat": "cpp",
"climits": "cpp",
"concepts": "cpp",
"format": "cpp",
"numbers": "cpp",
"semaphore": "cpp",
"cfenv": "cpp",
"cinttypes": "cpp",
"__bit_reference": "cpp",
"__functional_base": "cpp",
"__locale": "cpp",
"__node_handle": "cpp",
"__sso_allocator": "cpp",
"__std_stream": "cpp",
"__threading_support": "cpp",
"__tuple": "cpp",
"csignal": "cpp",
"coroutine": "cpp",
"source_location": "cpp",
"stdfloat": "cpp",
"typeindex": "cpp"
}
}

39
CMakeLists.txt Normal file
View File

@@ -0,0 +1,39 @@
cmake_minimum_required(VERSION 3.16)
project(example CXX)
set(CMAKE_CXX_STANDARD 17)
set(CMAKE_CXX_STANDARD_REQUIRED TRUE)
# set(COMPILE_FLAGS --cache ${CMAKE_BINARY_DIR}/cache)
set(LINK_FLAGS -sASSERTIONS=0 -sMALLOC=emmalloc)
add_compile_options(${COMPILE_FLAGS})
add_link_options(${COMPILE_FLAGS} ${LINK_FLAGS})
add_subdirectory(screepsxx)
# If you change TARGET_NAME, please, make corresponding changes in main.js.
set(TARGET_NAME douwco_hivemind)
include_directories(${CMAKE_SOURCE_DIR}/include)
file(GLOB SRC_FILES ${CMAKE_SOURCE_DIR}/src/*.cpp)
add_executable(${TARGET_NAME} ${SRC_FILES})
target_link_libraries(${TARGET_NAME} screepsxx)
target_link_options(${TARGET_NAME} PUBLIC -sMODULARIZE=1 --no-entry --bind -sEXPORT_ES6=0)
# Collect all artifacts in 'dist' directory
# WASM-module and corresponding JS-module must have different base names in order to use them in Screeps, so we add suffixes.
add_custom_command(TARGET ${TARGET_NAME} POST_BUILD COMMAND ${CMAKE_COMMAND} -E copy ${CMAKE_BINARY_DIR}/${TARGET_NAME}.wasm ${CMAKE_SOURCE_DIR}/dist/${TARGET_NAME}_module.wasm)
add_custom_command(TARGET ${TARGET_NAME} POST_BUILD COMMAND ${CMAKE_COMMAND} -E copy ${CMAKE_BINARY_DIR}/${TARGET_NAME}.js ${CMAKE_SOURCE_DIR}/dist/${TARGET_NAME}_loader.js)
add_custom_command(TARGET ${TARGET_NAME} POST_BUILD COMMAND ${CMAKE_COMMAND} -E copy ${CMAKE_SOURCE_DIR}/js/main.js ${CMAKE_SOURCE_DIR}/dist/main.js)
add_custom_command(TARGET ${TARGET_NAME} POST_BUILD COMMAND ${CMAKE_COMMAND} -E copy ${CMAKE_SOURCE_DIR}/js/wasm_loader.js ${CMAKE_SOURCE_DIR}/dist/wasm_loader.js)
# Following post-build step will automatically upload artifacts to
# official Screeps server. If you want to use it, please,
# set SCREEPS_TOKEN environment variable to your Screeps API token
# (https://docs.screeps.com/auth-tokens.html).
# If you don't want to use this script, please, remove following lines.
#find_package(Python COMPONENTS Interpreter REQUIRED)
#add_custom_command(TARGET ${TARGET_NAME} POST_BUILD COMMAND ${Python_EXECUTABLE} ${screepsxx_SOURCE_DIR}/tools/upload.py ${CMAKE_SOURCE_DIR}/dist $ENV{SCREEPS_TOKEN})

View File

@@ -1,61 +0,0 @@
module.exports = {
setup(){
global.fullReset = fullReset;
global.resetRooms = resetRooms;
global.resetStructures = resetStructures;
global.resetCreeps = resetCreeps;
global.resetConstruction = resetConstruction;
global.buildRoads = buildRoads;
}
}
function fullReset(){
resetRooms();
resetCreeps();
resetStructures();
resetConstruction();
global.started = false;
global.compiled = false;
return "OK";
}
function resetRooms(){
Object.values(Game.rooms).forEach(room => room.memory = {});
return "OK";
}
function resetStructures(){
Object.values(Game.structures).forEach(structure => structure.memory = {});
return "OK";
}
function resetCreeps(){
Object.values(Game.creeps).forEach(creep => creep.suicide());
return "OK";
}
function resetConstruction(){
Object.values(Game.rooms).forEach(room=>room.find(FIND_CONSTRUCTION_SITES).forEach(cs=>cs.remove()));
return "OK";
}
function buildRoads(){
Object.values(Game.rooms).forEach(room=>
{
room.memory.layout.sources.forEach(
sId => {
const source = Game.getObjectById(sId);
var roads = [];
roads = roads.concat(source.pos.findPathTo(room.controller));
roads.pop();
roads = roads.concat(source.pos.findPathTo(room.find(FIND_MY_STRUCTURES, { filter:{ structureType:STRUCTURE_SPAWN }})[0]));
roads.pop();
roads.forEach(tile => room.createConstructionSite(tile.x, tile.y, STRUCTURE_ROAD));
}
);
});
return "OK";
}

View File

@@ -1,36 +0,0 @@
const jobHarvester = require("JobHarvester");
const jobMiner = require("JobMiner");
module.exports = {
setup: function () {
Creep.prototype = _Creep.prototype;
global.Role = Role;
}
}
const Role = {
HARVESTER: 0,
MINER: 1,
SUPPLIER: 2,
UPGRADER: 3,
BUILDER: 4
}
class _Creep extends Creep {
begin(){
if(!this.memory.job) this.memory.job = { role: Role.HARVESTER };
switch (this.memory.job.role) {
case Role.HARVESTER: jobHarvester.begin(this); break;
case Role.MINER: jobMiner.begin(this); break;
}
this.memory.init = true;
}
tick(){
if(!this.memory.init) this.begin();
switch (this.memory.job.role) {
case Role.HARVESTER: jobHarvester.tick(this); break;
case Role.MINER: jobMiner.tick(this); break;
}
}
}

View File

@@ -1,8 +0,0 @@
module.exports = {
begin(creep){
},
tick(creep){
}
}

View File

@@ -1,89 +0,0 @@
module.exports = {
begin(creep){
if(!creep.memory.harvesting) creep.memory.harvesting = false;
if(!creep.memory.counter) creep.memory.counter = 0;
},
tick(creep){
if(creep.memory.harvesting) {
pickUpEnergy(creep);
onEnergyFullTurnToJobMode(creep);
}
else {
performJobs(creep);
onOutOfEnergyTurnHarvestingMode(creep);
}
}
}
function pickUpEnergy(creep){
if(!creep.memory.target) {
const target = creep.pos.findClosestByRange(FIND_DROPPED_RESOURCES, {filter: {resourceType: RESOURCE_ENERGY}});
if(target) creep.memory.target = target.id;
}
const resource = Game.getObjectById(creep.memory.target);
if(!resource) creep.memory.target = undefined;
if(creep.pos.isNearTo(resource)) creep.pickup(resource);
else creep.moveTo(resource);
}
function harvestSource(creep){
if(!creep.memory.target) creep.memory.target = getSourceIdFromRoomTable(creep);
var source = Game.getObjectById(creep.memory.target);
if(creep.pos.isNearTo(source)) creep.harvest(source);
else creep.moveTo(source);
}
function onEnergyFullTurnToJobMode(creep){
if(!creep.store.getFreeCapacity(RESOURCE_ENERGY)) {
creep.memory.harvesting = false;
creep.memory.target = undefined;
}
}
function performJobs(creep){
if(!creep.memory.target) creep.memory.target = getJobTarget(creep);
var target = Game.getObjectById(creep.memory.target);
if(creep.pos.isNearTo(target)) doJob(creep, target);
else creep.moveTo(target);
}
function onOutOfEnergyTurnHarvestingMode(creep){
if(!creep.store.getUsedCapacity(RESOURCE_ENERGY)) {
creep.memory.harvesting = true;
creep.memory.target = undefined;
creep.memory.counter += 1;
}
}
function getSourceIdFromRoomTable(creep) {
const sourceTable = creep.room.memory.layout.sources;
const sourceIterator = creep.memory.counter%creep.room.memory.layout.sources.length;
const sourceId = sourceTable[sourceIterator];
return sourceId;
}
function getJobTarget(creep) {
var target;
switch (creep.memory.counter%3) {
case 0: target = creep.room.controller; break;
case 1: target = creep.pos.findClosestByRange(FIND_MY_STRUCTURES, {filter:{structureType:STRUCTURE_SPAWN}}); break;
case 2: target = creep.pos.findClosestByRange(FIND_MY_CONSTRUCTION_SITES); break;
}
if(target) return target.id;
creep.memory.counter++;
return undefined;
}
function doJob(creep, target){
var response;
switch (creep.memory.counter%3) {
case 0: response = creep.upgradeController(target); break;
case 1: response = creep.transfer(target, RESOURCE_ENERGY); break;
case 2: response = creep.build(target); break;
}
if(response == ERR_FULL) {
creep.memory.counter++;
creep.memory.target = undefined;
}
}

View File

@@ -1,18 +0,0 @@
module.exports = {
begin(creep){},
tick(creep){
const source = Game.getObjectById(creep.memory.job.source);
if(creep.memory.aboveContainer) creep.harvest(source);
if(!creep.pos.isNearTo(source)) { creep.moveTo(source); return; }
if(creep.memory.container) {
const container = Game.getObjectById(creep.memory.container);
if(container.pos.x === creep.pos.x, container.pos.y === creep.pos.y) creep.memory.aboveContainer = true;
else creep.moveTo(container);
} else{
const container = source.pos.findInRange(FIND_STRUCTURES, 1, {filter:{structureType:STRUCTURE_CONTAINER}})[0];
if(container) creep.memory.container = container.id;
else creep.harvest(source);
}
}
}

View File

@@ -1,8 +0,0 @@
module.exports = {
begin(creep){
},
tick(creep){
}
}

View File

@@ -1,8 +0,0 @@
module.exports = {
begin(creep){
},
tick(creep){
}
}

View File

@@ -1,7 +0,0 @@
module.exports = {
clamp: function(v, min, max){
if(v<min) v = min;
else if (max < v) v = max;
return v;
}
}

View File

@@ -2,4 +2,4 @@
My source code for the MMO-programming game: Screeps.
# Status
To those interested in this code. I wrote the main body of the source code when just learning programming so its kind of a mess. I'm now slowly rewriting the code base to a more SOLID version. :)
As a way to learn c++ programming I used the screepsxx repo for controlling the screeps with c++.

View File

@@ -1,44 +0,0 @@
module.exports = {
setup: function () { Room.prototype = _Room.prototype; }
}
class _Room extends Room {
begin(){
roomScan(this);
jobScan(this);
vacancyScan(this);
this.memory.init = true;
}
tick(){
if(!this.memory.init) this.begin();
if(Game.time%100 === 1) vacancyScan(this);
}
}
function roomScan(room){
room.memory.layout = {
sources: room.find(FIND_SOURCES).map(s=>s.id)
};
}
function jobScan(room){
if(!room.memory.jobs) room.memory.jobs = Array(10).fill({role: Role.HARVESTER})
.concat(room.memory.layout.sources.map(s=> {return {role: Role.MINER, source: s}}));
}
function vacancyScan(room){
const activeJobs = room.find(FIND_MY_CREEPS).map(creep=>creep.memory.job);
console.log(activeJobs.toString());
console.log(room.memory.jobs.toString());
const jobs = room.memory.jobs.filter((j)=>{
const index = activeJobs.findIndex(aj=> _.isEqual(aj,j));
if(index < 0) return true;
activeJobs.splice(index,1);
return false;
});
console.log(jobs.toString());
room.memory.vacancies = jobs;
}

View File

@@ -1,21 +0,0 @@
const spawnClass = require("StructureSpawnClass");
module.exports = {
setup() {
spawnClass.setup();
},
begin(structure){
switch (structure.structureType) {
case STRUCTURE_SPAWN: structure.begin(); break;
default: break;
}
},
tick(structure){
switch (structure.structureType) {
case STRUCTURE_SPAWN: structure.tick(); break;
default: break;
}
}
}

View File

@@ -1,43 +0,0 @@
module.exports = {
setup: function () { StructureSpawn.prototype = _StructureSpawn.prototype; }
}
class _StructureSpawn extends StructureSpawn {
begin(){
if (!this.memory.creepCounter) this.memory.creepCounter = 0;
this.memory.init = true;
}
tick(){
if(!this.memory.init) this.begin();
if(this.store.getUsedCapacity(RESOURCE_ENERGY) < 300) return;
const job = this.room.memory.vacancies.pop();
if(job){
const name = getJobName(job.role);
const body = getBodyByJob(job.role);
if(this.createCreep(job, name, body) != OK) this.room.memory.vacancies.push(job);
}
}
createCreep(job, name, body) {
const response = this.spawnCreep(body, name + ": " + this.memory.creepCounter, {
memory: { job: job }
});
if (response == OK) this.memory.creepCounter++;
return response;
}
}
function getJobName(role){
switch (role) {
case Role.HARVESTER: return "Harvy";
case Role.MINER: return "minny";
}
}
function getBodyByJob(role){
switch (role) {
case Role.HARVESTER: return [WORK, CARRY, MOVE, MOVE];
case Role.MINER: return [WORK, WORK, MOVE];
}
}

22
dist/douwco_hivemind_loader.js vendored Normal file

File diff suppressed because one or more lines are too long

BIN
dist/douwco_hivemind_module.wasm vendored Normal file

Binary file not shown.

14
dist/main.js vendored Normal file
View File

@@ -0,0 +1,14 @@
'use strict';
const wasm_loader = require('wasm_loader')
var mod;
wasm_loader('douwco_hivemind_loader', 'douwco_hivemind_module').then((instance) => {
console.log("WASM module loaded.");
mod = instance;
});
module.exports.loop = function () {
if (mod !== undefined)
mod.loop();
}

24
dist/wasm_loader.js vendored Normal file
View File

@@ -0,0 +1,24 @@
'use strict';
module.exports = ((mod_js, mod_wasm, opts) => {
const mod_file = require(mod_js);
const bin_file = require(mod_wasm);
opts = opts || {};
opts.wasmBinary = bin_file;
opts.print = opts.print || ((text) => console.log(text));
opts.printErr = opts.printErr || ((text) => console.log(`error: ${text}`));
opts.onAbort = opts.onAbort || (() => console.log('WASM aborted!!!'));
// == don't call main()
if (typeof opts.noInitialRun === "undefined")
opts.noInitialRun = true;
// == don't terminate after returning from main()
if (typeof opts.noExitRuntime === "undefined")
opts.noExitRuntime = true;
return mod_file(opts);
});

1
emsdk Submodule

Submodule emsdk added at f39e849eff

10
include/Constants.hpp Normal file
View File

@@ -0,0 +1,10 @@
#ifndef DOUWCO_HIVEMIND_CONSTANTS_HPP
#define DOUWCO_HIVEMIND_CONSTANTS_HPP
namespace DouwcoHivemind{
enum CreepRole{ UNEMPLOYED, HARVESTER };
}
#endif // DOUWCO_HIVEMIND_CONSTANTS_HPP

33
include/Creeps/Creep.hpp Normal file
View File

@@ -0,0 +1,33 @@
#ifndef DOUWCO_HIVEMIND_CREEP_HPP
#define DOUWCO_HIVEMIND_CREEP_HPP
#include <Screeps/Creep.hpp>
#include "Constants.hpp"
namespace DouwcoHivemind
{
class Creep
{
public:
CreepRole role;
protected:
Screeps::Creep creep;
JSON memory;
public:
Creep(Screeps::Creep crp) : creep(crp),
memory(crp.memory())
{
role = memory.contains("role") ? static_cast<CreepRole>(memory["role"]) : CreepRole::UNEMPLOYED;
}
virtual ~Creep() {
creep.setMemory(memory);
}
virtual void loop() {}
};
}
#endif // DOUWCO_HIVEMIND_CREEP_HPP

View File

@@ -0,0 +1,47 @@
#ifndef DOUWCO_HIVEMIND_HARVESTER_HPP
#define DOUWCO_HIVEMIND_HARVESTER_HPP
#include <Screeps/Creep.hpp>
#include "Creeps/Creep.hpp"
namespace DouwcoHivemind
{
class HarvesterRole : public Creep
{
private:
bool harvesting;
std::string target_id;
int taskCounter;
public:
HarvesterRole(Screeps::Creep crp) : Creep(crp)
{
harvesting = memory.contains("harvesting") ? static_cast<bool>(memory["harvesting"]) : false;
target_id = memory.contains("target_id") ? static_cast<std::string>(memory["target_id"]) : std::string();
taskCounter = memory.contains("taskCounter") ? static_cast<int>(memory["taskCounter"]) : 0;
}
~HarvesterRole() override
{
memory["harvesting"] = harvesting;
memory["target_id"] = target_id;
memory["taskCounter"] = taskCounter;
}
void loop() override;
private:
void harvestSource();
std::unique_ptr<Screeps::Source> getSourceTarget();
void searchSource();
void depositEnergy();
std::unique_ptr<Screeps::Structure> getDepositTarget();
void searchDeposit();
std::unique_ptr<Screeps::RoomObject> getRoomObjectTarget();
};
}
#endif // DOUWCO_HIVEMIND_HARVESTER_HPP

74
include/Engine.hpp Normal file
View File

@@ -0,0 +1,74 @@
#ifndef DOUWCO_HIVEMIND_ENGINE_HPP
#define DOUWCO_HIVEMIND_ENGINE_HPP
#include <vector>
#include <Screeps/JS.hpp>
#include <Screeps/Game.hpp>
#include <Screeps/Creep.hpp>
#include "Constants.hpp"
#include "Creeps/Creep.hpp"
#include "Creeps/Harvester.hpp"
#include "Structures/Structure.hpp"
#include "Structures/Spawn.hpp"
namespace DouwcoHivemind
{
class Creep;
class Structure;
class Engine
{
private:
std::vector<std::unique_ptr<Creep>> creeps;
std::vector<std::unique_ptr<Structure>> structures;
public:
Engine()
{
ReadOutCreeps();
ReadOutStructures();
}
~Engine() {}
void loop()
{
for (auto &creep : creeps)
creep->loop();
for (auto &structure : structures)
structure->loop();
}
private:
void ReadOutCreeps()
{
auto src_creeps = Screeps::Game.creeps();
for (auto &creep : src_creeps)
{
CreepRole role = creep.second.memory()["role"];
switch (role)
{
case CreepRole::HARVESTER:
creeps.push_back(std::make_unique<HarvesterRole>(creep.second));
break;
case CreepRole::UNEMPLOYED:
default:
EM_ASM({console.log('Undefined role for creep' + $0)}, creep.first.c_str());
break;
}
}
}
void ReadOutStructures()
{
auto spawns = Screeps::Game.spawns();
for (auto &spawn : spawns)
{
structures.push_back(std::make_unique<Spawn>(spawn.second));
}
}
};
}
#endif // DOUWCO_HIVEMIND_ENGINE_HPP

View File

@@ -0,0 +1,24 @@
#ifndef DOUWCO_HIVEMIND_SPAWN_HPP
#define DOUWCO_HIVEMIND_SPAWN_HPP
#include <Screeps/StructureSpawn.hpp>
#include "Structures/Structure.hpp"
namespace DouwcoHivemind
{
class Spawn : public Structure
{
private:
Screeps::StructureSpawn spawn;
public:
Spawn(Screeps::StructureSpawn spwn) : spawn(spwn),
Structure() {}
~Spawn() {}
void loop() override;
};
}
#endif // DOUWCO_HIVEMIND_SPAWN_HPP

View File

@@ -0,0 +1,15 @@
#ifndef DOUWCO_HIVEMIND_STRUCTURE_HPP
#define DOUWCO_HIVEMIND_STRUCTURE_HPP
#include <Screeps/Structure.hpp>
namespace DouwcoHivemind
{
class Structure
{
public:
virtual void loop(){}
};
}
#endif // DOUWCO_HIVEMIND_STRUCTURE_HPP

14
js/main.js Normal file
View File

@@ -0,0 +1,14 @@
'use strict';
const wasm_loader = require('wasm_loader')
var mod;
wasm_loader('douwco_hivemind_loader', 'douwco_hivemind_module').then((instance) => {
console.log("WASM module loaded.");
mod = instance;
});
module.exports.loop = function () {
if (mod !== undefined)
mod.loop();
}

24
js/wasm_loader.js Normal file
View File

@@ -0,0 +1,24 @@
'use strict';
module.exports = ((mod_js, mod_wasm, opts) => {
const mod_file = require(mod_js);
const bin_file = require(mod_wasm);
opts = opts || {};
opts.wasmBinary = bin_file;
opts.print = opts.print || ((text) => console.log(text));
opts.printErr = opts.printErr || ((text) => console.log(`error: ${text}`));
opts.onAbort = opts.onAbort || (() => console.log('WASM aborted!!!'));
// == don't call main()
if (typeof opts.noInitialRun === "undefined")
opts.noInitialRun = true;
// == don't terminate after returning from main()
if (typeof opts.noExitRuntime === "undefined")
opts.noExitRuntime = true;
return mod_file(opts);
});

44
main.js
View File

@@ -1,44 +0,0 @@
const Commands = require("Commands");
const CreepClass = require("CreepClass");
const RoomClass = require("RoomClass");
const Structure = require("Structure");
module.exports.loop = function () {
if(!global.compiled) onRecompile();
else if (!global.started) onRestart();
else onTick();
}
function onRecompile(){
setupClasses();
console.log("Script recompiled...");
global.compiled = true;
}
function onRestart(){
Object.values(Game.rooms).forEach(room => room.begin());
Object.values(Game.creeps).forEach(creep => creep.begin());
Object.values(Game.structures).forEach(structure => Structure.begin(structure));
global.started = true;
}
function onTick(){
Object.values(Game.rooms).forEach(room => room.tick());
Object.values(Game.creeps).forEach(creep => creep.tick());
Object.values(Game.structures).forEach(structure => Structure.tick(structure));
if(!(Game.time % 100)) cleanUp();
}
function setupClasses(){
Commands.setup();
CreepClass.setup();
RoomClass.setup();
Structure.setup();
}
function cleanUp(){
Object.keys(Memory.rooms).forEach(roomName => { if(!Game.rooms[roomName]) Memory.rooms[roomName] = undefined; });
Object.keys(Memory.creeps).forEach(creepName => { if(!Game.creeps[creepName]) Memory.creeps[creepName] = undefined; });
}

15
running notes.txt Normal file
View File

@@ -0,0 +1,15 @@
# Emsdk
Use emsdk 2.0.0 to only use ES5 syntax for js.
cd emsdk && \
./emsdk install 2.0.0 && \
./emsdk activate 2.0.0 && \
source ./emsdk_env.sh && \
cd ..
# Cmake
In screeps project run dit om cmake setup in te stellen:
cmake -DCMAKE_BUILD_TYPE=Release -DCMAKE_TOOLCHAIN_FILE=emsdk/upstream/emscripten/cmake/Modules/Platform/Emscripten.cmake ..
Run dit om de code te compilen:
cmake --build .

1
screepsxx Submodule

Submodule screepsxx added at 8500506e1c

255
src/harvester.cpp Normal file
View File

@@ -0,0 +1,255 @@
#include <vector>
#include <optional>
#include <emscripten.h>
#include <Screeps/Game.hpp>
#include <Screeps/Creep.hpp>
#include <Screeps/Source.hpp>
#include <Screeps/Room.hpp>
#include <Screeps/RoomPosition.hpp>
#include <Screeps/RoomObject.hpp>
#include <Screeps/Structure.hpp>
#include <Screeps/StructureController.hpp>
#include <Screeps/StructureSpawn.hpp>
#include <Screeps/StructureExtension.hpp>
#include <Screeps/StructureTower.hpp>
#include <Screeps/Constants.hpp>
#include <Screeps/Store.hpp>
#include "Creeps/Harvester.hpp"
bool isNearTo(const Screeps::RoomPosition &pos1, const Screeps::RoomPosition &pos2, int dist);
void DouwcoHivemind::HarvesterRole::loop()
{
if (harvesting)
{
if (creep.store().getFreeCapacity(Screeps::RESOURCE_ENERGY) == 0)
{
harvesting = false;
target_id.clear();
}
harvestSource();
}
else
{
if (creep.store().getUsedCapacity(Screeps::RESOURCE_ENERGY) == 0)
{
harvesting = true;
target_id.clear();
}
depositEnergy();
}
}
void DouwcoHivemind::HarvesterRole::harvestSource()
{
auto source = getSourceTarget();
if (!source)
return;
if (isNearTo(creep.pos(), source->pos(), 1))
{
int resp = creep.harvest(*source);
}
else
creep.moveTo(*source);
}
std::unique_ptr<Screeps::Source> DouwcoHivemind::HarvesterRole::getSourceTarget()
{
auto roomObj = getRoomObjectTarget();
if (!roomObj)
{
searchSource();
return nullptr;
}
// Check if found roomobject is an actual source
auto source = std::unique_ptr<Screeps::Source>(dynamic_cast<Screeps::Source *>(roomObj.release()));
if (!source)
{
// EM_ASM({console.log($0 + ': Can\'t cast target to Source')}, creep.name().c_str());
searchSource();
return nullptr;
}
// Check if the source still has energy to harvest
if (source->energy() == 0)
{
searchSource();
return nullptr;
}
return std::move(source);
}
void DouwcoHivemind::HarvesterRole::searchSource()
{
target_id.clear();
auto sources = creep.room().find(Screeps::FIND_SOURCES_ACTIVE);
if (sources.size() == 0)
return;
Screeps::Source *selectedSource;
int maxEnergy = 0;
for (auto &sourceObj : sources)
{
auto source = dynamic_cast<Screeps::Source *>(sourceObj.get());
if (!source)
continue;
auto sourceEnergy = source->energy();
if (sourceEnergy > maxEnergy)
{
maxEnergy = sourceEnergy;
selectedSource = source;
}
}
if (!selectedSource)
{
// EM_ASM({console.log($0 + ': No sources with energy found!')}, creep.name().c_str());
return;
}
target_id = selectedSource->id();
}
void DouwcoHivemind::HarvesterRole::depositEnergy()
{
auto structure = getDepositTarget();
if (!structure)
return;
if (structure->structureType() == Screeps::STRUCTURE_CONTROLLER)
{
if (isNearTo(creep.pos(), structure->pos(), 3))
{
auto controller = dynamic_cast<Screeps::StructureController *>(structure.get());
if (!controller)
return;
int resp = creep.upgradeController(*controller);
}
else
creep.moveTo(*structure);
}
else
{
if (isNearTo(creep.pos(), structure->pos(), 1))
{
int resp = creep.transfer(*structure, Screeps::RESOURCE_ENERGY);
}
else
creep.moveTo(*structure);
}
}
std::unique_ptr<Screeps::Structure> DouwcoHivemind::HarvesterRole::getDepositTarget()
{
auto roomObj = getRoomObjectTarget();
if (!roomObj)
{
searchDeposit();
return nullptr;
}
// Check if found roomobject is an actual structure
auto structure = std::unique_ptr<Screeps::Structure>(dynamic_cast<Screeps::Structure *>(roomObj.release()));
if (!structure)
{
// EM_ASM({console.log($0 + ': Can\'t cast target to Source')}, creep.name().c_str());
searchDeposit();
return nullptr;
}
// Check if the structure can receive energy to harvest
int energyCapacity;
auto structureType = structure->structureType();
if (structureType == Screeps::STRUCTURE_CONTROLLER)
{
energyCapacity = 1;
}
else if (structureType == Screeps::STRUCTURE_SPAWN)
{
auto spawn = dynamic_cast<Screeps::StructureSpawn *>(structure.get());
energyCapacity = spawn->store().getFreeCapacity(Screeps::RESOURCE_ENERGY).value();
}
else if (structureType == Screeps::STRUCTURE_EXTENSION)
{
auto extension = dynamic_cast<Screeps::StructureExtension *>(structure.get());
energyCapacity = extension->store().getFreeCapacity(Screeps::RESOURCE_ENERGY).value();
}
if (energyCapacity == 0)
{
searchDeposit();
return nullptr;
}
return std::move(structure);
}
void DouwcoHivemind::HarvesterRole::searchDeposit()
{
int highestEnergyNeed = 0;
Screeps::Structure *selectedStructure;
auto structures = creep.room().find(Screeps::FIND_MY_STRUCTURES);
for (auto &structureObject : structures)
{
auto structure = dynamic_cast<Screeps::Structure *>(structureObject.get());
if (!structure)
continue;
int energyNeed;
auto structureType = structure->structureType();
if (structureType == Screeps::STRUCTURE_SPAWN)
{
auto spawn = dynamic_cast<Screeps::StructureSpawn *>(structure);
energyNeed = spawn->store().getFreeCapacity(Screeps::RESOURCE_ENERGY).value();
}
else if (structureType == Screeps::STRUCTURE_EXTENSION)
{
auto extension = dynamic_cast<Screeps::StructureExtension *>(structure);
energyNeed = extension->store().getFreeCapacity(Screeps::RESOURCE_ENERGY).value();
}
else if (structureType == Screeps::STRUCTURE_CONTROLLER)
{
energyNeed = 1;
}
if (energyNeed > highestEnergyNeed)
{
highestEnergyNeed = energyNeed;
selectedStructure = structure;
}
}
if (selectedStructure)
target_id = selectedStructure->id();
else
target_id.clear();
}
std::unique_ptr<Screeps::RoomObject> DouwcoHivemind::HarvesterRole::getRoomObjectTarget()
{
// Check if game can find target
auto roomObj = Screeps::Game.getObjectById(target_id);
if (!roomObj)
{
JS::console.log(creep.name() + ": Game can\'t find target id");
return nullptr;
}
return std::move(roomObj);
}
bool isNearTo(const Screeps::RoomPosition &pos1, const Screeps::RoomPosition &pos2, int dist)
{
int dx = pos1.x() - pos2.x();
int dy = pos1.y() - pos2.y();
int dist2 = dist * dist;
return dx * dx <= dist2 &&
dy * dy <= dist2 &&
pos1.roomName() == pos2.roomName();
}

33
src/loop.cpp Normal file
View File

@@ -0,0 +1,33 @@
#include <Screeps/Context.hpp>
#include <Screeps/Creep.hpp>
#include <Screeps/StructureSpawn.hpp>
#include <emscripten.h>
#include <emscripten/bind.h>
#include <emscripten/val.h>
#include "Constants.hpp"
#include "Engine.hpp"
#include "Structures/Spawn.hpp"
EMSCRIPTEN_KEEPALIVE
extern "C" void loop()
{
Screeps::Context::update();
JS::console.log(std::string("\n\n\n\n\n\n\n\n\n"));
JS::console.log(std::string("Processing tick:\t") + std::to_string(Screeps::Game.time()));
{
DouwcoHivemind::Engine engine;
engine.loop();
}
JS::console.log("Used CPU:\t" + std::to_string(Screeps::Game.cpuGetUsed()));
JS::console.log("Bucket:\t" + std::to_string(static_cast<int>(Screeps::Game.cpu()["bucket"])));
}
EMSCRIPTEN_BINDINGS(loop)
{
emscripten::function("loop", &loop);
}

28
src/spawn.cpp Normal file
View File

@@ -0,0 +1,28 @@
#include <nlohmann/json.hpp>
#include <Screeps/JS.hpp>
#include <Screeps/Game.hpp>
#include <Screeps/Room.hpp>
#include <Screeps/StructureSpawn.hpp>
#include <emscripten.h>
#include "Constants.hpp"
#include "Structures/Spawn.hpp"
void DouwcoHivemind::Spawn::loop()
{
int creepcount = spawn.room().find(Screeps::FIND_MY_CREEPS).size();
if (creepcount > 10)
{
EM_ASM({ console.log('To much creeps in this room'); });
return;
}
EM_ASM({ console.log('Creating a harvester'); });
JSON opts;
opts["memory"]["role"] = CreepRole::HARVESTER;
int resp = spawn.spawnCreep(
{"work", "carry", "move"},
"harvester" + std::to_string(Screeps::Game.time()),
opts);
}