feat: better code formatting

This commit is contained in:
2026-04-23 23:03:00 -03:00
parent a3841bd173
commit e18980938e
37 changed files with 1691 additions and 7930 deletions

2
.env Normal file
View File

@@ -0,0 +1,2 @@
SCREEPS_TOKEN=750fa279-9243-42f4-892f-614103d51394
SCREEPS_BRANCH=default

5
.gitignore vendored
View File

@@ -5,3 +5,8 @@
# Screeps Config
.screeps.yml
docker/.env
.env*
.idea/
.vscode/

View File

@@ -2,14 +2,13 @@ servers:
main:
host: screeps.com
secure: true
token: {TOKEN}
token: { TOKEN }
ptr:
host: screeps.com
secure: true
token: {TOKEN}
token: { TOKEN }
ptr: true
configs:
screepsconsole:
maxHistory: 20000

View File

@@ -1,5 +1,3 @@
{
"recommendations": [
"ms-vscode-remote.vscode-remote-extensionpack"
]
"recommendations": ["ms-vscode-remote.vscode-remote-extensionpack"]
}

View File

@@ -3,7 +3,7 @@ import { build } from 'esbuild';
build({
entryPoints: ['src/main.ts'],
bundle: true,
target: 'es6', // Screeps supports ES2018 well
target: 'es2018', // Screeps supports ES2018 well
platform: 'node',
tsconfig: 'tsconfig.json',
format: 'cjs',
@@ -13,6 +13,6 @@ build({
minify: false,
keepNames: true, // optional: keeps function/class names
banner: {
js: `// Vitor Hideyoshi <vitor.h.n.batista@gmail.com> - ${new Date().toISOString()}\n`
js: `// Vitor Hideyoshi <vitor.h.n.batista@gmail.com> - ${new Date().toISOString()}\n`,
},
}).catch(() => process.exit(1));

View File

@@ -1,61 +1,64 @@
const {
defineConfig,
} = require("eslint/config");
const { defineConfig } = require('eslint/config');
const globals = require("globals");
const tsParser = require("@typescript-eslint/parser");
const typescriptEslint = require("@typescript-eslint/eslint-plugin");
const js = require("@eslint/js");
const globals = require('globals');
const tsParser = require('@typescript-eslint/parser');
const typescriptEslint = require('@typescript-eslint/eslint-plugin');
const js = require('@eslint/js');
const {
FlatCompat,
} = require("@eslint/eslintrc");
const { FlatCompat } = require('@eslint/eslintrc');
const compat = new FlatCompat({
baseDirectory: __dirname,
recommendedConfig: js.configs.recommended,
allConfig: js.configs.all
allConfig: js.configs.all,
});
module.exports = defineConfig([{
module.exports = defineConfig([
{
languageOptions: {
globals: {
...globals.browser,
},
parser: tsParser,
"ecmaVersion": "latest",
"sourceType": "module",
ecmaVersion: 'latest',
sourceType: 'module',
parserOptions: {},
},
extends: compat.extends("eslint:recommended", "plugin:@typescript-eslint/recommended", "prettier"),
extends: compat.extends(
'eslint:recommended',
'plugin:@typescript-eslint/recommended',
'prettier'
),
plugins: {
"@typescript-eslint": typescriptEslint,
'@typescript-eslint': typescriptEslint,
},
"rules": {
"@typescript-eslint/no-namespace": "off",
"@typescript-eslint/no-explicit-any": "off",
"@typescript-eslint/no-unused-vars": [
"error",
rules: {
'@typescript-eslint/no-namespace': 'off',
'@typescript-eslint/no-explicit-any': 'off',
'@typescript-eslint/no-unused-vars': [
'error',
{
"argsIgnorePattern": "^_",
"varsIgnorePattern": "^_",
"caughtErrorsIgnorePattern": "^_"
}
argsIgnorePattern: '^_',
varsIgnorePattern: '^_',
caughtErrorsIgnorePattern: '^_',
},
],
},
}, {
},
{
languageOptions: {
globals: {
...globals.node,
},
"sourceType": "script",
sourceType: 'script',
parserOptions: {},
},
files: ["**/.eslintrc.{js,cjs}"],
}]);
files: ['**/.eslintrc.{js,cjs}'],
},
]);

7245
package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@@ -1,59 +1,42 @@
{
"name": "screeps-typescript-starter",
"version": "3.0.0",
"description": "",
"name": "hideyoshi-screeps",
"version": "0.0.0",
"description": "Personal Screeps codebase for Hideyoshi",
"scripts": {
"build": "node esbuild.config.mjs",
"push:main": "npm run build && screeps-api --server main upload dist/*.js",
"push:sim": "npm run build && screeps-api --server main upload --branch sim dist/*.js",
"push:local": "npm run build && screeps-api --server local upload dist/*.js",
"format": "prettier --config .prettierrc 'src/**/*.ts' --write && eslint --fix src/"
},
"repository": {
"type": "git",
"url": "git+https://github.com/screepers/screeps-typescript-starter.git"
},
"author": "",
"license": "Unlicense",
"bugs": {
"url": "https://github.com/screepers/screeps-typescript-starter/issues"
},
"homepage": "https://github.com/screepers/screeps-typescript-starter#readme",
"devDependencies": {
"@eslint/eslintrc": "^3.3.1",
"@eslint/js": "^9.30.1",
"@rollup/plugin-commonjs": "^28.0.6",
"@rollup/plugin-node-resolve": "^16.0.1",
"@types/chai": "^5.2.2",
"@types/lodash": "4.17.20",
"@types/mocha": "^10.0.10",
"@types/node": "^24.0.10",
"@types/screeps": "^3.3.8",
"@types/sinon": "^17.0.4",
"@types/sinon-chai": "^4.0.0",
"@typescript-eslint/eslint-plugin": "^8.35.1",
"@typescript-eslint/parser": "^8.35.1",
"@typescript-eslint/typescript-estree": "^8.35.1",
"chai": "^5.2.0",
"esbuild": "^0.25.5",
"eslint": "^9.30.1",
"eslint-config-prettier": "^10.1.5",
"eslint-import-resolver-typescript": "^4.4.4",
"eslint-plugin-import": "^2.32.0",
"eslint-plugin-prettier": "^5.5.1",
"globals": "^16.3.0",
"lodash": "^4.17.21",
"mocha": "^11.7.1",
"prettier": "^3.6.2",
"screeps-api": "^1.7.2",
"shelljs": "^0.10.0",
"sinon": "^21.0.0",
"sinon-chai": "^4.0.0",
"ts-node": "^10.9.2",
"tsconfig-paths": "^4.2.0",
"typescript": "^5.8.3"
"format": "prettier --check --ignore-path .gitignore .",
"format:fix": "prettier --write --ignore-path .gitignore ."
},
"dependencies": {
"source-map": "~0.7.4"
"@trivago/prettier-plugin-sort-imports": "^6.0.2",
"@types/screeps": "^3.3.8",
"dotenv": "^17.4.2",
"esbuild": "^0.28.0",
"prettier": "^3.8.3",
"ts-node": "^10.9.2",
"typescript": "^6.0.3",
"zod": "^4.3.6"
},
"devDependencies": {
"@types/node": "^25.6.0"
},
"prettier": {
"trailingComma": "es5",
"semi": true,
"tabWidth": 4,
"useTabs": false,
"singleQuote": true,
"jsxSingleQuote": true,
"plugins": [
"@trivago/prettier-plugin-sort-imports"
],
"importOrderParserPlugins": [
"typescript",
"jsx",
"decorators-legacy"
]
}
}

100
publish.ts Normal file
View File

@@ -0,0 +1,100 @@
import * as dotenv from 'dotenv';
import * as fs from 'node:fs';
import { z } from 'zod';
import path = require('node:path');
const EnvVariables = z.object({
DIST_PATH: z.string().default('./dist'),
SCREEPS_SERVER: z.url().default('https://screeps.com'),
SCREEPS_TOKEN: z.string(),
SCREEPS_BRANCH: z.string().default('default'),
});
type EnvVariables = z.infer<typeof EnvVariables>;
const readEnv = (): EnvVariables => {
return EnvVariables.parse(process.env);
};
type ScriptPayload = {
branch: string;
modules: Record<string, string>;
};
type ScreepsHeaders = {
'X-Token': string;
} & object;
const publishScript = async (
screeps_server: string,
payload: ScriptPayload,
headers: ScreepsHeaders
) => {
const resp = await fetch(screeps_server + '/api/user/code', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
...headers,
},
body: JSON.stringify(payload),
});
if (!resp.ok) {
const text = await resp.text();
throw new Error(`Upload failed: ${resp.status} ${text}`);
}
};
const genModuleKey = (filePath: string): string => {
filePath = filePath.split(path.sep).slice(1).join(path.sep);
return filePath.split('.')[0].split(path.sep).join('.');
};
const parseDist = (dist_path: string): Record<string, string> => {
let modules: Record<string, string> = {};
const files = fs.readdirSync(dist_path, { withFileTypes: true });
for (const file of files) {
if (file.isDirectory()) {
const subModules = parseDist(path.join(dist_path, file.name));
modules = {
...modules,
...subModules,
};
continue;
}
if (!file.name.endsWith('.js')) {
continue;
}
const filePath = path.join(dist_path, file.name);
const module_key = genModuleKey(filePath);
modules[module_key] = fs.readFileSync(filePath, 'utf-8');
}
return modules;
};
const main = async () => {
dotenv.config();
const env = readEnv();
const payload: ScriptPayload = {
branch: env.SCREEPS_BRANCH,
modules: parseDist(env.DIST_PATH),
};
console.log(JSON.stringify(payload));
const headers: ScreepsHeaders = {
'X-Token': env.SCREEPS_TOKEN,
};
await publishScript(env.SCREEPS_SERVER, payload, headers);
};
main()
.then(() => {
console.log('Script published successfully!');
})
.catch((error) => {
console.error(error);
});

View File

@@ -1,5 +1,5 @@
import { CreepRole, CreepRoles } from "types/creeps";
import { getRoomCreeps } from "utils/funcs/getRoomCreeps";
import { CreepRole, CreepRoles } from 'types/creeps';
import { getRoomCreeps } from 'utils/funcs/getRoomCreeps';
class CreepRunner {
public static run(room: Room, state: GameState): GameState {
@@ -23,10 +23,14 @@ class CreepRunner {
return state;
}
private static clearDeadCreepMemory(creepName: string, state: GameState): void {
private static clearDeadCreepMemory(
creepName: string,
state: GameState
): void {
console.log(`Creep ${creepName} is dead, cleaning up memory.`);
const roleDefinition = CreepRoles[Memory.creeps[creepName].role as CreepRole];
const roleDefinition =
CreepRoles[Memory.creeps[creepName].role as CreepRole];
roleDefinition.handler.destroy(Memory.creeps[creepName], state);
delete Memory.creeps[creepName]; // Clean up memory for dead creeps

View File

@@ -1,14 +1,14 @@
import { CreepRequisition, CreepRole, CreepRoles } from "types/creeps";
import { DEFAULT_GAME_CONFIG } from "types/gameConfig";
import { get_role_cost } from "utils/funcs/getRoleCost";
import { getRoomCreeps } from "utils/funcs/getRoomCreeps";
import { sortCreepRolesByPriority } from "utils/funcs/sortCreepRolesByPriority";
import { CreepRequisition, CreepRole, CreepRoles } from 'types/creeps';
import { DEFAULT_GAME_CONFIG } from 'types/gameConfig';
import { get_role_cost } from 'utils/funcs/getRoleCost';
import { getRoomCreeps } from 'utils/funcs/getRoomCreeps';
import { sortCreepRolesByPriority } from 'utils/funcs/sortCreepRolesByPriority';
class RequisitionsManager {
public static validateState(room: Room, state: GameState): GameState {
const creepRequisition = this.getRoomRequisition(room);
if (Object.values(creepRequisition).every(count => count <= 0)) {
if (Object.values(creepRequisition).every((count) => count <= 0)) {
return state;
}
@@ -24,7 +24,10 @@ class RequisitionsManager {
return state;
}
private static fulfillSpawnRequisition(spawn: StructureSpawn, creepRequisition: CreepRequisition): boolean {
private static fulfillSpawnRequisition(
spawn: StructureSpawn,
creepRequisition: CreepRequisition
): boolean {
if (spawn.spawning) {
return false;
}
@@ -42,14 +45,18 @@ class RequisitionsManager {
role: role.name,
room: spawn.room.name,
spawnId: spawn.id,
working: false
}
working: false,
},
});
if (spawnResult === OK) {
console.log(`Spawn ${spawn.name} successfully spawned a new ${role.name}: ${newName}.`);
console.log(
`Spawn ${spawn.name} successfully spawned a new ${role.name}: ${newName}.`
);
return true; // Exit after spawning one creep
} else {
console.error(`Spawn ${spawn.name} failed to spawn a new ${role.name}: ${spawnResult}`);
console.error(
`Spawn ${spawn.name} failed to spawn a new ${role.name}: ${spawnResult}`
);
}
}
@@ -66,7 +73,7 @@ class RequisitionsManager {
const requisition: CreepRequisition = {
harvester: 0,
upgrader: 0,
builder: 0
builder: 0,
};
for (const role in DEFAULT_GAME_CONFIG.minCreepsPerRole) {
if (!(role in CreepRoles)) {
@@ -74,7 +81,9 @@ class RequisitionsManager {
continue;
}
const roleType = role as CreepRole;
requisition[roleType] = DEFAULT_GAME_CONFIG.minCreepsPerRole[roleType] - (creepCounts[role] || 0);
requisition[roleType] =
DEFAULT_GAME_CONFIG.minCreepsPerRole[roleType] -
(creepCounts[role] || 0);
if (requisition[roleType] < 0) {
requisition[roleType] = 0; // Ensure we don't have negative requisitions

View File

@@ -1,11 +1,11 @@
import { checkPositionWalkable } from "utils/funcs/checkPosition";
import { checkPositionWalkable } from 'utils/funcs/checkPosition';
import {
createSourcePositionMatrix,
forEachMatrixSpot,
getPositionWithDelta,
PositionSpotStatus,
setSpotStatus
} from "utils/positions";
setSpotStatus,
} from 'utils/positions';
class RoomInspector {
public static inspectState(room: Room, state: GameState): GameState {
@@ -30,29 +30,43 @@ class RoomInspector {
return state;
}
private static configureSourceState(source: Source, state: GameState): void {
private static configureSourceState(
source: Source,
state: GameState
): void {
const sourceId = source.id.toString();
if (!state.sourcesStates[sourceId]) {
state.sourcesStates[sourceId] = {
id: sourceId,
pos: source.pos,
spots: createSourcePositionMatrix()
spots: createSourcePositionMatrix(),
};
}
forEachMatrixSpot(state.sourcesStates[sourceId].spots, (delta, status) => {
forEachMatrixSpot(
state.sourcesStates[sourceId].spots,
(delta, status) => {
if (status !== PositionSpotStatus.UNKNOWN) {
return; // Skip known spots
}
const pos = getPositionWithDelta(source.pos, delta);
if (checkPositionWalkable(pos)) {
setSpotStatus(state.sourcesStates[sourceId].spots, delta, PositionSpotStatus.EMPTY);
setSpotStatus(
state.sourcesStates[sourceId].spots,
delta,
PositionSpotStatus.EMPTY
);
state.maxHarvesters += 1;
} else {
setSpotStatus(state.sourcesStates[sourceId].spots, delta, PositionSpotStatus.INVALID);
setSpotStatus(
state.sourcesStates[sourceId].spots,
delta,
PositionSpotStatus.INVALID
);
}
});
}
);
}
}

View File

@@ -1,6 +1,6 @@
import CreepRunner from "CreepRunner";
import RequisitionsManager from "RequisitionsManager";
import RoomInspector from "RoomInspector";
import CreepRunner from 'CreepRunner';
import RequisitionsManager from 'RequisitionsManager';
import RoomInspector from 'RoomInspector';
class RoomRunner {
public static run(room: Room, state: GameState): GameState {

View File

@@ -1,6 +1,6 @@
import { CreepDestination } from "types/creeps";
import RoomRunner from "RoomRunner";
import { PositionMatrix } from "utils/positions";
import RoomRunner from 'RoomRunner';
import { CreepDestination } from 'types/creeps';
import { PositionMatrix } from 'utils/positions';
declare global {
/*
@@ -56,8 +56,11 @@ export const loop = () => {
Memory.roomStateRegistry[roomName] || {}
);
} catch (error) {
console.log(`Error running RoomRunner for room ${roomName}:`, error);
delete Memory.roomStateRegistry[roomName]
console.log(
`Error running RoomRunner for room ${roomName}:`,
error
);
delete Memory.roomStateRegistry[roomName];
}
}
};

View File

@@ -1,15 +1,20 @@
import { getSourceById, getSpawnById } from "utils/funcs/getById";
import { RoleHandler } from "./BaseHandler.interface";
import { SourceDestination } from "types/creeps";
import { getNextEmptySpot, getPositionWithDelta, PositionSpotStatus, setSpotStatus } from "utils/positions";
import { RoleHandler } from './BaseHandler.interface';
import { SourceDestination } from 'types/creeps';
import { getSourceById, getSpawnById } from 'utils/funcs/getById';
import {
getNextEmptySpot,
getPositionWithDelta,
PositionSpotStatus,
setSpotStatus,
} from 'utils/positions';
class HarvesterHandler extends RoleHandler {
public static destroy(creepMemory: CreepMemory, state: GameState): void {
if (creepMemory.destination?.type === "source") {
if (creepMemory.destination?.type === 'source') {
this.releaseSourceSpot(creepMemory.destination, state);
delete creepMemory.destination; // Clear destination after releasing the spot
}
if (creepMemory.previousDestination?.type === "source") {
if (creepMemory.previousDestination?.type === 'source') {
this.releaseSourceSpot(creepMemory.previousDestination, state);
delete creepMemory.previousDestination; // Clear previous destination after releasing the spot
}
@@ -19,10 +24,10 @@ class HarvesterHandler extends RoleHandler {
this.validateCreepMemory(creep, state);
switch (creep.memory.destination?.type) {
case "spawn":
case 'spawn':
this.onSpawnDestination(creep, state);
break;
case "source":
case 'source':
this.onSourceDestination(creep, state);
break;
default:
@@ -34,7 +39,7 @@ class HarvesterHandler extends RoleHandler {
}
private static validateCreepMemory(creep: Creep, state: GameState) {
if (creep.memory.previousDestination?.type === "source") {
if (creep.memory.previousDestination?.type === 'source') {
setSpotStatus(
state.sourcesStates[creep.memory.previousDestination.id].spots,
creep.memory.previousDestination.sourceSpot,
@@ -47,16 +52,22 @@ class HarvesterHandler extends RoleHandler {
return; // No destination set, nothing to validate
}
if (creep.memory.destination.type === "source" && !creep.store.getFreeCapacity(RESOURCE_ENERGY)) {
if (
creep.memory.destination.type === 'source' &&
!creep.store.getFreeCapacity(RESOURCE_ENERGY)
) {
creep.memory.previousDestination = creep.memory.destination;
creep.memory.destination = {
id: creep.memory.spawnId,
type: "spawn"
type: 'spawn',
};
return;
}
if (creep.memory.destination.type === "spawn" && creep.store.getUsedCapacity(RESOURCE_ENERGY) === 0) {
if (
creep.memory.destination.type === 'spawn' &&
creep.store.getUsedCapacity(RESOURCE_ENERGY) === 0
) {
delete creep.memory.destination; // Clear destination if no energy is available
return;
}
@@ -78,11 +89,15 @@ class HarvesterHandler extends RoleHandler {
continue; // No empty spots available, skip to next source
}
setSpotStatus(sourceState.spots, emptySpot, PositionSpotStatus.OCCUPIED);
setSpotStatus(
sourceState.spots,
emptySpot,
PositionSpotStatus.OCCUPIED
);
creep.memory.destination = {
id: source.id,
type: "source",
sourceSpot: emptySpot
type: 'source',
sourceSpot: emptySpot,
};
return;
}
@@ -91,7 +106,10 @@ class HarvesterHandler extends RoleHandler {
}
private static onSourceDestination(creep: Creep, _state: GameState) {
if (!creep.memory.destination || creep.memory.destination.type !== "source") {
if (
!creep.memory.destination ||
creep.memory.destination.type !== 'source'
) {
console.log(`Creep ${creep.name} has no valid destination set.`);
delete creep.memory.destination;
return;
@@ -104,10 +122,17 @@ class HarvesterHandler extends RoleHandler {
}
if (creep.harvest(source) === ERR_NOT_IN_RANGE) {
const sourceSpotPosition = getPositionWithDelta(source.pos, creep.memory.destination.sourceSpot);
const sourceSpotPosition = getPositionWithDelta(
source.pos,
creep.memory.destination.sourceSpot
);
creep.moveTo(sourceSpotPosition, {
reusePath: 10,
visualizePathStyle: { stroke: "#ffffff", lineStyle: "dashed", strokeWidth: 0.1 }
visualizePathStyle: {
stroke: '#ffffff',
lineStyle: 'dashed',
strokeWidth: 0.1,
},
});
}
}
@@ -116,7 +141,7 @@ class HarvesterHandler extends RoleHandler {
if (creep.memory.destination === undefined) {
creep.memory.destination = {
id: creep.memory.spawnId,
type: "spawn"
type: 'spawn',
};
}
@@ -129,22 +154,29 @@ class HarvesterHandler extends RoleHandler {
if (creep.transfer(spawn, RESOURCE_ENERGY) === ERR_NOT_IN_RANGE) {
creep.moveTo(spawn, {
reusePath: 10,
visualizePathStyle: { stroke: "#ffffff", lineStyle: "dashed", strokeWidth: 0.1 }
visualizePathStyle: {
stroke: '#ffffff',
lineStyle: 'dashed',
strokeWidth: 0.1,
},
});
}
}
private static findClosestSource(creep: Creep, state: GameState): Source[] {
const sources = Object.keys(state.sourcesStates)
.map(sourceId => getSourceById(sourceId))
.filter(source => source !== null)
.map((sourceId) => getSourceById(sourceId))
.filter((source) => source !== null)
.sort((a, b) => creep.pos.getRangeTo(a) - creep.pos.getRangeTo(b));
return sources as Source[];
}
private static releaseSourceSpot(destination: SourceDestination, state: GameState) {
if (!destination || destination.type !== "source") {
private static releaseSourceSpot(
destination: SourceDestination,
state: GameState
) {
if (!destination || destination.type !== 'source') {
return; // Not a source destination, nothing to release
}
@@ -154,7 +186,11 @@ class HarvesterHandler extends RoleHandler {
return;
}
setSpotStatus(sourceState.spots, destination.sourceSpot, PositionSpotStatus.EMPTY);
setSpotStatus(
sourceState.spots,
destination.sourceSpot,
PositionSpotStatus.EMPTY
);
}
}

View File

@@ -1,6 +1,5 @@
import { RoleHandler } from "./BaseHandler.interface";
import HarvesterHandler from "./harvester.handler";
import UpgraderHandler from "./upgrader.handler";
import { RoleHandler } from './BaseHandler.interface';
import HarvesterHandler from './harvester.handler';
import UpgraderHandler from './upgrader.handler';
export { RoleHandler, HarvesterHandler, UpgraderHandler };

View File

@@ -1,15 +1,20 @@
import { getControllerById, getSourceById } from "utils/funcs/getById";
import { RoleHandler } from "./BaseHandler.interface";
import { getNextEmptySpot, PositionSpotStatus, setSpotStatus, getPositionWithDelta } from "utils/positions";
import { SourceDestination } from "types/creeps";
import { RoleHandler } from './BaseHandler.interface';
import { SourceDestination } from 'types/creeps';
import { getControllerById, getSourceById } from 'utils/funcs/getById';
import {
getNextEmptySpot,
PositionSpotStatus,
setSpotStatus,
getPositionWithDelta,
} from 'utils/positions';
class UpgraderHandler extends RoleHandler {
public static destroy(creepMemory: CreepMemory, state: GameState): void {
if (creepMemory.destination?.type === "source") {
if (creepMemory.destination?.type === 'source') {
this.releaseSourceSpot(creepMemory.destination, state);
delete creepMemory.destination; // Clear destination after releasing the spot
}
if (creepMemory.previousDestination?.type === "source") {
if (creepMemory.previousDestination?.type === 'source') {
this.releaseSourceSpot(creepMemory.previousDestination, state);
delete creepMemory.previousDestination; // Clear previous destination after releasing the spot
}
@@ -19,10 +24,10 @@ class UpgraderHandler extends RoleHandler {
this.validateCreepMemory(creep, state);
switch (creep.memory.destination?.type) {
case "controller":
case 'controller':
this.onControllerDestination(creep, state);
break;
case "source":
case 'source':
this.onSourceDestination(creep, state);
break;
default:
@@ -34,7 +39,10 @@ class UpgraderHandler extends RoleHandler {
}
private static validateCreepMemory(creep: Creep, state: GameState) {
if (!!creep.memory.previousDestination && creep.memory.previousDestination.type === "source") {
if (
!!creep.memory.previousDestination &&
creep.memory.previousDestination.type === 'source'
) {
setSpotStatus(
state.sourcesStates[creep.memory.previousDestination.id].spots,
creep.memory.previousDestination.sourceSpot,
@@ -47,23 +55,31 @@ class UpgraderHandler extends RoleHandler {
return; // No destination set, nothing to validate
}
if (creep.memory.destination.type === "source" && !creep.store.getFreeCapacity(RESOURCE_ENERGY)) {
if (
creep.memory.destination.type === 'source' &&
!creep.store.getFreeCapacity(RESOURCE_ENERGY)
) {
creep.memory.previousDestination = creep.memory.destination;
if (!creep.room.controller) {
console.log(`Creep ${creep.name} has no valid controller to upgrade.`);
console.log(
`Creep ${creep.name} has no valid controller to upgrade.`
);
delete creep.memory.destination;
return;
}
creep.memory.destination = {
id: creep.room.controller.id,
type: "controller"
type: 'controller',
};
return;
}
if (creep.memory.destination.type === "controller" && creep.store.getUsedCapacity(RESOURCE_ENERGY) === 0) {
if (
creep.memory.destination.type === 'controller' &&
creep.store.getUsedCapacity(RESOURCE_ENERGY) === 0
) {
delete creep.memory.destination; // Clear destination if no energy is available
return;
}
@@ -85,11 +101,15 @@ class UpgraderHandler extends RoleHandler {
continue; // No empty spots available, skip to next source
}
setSpotStatus(sourceState.spots, emptySpot, PositionSpotStatus.OCCUPIED);
setSpotStatus(
sourceState.spots,
emptySpot,
PositionSpotStatus.OCCUPIED
);
creep.memory.destination = {
id: source.id,
type: "source",
sourceSpot: emptySpot
type: 'source',
sourceSpot: emptySpot,
};
return;
}
@@ -98,7 +118,10 @@ class UpgraderHandler extends RoleHandler {
}
private static onSourceDestination(creep: Creep, _state: GameState) {
if (!creep.memory.destination || creep.memory.destination.type !== "source") {
if (
!creep.memory.destination ||
creep.memory.destination.type !== 'source'
) {
console.log(`Creep ${creep.name} has no valid destination set.`);
delete creep.memory.destination;
return;
@@ -111,10 +134,17 @@ class UpgraderHandler extends RoleHandler {
}
if (creep.harvest(source) === ERR_NOT_IN_RANGE) {
const sourceSpotPosition = getPositionWithDelta(source.pos, creep.memory.destination.sourceSpot);
const sourceSpotPosition = getPositionWithDelta(
source.pos,
creep.memory.destination.sourceSpot
);
creep.moveTo(sourceSpotPosition, {
reusePath: 10,
visualizePathStyle: { stroke: "#ffffff", lineStyle: "dashed", strokeWidth: 0.1 }
visualizePathStyle: {
stroke: '#ffffff',
lineStyle: 'dashed',
strokeWidth: 0.1,
},
});
}
}
@@ -122,13 +152,15 @@ class UpgraderHandler extends RoleHandler {
private static onControllerDestination(creep: Creep, _state: GameState) {
if (creep.memory.destination === undefined) {
if (!creep.room.controller) {
console.log(`Creep ${creep.name} has no valid controller to upgrade.`);
console.log(
`Creep ${creep.name} has no valid controller to upgrade.`
);
delete creep.memory.destination;
return;
}
creep.memory.destination = {
id: creep.room.controller.id,
type: "controller"
type: 'controller',
};
}
@@ -141,22 +173,29 @@ class UpgraderHandler extends RoleHandler {
if (creep.upgradeController(controller) === ERR_NOT_IN_RANGE) {
creep.moveTo(controller, {
reusePath: 10,
visualizePathStyle: { stroke: "#ffffff", lineStyle: "dashed", strokeWidth: 0.1 }
visualizePathStyle: {
stroke: '#ffffff',
lineStyle: 'dashed',
strokeWidth: 0.1,
},
});
}
}
private static findClosestSource(creep: Creep, state: GameState): Source[] {
const sources = Object.keys(state.sourcesStates)
.map(sourceId => getSourceById(sourceId))
.filter(source => source !== null)
.map((sourceId) => getSourceById(sourceId))
.filter((source) => source !== null)
.sort((a, b) => creep.pos.getRangeTo(a) - creep.pos.getRangeTo(b));
return sources as Source[];
}
private static releaseSourceSpot(destination: SourceDestination, state: GameState) {
if (!destination || destination.type !== "source") {
private static releaseSourceSpot(
destination: SourceDestination,
state: GameState
) {
if (!destination || destination.type !== 'source') {
return; // Not a source destination, nothing to release
}
@@ -166,7 +205,11 @@ class UpgraderHandler extends RoleHandler {
return;
}
setSpotStatus(sourceState.spots, destination.sourceSpot, PositionSpotStatus.EMPTY);
setSpotStatus(
sourceState.spots,
destination.sourceSpot,
PositionSpotStatus.EMPTY
);
}
}

View File

@@ -1,5 +1,5 @@
import { HarvesterHandler, RoleHandler, UpgraderHandler } from "roleHandlers";
import { PositionDelta } from "utils/positions";
import { HarvesterHandler, RoleHandler, UpgraderHandler } from 'roleHandlers';
import { PositionDelta } from 'utils/positions';
export type RoleDefinition = {
name: string;
@@ -10,23 +10,23 @@ export type RoleDefinition = {
export const CreepRoles = {
harvester: {
name: "harvester",
name: 'harvester',
body: [WORK, CARRY, MOVE],
handler: HarvesterHandler,
priority: 1
priority: 1,
},
upgrader: {
name: "upgrader",
name: 'upgrader',
body: [WORK, CARRY, MOVE],
handler: UpgraderHandler,
priority: 2
priority: 2,
},
builder: {
name: "builder",
name: 'builder',
body: [WORK, CARRY, MOVE],
handler: HarvesterHandler,
priority: 3
}
priority: 3,
},
} satisfies Record<string, RoleDefinition>;
export type CreepRole = keyof typeof CreepRoles;
@@ -35,23 +35,23 @@ export type CreepRequisition = Record<CreepRole, number>;
export type SpawnDestination = {
id: string; // ID of the spawn
type: "spawn";
type: 'spawn';
};
export type SourceDestination = {
id: string; // ID of the source
type: "source";
type: 'source';
sourceSpot: PositionDelta; // Position delta for the source spot
};
export type ControllerDestination = {
id: string; // ID of the controller
type: "controller";
type: 'controller';
};
export type ConstructionSiteDestination = {
id: string; // ID of the construction site
type: "constructionSite";
type: 'constructionSite';
};
export type CreepDestination =

View File

@@ -1,4 +1,4 @@
import { CreepRequisition } from "./creeps";
import { CreepRequisition } from './creeps';
/**
* Configuration for the game, defining limits and minimum requirements for creeps.
@@ -22,6 +22,6 @@ export const DEFAULT_GAME_CONFIG: GameConfig = {
minCreepsPerRole: {
harvester: 3,
upgrader: 7,
builder: 0
}
builder: 0,
},
};

View File

@@ -1,5 +1,5 @@
export const checkPositionWalkable = (pos: RoomPosition) => {
// Check if the position is not obstructed by a wall
const terrain = pos.lookFor(LOOK_TERRAIN);
return terrain.length === 0 || terrain[0] !== "wall";
return terrain.length === 0 || terrain[0] !== 'wall';
};

View File

@@ -1,6 +1,8 @@
export const getSourceById = (sourceId: string): Source | null => {
if (!sourceId) {
console.log("getSourceById called with an empty or undefined sourceId.");
console.log(
'getSourceById called with an empty or undefined sourceId.'
);
return null;
}
@@ -15,7 +17,7 @@ export const getSourceById = (sourceId: string): Source | null => {
export const getSpawnById = (spawnId: string): StructureSpawn | null => {
if (!spawnId) {
console.log("getSpawnById called with an empty or undefined spawnId.");
console.log('getSpawnById called with an empty or undefined spawnId.');
return null;
}
@@ -28,9 +30,13 @@ export const getSpawnById = (spawnId: string): StructureSpawn | null => {
return spawn;
};
export const getControllerById = (controllerId: string): StructureController | null => {
export const getControllerById = (
controllerId: string
): StructureController | null => {
if (!controllerId) {
console.log("getControllerById called with an empty or undefined controllerId.");
console.log(
'getControllerById called with an empty or undefined controllerId.'
);
return null;
}

View File

@@ -1,4 +1,4 @@
import { RoleDefinition } from "types/creeps";
import { RoleDefinition } from 'types/creeps';
export const get_role_cost = (role: RoleDefinition) => {
return role.body.reduce((cost, part) => {

View File

@@ -1,6 +1,6 @@
export const getRoomCreeps = (room: Room): Record<string, CreepMemory> => {
return Object.keys(Memory.creeps)
.filter(name => Memory.creeps[name].room === room.name)
.filter((name) => Memory.creeps[name].room === room.name)
.reduce((creeps: Record<string, CreepMemory>, creepName: string) => {
creeps[creepName] = Memory.creeps[creepName];
return creeps;

View File

@@ -1,8 +1,15 @@
import { CreepRequisition, CreepRole, CreepRoles, RoleDefinition } from "types/creeps";
import {
CreepRequisition,
CreepRole,
CreepRoles,
RoleDefinition,
} from 'types/creeps';
export const sortCreepRolesByPriority = (requisition: CreepRequisition): RoleDefinition[] => {
export const sortCreepRolesByPriority = (
requisition: CreepRequisition
): RoleDefinition[] => {
return Object.keys(requisition)
.filter(role => requisition[role as CreepRole] > 0)
.map(role => CreepRoles[role as CreepRole])
.filter((role) => requisition[role as CreepRole] > 0)
.map((role) => CreepRoles[role as CreepRole])
.sort((a, b) => a.priority - b.priority);
};

View File

@@ -1,12 +1,16 @@
import { PositionSpotStatus, PositionDeltaValue, PositionMatrix, PositionDelta } from "./position.types";
import {
createSourcePositionMatrix,
forEachMatrixSpot,
getNextEmptySpot,
setSpotStatus,
getPositionWithDelta
} from "./position.funcs";
getPositionWithDelta,
} from './position.funcs';
import {
PositionSpotStatus,
PositionDeltaValue,
PositionMatrix,
PositionDelta,
} from './position.types';
export {
PositionSpotStatus,
@@ -17,5 +21,5 @@ export {
forEachMatrixSpot,
getNextEmptySpot,
setSpotStatus,
getPositionWithDelta
getPositionWithDelta,
};

View File

@@ -1,4 +1,9 @@
import { PositionDelta, PositionDeltaValue, PositionMatrix, PositionSpotStatus } from "./position.types";
import {
PositionDelta,
PositionDeltaValue,
PositionMatrix,
PositionSpotStatus,
} from './position.types';
/**
* Represents a point in the matrix with x and y coordinates.
@@ -23,7 +28,9 @@ const indexToMatrixPoint = (index: number): MatrixPoint => {
* The center of the matrix is always `PositionSpotStatus.CENTER`.
* The default value is used for all other spots.
*/
export const createSourcePositionMatrix = (default_value?: PositionSpotStatus): PositionMatrix => {
export const createSourcePositionMatrix = (
default_value?: PositionSpotStatus
): PositionMatrix => {
const center_value = PositionSpotStatus.CENTER;
default_value = default_value || PositionSpotStatus.UNKNOWN;
@@ -37,15 +44,19 @@ export const createSourcePositionMatrix = (default_value?: PositionSpotStatus):
default_value,
default_value,
default_value,
default_value
default_value,
];
};
/**
* Gets the next empty spot in the matrix.
*/
export const getNextEmptySpot = (matrix: PositionMatrix): PositionDelta | null => {
const index = matrix.findIndex(status => status === PositionSpotStatus.EMPTY);
export const getNextEmptySpot = (
matrix: PositionMatrix
): PositionDelta | null => {
const index = matrix.findIndex(
(status) => status === PositionSpotStatus.EMPTY
);
if (index === -1) {
return null; // No empty spot found
@@ -58,9 +69,15 @@ export const getNextEmptySpot = (matrix: PositionMatrix): PositionDelta | null =
* Sets the status of a spot in the matrix.
* Throws an error if the delta is out of bounds.
*/
export const setSpotStatus = (matrix: PositionMatrix, delta: PositionDelta, status: PositionSpotStatus): void => {
export const setSpotStatus = (
matrix: PositionMatrix,
delta: PositionDelta,
status: PositionSpotStatus
): void => {
if (delta < 0 || delta >= matrix.length) {
throw new Error(`Invalid delta: ${delta}. Must be between 0 and ${matrix.length - 1}.`);
throw new Error(
`Invalid delta: ${delta}. Must be between 0 and ${matrix.length - 1}.`
);
}
matrix[delta] = status;
};
@@ -68,9 +85,16 @@ export const setSpotStatus = (matrix: PositionMatrix, delta: PositionDelta, stat
/**
* Gets the position with a delta applied to the given RoomPosition.
*/
export const getPositionWithDelta = (pos: RoomPosition, delta: PositionDelta): RoomPosition => {
export const getPositionWithDelta = (
pos: RoomPosition,
delta: PositionDelta
): RoomPosition => {
const matrixPoint = indexToMatrixPoint(delta as number);
return new RoomPosition(pos.x + matrixPoint.x, pos.y + matrixPoint.y, pos.roomName);
return new RoomPosition(
pos.x + matrixPoint.x,
pos.y + matrixPoint.y,
pos.roomName
);
};
/**

View File

@@ -2,14 +2,15 @@
* Represents the status of a position spot
*/
export const PositionSpotStatus = {
INVALID: "-2",
CENTER: "-1",
UNKNOWN: "0",
EMPTY: "1",
OCCUPIED: "2"
INVALID: '-2',
CENTER: '-1',
UNKNOWN: '0',
EMPTY: '1',
OCCUPIED: '2',
} as const;
export type PositionSpotStatus = (typeof PositionSpotStatus)[keyof typeof PositionSpotStatus];
export type PositionSpotStatus =
(typeof PositionSpotStatus)[keyof typeof PositionSpotStatus];
/**
* Represents dislocation to be applied a axis to a position relative to a source or a point of interest.
@@ -30,7 +31,7 @@ export type PositionMatrix = [
PositionSpotStatus,
PositionSpotStatus,
PositionSpotStatus,
PositionSpotStatus
PositionSpotStatus,
];
// Valid indices for the 3x3 matrix (0-8)

View File

@@ -33,7 +33,13 @@ class IntegrationTestHelper {
const modules = {
main: readFileSync(DIST_MAIN_JS).toString(),
};
this._player = await this._server.world.addBot({ username: 'player', room: 'W0N1', x: 15, y: 15, modules });
this._player = await this._server.world.addBot({
username: 'player',
room: 'W0N1',
x: 15,
y: 15,
modules,
});
// Start server
await this._server.start();

View File

@@ -1,15 +1,15 @@
import {assert} from "chai";
import {helper} from "./helper";
import { helper } from './helper';
import { assert } from 'chai';
describe("main", () => {
it("runs a server and matches the game tick", async function () {
describe('main', () => {
it('runs a server and matches the game tick', async function () {
for (let i = 1; i < 10; i += 1) {
assert.equal(await helper.server.world.gameTime, i);
await helper.server.tick();
}
});
it("writes and reads to memory", async function () {
it('writes and reads to memory', async function () {
await helper.player.console(`Memory.foo = 'bar'`);
await helper.server.tick();
const memory = JSON.parse(await helper.player.memory);

View File

@@ -6,4 +6,4 @@ global.sinon = require('sinon');
global.chai.use(require('sinon-chai'));
// Override ts-node compiler options
process.env.TS_NODE_PROJECT = 'tsconfig.test.json'
process.env.TS_NODE_PROJECT = 'tsconfig.test.json';

View File

@@ -1,8 +1,8 @@
import {assert} from "chai";
import {loop} from "../../src/main";
import {Game, Memory} from "./mock"
import { loop } from '../../src/main';
import { Game, Memory } from './mock';
import { assert } from 'chai';
describe("main", () => {
describe('main', () => {
before(() => {
// runs before all test in this block
});
@@ -15,19 +15,19 @@ describe("main", () => {
global.Memory = _.clone(Memory);
});
it("should export a loop function", () => {
assert.isTrue(typeof loop === "function");
it('should export a loop function', () => {
assert.isTrue(typeof loop === 'function');
});
it("should return void when called with no context", () => {
it('should return void when called with no context', () => {
assert.isUndefined(loop());
});
it("Automatically delete memory of missing creeps", () => {
Memory.creeps.persistValue = "any value";
Memory.creeps.notPersistValue = "any value";
it('Automatically delete memory of missing creeps', () => {
Memory.creeps.persistValue = 'any value';
Memory.creeps.notPersistValue = 'any value';
Game.creeps.persistValue = "any value";
Game.creeps.persistValue = 'any value';
loop();

View File

@@ -7,11 +7,11 @@ export const Game: {
creeps: {},
rooms: [],
spawns: {},
time: 12345
time: 12345,
};
export const Memory: {
creeps: { [name: string]: any };
} = {
creeps: {}
creeps: {},
};

View File

@@ -16,8 +16,8 @@
"sourceMap": true,
"experimentalDecorators": true,
"allowSyntheticDefaultImports": true,
"types": ["screeps"]
"types": ["node", "screeps"]
},
"include": ["src/**/*", "src/RequisitionsManager.ts"],
"include": ["src/*.ts", "src/**/*.ts"],
"exclude": ["node_modules", "dist"]
}