Skip to content

Commit

Permalink
Reservation, carry, getEnergyFromStorage (#642)
Browse files Browse the repository at this point in the history
- Improve and fix reservation logic. Intended reservered rooms were
  flagged as unreservered
- Reduce code complexity
- New carrys more first to the target before accepting transfers. E.g.
  commodity carry are integrated into the carry network and reached the
  target to late
- Fix getEnergyFromStorage, especially on `misplacedSpawn`
- Adapt code to the quest logic from the documentation
  • Loading branch information
TooAngel authored Apr 18, 2022
1 parent a88c203 commit 8240847
Show file tree
Hide file tree
Showing 21 changed files with 341 additions and 156 deletions.
8 changes: 4 additions & 4 deletions doc/API.md
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ The sign has the format:
"type": "quest",
"id": "QUEST_ID",
"origin": "ROOM_NAME",
"info": "http://tooangel.github.io/screeps",
"info": "http://tooangel.github.io/screeps"
}
```

Expand All @@ -48,6 +48,7 @@ To apply for a Quest send a message via terminal transfer to the `origin` room,
{
"type": "quest",
"id": "QUEST_ID",
"action": "apply"
}
```

Expand All @@ -58,7 +59,6 @@ The actual quest will be send to the room the transfer was initiated from.
Quests can be received from the TooAngel NPC and also send to the TooAngel NPC.
When quests are solved the reputation increases.
When quests are send to the TooAngel NPC the reputation is decreased.
In case quests are requested from the TooAngel NPC, while the reputation is too low, these are not executed and a portion is still reduced as a arrogance (TODO maybe find a better word) fee.

### Quest format

Expand All @@ -69,7 +69,7 @@ Quests are send via terminal transfer:
"type": "quest",
"id": "QUEST_ID",
"room": "ROOM_NAME, in which the quest needs to be solved",
"type": "TYPE OF QUEST",
"quest": "TYPE OF QUEST",
"end": "Game.time when the quest needs to be finished"
}
```
Expand All @@ -85,6 +85,6 @@ Internally the reputation is increased.
{
"type": "quest",
"id": "QUEST_ID",
"result": "won",
"result": "won"
};
```
11 changes: 9 additions & 2 deletions doc/BaseBuilding.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
## Room
# Room

### Setup
## Setup

Positions:
- `upgrader` creep next to the `controller`
Expand All @@ -15,3 +15,10 @@ extension, lab, observer, terminal, tower) next to it. Next to `filler` a link,
tower and power_spawn is located. `Link`s are placed next to the sources and at
the paths to the exits. Layers of walls are placed at the exits, positions
within the precalculated paths are replaced by ramparts.

## Pathing

Paths are precalculated and cached and reused by most of the creeps.

Swamps are ignored because roads will be built automatically over time.
The creeps only move on the precalculated paths (to reduce complexity). Instead, blockers are recognized and `structurer` are sent to destroy the structure, `carry` creeps try it as well.
2 changes: 2 additions & 0 deletions docker-compose-setup.yml
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,8 @@ services:
command: redis-server --loglevel warning
mongo:
image: mongo
volumes:
- ./tmp-test-server-database/:/data/db
ports:
- 27017:27017
command: mongod --quiet --logpath /dev/null
Expand Down
2 changes: 2 additions & 0 deletions docker-compose.yml
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,8 @@ services:
command: redis-server --loglevel warning
mongo:
image: mongo
volumes:
- ./tmp-test-server-database/:/data/db
ports:
- 27017:27017
command: mongod --quiet --logpath /dev/null
Expand Down
2 changes: 1 addition & 1 deletion package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "screeps-bot-tooangel",
"version": "1.4.2",
"version": "1.4.3",
"description": "",
"main": "src/main.js",
"screeps_bot": true,
Expand Down
46 changes: 30 additions & 16 deletions src/brain_nextroom.js
Original file line number Diff line number Diff line change
Expand Up @@ -75,44 +75,58 @@ function getNextRoomValuatedRoomMap(rooms) {
return evaluatedRooms;
}

