Compare commits
10 Commits
restructur
...
main
| Author | SHA1 | Date | |
|---|---|---|---|
|
1c75030ef4
|
|||
|
a60e686407
|
|||
|
dda6942228
|
|||
|
90701eec3d
|
|||
|
e18980938e
|
|||
|
a3841bd173
|
|||
|
a4b8081006
|
|||
|
f8bb65c0f4
|
|||
|
be66fe0822
|
|||
|
fb689cc300
|
2
.env
Normal file
2
.env
Normal file
@@ -0,0 +1,2 @@
|
|||||||
|
SCREEPS_TOKEN=750fa279-9243-42f4-892f-614103d51394
|
||||||
|
SCREEPS_BRANCH=default
|
||||||
6
.gitignore
vendored
6
.gitignore
vendored
@@ -4,3 +4,9 @@
|
|||||||
|
|
||||||
# Screeps Config
|
# Screeps Config
|
||||||
.screeps.yml
|
.screeps.yml
|
||||||
|
docker/.env
|
||||||
|
|
||||||
|
.env*
|
||||||
|
|
||||||
|
.idea/
|
||||||
|
.vscode/
|
||||||
@@ -1,9 +0,0 @@
|
|||||||
{
|
|
||||||
"semi": true,
|
|
||||||
"tabWidth": 4,
|
|
||||||
"printWidth": 120,
|
|
||||||
"singleQuote": false,
|
|
||||||
"trailingComma": "none",
|
|
||||||
"arrowParens": "avoid",
|
|
||||||
"endOfLine": "auto"
|
|
||||||
}
|
|
||||||
@@ -1,16 +0,0 @@
|
|||||||
servers:
|
|
||||||
main:
|
|
||||||
host: screeps.com
|
|
||||||
secure: true
|
|
||||||
token: {TOKEN}
|
|
||||||
ptr:
|
|
||||||
host: screeps.com
|
|
||||||
secure: true
|
|
||||||
token: {TOKEN}
|
|
||||||
ptr: true
|
|
||||||
|
|
||||||
|
|
||||||
configs:
|
|
||||||
screepsconsole:
|
|
||||||
maxHistory: 20000
|
|
||||||
maxScroll: 20000
|
|
||||||
4
.vscode/extensions.json
vendored
4
.vscode/extensions.json
vendored
@@ -1,5 +1,3 @@
|
|||||||
{
|
{
|
||||||
"recommendations": [
|
"recommendations": ["ms-vscode-remote.vscode-remote-extensionpack"]
|
||||||
"ms-vscode-remote.vscode-remote-extensionpack"
|
|
||||||
]
|
|
||||||
}
|
}
|
||||||
|
|||||||
1
docker/.env.sample
Normal file
1
docker/.env.sample
Normal file
@@ -0,0 +1 @@
|
|||||||
|
STEAM_KEY="<https://steamcommunity.com/dev/apikey>"
|
||||||
21
docker/config.yml
Normal file
21
docker/config.yml
Normal file
@@ -0,0 +1,21 @@
|
|||||||
|
serverConfig:
|
||||||
|
tickRate: 100
|
||||||
|
whitelist:
|
||||||
|
- YoshiUnfriendly
|
||||||
|
gclToCPU: true
|
||||||
|
maxCPU: 100
|
||||||
|
baseCPU: 20
|
||||||
|
stepCPU: 10
|
||||||
|
|
||||||
|
mods:
|
||||||
|
- screepsmod-auth
|
||||||
|
- screepsmod-admin-utils
|
||||||
|
- screepsmod-mongo
|
||||||
|
bots:
|
||||||
|
simplebot: screepsbot-zeswarm
|
||||||
|
|
||||||
|
launcherOptions:
|
||||||
|
# If set, automatically ensures all mods are updated
|
||||||
|
autoUpdate: false
|
||||||
|
# If set, forward console messages to terminal
|
||||||
|
logConsole: false
|
||||||
38
docker/docker-compose.yml
Normal file
38
docker/docker-compose.yml
Normal file
@@ -0,0 +1,38 @@
|
|||||||
|
services:
|
||||||
|
mongo:
|
||||||
|
container_name: screeps-mongo
|
||||||
|
image: mongo:4.4.18
|
||||||
|
volumes:
|
||||||
|
- mongo-data:/data/db
|
||||||
|
restart: unless-stopped
|
||||||
|
|
||||||
|
redis:
|
||||||
|
container_name: screeps-redis
|
||||||
|
image: redis:7
|
||||||
|
volumes:
|
||||||
|
- redis-data:/data
|
||||||
|
restart: unless-stopped
|
||||||
|
|
||||||
|
screeps:
|
||||||
|
container_name: screeps-server
|
||||||
|
image: ghcr.io/jomik/screeps-server:edge
|
||||||
|
depends_on:
|
||||||
|
- mongo
|
||||||
|
- redis
|
||||||
|
ports:
|
||||||
|
- 21025:21025
|
||||||
|
environment:
|
||||||
|
MONGO_HOST: mongo
|
||||||
|
REDIS_HOST: redis
|
||||||
|
STEAM_KEY: ${STEAM_KEY:?"Missing steam key"}
|
||||||
|
volumes:
|
||||||
|
- ./config.yml:/screeps/config.yml
|
||||||
|
- screeps-data:/data
|
||||||
|
- screeps-mods:/screeps/mods
|
||||||
|
restart: unless-stopped
|
||||||
|
|
||||||
|
volumes:
|
||||||
|
screeps-data:
|
||||||
|
screeps-mods:
|
||||||
|
redis-data:
|
||||||
|
mongo-data:
|
||||||
@@ -1,18 +1,18 @@
|
|||||||
import { build } from 'esbuild';
|
import { build } from 'esbuild';
|
||||||
|
|
||||||
build({
|
build({
|
||||||
entryPoints: ['src/main.ts'],
|
entryPoints: ['src/main.ts'],
|
||||||
bundle: true,
|
bundle: true,
|
||||||
target: 'es6', // Screeps supports ES2018 well
|
target: 'es2018', // Screeps supports ES2018 well
|
||||||
platform: 'node',
|
platform: 'node',
|
||||||
tsconfig: 'tsconfig.json',
|
tsconfig: 'tsconfig.json',
|
||||||
format: 'cjs',
|
format: 'cjs',
|
||||||
outdir: 'dist',
|
outdir: 'dist',
|
||||||
sourcemap: true,
|
sourcemap: true,
|
||||||
logLevel: 'info',
|
logLevel: 'info',
|
||||||
minify: false,
|
minify: false,
|
||||||
keepNames: true, // optional: keeps function/class names
|
keepNames: true, // optional: keeps function/class names
|
||||||
banner: {
|
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));
|
}).catch(() => process.exit(1));
|
||||||
|
|||||||
@@ -1,61 +1,64 @@
|
|||||||
const {
|
const { defineConfig } = require('eslint/config');
|
||||||
defineConfig,
|
|
||||||
} = require("eslint/config");
|
|
||||||
|
|
||||||
const globals = require("globals");
|
const globals = require('globals');
|
||||||
const tsParser = require("@typescript-eslint/parser");
|
const tsParser = require('@typescript-eslint/parser');
|
||||||
const typescriptEslint = require("@typescript-eslint/eslint-plugin");
|
const typescriptEslint = require('@typescript-eslint/eslint-plugin');
|
||||||
const js = require("@eslint/js");
|
const js = require('@eslint/js');
|
||||||
|
|
||||||
const {
|
const { FlatCompat } = require('@eslint/eslintrc');
|
||||||
FlatCompat,
|
|
||||||
} = require("@eslint/eslintrc");
|
|
||||||
|
|
||||||
const compat = new FlatCompat({
|
const compat = new FlatCompat({
|
||||||
baseDirectory: __dirname,
|
baseDirectory: __dirname,
|
||||||
recommendedConfig: js.configs.recommended,
|
recommendedConfig: js.configs.recommended,
|
||||||
allConfig: js.configs.all
|
allConfig: js.configs.all,
|
||||||
});
|
});
|
||||||
|
|
||||||
module.exports = defineConfig([{
|
module.exports = defineConfig([
|
||||||
languageOptions: {
|
{
|
||||||
globals: {
|
languageOptions: {
|
||||||
...globals.browser,
|
globals: {
|
||||||
|
...globals.browser,
|
||||||
|
},
|
||||||
|
|
||||||
|
parser: tsParser,
|
||||||
|
ecmaVersion: 'latest',
|
||||||
|
sourceType: 'module',
|
||||||
|
parserOptions: {},
|
||||||
},
|
},
|
||||||
|
|
||||||
parser: tsParser,
|
extends: compat.extends(
|
||||||
"ecmaVersion": "latest",
|
'eslint:recommended',
|
||||||
"sourceType": "module",
|
'plugin:@typescript-eslint/recommended',
|
||||||
parserOptions: {},
|
'prettier'
|
||||||
},
|
),
|
||||||
|
|
||||||
extends: compat.extends("eslint:recommended", "plugin:@typescript-eslint/recommended", "prettier"),
|
plugins: {
|
||||||
|
'@typescript-eslint': typescriptEslint,
|
||||||
plugins: {
|
|
||||||
"@typescript-eslint": typescriptEslint,
|
|
||||||
},
|
|
||||||
|
|
||||||
"rules": {
|
|
||||||
"@typescript-eslint/no-namespace": "off",
|
|
||||||
"@typescript-eslint/no-explicit-any": "off",
|
|
||||||
"@typescript-eslint/no-unused-vars": [
|
|
||||||
"error",
|
|
||||||
{
|
|
||||||
"argsIgnorePattern": "^_",
|
|
||||||
"varsIgnorePattern": "^_",
|
|
||||||
"caughtErrorsIgnorePattern": "^_"
|
|
||||||
}
|
|
||||||
],
|
|
||||||
},
|
|
||||||
}, {
|
|
||||||
languageOptions: {
|
|
||||||
globals: {
|
|
||||||
...globals.node,
|
|
||||||
},
|
},
|
||||||
|
|
||||||
"sourceType": "script",
|
rules: {
|
||||||
parserOptions: {},
|
'@typescript-eslint/no-namespace': 'off',
|
||||||
|
'@typescript-eslint/no-explicit-any': 'off',
|
||||||
|
'@typescript-eslint/no-unused-vars': [
|
||||||
|
'error',
|
||||||
|
{
|
||||||
|
argsIgnorePattern: '^_',
|
||||||
|
varsIgnorePattern: '^_',
|
||||||
|
caughtErrorsIgnorePattern: '^_',
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
},
|
},
|
||||||
|
{
|
||||||
|
languageOptions: {
|
||||||
|
globals: {
|
||||||
|
...globals.node,
|
||||||
|
},
|
||||||
|
|
||||||
files: ["**/.eslintrc.{js,cjs}"],
|
sourceType: 'script',
|
||||||
}]);
|
parserOptions: {},
|
||||||
|
},
|
||||||
|
|
||||||
|
files: ['**/.eslintrc.{js,cjs}'],
|
||||||
|
},
|
||||||
|
]);
|
||||||
|
|||||||
12488
package-lock.json
generated
12488
package-lock.json
generated
File diff suppressed because it is too large
Load Diff
117
package.json
117
package.json
@@ -1,58 +1,63 @@
|
|||||||
{
|
{
|
||||||
"name": "screeps-typescript-starter",
|
"name": "hideyoshi-screeps",
|
||||||
"version": "3.0.0",
|
"version": "0.0.0",
|
||||||
"description": "",
|
"description": "Personal Screeps codebase for Hideyoshi",
|
||||||
"scripts": {
|
"scripts": {
|
||||||
"build": "node esbuild.config.mjs",
|
"build": "node esbuild.config.mjs",
|
||||||
"push:main": "npm run build && screeps-api --server main upload dist/*.js",
|
"push": "npm run build && ts-node publish.ts",
|
||||||
"push:sim": "npm run build && screeps-api --server main upload --branch sim dist/*.js",
|
"format": "prettier --check --ignore-path .gitignore .",
|
||||||
"format": "prettier --config .prettierrc 'src/**/*.ts' --write && eslint --fix src/"
|
"format:fix": "prettier --write --ignore-path .gitignore .",
|
||||||
},
|
"test": "jest"
|
||||||
"repository": {
|
},
|
||||||
"type": "git",
|
"dependencies": {
|
||||||
"url": "git+https://github.com/screepers/screeps-typescript-starter.git"
|
"@trivago/prettier-plugin-sort-imports": "^6.0.2",
|
||||||
},
|
"@types/screeps": "^3.3.8",
|
||||||
"author": "",
|
"dotenv": "^17.4.2",
|
||||||
"license": "Unlicense",
|
"esbuild": "^0.28.0",
|
||||||
"bugs": {
|
"jest": "^30.3.0",
|
||||||
"url": "https://github.com/screepers/screeps-typescript-starter/issues"
|
"prettier": "^3.8.3",
|
||||||
},
|
"ts-jest": "^29.4.9",
|
||||||
"homepage": "https://github.com/screepers/screeps-typescript-starter#readme",
|
"ts-node": "^10.9.2",
|
||||||
"devDependencies": {
|
"typescript": "^6.0.3",
|
||||||
"@eslint/eslintrc": "^3.3.1",
|
"zod": "^4.3.6"
|
||||||
"@eslint/js": "^9.30.1",
|
},
|
||||||
"@rollup/plugin-commonjs": "^28.0.6",
|
"devDependencies": {
|
||||||
"@rollup/plugin-node-resolve": "^16.0.1",
|
"@types/jest": "^30.0.0",
|
||||||
"@types/chai": "^5.2.2",
|
"@types/node": "^25.6.0"
|
||||||
"@types/lodash": "4.17.20",
|
},
|
||||||
"@types/mocha": "^10.0.10",
|
"prettier": {
|
||||||
"@types/node": "^24.0.10",
|
"trailingComma": "es5",
|
||||||
"@types/screeps": "^3.3.8",
|
"semi": true,
|
||||||
"@types/sinon": "^17.0.4",
|
"tabWidth": 4,
|
||||||
"@types/sinon-chai": "^4.0.0",
|
"useTabs": false,
|
||||||
"@typescript-eslint/eslint-plugin": "^8.35.1",
|
"singleQuote": true,
|
||||||
"@typescript-eslint/parser": "^8.35.1",
|
"jsxSingleQuote": true,
|
||||||
"@typescript-eslint/typescript-estree": "^8.35.1",
|
"plugins": [
|
||||||
"chai": "^5.2.0",
|
"@trivago/prettier-plugin-sort-imports"
|
||||||
"esbuild": "^0.25.5",
|
],
|
||||||
"eslint": "^9.30.1",
|
"importOrderParserPlugins": [
|
||||||
"eslint-config-prettier": "^10.1.5",
|
"typescript",
|
||||||
"eslint-import-resolver-typescript": "^4.4.4",
|
"jsx",
|
||||||
"eslint-plugin-import": "^2.32.0",
|
"decorators-legacy"
|
||||||
"eslint-plugin-prettier": "^5.5.1",
|
]
|
||||||
"globals": "^16.3.0",
|
},
|
||||||
"lodash": "^4.17.21",
|
"jest": {
|
||||||
"mocha": "^11.7.1",
|
"testEnvironment": "node",
|
||||||
"prettier": "^3.6.2",
|
"transform": {
|
||||||
"screeps-api": "^1.7.2",
|
"^.+\\.(ts|tsx)$": "ts-jest"
|
||||||
"shelljs": "^0.10.0",
|
},
|
||||||
"sinon": "^21.0.0",
|
"moduleNameMapper": {
|
||||||
"sinon-chai": "^4.0.0",
|
"\\.(png|jpg|jpeg|gif|webp|svg|ico)$": "<rootDir>/tests/setup/__mocks__/fileMock.js",
|
||||||
"ts-node": "^10.9.2",
|
"^@/(.*)$": "<rootDir>/src/$1",
|
||||||
"tsconfig-paths": "^4.2.0",
|
"^~/(.*)$": "<rootDir>/$1"
|
||||||
"typescript": "^5.8.3"
|
},
|
||||||
},
|
"moduleFileExtensions": [
|
||||||
"dependencies": {
|
"ts",
|
||||||
"source-map": "~0.7.4"
|
"tsx",
|
||||||
}
|
"js"
|
||||||
|
],
|
||||||
|
"testMatch": [
|
||||||
|
"**/?(*.)+(spec|test).[jt]s?(x)"
|
||||||
|
]
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
99
publish.ts
Normal file
99
publish.ts
Normal file
@@ -0,0 +1,99 @@
|
|||||||
|
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),
|
||||||
|
};
|
||||||
|
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);
|
||||||
|
});
|
||||||
40
src/CreepRunner.ts
Normal file
40
src/CreepRunner.ts
Normal file
@@ -0,0 +1,40 @@
|
|||||||
|
import { CreepRole, CreepRoles } from '@/types/creeps';
|
||||||
|
import { getRoomCreeps } from '@/utils/funcs/getRoomCreeps';
|
||||||
|
|
||||||
|
class CreepRunner {
|
||||||
|
public static run(room: Room, state: GameState): GameState {
|
||||||
|
for (const name in getRoomCreeps(room)) {
|
||||||
|
const creep = Game.creeps[name];
|
||||||
|
|
||||||
|
if (!creep) {
|
||||||
|
this.clearDeadCreepMemory(name, state);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
const roleDefinition = CreepRoles[creep.memory.role as CreepRole];
|
||||||
|
if (!roleDefinition) {
|
||||||
|
this.clearDeadCreepMemory(name, state);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
state = roleDefinition.handler.run(creep, state);
|
||||||
|
}
|
||||||
|
|
||||||
|
return state;
|
||||||
|
}
|
||||||
|
|
||||||
|
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];
|
||||||
|
roleDefinition.handler.destroy(Memory.creeps[creepName], state);
|
||||||
|
|
||||||
|
delete Memory.creeps[creepName]; // Clean up memory for dead creeps
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export default CreepRunner;
|
||||||
97
src/RequisitionsManager.ts
Normal file
97
src/RequisitionsManager.ts
Normal file
@@ -0,0 +1,97 @@
|
|||||||
|
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)) {
|
||||||
|
return state;
|
||||||
|
}
|
||||||
|
|
||||||
|
const totalCreeps = Object.values(room.find(FIND_MY_CREEPS)).length;
|
||||||
|
if (totalCreeps >= state.maxHarvesters) {
|
||||||
|
return state; // No need to spawn more creeps
|
||||||
|
}
|
||||||
|
|
||||||
|
for (const spawn of room.find(FIND_MY_SPAWNS)) {
|
||||||
|
this.fulfillSpawnRequisition(spawn, creepRequisition);
|
||||||
|
}
|
||||||
|
|
||||||
|
return state;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static fulfillSpawnRequisition(
|
||||||
|
spawn: StructureSpawn,
|
||||||
|
creepRequisition: CreepRequisition
|
||||||
|
): boolean {
|
||||||
|
if (spawn.spawning) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
const rolesToSpawn = sortCreepRolesByPriority(creepRequisition);
|
||||||
|
|
||||||
|
for (const role of rolesToSpawn) {
|
||||||
|
if (spawn.store[RESOURCE_ENERGY] < get_role_cost(role)) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
const newName = `${role.name}_${Game.time}`;
|
||||||
|
const spawnResult = spawn.spawnCreep(role.body, newName, {
|
||||||
|
memory: {
|
||||||
|
role: role.name,
|
||||||
|
room: spawn.room.name,
|
||||||
|
spawnId: spawn.id,
|
||||||
|
working: false,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
if (spawnResult === OK) {
|
||||||
|
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}`
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return false; // No creeps were spawned
|
||||||
|
}
|
||||||
|
|
||||||
|
private static getRoomRequisition(room: Room): CreepRequisition {
|
||||||
|
const creepCounts: Record<string, number> = {};
|
||||||
|
for (const creepMemory of Object.values(getRoomCreeps(room))) {
|
||||||
|
const role = creepMemory.role;
|
||||||
|
creepCounts[role] = (creepCounts[role] || 0) + 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
const requisition: CreepRequisition = {
|
||||||
|
harvester: 0,
|
||||||
|
upgrader: 0,
|
||||||
|
builder: 0,
|
||||||
|
};
|
||||||
|
for (const role in DEFAULT_GAME_CONFIG.minCreepsPerRole) {
|
||||||
|
if (!(role in CreepRoles)) {
|
||||||
|
console.log(`Unknown creep role: ${role}`);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
const roleType = role as CreepRole;
|
||||||
|
requisition[roleType] =
|
||||||
|
DEFAULT_GAME_CONFIG.minCreepsPerRole[roleType] -
|
||||||
|
(creepCounts[role] || 0);
|
||||||
|
|
||||||
|
if (requisition[roleType] < 0) {
|
||||||
|
requisition[roleType] = 0; // Ensure we don't have negative requisitions
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return requisition;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export default RequisitionsManager;
|
||||||
73
src/RoomInspector.ts
Normal file
73
src/RoomInspector.ts
Normal file
@@ -0,0 +1,73 @@
|
|||||||
|
import { checkPositionWalkable } from '@/utils/funcs/checkPosition';
|
||||||
|
import {
|
||||||
|
createSourcePositionMatrix,
|
||||||
|
forEachMatrixSpot,
|
||||||
|
getPositionWithDelta,
|
||||||
|
PositionSpotStatus,
|
||||||
|
setSpotStatus,
|
||||||
|
} from '@/utils/positions';
|
||||||
|
|
||||||
|
class RoomInspector {
|
||||||
|
public static inspectState(room: Room, state: GameState): GameState {
|
||||||
|
if (!this.stateWasInitialized(state)) {
|
||||||
|
state = this.initializeState(room, state);
|
||||||
|
}
|
||||||
|
return state;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static stateWasInitialized(state: GameState): boolean {
|
||||||
|
return !!state.sourcesStates;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static initializeState(room: Room, state: GameState): GameState {
|
||||||
|
state.sourcesStates = {};
|
||||||
|
state.maxHarvesters = 0;
|
||||||
|
|
||||||
|
for (const source of room.find(FIND_SOURCES)) {
|
||||||
|
this.configureSourceState(source, state);
|
||||||
|
}
|
||||||
|
|
||||||
|
return state;
|
||||||
|
}
|
||||||
|
|
||||||
|
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(),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
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
|
||||||
|
);
|
||||||
|
state.maxHarvesters += 1;
|
||||||
|
} else {
|
||||||
|
setSpotStatus(
|
||||||
|
state.sourcesStates[sourceId].spots,
|
||||||
|
delta,
|
||||||
|
PositionSpotStatus.INVALID
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export default RoomInspector;
|
||||||
@@ -1,162 +1,14 @@
|
|||||||
import { CreepRequisition, CreepRole, CreepRoles, RoleDefinition } from "types/creeps";
|
import CreepRunner from '@/CreepRunner';
|
||||||
import { DEFAULT_GAME_CONFIG } from "types/gameConfig";
|
import RequisitionsManager from '@/RequisitionsManager';
|
||||||
import { checkPositionWalkable } from "utils/funcs/checkPosition";
|
import RoomInspector from '@/RoomInspector';
|
||||||
import { get_role_cost as get_role_cost } from "utils/funcs/getRoleCost";
|
|
||||||
import {
|
|
||||||
createSourcePositionMatrix,
|
|
||||||
forEachMatrixSpot,
|
|
||||||
getPositionWithDelta,
|
|
||||||
PositionSpotStatus,
|
|
||||||
setSpotStatus
|
|
||||||
} from "utils/positions";
|
|
||||||
|
|
||||||
class RoomRunner {
|
class RoomRunner {
|
||||||
public static run(room: Room, state: GameState): GameState {
|
public static run(room: Room, state: GameState): GameState {
|
||||||
this.updateSpawnState(room, state);
|
state = RoomInspector.inspectState(room, state);
|
||||||
|
|
||||||
for (const name in this.getRoomCreeps(room)) {
|
state = CreepRunner.run(room, state);
|
||||||
if (!Game.creeps[name]) {
|
|
||||||
console.log(`Creep ${name} is dead, cleaning up memory.`);
|
|
||||||
|
|
||||||
const roleDefinition = CreepRoles[Memory.creeps[name].role as CreepRole];
|
return RequisitionsManager.validateState(room, state);
|
||||||
roleDefinition.handler.destroy(Memory.creeps[name], state);
|
|
||||||
delete Memory.creeps[name]; // Clean up memory for dead creeps
|
|
||||||
|
|
||||||
continue; // Skip to the next creep
|
|
||||||
}
|
|
||||||
const creep = Game.creeps[name];
|
|
||||||
|
|
||||||
const roleDefinition = CreepRoles[creep.memory.role as CreepRole];
|
|
||||||
if (!roleDefinition) {
|
|
||||||
console.log(`Creep ${creep.name} has an unknown role: ${creep.memory.role}`);
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
|
|
||||||
state = roleDefinition.handler.run(creep, state);
|
|
||||||
}
|
|
||||||
|
|
||||||
for (const spawn of room.find(FIND_MY_SPAWNS)) {
|
|
||||||
this.validateSpawnState(spawn, state);
|
|
||||||
}
|
|
||||||
|
|
||||||
return state;
|
|
||||||
}
|
|
||||||
|
|
||||||
private static getRoomCreeps(room: Room): Record<string, CreepMemory> {
|
|
||||||
return Object.keys(Memory.creeps)
|
|
||||||
.filter(name => Memory.creeps[name].room === room.name)
|
|
||||||
.reduce((creeps: Record<string, CreepMemory>, creepName: string) => {
|
|
||||||
creeps[creepName] = Memory.creeps[creepName];
|
|
||||||
return creeps;
|
|
||||||
}, {});
|
|
||||||
}
|
|
||||||
|
|
||||||
private static updateSpawnState(room: Room, state: GameState) {
|
|
||||||
const sources = room.find(FIND_SOURCES);
|
|
||||||
if (!state.sourcesStates) {
|
|
||||||
state.sourcesStates = {};
|
|
||||||
state.maxHarvesters = 0;
|
|
||||||
}
|
|
||||||
for (const source of sources) {
|
|
||||||
const sourceId = source.id.toString();
|
|
||||||
|
|
||||||
if (!state.sourcesStates[sourceId]) {
|
|
||||||
state.sourcesStates[sourceId] = {
|
|
||||||
id: sourceId,
|
|
||||||
pos: source.pos,
|
|
||||||
spots: createSourcePositionMatrix()
|
|
||||||
};
|
|
||||||
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);
|
|
||||||
state.maxHarvesters = state.maxHarvesters + 1;
|
|
||||||
} else {
|
|
||||||
setSpotStatus(state.sourcesStates[sourceId].spots, delta, PositionSpotStatus.INVALID);
|
|
||||||
}
|
|
||||||
});
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private static validateSpawnState(spawn: StructureSpawn, state: GameState) {
|
|
||||||
if (spawn.spawning) {
|
|
||||||
// console.log(`Spawn ${this.spawn.name} is currently spawning a creep.`);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
const creepRequisition = this.checksNeedsCreeps(spawn.room);
|
|
||||||
if (Object.values(creepRequisition).every(count => count <= 0)) {
|
|
||||||
// console.log(`Spawn ${this.spawn.name} has no creep needs.`);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
const totalCreeps = Object.values(Game.creeps).length;
|
|
||||||
if (totalCreeps >= state.maxHarvesters) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
const rolesToSpawn = this.sortCreepRolesByPriority(creepRequisition);
|
|
||||||
|
|
||||||
for (const role of rolesToSpawn) {
|
|
||||||
if (spawn.store[RESOURCE_ENERGY] < get_role_cost(role)) {
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
|
|
||||||
const newName = `${role.name}_${Game.time}`;
|
|
||||||
const spawnResult = spawn.spawnCreep(role.body, newName, {
|
|
||||||
memory: {
|
|
||||||
role: role.name,
|
|
||||||
room: spawn.room.name,
|
|
||||||
spawnId: spawn.id,
|
|
||||||
working: false
|
|
||||||
}
|
|
||||||
});
|
|
||||||
if (spawnResult === OK) {
|
|
||||||
console.log(`Spawn ${spawn.name} successfully spawned a new ${role.name}: ${newName}.`);
|
|
||||||
return; // Exit after spawning one creep
|
|
||||||
} else {
|
|
||||||
console.error(`Spawn ${spawn.name} failed to spawn a new ${role.name}: ${spawnResult}`);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private static checksNeedsCreeps(room: Room): CreepRequisition {
|
|
||||||
const creepCounts: Record<string, number> = {};
|
|
||||||
for (const creepMemory of Object.values(this.getRoomCreeps(room))) {
|
|
||||||
const role = creepMemory.role;
|
|
||||||
creepCounts[role] = (creepCounts[role] || 0) + 1;
|
|
||||||
}
|
|
||||||
|
|
||||||
const requisition: CreepRequisition = {
|
|
||||||
harvester: 0,
|
|
||||||
upgrader: 0,
|
|
||||||
builder: 0
|
|
||||||
};
|
|
||||||
for (const role in DEFAULT_GAME_CONFIG.minCreepsPerRole) {
|
|
||||||
if (!(role in CreepRoles)) {
|
|
||||||
console.log(`Unknown creep role: ${role}`);
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
const roleType = role as CreepRole;
|
|
||||||
requisition[roleType] = DEFAULT_GAME_CONFIG.minCreepsPerRole[roleType] - (creepCounts[role] || 0);
|
|
||||||
|
|
||||||
if (requisition[roleType] < 0) {
|
|
||||||
requisition[roleType] = 0; // Ensure we don't have negative requisitions
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return requisition;
|
|
||||||
}
|
|
||||||
|
|
||||||
private static sortCreepRolesByPriority(requisition: CreepRequisition): RoleDefinition[] {
|
|
||||||
return Object.keys(requisition)
|
|
||||||
.filter(role => requisition[role as CreepRole] > 0)
|
|
||||||
.map(role => CreepRoles[role as CreepRole])
|
|
||||||
.sort((a, b) => a.priority - b.priority);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
48
src/global.d.ts
vendored
Normal file
48
src/global.d.ts
vendored
Normal file
@@ -0,0 +1,48 @@
|
|||||||
|
import { CreepDestination } from '@/types/creeps';
|
||||||
|
import { PositionMatrix } from '@/utils/positions';
|
||||||
|
|
||||||
|
declare global {
|
||||||
|
/*
|
||||||
|
Example types, expand on these or remove them and add your own.
|
||||||
|
Note: Values, properties defined here do no fully *exist* by this type definiton alone.
|
||||||
|
You must also give them an implemention if you would like to use them. (ex. actually setting a `role` property in a Creeps memory)
|
||||||
|
|
||||||
|
Types added in this `global` block are in an ambient, global context. This is needed because `main.ts` is a module file (uses import or export).
|
||||||
|
Interfaces matching on name from @types/screeps will be merged. This is how you can extend the 'built-in' interfaces from @types/screeps.
|
||||||
|
*/
|
||||||
|
interface SourceState {
|
||||||
|
id: string;
|
||||||
|
spots: PositionMatrix;
|
||||||
|
pos: RoomPosition;
|
||||||
|
}
|
||||||
|
|
||||||
|
interface GameState {
|
||||||
|
sourcesStates: { [sourceId: string]: SourceState };
|
||||||
|
maxHarvesters: number; // Maximum number of harvesters allowed in the game
|
||||||
|
}
|
||||||
|
|
||||||
|
// Memory extension samples
|
||||||
|
interface Memory {
|
||||||
|
uuid: number;
|
||||||
|
log: any;
|
||||||
|
roomStateRegistry: { [name: string]: GameState };
|
||||||
|
}
|
||||||
|
|
||||||
|
interface CreepMemory {
|
||||||
|
role: string;
|
||||||
|
room: string;
|
||||||
|
spawnId: string;
|
||||||
|
working: boolean;
|
||||||
|
destination?: CreepDestination;
|
||||||
|
previousDestination?: CreepDestination;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Syntax for adding proprties to `global` (ex "global.log")
|
||||||
|
namespace NodeJS {
|
||||||
|
interface Global {
|
||||||
|
log: any;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export {};
|
||||||
64
src/main.ts
64
src/main.ts
@@ -1,58 +1,20 @@
|
|||||||
import { CreepDestination } from "types/creeps";
|
import RoomRunner from '@/RoomRunner';
|
||||||
import RoomRunner from "RoomRunner";
|
|
||||||
import { PositionMatrix } from "utils/positions";
|
|
||||||
|
|
||||||
declare global {
|
|
||||||
/*
|
|
||||||
Example types, expand on these or remove them and add your own.
|
|
||||||
Note: Values, properties defined here do no fully *exist* by this type definiton alone.
|
|
||||||
You must also give them an implemention if you would like to use them. (ex. actually setting a `role` property in a Creeps memory)
|
|
||||||
|
|
||||||
Types added in this `global` block are in an ambient, global context. This is needed because `main.ts` is a module file (uses import or export).
|
|
||||||
Interfaces matching on name from @types/screeps will be merged. This is how you can extend the 'built-in' interfaces from @types/screeps.
|
|
||||||
*/
|
|
||||||
interface SourceState {
|
|
||||||
id: string;
|
|
||||||
spots: PositionMatrix;
|
|
||||||
pos: RoomPosition;
|
|
||||||
}
|
|
||||||
|
|
||||||
interface GameState {
|
|
||||||
sourcesStates: { [sourceId: string]: SourceState };
|
|
||||||
maxHarvesters: number; // Maximum number of harvesters allowed in the game
|
|
||||||
}
|
|
||||||
|
|
||||||
// Memory extension samples
|
|
||||||
interface Memory {
|
|
||||||
uuid: number;
|
|
||||||
log: any;
|
|
||||||
roomStateRegistry: { [name: string]: GameState };
|
|
||||||
}
|
|
||||||
|
|
||||||
interface CreepMemory {
|
|
||||||
role: string;
|
|
||||||
room: string;
|
|
||||||
spawnId: string;
|
|
||||||
working: boolean;
|
|
||||||
destination?: CreepDestination;
|
|
||||||
previousDestination?: CreepDestination;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Syntax for adding proprties to `global` (ex "global.log")
|
|
||||||
namespace NodeJS {
|
|
||||||
interface Global {
|
|
||||||
log: any;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
export const loop = () => {
|
export const loop = () => {
|
||||||
Memory.roomStateRegistry = Memory.roomStateRegistry || {};
|
Memory.roomStateRegistry = Memory.roomStateRegistry || {};
|
||||||
|
|
||||||
for (const roomName of Object.keys(Game.rooms)) {
|
for (const roomName of Object.keys(Game.rooms)) {
|
||||||
Memory.roomStateRegistry[roomName] = RoomRunner.run(
|
try {
|
||||||
Game.rooms[roomName],
|
Memory.roomStateRegistry[roomName] = RoomRunner.run(
|
||||||
Memory.roomStateRegistry[roomName] || {}
|
Game.rooms[roomName],
|
||||||
);
|
Memory.roomStateRegistry[roomName] || {}
|
||||||
|
);
|
||||||
|
} catch (error) {
|
||||||
|
console.log(
|
||||||
|
`Error running RoomRunner for room ${roomName}:`,
|
||||||
|
error
|
||||||
|
);
|
||||||
|
delete Memory.roomStateRegistry[roomName];
|
||||||
|
}
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -1,15 +1,20 @@
|
|||||||
import { getSourceById, getSpawnById } from "utils/funcs/getById";
|
import { RoleHandler } from './BaseHandler.interface';
|
||||||
import { RoleHandler } from "./BaseHandler.interface";
|
import { SourceDestination } from '@/types/creeps';
|
||||||
import { SourceDestination } from "types/creeps";
|
import { getSourceById, getSpawnById } from '@/utils/funcs/getById';
|
||||||
import { getNextEmptySpot, getPositionWithDelta, PositionSpotStatus, setSpotStatus } from "utils/positions";
|
import {
|
||||||
|
getNextEmptySpot,
|
||||||
|
getPositionWithDelta,
|
||||||
|
PositionSpotStatus,
|
||||||
|
setSpotStatus,
|
||||||
|
} from '@/utils/positions';
|
||||||
|
|
||||||
class HarvesterHandler extends RoleHandler {
|
class HarvesterHandler extends RoleHandler {
|
||||||
public static destroy(creepMemory: CreepMemory, state: GameState): void {
|
public static destroy(creepMemory: CreepMemory, state: GameState): void {
|
||||||
if (creepMemory.destination?.type === "source") {
|
if (creepMemory.destination?.type === 'source') {
|
||||||
this.releaseSourceSpot(creepMemory.destination, state);
|
this.releaseSourceSpot(creepMemory.destination, state);
|
||||||
delete creepMemory.destination; // Clear destination after releasing the spot
|
delete creepMemory.destination; // Clear destination after releasing the spot
|
||||||
}
|
}
|
||||||
if (creepMemory.previousDestination?.type === "source") {
|
if (creepMemory.previousDestination?.type === 'source') {
|
||||||
this.releaseSourceSpot(creepMemory.previousDestination, state);
|
this.releaseSourceSpot(creepMemory.previousDestination, state);
|
||||||
delete creepMemory.previousDestination; // Clear previous destination after releasing the spot
|
delete creepMemory.previousDestination; // Clear previous destination after releasing the spot
|
||||||
}
|
}
|
||||||
@@ -19,10 +24,10 @@ class HarvesterHandler extends RoleHandler {
|
|||||||
this.validateCreepMemory(creep, state);
|
this.validateCreepMemory(creep, state);
|
||||||
|
|
||||||
switch (creep.memory.destination?.type) {
|
switch (creep.memory.destination?.type) {
|
||||||
case "spawn":
|
case 'spawn':
|
||||||
this.onSpawnDestination(creep, state);
|
this.onSpawnDestination(creep, state);
|
||||||
break;
|
break;
|
||||||
case "source":
|
case 'source':
|
||||||
this.onSourceDestination(creep, state);
|
this.onSourceDestination(creep, state);
|
||||||
break;
|
break;
|
||||||
default:
|
default:
|
||||||
@@ -34,7 +39,7 @@ class HarvesterHandler extends RoleHandler {
|
|||||||
}
|
}
|
||||||
|
|
||||||
private static validateCreepMemory(creep: Creep, state: GameState) {
|
private static validateCreepMemory(creep: Creep, state: GameState) {
|
||||||
if (creep.memory.previousDestination?.type === "source") {
|
if (creep.memory.previousDestination?.type === 'source') {
|
||||||
setSpotStatus(
|
setSpotStatus(
|
||||||
state.sourcesStates[creep.memory.previousDestination.id].spots,
|
state.sourcesStates[creep.memory.previousDestination.id].spots,
|
||||||
creep.memory.previousDestination.sourceSpot,
|
creep.memory.previousDestination.sourceSpot,
|
||||||
@@ -47,16 +52,22 @@ class HarvesterHandler extends RoleHandler {
|
|||||||
return; // No destination set, nothing to validate
|
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.previousDestination = creep.memory.destination;
|
||||||
creep.memory.destination = {
|
creep.memory.destination = {
|
||||||
id: creep.memory.spawnId,
|
id: creep.memory.spawnId,
|
||||||
type: "spawn"
|
type: 'spawn',
|
||||||
};
|
};
|
||||||
return;
|
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
|
delete creep.memory.destination; // Clear destination if no energy is available
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
@@ -78,11 +89,15 @@ class HarvesterHandler extends RoleHandler {
|
|||||||
continue; // No empty spots available, skip to next source
|
continue; // No empty spots available, skip to next source
|
||||||
}
|
}
|
||||||
|
|
||||||
setSpotStatus(sourceState.spots, emptySpot, PositionSpotStatus.OCCUPIED);
|
setSpotStatus(
|
||||||
|
sourceState.spots,
|
||||||
|
emptySpot,
|
||||||
|
PositionSpotStatus.OCCUPIED
|
||||||
|
);
|
||||||
creep.memory.destination = {
|
creep.memory.destination = {
|
||||||
id: source.id,
|
id: source.id,
|
||||||
type: "source",
|
type: 'source',
|
||||||
sourceSpot: emptySpot
|
sourceSpot: emptySpot,
|
||||||
};
|
};
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
@@ -91,7 +106,10 @@ class HarvesterHandler extends RoleHandler {
|
|||||||
}
|
}
|
||||||
|
|
||||||
private static onSourceDestination(creep: Creep, _state: GameState) {
|
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.`);
|
console.log(`Creep ${creep.name} has no valid destination set.`);
|
||||||
delete creep.memory.destination;
|
delete creep.memory.destination;
|
||||||
return;
|
return;
|
||||||
@@ -104,10 +122,17 @@ class HarvesterHandler extends RoleHandler {
|
|||||||
}
|
}
|
||||||
|
|
||||||
if (creep.harvest(source) === ERR_NOT_IN_RANGE) {
|
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, {
|
creep.moveTo(sourceSpotPosition, {
|
||||||
reusePath: 10,
|
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) {
|
if (creep.memory.destination === undefined) {
|
||||||
creep.memory.destination = {
|
creep.memory.destination = {
|
||||||
id: creep.memory.spawnId,
|
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) {
|
if (creep.transfer(spawn, RESOURCE_ENERGY) === ERR_NOT_IN_RANGE) {
|
||||||
creep.moveTo(spawn, {
|
creep.moveTo(spawn, {
|
||||||
reusePath: 10,
|
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[] {
|
private static findClosestSource(creep: Creep, state: GameState): Source[] {
|
||||||
const sources = Object.keys(state.sourcesStates)
|
const sources = Object.keys(state.sourcesStates)
|
||||||
.map(sourceId => getSourceById(sourceId))
|
.map((sourceId) => getSourceById(sourceId))
|
||||||
.filter(source => source !== null)
|
.filter((source) => source !== null)
|
||||||
.sort((a, b) => creep.pos.getRangeTo(a) - creep.pos.getRangeTo(b));
|
.sort((a, b) => creep.pos.getRangeTo(a) - creep.pos.getRangeTo(b));
|
||||||
|
|
||||||
return sources as Source[];
|
return sources as Source[];
|
||||||
}
|
}
|
||||||
|
|
||||||
private static releaseSourceSpot(destination: SourceDestination, state: GameState) {
|
private static releaseSourceSpot(
|
||||||
if (!destination || destination.type !== "source") {
|
destination: SourceDestination,
|
||||||
|
state: GameState
|
||||||
|
) {
|
||||||
|
if (!destination || destination.type !== 'source') {
|
||||||
return; // Not a source destination, nothing to release
|
return; // Not a source destination, nothing to release
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -154,7 +186,11 @@ class HarvesterHandler extends RoleHandler {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
setSpotStatus(sourceState.spots, destination.sourceSpot, PositionSpotStatus.EMPTY);
|
setSpotStatus(
|
||||||
|
sourceState.spots,
|
||||||
|
destination.sourceSpot,
|
||||||
|
PositionSpotStatus.EMPTY
|
||||||
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,6 +1,5 @@
|
|||||||
import { RoleHandler } from "./BaseHandler.interface";
|
import { RoleHandler } from './BaseHandler.interface';
|
||||||
|
import HarvesterHandler from './harvester.handler';
|
||||||
import HarvesterHandler from "./harvester.handler";
|
import UpgraderHandler from './upgrader.handler';
|
||||||
import UpgraderHandler from "./upgrader.handler";
|
|
||||||
|
|
||||||
export { RoleHandler, HarvesterHandler, UpgraderHandler };
|
export { RoleHandler, HarvesterHandler, UpgraderHandler };
|
||||||
|
|||||||
@@ -1,15 +1,20 @@
|
|||||||
import { getControllerById, getSourceById } from "utils/funcs/getById";
|
import { RoleHandler } from './BaseHandler.interface';
|
||||||
import { RoleHandler } from "./BaseHandler.interface";
|
import { SourceDestination } from '@/types/creeps';
|
||||||
import { getNextEmptySpot, PositionSpotStatus, setSpotStatus, getPositionWithDelta } from "utils/positions";
|
import { getControllerById, getSourceById } from '@/utils/funcs/getById';
|
||||||
import { SourceDestination } from "types/creeps";
|
import {
|
||||||
|
getNextEmptySpot,
|
||||||
|
getPositionWithDelta,
|
||||||
|
PositionSpotStatus,
|
||||||
|
setSpotStatus,
|
||||||
|
} from '@/utils/positions';
|
||||||
|
|
||||||
class UpgraderHandler extends RoleHandler {
|
class UpgraderHandler extends RoleHandler {
|
||||||
public static destroy(creepMemory: CreepMemory, state: GameState): void {
|
public static destroy(creepMemory: CreepMemory, state: GameState): void {
|
||||||
if (creepMemory.destination?.type === "source") {
|
if (creepMemory.destination?.type === 'source') {
|
||||||
this.releaseSourceSpot(creepMemory.destination, state);
|
this.releaseSourceSpot(creepMemory.destination, state);
|
||||||
delete creepMemory.destination; // Clear destination after releasing the spot
|
delete creepMemory.destination; // Clear destination after releasing the spot
|
||||||
}
|
}
|
||||||
if (creepMemory.previousDestination?.type === "source") {
|
if (creepMemory.previousDestination?.type === 'source') {
|
||||||
this.releaseSourceSpot(creepMemory.previousDestination, state);
|
this.releaseSourceSpot(creepMemory.previousDestination, state);
|
||||||
delete creepMemory.previousDestination; // Clear previous destination after releasing the spot
|
delete creepMemory.previousDestination; // Clear previous destination after releasing the spot
|
||||||
}
|
}
|
||||||
@@ -19,10 +24,10 @@ class UpgraderHandler extends RoleHandler {
|
|||||||
this.validateCreepMemory(creep, state);
|
this.validateCreepMemory(creep, state);
|
||||||
|
|
||||||
switch (creep.memory.destination?.type) {
|
switch (creep.memory.destination?.type) {
|
||||||
case "controller":
|
case 'controller':
|
||||||
this.onControllerDestination(creep, state);
|
this.onControllerDestination(creep, state);
|
||||||
break;
|
break;
|
||||||
case "source":
|
case 'source':
|
||||||
this.onSourceDestination(creep, state);
|
this.onSourceDestination(creep, state);
|
||||||
break;
|
break;
|
||||||
default:
|
default:
|
||||||
@@ -34,7 +39,10 @@ class UpgraderHandler extends RoleHandler {
|
|||||||
}
|
}
|
||||||
|
|
||||||
private static validateCreepMemory(creep: Creep, state: GameState) {
|
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(
|
setSpotStatus(
|
||||||
state.sourcesStates[creep.memory.previousDestination.id].spots,
|
state.sourcesStates[creep.memory.previousDestination.id].spots,
|
||||||
creep.memory.previousDestination.sourceSpot,
|
creep.memory.previousDestination.sourceSpot,
|
||||||
@@ -47,23 +55,31 @@ class UpgraderHandler extends RoleHandler {
|
|||||||
return; // No destination set, nothing to validate
|
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.previousDestination = creep.memory.destination;
|
||||||
|
|
||||||
if (!creep.room.controller) {
|
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;
|
delete creep.memory.destination;
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
creep.memory.destination = {
|
creep.memory.destination = {
|
||||||
id: creep.room.controller.id,
|
id: creep.room.controller.id,
|
||||||
type: "controller"
|
type: 'controller',
|
||||||
};
|
};
|
||||||
return;
|
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
|
delete creep.memory.destination; // Clear destination if no energy is available
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
@@ -85,11 +101,15 @@ class UpgraderHandler extends RoleHandler {
|
|||||||
continue; // No empty spots available, skip to next source
|
continue; // No empty spots available, skip to next source
|
||||||
}
|
}
|
||||||
|
|
||||||
setSpotStatus(sourceState.spots, emptySpot, PositionSpotStatus.OCCUPIED);
|
setSpotStatus(
|
||||||
|
sourceState.spots,
|
||||||
|
emptySpot,
|
||||||
|
PositionSpotStatus.OCCUPIED
|
||||||
|
);
|
||||||
creep.memory.destination = {
|
creep.memory.destination = {
|
||||||
id: source.id,
|
id: source.id,
|
||||||
type: "source",
|
type: 'source',
|
||||||
sourceSpot: emptySpot
|
sourceSpot: emptySpot,
|
||||||
};
|
};
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
@@ -98,7 +118,10 @@ class UpgraderHandler extends RoleHandler {
|
|||||||
}
|
}
|
||||||
|
|
||||||
private static onSourceDestination(creep: Creep, _state: GameState) {
|
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.`);
|
console.log(`Creep ${creep.name} has no valid destination set.`);
|
||||||
delete creep.memory.destination;
|
delete creep.memory.destination;
|
||||||
return;
|
return;
|
||||||
@@ -111,10 +134,17 @@ class UpgraderHandler extends RoleHandler {
|
|||||||
}
|
}
|
||||||
|
|
||||||
if (creep.harvest(source) === ERR_NOT_IN_RANGE) {
|
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, {
|
creep.moveTo(sourceSpotPosition, {
|
||||||
reusePath: 10,
|
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) {
|
private static onControllerDestination(creep: Creep, _state: GameState) {
|
||||||
if (creep.memory.destination === undefined) {
|
if (creep.memory.destination === undefined) {
|
||||||
if (!creep.room.controller) {
|
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;
|
delete creep.memory.destination;
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
creep.memory.destination = {
|
creep.memory.destination = {
|
||||||
id: creep.room.controller.id,
|
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) {
|
if (creep.upgradeController(controller) === ERR_NOT_IN_RANGE) {
|
||||||
creep.moveTo(controller, {
|
creep.moveTo(controller, {
|
||||||
reusePath: 10,
|
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[] {
|
private static findClosestSource(creep: Creep, state: GameState): Source[] {
|
||||||
const sources = Object.keys(state.sourcesStates)
|
const sources = Object.keys(state.sourcesStates)
|
||||||
.map(sourceId => getSourceById(sourceId))
|
.map((sourceId) => getSourceById(sourceId))
|
||||||
.filter(source => source !== null)
|
.filter((source) => source !== null)
|
||||||
.sort((a, b) => creep.pos.getRangeTo(a) - creep.pos.getRangeTo(b));
|
.sort((a, b) => creep.pos.getRangeTo(a) - creep.pos.getRangeTo(b));
|
||||||
|
|
||||||
return sources as Source[];
|
return sources as Source[];
|
||||||
}
|
}
|
||||||
|
|
||||||
private static releaseSourceSpot(destination: SourceDestination, state: GameState) {
|
private static releaseSourceSpot(
|
||||||
if (!destination || destination.type !== "source") {
|
destination: SourceDestination,
|
||||||
|
state: GameState
|
||||||
|
) {
|
||||||
|
if (!destination || destination.type !== 'source') {
|
||||||
return; // Not a source destination, nothing to release
|
return; // Not a source destination, nothing to release
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -166,7 +205,11 @@ class UpgraderHandler extends RoleHandler {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
setSpotStatus(sourceState.spots, destination.sourceSpot, PositionSpotStatus.EMPTY);
|
setSpotStatus(
|
||||||
|
sourceState.spots,
|
||||||
|
destination.sourceSpot,
|
||||||
|
PositionSpotStatus.EMPTY
|
||||||
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
import { HarvesterHandler, RoleHandler, UpgraderHandler } from "roleHandlers";
|
import { HarvesterHandler, RoleHandler, UpgraderHandler } from '@/roleHandlers';
|
||||||
import { PositionDelta } from "utils/positions";
|
import { PositionDelta } from '@/utils/positions';
|
||||||
|
|
||||||
export type RoleDefinition = {
|
export type RoleDefinition = {
|
||||||
name: string;
|
name: string;
|
||||||
@@ -10,23 +10,23 @@ export type RoleDefinition = {
|
|||||||
|
|
||||||
export const CreepRoles = {
|
export const CreepRoles = {
|
||||||
harvester: {
|
harvester: {
|
||||||
name: "harvester",
|
name: 'harvester',
|
||||||
body: [WORK, CARRY, MOVE],
|
body: [WORK, CARRY, MOVE],
|
||||||
handler: HarvesterHandler,
|
handler: HarvesterHandler,
|
||||||
priority: 1
|
priority: 1,
|
||||||
},
|
},
|
||||||
upgrader: {
|
upgrader: {
|
||||||
name: "upgrader",
|
name: 'upgrader',
|
||||||
body: [WORK, CARRY, MOVE],
|
body: [WORK, CARRY, MOVE],
|
||||||
handler: UpgraderHandler,
|
handler: UpgraderHandler,
|
||||||
priority: 2
|
priority: 2,
|
||||||
},
|
},
|
||||||
builder: {
|
builder: {
|
||||||
name: "builder",
|
name: 'builder',
|
||||||
body: [WORK, CARRY, MOVE],
|
body: [WORK, CARRY, MOVE],
|
||||||
handler: HarvesterHandler,
|
handler: HarvesterHandler,
|
||||||
priority: 3
|
priority: 3,
|
||||||
}
|
},
|
||||||
} satisfies Record<string, RoleDefinition>;
|
} satisfies Record<string, RoleDefinition>;
|
||||||
|
|
||||||
export type CreepRole = keyof typeof CreepRoles;
|
export type CreepRole = keyof typeof CreepRoles;
|
||||||
@@ -35,23 +35,23 @@ export type CreepRequisition = Record<CreepRole, number>;
|
|||||||
|
|
||||||
export type SpawnDestination = {
|
export type SpawnDestination = {
|
||||||
id: string; // ID of the spawn
|
id: string; // ID of the spawn
|
||||||
type: "spawn";
|
type: 'spawn';
|
||||||
};
|
};
|
||||||
|
|
||||||
export type SourceDestination = {
|
export type SourceDestination = {
|
||||||
id: string; // ID of the source
|
id: string; // ID of the source
|
||||||
type: "source";
|
type: 'source';
|
||||||
sourceSpot: PositionDelta; // Position delta for the source spot
|
sourceSpot: PositionDelta; // Position delta for the source spot
|
||||||
};
|
};
|
||||||
|
|
||||||
export type ControllerDestination = {
|
export type ControllerDestination = {
|
||||||
id: string; // ID of the controller
|
id: string; // ID of the controller
|
||||||
type: "controller";
|
type: 'controller';
|
||||||
};
|
};
|
||||||
|
|
||||||
export type ConstructionSiteDestination = {
|
export type ConstructionSiteDestination = {
|
||||||
id: string; // ID of the construction site
|
id: string; // ID of the construction site
|
||||||
type: "constructionSite";
|
type: 'constructionSite';
|
||||||
};
|
};
|
||||||
|
|
||||||
export type CreepDestination =
|
export type CreepDestination =
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
import { CreepRequisition } from "./creeps";
|
import { CreepRequisition } from './creeps';
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Configuration for the game, defining limits and minimum requirements for creeps.
|
* Configuration for the game, defining limits and minimum requirements for creeps.
|
||||||
@@ -22,6 +22,6 @@ export const DEFAULT_GAME_CONFIG: GameConfig = {
|
|||||||
minCreepsPerRole: {
|
minCreepsPerRole: {
|
||||||
harvester: 3,
|
harvester: 3,
|
||||||
upgrader: 7,
|
upgrader: 7,
|
||||||
builder: 0
|
builder: 0,
|
||||||
}
|
},
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
export const checkPositionWalkable = (pos: RoomPosition) => {
|
export const checkPositionWalkable = (pos: RoomPosition) => {
|
||||||
// Check if the position is not obstructed by a wall
|
// Check if the position is not obstructed by a wall
|
||||||
const terrain = pos.lookFor(LOOK_TERRAIN);
|
const terrain = pos.lookFor(LOOK_TERRAIN);
|
||||||
return terrain.length === 0 || terrain[0] !== "wall";
|
return terrain.length === 0 || terrain[0] !== 'wall';
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -1,6 +1,8 @@
|
|||||||
export const getSourceById = (sourceId: string): Source | null => {
|
export const getSourceById = (sourceId: string): Source | null => {
|
||||||
if (!sourceId) {
|
if (!sourceId) {
|
||||||
console.log("getSourceById called with an empty or undefined sourceId.");
|
console.log(
|
||||||
|
'getSourceById called with an empty or undefined sourceId.'
|
||||||
|
);
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -15,7 +17,7 @@ export const getSourceById = (sourceId: string): Source | null => {
|
|||||||
|
|
||||||
export const getSpawnById = (spawnId: string): StructureSpawn | null => {
|
export const getSpawnById = (spawnId: string): StructureSpawn | null => {
|
||||||
if (!spawnId) {
|
if (!spawnId) {
|
||||||
console.log("getSpawnById called with an empty or undefined spawnId.");
|
console.log('getSpawnById called with an empty or undefined spawnId.');
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -28,9 +30,13 @@ export const getSpawnById = (spawnId: string): StructureSpawn | null => {
|
|||||||
return spawn;
|
return spawn;
|
||||||
};
|
};
|
||||||
|
|
||||||
export const getControllerById = (controllerId: string): StructureController | null => {
|
export const getControllerById = (
|
||||||
|
controllerId: string
|
||||||
|
): StructureController | null => {
|
||||||
if (!controllerId) {
|
if (!controllerId) {
|
||||||
console.log("getControllerById called with an empty or undefined controllerId.");
|
console.log(
|
||||||
|
'getControllerById called with an empty or undefined controllerId.'
|
||||||
|
);
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
import { RoleDefinition } from "types/creeps";
|
import { RoleDefinition } from '@/types/creeps';
|
||||||
|
|
||||||
export const get_role_cost = (role: RoleDefinition) => {
|
export const get_role_cost = (role: RoleDefinition) => {
|
||||||
return role.body.reduce((cost, part) => {
|
return role.body.reduce((cost, part) => {
|
||||||
|
|||||||
8
src/utils/funcs/getRoomCreeps.ts
Normal file
8
src/utils/funcs/getRoomCreeps.ts
Normal file
@@ -0,0 +1,8 @@
|
|||||||
|
export const getRoomCreeps = (room: Room): Record<string, CreepMemory> => {
|
||||||
|
return Object.keys(Memory.creeps)
|
||||||
|
.filter((name) => Memory.creeps[name].room === room.name)
|
||||||
|
.reduce((creeps: Record<string, CreepMemory>, creepName: string) => {
|
||||||
|
creeps[creepName] = Memory.creeps[creepName];
|
||||||
|
return creeps;
|
||||||
|
}, {});
|
||||||
|
};
|
||||||
15
src/utils/funcs/sortCreepRolesByPriority.ts
Normal file
15
src/utils/funcs/sortCreepRolesByPriority.ts
Normal file
@@ -0,0 +1,15 @@
|
|||||||
|
import {
|
||||||
|
CreepRequisition,
|
||||||
|
CreepRole,
|
||||||
|
CreepRoles,
|
||||||
|
RoleDefinition,
|
||||||
|
} from '@/types/creeps';
|
||||||
|
|
||||||
|
export const sortCreepRolesByPriority = (
|
||||||
|
requisition: CreepRequisition
|
||||||
|
): RoleDefinition[] => {
|
||||||
|
return Object.keys(requisition)
|
||||||
|
.filter((role) => requisition[role as CreepRole] > 0)
|
||||||
|
.map((role) => CreepRoles[role as CreepRole])
|
||||||
|
.sort((a, b) => a.priority - b.priority);
|
||||||
|
};
|
||||||
@@ -1,12 +1,16 @@
|
|||||||
import { PositionSpotStatus, PositionDeltaValue, PositionMatrix, PositionDelta } from "./position.types";
|
|
||||||
|
|
||||||
import {
|
import {
|
||||||
createSourcePositionMatrix,
|
createSourcePositionMatrix,
|
||||||
forEachMatrixSpot,
|
forEachMatrixSpot,
|
||||||
getNextEmptySpot,
|
getNextEmptySpot,
|
||||||
setSpotStatus,
|
setSpotStatus,
|
||||||
getPositionWithDelta
|
getPositionWithDelta,
|
||||||
} from "./position.funcs";
|
} from './position.funcs';
|
||||||
|
import {
|
||||||
|
PositionSpotStatus,
|
||||||
|
PositionDeltaValue,
|
||||||
|
PositionMatrix,
|
||||||
|
PositionDelta,
|
||||||
|
} from './position.types';
|
||||||
|
|
||||||
export {
|
export {
|
||||||
PositionSpotStatus,
|
PositionSpotStatus,
|
||||||
@@ -17,5 +21,5 @@ export {
|
|||||||
forEachMatrixSpot,
|
forEachMatrixSpot,
|
||||||
getNextEmptySpot,
|
getNextEmptySpot,
|
||||||
setSpotStatus,
|
setSpotStatus,
|
||||||
getPositionWithDelta
|
getPositionWithDelta,
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -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.
|
* 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 center of the matrix is always `PositionSpotStatus.CENTER`.
|
||||||
* The default value is used for all other spots.
|
* 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;
|
const center_value = PositionSpotStatus.CENTER;
|
||||||
|
|
||||||
default_value = default_value || PositionSpotStatus.UNKNOWN;
|
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,
|
default_value,
|
||||||
default_value
|
default_value,
|
||||||
];
|
];
|
||||||
};
|
};
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Gets the next empty spot in the matrix.
|
* Gets the next empty spot in the matrix.
|
||||||
*/
|
*/
|
||||||
export const getNextEmptySpot = (matrix: PositionMatrix): PositionDelta | null => {
|
export const getNextEmptySpot = (
|
||||||
const index = matrix.findIndex(status => status === PositionSpotStatus.EMPTY);
|
matrix: PositionMatrix
|
||||||
|
): PositionDelta | null => {
|
||||||
|
const index = matrix.findIndex(
|
||||||
|
(status) => status === PositionSpotStatus.EMPTY
|
||||||
|
);
|
||||||
|
|
||||||
if (index === -1) {
|
if (index === -1) {
|
||||||
return null; // No empty spot found
|
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.
|
* Sets the status of a spot in the matrix.
|
||||||
* Throws an error if the delta is out of bounds.
|
* 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) {
|
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;
|
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.
|
* 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);
|
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
|
||||||
|
);
|
||||||
};
|
};
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
|||||||
@@ -2,14 +2,15 @@
|
|||||||
* Represents the status of a position spot
|
* Represents the status of a position spot
|
||||||
*/
|
*/
|
||||||
export const PositionSpotStatus = {
|
export const PositionSpotStatus = {
|
||||||
INVALID: "-2",
|
INVALID: '-2',
|
||||||
CENTER: "-1",
|
CENTER: '-1',
|
||||||
UNKNOWN: "0",
|
UNKNOWN: '0',
|
||||||
EMPTY: "1",
|
EMPTY: '1',
|
||||||
OCCUPIED: "2"
|
OCCUPIED: '2',
|
||||||
} as const;
|
} 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.
|
* 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,
|
PositionSpotStatus,
|
||||||
PositionSpotStatus
|
PositionSpotStatus,
|
||||||
];
|
];
|
||||||
|
|
||||||
// Valid indices for the 3x3 matrix (0-8)
|
// Valid indices for the 3x3 matrix (0-8)
|
||||||
|
|||||||
@@ -1,59 +0,0 @@
|
|||||||
const { readFileSync } = require('fs');
|
|
||||||
const _ = require('lodash');
|
|
||||||
const { ScreepsServer, stdHooks } = require('screeps-server-mockup');
|
|
||||||
const DIST_MAIN_JS = 'dist/main.js';
|
|
||||||
|
|
||||||
/*
|
|
||||||
* Helper class for creating a ScreepsServer and resetting it between tests.
|
|
||||||
* See https://github.com/Hiryus/screeps-server-mockup for instructions on
|
|
||||||
* manipulating the terrain and game state.
|
|
||||||
*/
|
|
||||||
class IntegrationTestHelper {
|
|
||||||
private _server: any;
|
|
||||||
private _player: any;
|
|
||||||
|
|
||||||
get server() {
|
|
||||||
return this._server;
|
|
||||||
}
|
|
||||||
|
|
||||||
get player() {
|
|
||||||
return this._player;
|
|
||||||
}
|
|
||||||
|
|
||||||
async beforeEach() {
|
|
||||||
this._server = new ScreepsServer();
|
|
||||||
|
|
||||||
// reset world but add invaders and source keepers bots
|
|
||||||
await this._server.world.reset();
|
|
||||||
|
|
||||||
// create a stub world composed of 9 rooms with sources and controller
|
|
||||||
await this._server.world.stubWorld();
|
|
||||||
|
|
||||||
// add a player with the built dist/main.js file
|
|
||||||
const modules = {
|
|
||||||
main: readFileSync(DIST_MAIN_JS).toString(),
|
|
||||||
};
|
|
||||||
this._player = await this._server.world.addBot({ username: 'player', room: 'W0N1', x: 15, y: 15, modules });
|
|
||||||
|
|
||||||
// Start server
|
|
||||||
await this._server.start();
|
|
||||||
}
|
|
||||||
|
|
||||||
async afterEach() {
|
|
||||||
await this._server.stop();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
beforeEach(async () => {
|
|
||||||
await helper.beforeEach();
|
|
||||||
});
|
|
||||||
|
|
||||||
afterEach(async () => {
|
|
||||||
await helper.afterEach();
|
|
||||||
});
|
|
||||||
|
|
||||||
before(() => {
|
|
||||||
stdHooks.hookWrite();
|
|
||||||
});
|
|
||||||
|
|
||||||
export const helper = new IntegrationTestHelper();
|
|
||||||
@@ -1,18 +0,0 @@
|
|||||||
import {assert} from "chai";
|
|
||||||
import {helper} from "./helper";
|
|
||||||
|
|
||||||
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 () {
|
|
||||||
await helper.player.console(`Memory.foo = 'bar'`);
|
|
||||||
await helper.server.tick();
|
|
||||||
const memory = JSON.parse(await helper.player.memory);
|
|
||||||
assert.equal(memory.foo, 'bar');
|
|
||||||
});
|
|
||||||
});
|
|
||||||
@@ -1,14 +0,0 @@
|
|||||||
--require test/setup-mocha.js
|
|
||||||
--require ts-node/register
|
|
||||||
--require tsconfig-paths/register
|
|
||||||
--ui bdd
|
|
||||||
|
|
||||||
--reporter spec
|
|
||||||
--bail
|
|
||||||
--full-trace
|
|
||||||
--watch-extensions tsx,ts
|
|
||||||
--colors
|
|
||||||
|
|
||||||
--recursive
|
|
||||||
--timeout 5000
|
|
||||||
--exit
|
|
||||||
@@ -1,9 +0,0 @@
|
|||||||
//inject mocha globally to allow custom interface refer without direct import - bypass bundle issue
|
|
||||||
global._ = require('lodash');
|
|
||||||
global.mocha = require('mocha');
|
|
||||||
global.chai = require('chai');
|
|
||||||
global.sinon = require('sinon');
|
|
||||||
global.chai.use(require('sinon-chai'));
|
|
||||||
|
|
||||||
// Override ts-node compiler options
|
|
||||||
process.env.TS_NODE_PROJECT = 'tsconfig.test.json'
|
|
||||||
@@ -1,37 +0,0 @@
|
|||||||
import {assert} from "chai";
|
|
||||||
import {loop} from "../../src/main";
|
|
||||||
import {Game, Memory} from "./mock"
|
|
||||||
|
|
||||||
describe("main", () => {
|
|
||||||
before(() => {
|
|
||||||
// runs before all test in this block
|
|
||||||
});
|
|
||||||
|
|
||||||
beforeEach(() => {
|
|
||||||
// runs before each test in this block
|
|
||||||
// @ts-ignore : allow adding Game to global
|
|
||||||
global.Game = _.clone(Game);
|
|
||||||
// @ts-ignore : allow adding Memory to global
|
|
||||||
global.Memory = _.clone(Memory);
|
|
||||||
});
|
|
||||||
|
|
||||||
it("should export a loop function", () => {
|
|
||||||
assert.isTrue(typeof loop === "function");
|
|
||||||
});
|
|
||||||
|
|
||||||
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";
|
|
||||||
|
|
||||||
Game.creeps.persistValue = "any value";
|
|
||||||
|
|
||||||
loop();
|
|
||||||
|
|
||||||
assert.isDefined(Memory.creeps.persistValue);
|
|
||||||
assert.isUndefined(Memory.creeps.notPersistValue);
|
|
||||||
});
|
|
||||||
});
|
|
||||||
@@ -1,17 +0,0 @@
|
|||||||
export const Game: {
|
|
||||||
creeps: { [name: string]: any };
|
|
||||||
rooms: any;
|
|
||||||
spawns: any;
|
|
||||||
time: any;
|
|
||||||
} = {
|
|
||||||
creeps: {},
|
|
||||||
rooms: [],
|
|
||||||
spawns: {},
|
|
||||||
time: 12345
|
|
||||||
};
|
|
||||||
|
|
||||||
export const Memory: {
|
|
||||||
creeps: { [name: string]: any };
|
|
||||||
} = {
|
|
||||||
creeps: {}
|
|
||||||
};
|
|
||||||
35
tests/__mocks__/screeps.ts
Normal file
35
tests/__mocks__/screeps.ts
Normal file
@@ -0,0 +1,35 @@
|
|||||||
|
/**
|
||||||
|
* Minimal Screeps global mocks used across tests.
|
||||||
|
*/
|
||||||
|
|
||||||
|
// Constants
|
||||||
|
(global as any).RESOURCE_ENERGY = 'energy';
|
||||||
|
(global as any).ERR_NOT_IN_RANGE = -9;
|
||||||
|
(global as any).OK = 0;
|
||||||
|
(global as any).WORK = 'work';
|
||||||
|
(global as any).CARRY = 'carry';
|
||||||
|
(global as any).MOVE = 'move';
|
||||||
|
|
||||||
|
// RoomPosition constructor mock
|
||||||
|
(global as any).RoomPosition = class RoomPosition {
|
||||||
|
x: number;
|
||||||
|
y: number;
|
||||||
|
roomName: string;
|
||||||
|
|
||||||
|
constructor(x: number, y: number, roomName: string) {
|
||||||
|
this.x = x;
|
||||||
|
this.y = y;
|
||||||
|
this.roomName = roomName;
|
||||||
|
}
|
||||||
|
|
||||||
|
getRangeTo(_target: any): number {
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
// Game mock
|
||||||
|
(global as any).Game = {
|
||||||
|
getObjectById: jest.fn(),
|
||||||
|
};
|
||||||
|
|
||||||
|
export {};
|
||||||
371
tests/roleHandlers/harvester.handler.test.ts
Normal file
371
tests/roleHandlers/harvester.handler.test.ts
Normal file
@@ -0,0 +1,371 @@
|
|||||||
|
import HarvesterHandler from '@/roleHandlers/harvester.handler';
|
||||||
|
import * as getById from '@/utils/funcs/getById';
|
||||||
|
import {
|
||||||
|
PositionSpotStatus,
|
||||||
|
createSourcePositionMatrix,
|
||||||
|
} from '@/utils/positions';
|
||||||
|
import '~/tests/__mocks__/screeps';
|
||||||
|
|
||||||
|
// ─── Helpers ────────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
function makeMatrix(fill: string = PositionSpotStatus.EMPTY) {
|
||||||
|
const m = createSourcePositionMatrix(fill as any);
|
||||||
|
return m;
|
||||||
|
}
|
||||||
|
|
||||||
|
function makeState(overrides: Partial<GameState> = {}): GameState {
|
||||||
|
const spots = makeMatrix();
|
||||||
|
return {
|
||||||
|
sourcesStates: {
|
||||||
|
src1: { spots },
|
||||||
|
},
|
||||||
|
...overrides,
|
||||||
|
} as unknown as GameState;
|
||||||
|
}
|
||||||
|
|
||||||
|
function makeCreepMemory(overrides: Partial<CreepMemory> = {}): CreepMemory {
|
||||||
|
return {
|
||||||
|
role: 'harvester',
|
||||||
|
spawnId: 'spawn1',
|
||||||
|
...overrides,
|
||||||
|
} as CreepMemory;
|
||||||
|
}
|
||||||
|
|
||||||
|
function makeStore(used: number, capacity: number) {
|
||||||
|
return {
|
||||||
|
getFreeCapacity: (_res: string) => capacity - used,
|
||||||
|
getUsedCapacity: (_res: string) => used,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function makePos(x = 0, y = 0, roomName = 'W1N1') {
|
||||||
|
return new (global as any).RoomPosition(x, y, roomName);
|
||||||
|
}
|
||||||
|
|
||||||
|
function makeSource(id = 'src1', x = 5, y = 5, roomName = 'W1N1') {
|
||||||
|
return {
|
||||||
|
id,
|
||||||
|
pos: makePos(x, y, roomName),
|
||||||
|
} as unknown as Source;
|
||||||
|
}
|
||||||
|
|
||||||
|
function makeSpawn(id = 'spawn1') {
|
||||||
|
return { id } as unknown as StructureSpawn;
|
||||||
|
}
|
||||||
|
|
||||||
|
function makeCreep(
|
||||||
|
memoryOverrides: Partial<CreepMemory> = {},
|
||||||
|
storeUsed = 0,
|
||||||
|
storeCapacity = 50
|
||||||
|
): Creep {
|
||||||
|
const memory = makeCreepMemory(memoryOverrides);
|
||||||
|
return {
|
||||||
|
name: 'Creep1',
|
||||||
|
memory,
|
||||||
|
store: makeStore(storeUsed, storeCapacity),
|
||||||
|
pos: makePos(),
|
||||||
|
room: {},
|
||||||
|
harvest: jest.fn().mockReturnValue((global as any).OK),
|
||||||
|
moveTo: jest.fn().mockReturnValue((global as any).OK),
|
||||||
|
transfer: jest.fn().mockReturnValue((global as any).OK),
|
||||||
|
} as unknown as Creep;
|
||||||
|
}
|
||||||
|
|
||||||
|
// ─── Tests ───────────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
describe('HarvesterHandler', () => {
|
||||||
|
beforeEach(() => {
|
||||||
|
jest.clearAllMocks();
|
||||||
|
jest.spyOn(console, 'log').mockImplementation(() => {});
|
||||||
|
});
|
||||||
|
|
||||||
|
afterEach(() => {
|
||||||
|
jest.restoreAllMocks();
|
||||||
|
});
|
||||||
|
|
||||||
|
// ── destroy ──────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
describe('destroy', () => {
|
||||||
|
it('releases the source spot from destination and clears it', () => {
|
||||||
|
const state = makeState();
|
||||||
|
state.sourcesStates['src1'].spots[0] = PositionSpotStatus.OCCUPIED;
|
||||||
|
|
||||||
|
const memory = makeCreepMemory({
|
||||||
|
destination: { type: 'source', id: 'src1', sourceSpot: 0 },
|
||||||
|
});
|
||||||
|
|
||||||
|
HarvesterHandler.destroy(memory, state);
|
||||||
|
|
||||||
|
expect(state.sourcesStates['src1'].spots[0]).toBe(
|
||||||
|
PositionSpotStatus.EMPTY
|
||||||
|
);
|
||||||
|
expect(memory.destination).toBeUndefined();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('releases the source spot from previousDestination and clears it', () => {
|
||||||
|
const state = makeState();
|
||||||
|
state.sourcesStates['src1'].spots[2] = PositionSpotStatus.OCCUPIED;
|
||||||
|
|
||||||
|
const memory = makeCreepMemory({
|
||||||
|
previousDestination: {
|
||||||
|
type: 'source',
|
||||||
|
id: 'src1',
|
||||||
|
sourceSpot: 2,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
HarvesterHandler.destroy(memory, state);
|
||||||
|
|
||||||
|
expect(state.sourcesStates['src1'].spots[2]).toBe(
|
||||||
|
PositionSpotStatus.EMPTY
|
||||||
|
);
|
||||||
|
expect(memory.previousDestination).toBeUndefined();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('does nothing when destination is not a source', () => {
|
||||||
|
const state = makeState();
|
||||||
|
const memory = makeCreepMemory({
|
||||||
|
destination: { type: 'spawn', id: 'spawn1' },
|
||||||
|
});
|
||||||
|
|
||||||
|
HarvesterHandler.destroy(memory, state);
|
||||||
|
|
||||||
|
// None of the source spots should have changed
|
||||||
|
expect(
|
||||||
|
state.sourcesStates['src1'].spots.every(
|
||||||
|
(s: PositionSpotStatus) =>
|
||||||
|
s === PositionSpotStatus.EMPTY ||
|
||||||
|
s === PositionSpotStatus.CENTER
|
||||||
|
)
|
||||||
|
).toBe(true);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('does nothing when memory has no destination', () => {
|
||||||
|
const state = makeState();
|
||||||
|
const memory = makeCreepMemory();
|
||||||
|
|
||||||
|
expect(() => HarvesterHandler.destroy(memory, state)).not.toThrow();
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
// ── validateCreepMemory (via run) ────────────────────────────────────────
|
||||||
|
|
||||||
|
describe('validateCreepMemory (via run)', () => {
|
||||||
|
it('releases previousDestination source spot and deletes it', () => {
|
||||||
|
const state = makeState();
|
||||||
|
state.sourcesStates['src1'].spots[1] = PositionSpotStatus.OCCUPIED;
|
||||||
|
|
||||||
|
const creep = makeCreep({
|
||||||
|
previousDestination: {
|
||||||
|
type: 'source',
|
||||||
|
id: 'src1',
|
||||||
|
sourceSpot: 1,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
jest.spyOn(getById, 'getSourceById').mockReturnValue(null);
|
||||||
|
|
||||||
|
HarvesterHandler.run(creep, state);
|
||||||
|
|
||||||
|
expect(state.sourcesStates['src1'].spots[1]).toBe(
|
||||||
|
PositionSpotStatus.EMPTY
|
||||||
|
);
|
||||||
|
expect(creep.memory.previousDestination).toBeUndefined();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('transitions from source to spawn destination when energy is full', () => {
|
||||||
|
const state = makeState();
|
||||||
|
const source = makeSource();
|
||||||
|
jest.spyOn(getById, 'getSourceById').mockReturnValue(source);
|
||||||
|
jest.spyOn(getById, 'getSpawnById').mockReturnValue(makeSpawn());
|
||||||
|
|
||||||
|
const creep = makeCreep(
|
||||||
|
{
|
||||||
|
destination: { type: 'source', id: 'src1', sourceSpot: 0 },
|
||||||
|
spawnId: 'spawn1',
|
||||||
|
},
|
||||||
|
50, // used = full
|
||||||
|
50
|
||||||
|
);
|
||||||
|
|
||||||
|
HarvesterHandler.run(creep, state);
|
||||||
|
|
||||||
|
expect(creep.memory.destination?.type).toBe('spawn');
|
||||||
|
expect(creep.memory.previousDestination?.type).toBe('source');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('clears spawn destination when energy is empty', () => {
|
||||||
|
const state = makeState();
|
||||||
|
jest.spyOn(getById, 'getSpawnById').mockReturnValue(makeSpawn());
|
||||||
|
|
||||||
|
const creep = makeCreep(
|
||||||
|
{
|
||||||
|
destination: { type: 'spawn', id: 'spawn1' },
|
||||||
|
},
|
||||||
|
0, // used = 0
|
||||||
|
50
|
||||||
|
);
|
||||||
|
|
||||||
|
HarvesterHandler.run(creep, state);
|
||||||
|
|
||||||
|
expect(creep.memory.destination).toBeUndefined();
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
// ── onFindNewSource ───────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
describe('onFindNewSource', () => {
|
||||||
|
it('assigns the first available source spot to the creep', () => {
|
||||||
|
const state = makeState();
|
||||||
|
jest.spyOn(getById, 'getSourceById').mockReturnValue(makeSource());
|
||||||
|
|
||||||
|
const creep = makeCreep(); // no destination, empty store
|
||||||
|
|
||||||
|
HarvesterHandler.run(creep, state);
|
||||||
|
|
||||||
|
expect(creep.memory.destination?.type).toBe('source');
|
||||||
|
expect((creep.memory.destination as any).id).toBe('src1');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('does not assign a source when all spots are occupied', () => {
|
||||||
|
const state = makeState();
|
||||||
|
// Fill all non-center spots with OCCUPIED
|
||||||
|
state.sourcesStates['src1'].spots = state.sourcesStates[
|
||||||
|
'src1'
|
||||||
|
].spots.map((s: PositionSpotStatus) =>
|
||||||
|
s === PositionSpotStatus.CENTER
|
||||||
|
? s
|
||||||
|
: PositionSpotStatus.OCCUPIED
|
||||||
|
) as any;
|
||||||
|
|
||||||
|
jest.spyOn(getById, 'getSourceById').mockReturnValue(makeSource());
|
||||||
|
const creep = makeCreep();
|
||||||
|
|
||||||
|
HarvesterHandler.run(creep, state);
|
||||||
|
|
||||||
|
expect(creep.memory.destination).toBeUndefined();
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
// ── onSourceDestination ───────────────────────────────────────────────────
|
||||||
|
|
||||||
|
describe('onSourceDestination', () => {
|
||||||
|
it('harvests when in range', () => {
|
||||||
|
const state = makeState();
|
||||||
|
const source = makeSource();
|
||||||
|
jest.spyOn(getById, 'getSourceById').mockReturnValue(source);
|
||||||
|
|
||||||
|
const creep = makeCreep(
|
||||||
|
{ destination: { type: 'source', id: 'src1', sourceSpot: 0 } },
|
||||||
|
0,
|
||||||
|
50
|
||||||
|
);
|
||||||
|
(creep.harvest as jest.Mock).mockReturnValue((global as any).OK);
|
||||||
|
|
||||||
|
HarvesterHandler.run(creep, state);
|
||||||
|
|
||||||
|
expect(creep.harvest).toHaveBeenCalledWith(source);
|
||||||
|
expect(creep.moveTo).not.toHaveBeenCalled();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('moves to source when not in range', () => {
|
||||||
|
const state = makeState();
|
||||||
|
const source = makeSource();
|
||||||
|
jest.spyOn(getById, 'getSourceById').mockReturnValue(source);
|
||||||
|
|
||||||
|
const creep = makeCreep(
|
||||||
|
{ destination: { type: 'source', id: 'src1', sourceSpot: 0 } },
|
||||||
|
0,
|
||||||
|
50
|
||||||
|
);
|
||||||
|
(creep.harvest as jest.Mock).mockReturnValue(
|
||||||
|
(global as any).ERR_NOT_IN_RANGE
|
||||||
|
);
|
||||||
|
|
||||||
|
HarvesterHandler.run(creep, state);
|
||||||
|
|
||||||
|
expect(creep.moveTo).toHaveBeenCalled();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('logs and returns when source is not found', () => {
|
||||||
|
const state = makeState();
|
||||||
|
jest.spyOn(getById, 'getSourceById').mockReturnValue(null);
|
||||||
|
|
||||||
|
const creep = makeCreep(
|
||||||
|
{
|
||||||
|
destination: {
|
||||||
|
type: 'source',
|
||||||
|
id: 'unknown',
|
||||||
|
sourceSpot: 0,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
0,
|
||||||
|
50
|
||||||
|
);
|
||||||
|
|
||||||
|
expect(() => HarvesterHandler.run(creep, state)).not.toThrow();
|
||||||
|
expect(creep.harvest).not.toHaveBeenCalled();
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
// ── onSpawnDestination ────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
describe('onSpawnDestination', () => {
|
||||||
|
it('transfers energy when in range', () => {
|
||||||
|
const state = makeState();
|
||||||
|
const spawn = makeSpawn();
|
||||||
|
jest.spyOn(getById, 'getSpawnById').mockReturnValue(spawn);
|
||||||
|
|
||||||
|
const creep = makeCreep(
|
||||||
|
{ destination: { type: 'spawn', id: 'spawn1' } },
|
||||||
|
50,
|
||||||
|
50
|
||||||
|
);
|
||||||
|
(creep.transfer as jest.Mock).mockReturnValue((global as any).OK);
|
||||||
|
|
||||||
|
HarvesterHandler.run(creep, state);
|
||||||
|
|
||||||
|
expect(creep.transfer).toHaveBeenCalledWith(
|
||||||
|
spawn,
|
||||||
|
(global as any).RESOURCE_ENERGY
|
||||||
|
);
|
||||||
|
expect(creep.moveTo).not.toHaveBeenCalled();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('moves to spawn when not in range', () => {
|
||||||
|
const state = makeState();
|
||||||
|
const spawn = makeSpawn();
|
||||||
|
jest.spyOn(getById, 'getSpawnById').mockReturnValue(spawn);
|
||||||
|
|
||||||
|
const creep = makeCreep(
|
||||||
|
{ destination: { type: 'spawn', id: 'spawn1' } },
|
||||||
|
50,
|
||||||
|
50
|
||||||
|
);
|
||||||
|
(creep.transfer as jest.Mock).mockReturnValue(
|
||||||
|
(global as any).ERR_NOT_IN_RANGE
|
||||||
|
);
|
||||||
|
|
||||||
|
HarvesterHandler.run(creep, state);
|
||||||
|
|
||||||
|
expect(creep.moveTo).toHaveBeenCalledWith(
|
||||||
|
spawn,
|
||||||
|
expect.any(Object)
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('logs and returns when spawn is not found', () => {
|
||||||
|
const state = makeState();
|
||||||
|
jest.spyOn(getById, 'getSpawnById').mockReturnValue(null);
|
||||||
|
|
||||||
|
const creep = makeCreep(
|
||||||
|
{ destination: { type: 'spawn', id: 'spawn1' } },
|
||||||
|
50,
|
||||||
|
50
|
||||||
|
);
|
||||||
|
|
||||||
|
expect(() => HarvesterHandler.run(creep, state)).not.toThrow();
|
||||||
|
expect(creep.transfer).not.toHaveBeenCalled();
|
||||||
|
});
|
||||||
|
});
|
||||||
|
});
|
||||||
404
tests/roleHandlers/upgrader.handler.test.ts
Normal file
404
tests/roleHandlers/upgrader.handler.test.ts
Normal file
@@ -0,0 +1,404 @@
|
|||||||
|
import UpgraderHandler from '@/roleHandlers/upgrader.handler';
|
||||||
|
import * as getById from '@/utils/funcs/getById';
|
||||||
|
import {
|
||||||
|
PositionSpotStatus,
|
||||||
|
createSourcePositionMatrix,
|
||||||
|
} from '@/utils/positions';
|
||||||
|
import '~/tests/__mocks__/screeps';
|
||||||
|
|
||||||
|
// ─── Helpers ────────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
function makeState(overrides: Partial<GameState> = {}): GameState {
|
||||||
|
const spots = createSourcePositionMatrix(PositionSpotStatus.EMPTY);
|
||||||
|
return {
|
||||||
|
sourcesStates: {
|
||||||
|
src1: { spots },
|
||||||
|
},
|
||||||
|
...overrides,
|
||||||
|
} as unknown as GameState;
|
||||||
|
}
|
||||||
|
|
||||||
|
function makeCreepMemory(overrides: Partial<CreepMemory> = {}): CreepMemory {
|
||||||
|
return {
|
||||||
|
role: 'upgrader',
|
||||||
|
spawnId: 'spawn1',
|
||||||
|
...overrides,
|
||||||
|
} as CreepMemory;
|
||||||
|
}
|
||||||
|
|
||||||
|
function makeStore(used: number, capacity: number) {
|
||||||
|
return {
|
||||||
|
getFreeCapacity: (_res: string) => capacity - used,
|
||||||
|
getUsedCapacity: (_res: string) => used,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function makePos(x = 0, y = 0, roomName = 'W1N1') {
|
||||||
|
return new (global as any).RoomPosition(x, y, roomName);
|
||||||
|
}
|
||||||
|
|
||||||
|
function makeSource(id = 'src1', x = 5, y = 5, roomName = 'W1N1') {
|
||||||
|
return {
|
||||||
|
id,
|
||||||
|
pos: makePos(x, y, roomName),
|
||||||
|
} as unknown as Source;
|
||||||
|
}
|
||||||
|
|
||||||
|
function makeController(id = 'ctrl1') {
|
||||||
|
return { id } as unknown as StructureController;
|
||||||
|
}
|
||||||
|
|
||||||
|
function makeCreep(
|
||||||
|
memoryOverrides: Partial<CreepMemory> = {},
|
||||||
|
storeUsed = 0,
|
||||||
|
storeCapacity = 50,
|
||||||
|
controller: StructureController | null = null
|
||||||
|
): Creep {
|
||||||
|
const memory = makeCreepMemory(memoryOverrides);
|
||||||
|
return {
|
||||||
|
name: 'Creep1',
|
||||||
|
memory,
|
||||||
|
store: makeStore(storeUsed, storeCapacity),
|
||||||
|
pos: makePos(),
|
||||||
|
room: {
|
||||||
|
controller:
|
||||||
|
controller !== null ? (controller ?? makeController()) : null,
|
||||||
|
},
|
||||||
|
harvest: jest.fn().mockReturnValue((global as any).OK),
|
||||||
|
moveTo: jest.fn().mockReturnValue((global as any).OK),
|
||||||
|
upgradeController: jest.fn().mockReturnValue((global as any).OK),
|
||||||
|
} as unknown as Creep;
|
||||||
|
}
|
||||||
|
|
||||||
|
// ─── Tests ───────────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
describe('UpgraderHandler', () => {
|
||||||
|
beforeEach(() => {
|
||||||
|
jest.clearAllMocks();
|
||||||
|
jest.spyOn(console, 'log').mockImplementation(() => {});
|
||||||
|
});
|
||||||
|
|
||||||
|
afterEach(() => {
|
||||||
|
jest.restoreAllMocks();
|
||||||
|
});
|
||||||
|
|
||||||
|
// ── destroy ──────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
describe('destroy', () => {
|
||||||
|
it('releases the source spot from destination and clears it', () => {
|
||||||
|
const state = makeState();
|
||||||
|
state.sourcesStates['src1'].spots[0] = PositionSpotStatus.OCCUPIED;
|
||||||
|
|
||||||
|
const memory = makeCreepMemory({
|
||||||
|
destination: { type: 'source', id: 'src1', sourceSpot: 0 },
|
||||||
|
});
|
||||||
|
|
||||||
|
UpgraderHandler.destroy(memory, state);
|
||||||
|
|
||||||
|
expect(state.sourcesStates['src1'].spots[0]).toBe(
|
||||||
|
PositionSpotStatus.EMPTY
|
||||||
|
);
|
||||||
|
expect(memory.destination).toBeUndefined();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('releases the source spot from previousDestination and clears it', () => {
|
||||||
|
const state = makeState();
|
||||||
|
state.sourcesStates['src1'].spots[3] = PositionSpotStatus.OCCUPIED;
|
||||||
|
|
||||||
|
const memory = makeCreepMemory({
|
||||||
|
previousDestination: {
|
||||||
|
type: 'source',
|
||||||
|
id: 'src1',
|
||||||
|
sourceSpot: 3,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
UpgraderHandler.destroy(memory, state);
|
||||||
|
|
||||||
|
expect(state.sourcesStates['src1'].spots[3]).toBe(
|
||||||
|
PositionSpotStatus.EMPTY
|
||||||
|
);
|
||||||
|
expect(memory.previousDestination).toBeUndefined();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('does nothing when destination is not a source', () => {
|
||||||
|
const state = makeState();
|
||||||
|
const memory = makeCreepMemory({
|
||||||
|
destination: { type: 'controller', id: 'ctrl1' },
|
||||||
|
});
|
||||||
|
|
||||||
|
UpgraderHandler.destroy(memory, state);
|
||||||
|
|
||||||
|
expect(
|
||||||
|
state.sourcesStates['src1'].spots.every(
|
||||||
|
(s: PositionSpotStatus) =>
|
||||||
|
s === PositionSpotStatus.EMPTY ||
|
||||||
|
s === PositionSpotStatus.CENTER
|
||||||
|
)
|
||||||
|
).toBe(true);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('does nothing when memory has no destination', () => {
|
||||||
|
const state = makeState();
|
||||||
|
const memory = makeCreepMemory();
|
||||||
|
|
||||||
|
expect(() => UpgraderHandler.destroy(memory, state)).not.toThrow();
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
// ── validateCreepMemory (via run) ────────────────────────────────────────
|
||||||
|
|
||||||
|
describe('validateCreepMemory (via run)', () => {
|
||||||
|
it('releases previousDestination source spot and deletes it', () => {
|
||||||
|
const state = makeState();
|
||||||
|
state.sourcesStates['src1'].spots[1] = PositionSpotStatus.OCCUPIED;
|
||||||
|
|
||||||
|
const creep = makeCreep({
|
||||||
|
previousDestination: {
|
||||||
|
type: 'source',
|
||||||
|
id: 'src1',
|
||||||
|
sourceSpot: 1,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
jest.spyOn(getById, 'getSourceById').mockReturnValue(null);
|
||||||
|
|
||||||
|
UpgraderHandler.run(creep, state);
|
||||||
|
|
||||||
|
expect(state.sourcesStates['src1'].spots[1]).toBe(
|
||||||
|
PositionSpotStatus.EMPTY
|
||||||
|
);
|
||||||
|
expect(creep.memory.previousDestination).toBeUndefined();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('transitions from source to controller destination when energy is full', () => {
|
||||||
|
const state = makeState();
|
||||||
|
const source = makeSource();
|
||||||
|
jest.spyOn(getById, 'getSourceById').mockReturnValue(source);
|
||||||
|
|
||||||
|
const controller = makeController();
|
||||||
|
jest.spyOn(getById, 'getControllerById').mockReturnValue(
|
||||||
|
controller
|
||||||
|
);
|
||||||
|
|
||||||
|
const creep = makeCreep(
|
||||||
|
{
|
||||||
|
destination: { type: 'source', id: 'src1', sourceSpot: 0 },
|
||||||
|
},
|
||||||
|
50, // full
|
||||||
|
50,
|
||||||
|
controller
|
||||||
|
);
|
||||||
|
|
||||||
|
UpgraderHandler.run(creep, state);
|
||||||
|
|
||||||
|
expect(creep.memory.destination?.type).toBe('controller');
|
||||||
|
expect(creep.memory.previousDestination?.type).toBe('source');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('clears controller destination when energy is empty', () => {
|
||||||
|
const state = makeState();
|
||||||
|
const controller = makeController();
|
||||||
|
jest.spyOn(getById, 'getControllerById').mockReturnValue(
|
||||||
|
controller
|
||||||
|
);
|
||||||
|
|
||||||
|
const creep = makeCreep(
|
||||||
|
{ destination: { type: 'controller', id: 'ctrl1' } },
|
||||||
|
0, // empty
|
||||||
|
50,
|
||||||
|
controller
|
||||||
|
);
|
||||||
|
|
||||||
|
UpgraderHandler.run(creep, state);
|
||||||
|
|
||||||
|
expect(creep.memory.destination).toBeUndefined();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('clears destination and logs when room has no controller during source→controller transition', () => {
|
||||||
|
const state = makeState();
|
||||||
|
// Occupy all spots so onFindNewSource cannot reassign a source
|
||||||
|
state.sourcesStates['src1'].spots = state.sourcesStates[
|
||||||
|
'src1'
|
||||||
|
].spots.map((s: PositionSpotStatus) =>
|
||||||
|
s === PositionSpotStatus.CENTER
|
||||||
|
? s
|
||||||
|
: PositionSpotStatus.OCCUPIED
|
||||||
|
) as any;
|
||||||
|
|
||||||
|
jest.spyOn(getById, 'getSourceById').mockReturnValue(makeSource());
|
||||||
|
|
||||||
|
const creep = makeCreep(
|
||||||
|
{ destination: { type: 'source', id: 'src1', sourceSpot: 0 } },
|
||||||
|
50,
|
||||||
|
50,
|
||||||
|
null // no controller in room
|
||||||
|
);
|
||||||
|
|
||||||
|
UpgraderHandler.run(creep, state);
|
||||||
|
|
||||||
|
expect(creep.memory.destination).toBeUndefined();
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
// ── onFindNewSource ───────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
describe('onFindNewSource', () => {
|
||||||
|
it('assigns the first available source spot to the creep', () => {
|
||||||
|
const state = makeState();
|
||||||
|
jest.spyOn(getById, 'getSourceById').mockReturnValue(makeSource());
|
||||||
|
|
||||||
|
const creep = makeCreep(); // no destination, empty store
|
||||||
|
|
||||||
|
UpgraderHandler.run(creep, state);
|
||||||
|
|
||||||
|
expect(creep.memory.destination?.type).toBe('source');
|
||||||
|
expect((creep.memory.destination as any).id).toBe('src1');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('does not assign a source when all spots are occupied', () => {
|
||||||
|
const state = makeState();
|
||||||
|
state.sourcesStates['src1'].spots = state.sourcesStates[
|
||||||
|
'src1'
|
||||||
|
].spots.map((s: PositionSpotStatus) =>
|
||||||
|
s === PositionSpotStatus.CENTER
|
||||||
|
? s
|
||||||
|
: PositionSpotStatus.OCCUPIED
|
||||||
|
) as any;
|
||||||
|
|
||||||
|
jest.spyOn(getById, 'getSourceById').mockReturnValue(makeSource());
|
||||||
|
const creep = makeCreep();
|
||||||
|
|
||||||
|
UpgraderHandler.run(creep, state);
|
||||||
|
|
||||||
|
expect(creep.memory.destination).toBeUndefined();
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
// ── onSourceDestination ───────────────────────────────────────────────────
|
||||||
|
|
||||||
|
describe('onSourceDestination', () => {
|
||||||
|
it('harvests when in range', () => {
|
||||||
|
const state = makeState();
|
||||||
|
const source = makeSource();
|
||||||
|
jest.spyOn(getById, 'getSourceById').mockReturnValue(source);
|
||||||
|
|
||||||
|
const creep = makeCreep(
|
||||||
|
{ destination: { type: 'source', id: 'src1', sourceSpot: 0 } },
|
||||||
|
0,
|
||||||
|
50
|
||||||
|
);
|
||||||
|
(creep.harvest as jest.Mock).mockReturnValue((global as any).OK);
|
||||||
|
|
||||||
|
UpgraderHandler.run(creep, state);
|
||||||
|
|
||||||
|
expect(creep.harvest).toHaveBeenCalledWith(source);
|
||||||
|
expect(creep.moveTo).not.toHaveBeenCalled();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('moves to source when not in range', () => {
|
||||||
|
const state = makeState();
|
||||||
|
const source = makeSource();
|
||||||
|
jest.spyOn(getById, 'getSourceById').mockReturnValue(source);
|
||||||
|
|
||||||
|
const creep = makeCreep(
|
||||||
|
{ destination: { type: 'source', id: 'src1', sourceSpot: 0 } },
|
||||||
|
0,
|
||||||
|
50
|
||||||
|
);
|
||||||
|
(creep.harvest as jest.Mock).mockReturnValue(
|
||||||
|
(global as any).ERR_NOT_IN_RANGE
|
||||||
|
);
|
||||||
|
|
||||||
|
UpgraderHandler.run(creep, state);
|
||||||
|
|
||||||
|
expect(creep.moveTo).toHaveBeenCalled();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('logs and returns when source is not found', () => {
|
||||||
|
const state = makeState();
|
||||||
|
jest.spyOn(getById, 'getSourceById').mockReturnValue(null);
|
||||||
|
|
||||||
|
const creep = makeCreep(
|
||||||
|
{
|
||||||
|
destination: {
|
||||||
|
type: 'source',
|
||||||
|
id: 'unknown',
|
||||||
|
sourceSpot: 0,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
0,
|
||||||
|
50
|
||||||
|
);
|
||||||
|
|
||||||
|
expect(() => UpgraderHandler.run(creep, state)).not.toThrow();
|
||||||
|
expect(creep.harvest).not.toHaveBeenCalled();
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
// ── onControllerDestination ───────────────────────────────────────────────
|
||||||
|
|
||||||
|
describe('onControllerDestination', () => {
|
||||||
|
it('upgrades controller when in range', () => {
|
||||||
|
const state = makeState();
|
||||||
|
const controller = makeController();
|
||||||
|
jest.spyOn(getById, 'getControllerById').mockReturnValue(
|
||||||
|
controller
|
||||||
|
);
|
||||||
|
|
||||||
|
const creep = makeCreep(
|
||||||
|
{ destination: { type: 'controller', id: 'ctrl1' } },
|
||||||
|
50,
|
||||||
|
50,
|
||||||
|
controller
|
||||||
|
);
|
||||||
|
(creep.upgradeController as jest.Mock).mockReturnValue(
|
||||||
|
(global as any).OK
|
||||||
|
);
|
||||||
|
|
||||||
|
UpgraderHandler.run(creep, state);
|
||||||
|
|
||||||
|
expect(creep.upgradeController).toHaveBeenCalledWith(controller);
|
||||||
|
expect(creep.moveTo).not.toHaveBeenCalled();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('moves to controller when not in range', () => {
|
||||||
|
const state = makeState();
|
||||||
|
const controller = makeController();
|
||||||
|
jest.spyOn(getById, 'getControllerById').mockReturnValue(
|
||||||
|
controller
|
||||||
|
);
|
||||||
|
|
||||||
|
const creep = makeCreep(
|
||||||
|
{ destination: { type: 'controller', id: 'ctrl1' } },
|
||||||
|
50,
|
||||||
|
50,
|
||||||
|
controller
|
||||||
|
);
|
||||||
|
(creep.upgradeController as jest.Mock).mockReturnValue(
|
||||||
|
(global as any).ERR_NOT_IN_RANGE
|
||||||
|
);
|
||||||
|
|
||||||
|
UpgraderHandler.run(creep, state);
|
||||||
|
|
||||||
|
expect(creep.moveTo).toHaveBeenCalledWith(
|
||||||
|
controller,
|
||||||
|
expect.any(Object)
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('logs and returns when controller is not found by ID', () => {
|
||||||
|
const state = makeState();
|
||||||
|
jest.spyOn(getById, 'getControllerById').mockReturnValue(null);
|
||||||
|
|
||||||
|
const creep = makeCreep(
|
||||||
|
{ destination: { type: 'controller', id: 'ctrl1' } },
|
||||||
|
50,
|
||||||
|
50
|
||||||
|
);
|
||||||
|
|
||||||
|
expect(() => UpgraderHandler.run(creep, state)).not.toThrow();
|
||||||
|
expect(creep.upgradeController).not.toHaveBeenCalled();
|
||||||
|
});
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -1,23 +1,27 @@
|
|||||||
{
|
{
|
||||||
"compilerOptions": {
|
"compilerOptions": {
|
||||||
"target": "ES6",
|
"target": "ES6",
|
||||||
"lib": ["ES2017", "DOM"],
|
"lib": ["ES2017", "DOM"],
|
||||||
"module": "commonjs",
|
"module": "commonjs",
|
||||||
"moduleResolution": "node",
|
"moduleResolution": "node",
|
||||||
"outDir": "dist",
|
"outDir": "dist",
|
||||||
"rootDir": "src",
|
"baseUrl": ".",
|
||||||
"baseUrl": "src",
|
"strict": true,
|
||||||
"strict": true,
|
"noImplicitReturns": true,
|
||||||
"noImplicitReturns": true,
|
"noUnusedLocals": true,
|
||||||
"noUnusedLocals": true,
|
"noUnusedParameters": true,
|
||||||
"noUnusedParameters": true,
|
"noFallthroughCasesInSwitch": true,
|
||||||
"noFallthroughCasesInSwitch": true,
|
"allowUnreachableCode": false,
|
||||||
"allowUnreachableCode": false,
|
"sourceMap": true,
|
||||||
"sourceMap": true,
|
"experimentalDecorators": true,
|
||||||
"experimentalDecorators": true,
|
"allowSyntheticDefaultImports": true,
|
||||||
"allowSyntheticDefaultImports": true,
|
"types": ["node", "screeps", "jest"],
|
||||||
"types": ["screeps"]
|
"paths": {
|
||||||
},
|
"@/*": ["./src/*"],
|
||||||
"include": ["src/**/*"],
|
"~/*": ["./*"]
|
||||||
"exclude": ["node_modules", "dist"]
|
},
|
||||||
|
"typeRoots": ["node_modules/@types", "src"]
|
||||||
|
},
|
||||||
|
"include": ["src/global.d.ts", "src/*.ts", "src/**/*.ts"],
|
||||||
|
"exclude": ["node_modules", "dist"]
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,6 +0,0 @@
|
|||||||
{
|
|
||||||
"extends": "./tsconfig.json",
|
|
||||||
"compilerOptions": {
|
|
||||||
"module": "CommonJs"
|
|
||||||
}
|
|
||||||
}
|
|
||||||
Reference in New Issue
Block a user