brain.handleNextroomer = function() {
if (!Memory.myRooms) {
return;
}
if (Memory.myRooms.length >= Game.gcl.level) {
return;
}
if (Game.time % config.nextRoom.intervalToCheck !== 0) {
return;
}
debugLog('nextroomer', 'handleNextroomer !!!!!!!!!!!!!!!!!!!!!!!');
/**
* haveEnoughSystemResources
*
* @return {bool}
*/
function haveEnoughSystemResources() {
if (config.nextRoom.resourceStats) {
debugLog('nextroomer', `stats: ${JSON.stringify(global.stats)}`);
const myRoomsLength = Memory.myRooms.length;
const cpuPerRoom = global.stats.cpuUsed / myRoomsLength;
if (cpuPerRoom > global.stats.cpuIdle) {
debugLog('nextroomer', `not enough cpu: ${cpuPerRoom} > ${global.stats.cpuIdle}`);
return;
return false;
}
const heapPerRoom = global.stats.heapUsed / myRoomsLength;
if (heapPerRoom > global.stats.heapFree) {
debugLog('nextroomer', `not enough heap: ${heapPerRoom} > ${global.stats.heapFree}`);
return;
return false;
}
const memoryPerRoom = global.stats.memoryUsed / myRoomsLength;
if (memoryPerRoom > global.stats.memoryFree) {
debugLog('nextroomer', `not enough heap: ${memoryPerRoom} > ${global.stats.memoryFree}`);
return;
return false;
}
} else {
if (Memory.myRooms.length >= 0) { // config.nextRoom.maxRooms) {
return;
return false;
}

if ((Memory.myRooms.length + 1) * config.nextRoom.cpuPerRoom >= Game.cpu.limit) {
return;
return false;
}
}
return true;
}

brain.handleNextroomer = function() {
if (!Memory.myRooms) {
return;
}
if (Memory.myRooms.length >= Game.gcl.level) {
return;
}
if (Game.time % config.nextRoom.intervalToCheck !== 0) {
return;
}

debugLog('nextroomer', 'handleNextroom !!!!!!!!!!!!!!!!!!!!!!!');
if (!haveEnoughSystemResources()) {
return;
}


debugLog('nextroomer', 'handleNextroomer');

Expand Down
19 changes: 9 additions & 10 deletions src/config.js
Original file line number Diff line number Diff line change
Expand Up @@ -182,7 +182,6 @@ global.config = {
},

external: {
distance: 2,
defendDistance: 1,
checkForReservingInterval: 1499,
},
Expand Down Expand Up @@ -222,15 +221,15 @@ global.config = {

room: {
reservedRCL: {
0: 1,
1: 1,
2: 1,
3: 1,
4: 1,
5: 1,
6: 2,
7: 2,
8: 2,
0: 4,
1: 4,
2: 4,
3: 4,
4: 4,
5: 4,
6: 4,
7: 8,
8: 8,
},
isHealthyStorageThreshold: 50000,
handleNukeAttackInterval: 132,
Expand Down
12 changes: 10 additions & 2 deletions src/diplomacy.js
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@ function checkPlayers() {
module.exports.checkPlayers = checkPlayers;

const findRoomPairs = function(player) {
for (const roomName of Object.keys(player.rooms).sort((a, b) => 0.5 - Math.random())) {
for (const roomName of Object.keys(player.rooms).sort(() => 0.5 - Math.random())) {
debugLog('diplomacy', `findRoomPairs: room ${roomName} data: ${JSON.stringify(global.data.rooms[roomName])}`);
const minRCL = ((global.data.rooms[roomName] || {}).controller || {}).level || 8;
const range = 7;
Expand Down Expand Up @@ -123,7 +123,7 @@ function handleRetaliation(player) {
debugLog('diplomacy', `handleRetaliation: Can not find a fitting room pair`);
return;
}
possibleActions.sort((a, b) => 0.5 - Math.random());
possibleActions.sort(() => 0.5 - Math.random());
debugLog('diplomacy', `Running attach roomPair: ${JSON.stringify(roomPair)} action: ${JSON.stringify(possibleActions[0])}`);
player.lastAttacked = Game.time;
if (config.autoAttack.notify) {
Expand Down Expand Up @@ -166,7 +166,9 @@ function addToReputation(name, value) {
try {
handleRetaliation(player);
} catch (e) {
console.log('addToReputation');
console.log(e);
console.log(e.stack);
}
}
}
Expand All @@ -193,6 +195,12 @@ function initPlayer(name) {
}
module.exports.initPlayer = initPlayer;

/**
* addRoomToPlayer
*
* @param {object} player
* @param {object} room
*/
function addRoomToPlayer(player, room) {
if (!player.rooms) {
player.rooms = {};
Expand Down
6 changes: 6 additions & 0 deletions src/logging.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,9 @@
/**
* debugLog
*
* @param {string} type
* @param {...string} messages
*/
function debugLog(type, ...messages) {
if (config.debug[type]) {
console.log(`${Game.time} ${messages.join(' ')}`);
Expand Down
4 changes: 1 addition & 3 deletions src/prototype_creep.js
Original file line number Diff line number Diff line change
Expand Up @@ -51,14 +51,12 @@ Creep.prototype.mySignController = function() {
if (config.quests.enabled && this.memory.role === 'reserver' && Game.rooms[this.memory.base].terminal) {
if (Math.random() < config.quests.signControllerPercentage) {
const quest = {
type: 'quest',
id: Math.floor(Math.random() * 100000),
origin: this.memory.base,
end: Math.floor(Game.time / 100) * 100 + config.quests.endTime,
type: 'Quest',
info: 'http://tooangel.github.io/screeps',
};
text = JSON.stringify(quest);
// Memory.quests[quest.id] = quest;
this.room.debugLog('quests', `Attach quest: ${text}`);
}
}
Expand Down
90 changes: 0 additions & 90 deletions src/prototype_creep_resources.js
Original file line number Diff line number Diff line change
Expand Up @@ -52,49 +52,6 @@ Creep.prototype.checkCarryEnergyForBringingBackToStorage = function(otherCreep)
return offset + this.store.getUsedCapacity() > carryPercentage * this.store.getCapacity();
};

// return true if helper can't transfer to creep
Creep.prototype.checkHelperNoTransfer = function(creep) {
return creep.memory.base !== this.memory.base;
};

Creep.prototype.findCreepWhichCanTransfer = function(creeps) {
for (let i = 0; i < creeps.length; i++) {
const otherCreep = creeps[i];
if (!Game.creeps[otherCreep.name] || otherCreep.store.getUsedCapacity() < 50 || otherCreep.memory.recycle) {
continue;
}

if (otherCreep.memory.role === 'carry') {
if (otherCreep.checkHelperNoTransfer(this)) {
continue;
}
if (otherCreep.memory.routing.pathPos < 0) {
continue;
}
return this.checkCarryEnergyForBringingBackToStorage(otherCreep);
}
continue;
}
return false;
};

Creep.prototype.checkForTransfer = function(direction) {
if (!direction) {
this.creepLog(`checkForTransfer no direction}`);
return false;
}

const adjacentPos = this.pos.getAdjacentPosition(direction);

if (adjacentPos.isBorder(-2)) {
this.creepLog(`checkForTransfer isBorder}`);
return false;
}

const creeps = adjacentPos.lookFor(LOOK_CREEPS);
return this.findCreepWhichCanTransfer(creeps);
};

Creep.prototype.pickupWhileMoving = function() {
if (this.inBase() && this.memory.routing.pathPos < 2) {
return false;
Expand Down Expand Up @@ -225,53 +182,6 @@ Creep.prototype.pickupEnergy = function() {
return this.giveSourcersEnergy();
};

const checkCreepForTransfer = function(otherCreep, thisCreep) {
if (!Memory.creeps[otherCreep.name]) {
return false;
}
// don't transfer to extractor, fixes full terminal with 80% energy?
if (Memory.creeps[otherCreep.name].role === 'extractor') {
return false;
}
// don't transfer to mineral, fixes full terminal with 80% energy?
if (Memory.creeps[otherCreep.name].role === 'mineral') {
return false;
}
if (!thisCreep.store[RESOURCE_ENERGY] && Memory.creeps[otherCreep.name].role === 'sourcer') {
return false;
}
// Do we want this?
if (Memory.creeps[otherCreep.name].role === 'powertransporter') {
return false;
}
if (otherCreep.store.getFreeCapacity() === 0) {
return false;
}
return true;
};

Creep.prototype.transferToCreep = function(direction) {
const adjacentPos = this.pos.getAdjacentPosition(direction);
if (!adjacentPos.isValid()) {
return false;
}

const creeps = adjacentPos.lookFor('creep');
for (let i = 0; i < creeps.length; i++) {
const otherCreep = creeps[i];
if (!checkCreepForTransfer(otherCreep, this) || this.checkHelperNoTransfer(otherCreep)) {
continue;
}
for (const resource of Object.keys(this.store)) {
const returnCode = this.transfer(otherCreep, resource);
if (returnCode === OK) {
return this.store.getUsedCapacity() * 0.5 <= otherCreep.store.getCapacity() - otherCreep.store.getUsedCapacity();
}
}
}
return false;
};

const canStoreEnergy = function(object) {
const structureTypes = [STRUCTURE_CONTROLLER, STRUCTURE_ROAD, STRUCTURE_WALL, STRUCTURE_RAMPART, STRUCTURE_OBSERVER];
if (structureTypes.indexOf(object.structureType) >= 0) {
Expand Down
6 changes: 5 additions & 1 deletion src/prototype_creep_startup_tasks.js
Original file line number Diff line number Diff line change
Expand Up @@ -165,7 +165,11 @@ Creep.prototype.getEnergyFromStorage = function() {
return false;
}

if (!this.room.memory.misplacedSpawn && this.room.isStruggling()) {
if (this.room.memory.misplacedSpawn) {
return false;
}

if (this.room.isStruggeling()) {
return false;
}

Expand Down
Loading

0 comments on commit 8240847

Please sign in to comment.