Compare commits
13 Commits
restructur
...
dda6942228
| Author | SHA1 | Date | |
|---|---|---|---|
|
dda6942228
|
|||
|
90701eec3d
|
|||
|
e18980938e
|
|||
|
a3841bd173
|
|||
|
a4b8081006
|
|||
|
f8bb65c0f4
|
|||
|
be66fe0822
|
|||
|
fb689cc300
|
|||
|
952d274c53
|
|||
|
230153403f
|
|||
|
6ebf591d64
|
|||
|
2c93b65b3d
|
|||
|
6e8c8ae428
|
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.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": [
|
||||
"ms-vscode-remote.vscode-remote-extensionpack"
|
||||
]
|
||||
"recommendations": ["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,15 +1,18 @@
|
||||
import { build } from 'esbuild';
|
||||
|
||||
build({
|
||||
entryPoints: ['src/main.ts'],
|
||||
bundle: true,
|
||||
target: 'es6', // Screeps supports ES2018 well
|
||||
platform: 'node',
|
||||
tsconfig: 'tsconfig.json',
|
||||
format: 'cjs',
|
||||
outdir: 'dist',
|
||||
sourcemap: true,
|
||||
logLevel: 'info',
|
||||
minify: false,
|
||||
keepNames: true, // optional: keeps function/class names
|
||||
entryPoints: ['src/main.ts'],
|
||||
bundle: true,
|
||||
target: 'es2018', // Screeps supports ES2018 well
|
||||
platform: 'node',
|
||||
tsconfig: 'tsconfig.json',
|
||||
format: 'cjs',
|
||||
outdir: 'dist',
|
||||
sourcemap: true,
|
||||
logLevel: 'info',
|
||||
minify: false,
|
||||
keepNames: true, // optional: keeps function/class names
|
||||
banner: {
|
||||
js: `// Vitor Hideyoshi <vitor.h.n.batista@gmail.com> - ${new Date().toISOString()}\n`,
|
||||
},
|
||||
}).catch(() => process.exit(1));
|
||||
|
||||
@@ -1,53 +1,64 @@
|
||||
const {
|
||||
defineConfig,
|
||||
} = require("eslint/config");
|
||||
const { defineConfig } = require('eslint/config');
|
||||
|
||||
const globals = require("globals");
|
||||
const tsParser = require("@typescript-eslint/parser");
|
||||
const typescriptEslint = require("@typescript-eslint/eslint-plugin");
|
||||
const js = require("@eslint/js");
|
||||
const globals = require('globals');
|
||||
const tsParser = require('@typescript-eslint/parser');
|
||||
const typescriptEslint = require('@typescript-eslint/eslint-plugin');
|
||||
const js = require('@eslint/js');
|
||||
|
||||
const {
|
||||
FlatCompat,
|
||||
} = require("@eslint/eslintrc");
|
||||
const { FlatCompat } = require('@eslint/eslintrc');
|
||||
|
||||
const compat = new FlatCompat({
|
||||
baseDirectory: __dirname,
|
||||
recommendedConfig: js.configs.recommended,
|
||||
allConfig: js.configs.all
|
||||
allConfig: js.configs.all,
|
||||
});
|
||||
|
||||
module.exports = defineConfig([{
|
||||
languageOptions: {
|
||||
globals: {
|
||||
...globals.browser,
|
||||
module.exports = defineConfig([
|
||||
{
|
||||
languageOptions: {
|
||||
globals: {
|
||||
...globals.browser,
|
||||
},
|
||||
|
||||
parser: tsParser,
|
||||
ecmaVersion: 'latest',
|
||||
sourceType: 'module',
|
||||
parserOptions: {},
|
||||
},
|
||||
|
||||
parser: tsParser,
|
||||
"ecmaVersion": "latest",
|
||||
"sourceType": "module",
|
||||
parserOptions: {},
|
||||
},
|
||||
extends: compat.extends(
|
||||
'eslint:recommended',
|
||||
'plugin:@typescript-eslint/recommended',
|
||||
'prettier'
|
||||
),
|
||||
|
||||
extends: compat.extends("eslint:recommended", "plugin:@typescript-eslint/recommended", "prettier"),
|
||||
|
||||
plugins: {
|
||||
"@typescript-eslint": typescriptEslint,
|
||||
},
|
||||
|
||||
"rules": {
|
||||
"@typescript-eslint/no-namespace": "off",
|
||||
"@typescript-eslint/no-explicit-any": "off",
|
||||
},
|
||||
}, {
|
||||
languageOptions: {
|
||||
globals: {
|
||||
...globals.node,
|
||||
plugins: {
|
||||
'@typescript-eslint': typescriptEslint,
|
||||
},
|
||||
|
||||
"sourceType": "script",
|
||||
parserOptions: {},
|
||||
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,
|
||||
},
|
||||
|
||||
files: ["**/.eslintrc.{js,cjs}"],
|
||||
}]);
|
||||
sourceType: 'script',
|
||||
parserOptions: {},
|
||||
},
|
||||
|
||||
files: ['**/.eslintrc.{js,cjs}'],
|
||||
},
|
||||
]);
|
||||
|
||||
8495
package-lock.json
generated
8495
package-lock.json
generated
File diff suppressed because it is too large
Load Diff
94
package.json
94
package.json
@@ -1,58 +1,40 @@
|
||||
{
|
||||
"name": "screeps-typescript-starter",
|
||||
"version": "3.0.0",
|
||||
"description": "",
|
||||
"scripts": {
|
||||
"build": "node esbuild.config.mjs",
|
||||
"push:main": "npm run build && screeps-api --server main upload dist/*.js",
|
||||
"push:sim": "npm run build && screeps-api --server main upload --branch sim dist/*.js",
|
||||
"format": "prettier --config .prettierrc 'src/**/*.ts' --write && eslint --fix src/"
|
||||
},
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "git+https://github.com/screepers/screeps-typescript-starter.git"
|
||||
},
|
||||
"author": "",
|
||||
"license": "Unlicense",
|
||||
"bugs": {
|
||||
"url": "https://github.com/screepers/screeps-typescript-starter/issues"
|
||||
},
|
||||
"homepage": "https://github.com/screepers/screeps-typescript-starter#readme",
|
||||
"devDependencies": {
|
||||
"@eslint/eslintrc": "^3.3.1",
|
||||
"@eslint/js": "^9.30.1",
|
||||
"@rollup/plugin-commonjs": "^28.0.6",
|
||||
"@rollup/plugin-node-resolve": "^16.0.1",
|
||||
"@types/chai": "^5.2.2",
|
||||
"@types/lodash": "4.17.20",
|
||||
"@types/mocha": "^10.0.10",
|
||||
"@types/node": "^24.0.10",
|
||||
"@types/screeps": "^3.3.8",
|
||||
"@types/sinon": "^17.0.4",
|
||||
"@types/sinon-chai": "^4.0.0",
|
||||
"@typescript-eslint/eslint-plugin": "^8.35.1",
|
||||
"@typescript-eslint/parser": "^8.35.1",
|
||||
"@typescript-eslint/typescript-estree": "^8.35.1",
|
||||
"chai": "^5.2.0",
|
||||
"esbuild": "^0.25.5",
|
||||
"eslint": "^9.30.1",
|
||||
"eslint-config-prettier": "^10.1.5",
|
||||
"eslint-import-resolver-typescript": "^4.4.4",
|
||||
"eslint-plugin-import": "^2.32.0",
|
||||
"eslint-plugin-prettier": "^5.5.1",
|
||||
"globals": "^16.3.0",
|
||||
"lodash": "^4.17.21",
|
||||
"mocha": "^11.7.1",
|
||||
"prettier": "^3.6.2",
|
||||
"screeps-api": "^1.7.2",
|
||||
"shelljs": "^0.10.0",
|
||||
"sinon": "^21.0.0",
|
||||
"sinon-chai": "^4.0.0",
|
||||
"ts-node": "^10.9.2",
|
||||
"tsconfig-paths": "^4.2.0",
|
||||
"typescript": "^5.8.3"
|
||||
},
|
||||
"dependencies": {
|
||||
"source-map": "~0.7.4"
|
||||
}
|
||||
"name": "hideyoshi-screeps",
|
||||
"version": "0.0.0",
|
||||
"description": "Personal Screeps codebase for Hideyoshi",
|
||||
"scripts": {
|
||||
"build": "node esbuild.config.mjs",
|
||||
"push": "npm run build && ts-node publish.ts",
|
||||
"format": "prettier --check --ignore-path .gitignore .",
|
||||
"format:fix": "prettier --write --ignore-path .gitignore ."
|
||||
},
|
||||
"dependencies": {
|
||||
"@trivago/prettier-plugin-sort-imports": "^6.0.2",
|
||||
"@types/screeps": "^3.3.8",
|
||||
"dotenv": "^17.4.2",
|
||||
"esbuild": "^0.28.0",
|
||||
"prettier": "^3.8.3",
|
||||
"ts-node": "^10.9.2",
|
||||
"typescript": "^6.0.3",
|
||||
"zod": "^4.3.6"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/node": "^25.6.0"
|
||||
},
|
||||
"prettier": {
|
||||
"trailingComma": "es5",
|
||||
"semi": true,
|
||||
"tabWidth": 4,
|
||||
"useTabs": false,
|
||||
"singleQuote": true,
|
||||
"jsxSingleQuote": true,
|
||||
"plugins": [
|
||||
"@trivago/prettier-plugin-sort-imports"
|
||||
],
|
||||
"importOrderParserPlugins": [
|
||||
"typescript",
|
||||
"jsx",
|
||||
"decorators-legacy"
|
||||
]
|
||||
}
|
||||
}
|
||||
|
||||
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;
|
||||
15
src/RoomRunner.ts
Normal file
15
src/RoomRunner.ts
Normal file
@@ -0,0 +1,15 @@
|
||||
import CreepRunner from 'CreepRunner';
|
||||
import RequisitionsManager from 'RequisitionsManager';
|
||||
import RoomInspector from 'RoomInspector';
|
||||
|
||||
class RoomRunner {
|
||||
public static run(room: Room, state: GameState): GameState {
|
||||
state = RoomInspector.inspectState(room, state);
|
||||
|
||||
state = CreepRunner.run(room, state);
|
||||
|
||||
return RequisitionsManager.validateState(room, state);
|
||||
}
|
||||
}
|
||||
|
||||
export default RoomRunner;
|
||||
32
src/main.ts
32
src/main.ts
@@ -1,6 +1,6 @@
|
||||
import { CreepDestination } from "types/creeps";
|
||||
import { SourcePositionMatrix, SourceSpotStatus } from "./types/source";
|
||||
import SpawnHandler from "spawnHandler";
|
||||
import RoomRunner from 'RoomRunner';
|
||||
import { CreepDestination } from 'types/creeps';
|
||||
import { PositionMatrix } from 'utils/positions';
|
||||
|
||||
declare global {
|
||||
/*
|
||||
@@ -13,7 +13,7 @@ declare global {
|
||||
*/
|
||||
interface SourceState {
|
||||
id: string;
|
||||
spots: SourcePositionMatrix;
|
||||
spots: PositionMatrix;
|
||||
pos: RoomPosition;
|
||||
}
|
||||
|
||||
@@ -26,7 +26,7 @@ declare global {
|
||||
interface Memory {
|
||||
uuid: number;
|
||||
log: any;
|
||||
spawnStates: { [name: string]: GameState };
|
||||
roomStateRegistry: { [name: string]: GameState };
|
||||
}
|
||||
|
||||
interface CreepMemory {
|
||||
@@ -46,15 +46,21 @@ declare global {
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
export const loop = () => {
|
||||
Memory.spawnStates = Memory.spawnStates || {};
|
||||
Memory.roomStateRegistry = Memory.roomStateRegistry || {};
|
||||
|
||||
for (const spawnName of Object.keys(Game.spawns)) {
|
||||
const spawnState = Memory.spawnStates[spawnName] || {};
|
||||
|
||||
const spawnHandler = new SpawnHandler(Game.spawns[spawnName]);
|
||||
|
||||
Memory.spawnStates[spawnName] = spawnHandler.run(spawnState);
|
||||
for (const roomName of Object.keys(Game.rooms)) {
|
||||
try {
|
||||
Memory.roomStateRegistry[roomName] = RoomRunner.run(
|
||||
Game.rooms[roomName],
|
||||
Memory.roomStateRegistry[roomName] || {}
|
||||
);
|
||||
} catch (error) {
|
||||
console.log(
|
||||
`Error running RoomRunner for room ${roomName}:`,
|
||||
error
|
||||
);
|
||||
delete Memory.roomStateRegistry[roomName];
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
12
src/roleHandlers/BaseHandler.interface.ts
Normal file
12
src/roleHandlers/BaseHandler.interface.ts
Normal file
@@ -0,0 +1,12 @@
|
||||
export abstract class RoleHandler {
|
||||
public static destroy(_creepMemory: CreepMemory, _state: GameState): void {
|
||||
// Default implementation does nothing
|
||||
// Subclasses should override this method
|
||||
}
|
||||
|
||||
public static run(_creep: Creep, state: GameState): GameState {
|
||||
// Default implementation returns state unchanged
|
||||
// Subclasses should override this method
|
||||
return state;
|
||||
}
|
||||
}
|
||||
@@ -1,4 +0,0 @@
|
||||
export abstract class RoleHandler {
|
||||
static destroy(creepMemory: CreepMemory, state: GameState): void {};
|
||||
static run(creep: Creep, state: GameState): GameState {};
|
||||
}
|
||||
@@ -1,17 +1,20 @@
|
||||
import { getSourceById, getSpawnById } from "utils/funcs/get_by_id";
|
||||
import { RoleHandler } from "./base.handler.interface";
|
||||
import { getNextEmptySpot, getPositionWithDelta, setSpotStatus, SourceSpotStatus } from "types/source";
|
||||
import { SourceDestination } from "types/creeps";
|
||||
|
||||
|
||||
import { RoleHandler } from './BaseHandler.interface';
|
||||
import { SourceDestination } from 'types/creeps';
|
||||
import { getSourceById, getSpawnById } from 'utils/funcs/getById';
|
||||
import {
|
||||
getNextEmptySpot,
|
||||
getPositionWithDelta,
|
||||
PositionSpotStatus,
|
||||
setSpotStatus,
|
||||
} from 'utils/positions';
|
||||
|
||||
class HarvesterHandler extends RoleHandler {
|
||||
public static destroy(creepMemory: CreepMemory, state: GameState): void {
|
||||
if (creepMemory.destination?.type === "source") {
|
||||
if (creepMemory.destination?.type === 'source') {
|
||||
this.releaseSourceSpot(creepMemory.destination, state);
|
||||
delete creepMemory.destination; // Clear destination after releasing the spot
|
||||
}
|
||||
if (creepMemory.previousDestination?.type === "source") {
|
||||
if (creepMemory.previousDestination?.type === 'source') {
|
||||
this.releaseSourceSpot(creepMemory.previousDestination, state);
|
||||
delete creepMemory.previousDestination; // Clear previous destination after releasing the spot
|
||||
}
|
||||
@@ -21,10 +24,10 @@ class HarvesterHandler extends RoleHandler {
|
||||
this.validateCreepMemory(creep, state);
|
||||
|
||||
switch (creep.memory.destination?.type) {
|
||||
case "spawn":
|
||||
case 'spawn':
|
||||
this.onSpawnDestination(creep, state);
|
||||
break;
|
||||
case "source":
|
||||
case 'source':
|
||||
this.onSourceDestination(creep, state);
|
||||
break;
|
||||
default:
|
||||
@@ -36,11 +39,11 @@ class HarvesterHandler extends RoleHandler {
|
||||
}
|
||||
|
||||
private static validateCreepMemory(creep: Creep, state: GameState) {
|
||||
if (creep.memory.previousDestination?.type === "source") {
|
||||
if (creep.memory.previousDestination?.type === 'source') {
|
||||
setSpotStatus(
|
||||
state.sourcesStates[creep.memory.previousDestination.id].spots,
|
||||
creep.memory.previousDestination.sourceSpot,
|
||||
SourceSpotStatus.EMPTY
|
||||
PositionSpotStatus.EMPTY
|
||||
);
|
||||
delete creep.memory.previousDestination;
|
||||
}
|
||||
@@ -49,16 +52,22 @@ class HarvesterHandler extends RoleHandler {
|
||||
return; // No destination set, nothing to validate
|
||||
}
|
||||
|
||||
if (creep.memory.destination.type === "source" && !creep.store.getFreeCapacity(RESOURCE_ENERGY)) {
|
||||
if (
|
||||
creep.memory.destination.type === 'source' &&
|
||||
!creep.store.getFreeCapacity(RESOURCE_ENERGY)
|
||||
) {
|
||||
creep.memory.previousDestination = creep.memory.destination;
|
||||
creep.memory.destination = {
|
||||
id: creep.memory.spawnId,
|
||||
type: "spawn"
|
||||
type: 'spawn',
|
||||
};
|
||||
return;
|
||||
}
|
||||
|
||||
if (creep.memory.destination.type === "spawn" && creep.store.getUsedCapacity(RESOURCE_ENERGY) === 0) {
|
||||
if (
|
||||
creep.memory.destination.type === 'spawn' &&
|
||||
creep.store.getUsedCapacity(RESOURCE_ENERGY) === 0
|
||||
) {
|
||||
delete creep.memory.destination; // Clear destination if no energy is available
|
||||
return;
|
||||
}
|
||||
@@ -83,21 +92,24 @@ class HarvesterHandler extends RoleHandler {
|
||||
setSpotStatus(
|
||||
sourceState.spots,
|
||||
emptySpot,
|
||||
SourceSpotStatus.OCCUPIED
|
||||
PositionSpotStatus.OCCUPIED
|
||||
);
|
||||
creep.memory.destination = {
|
||||
id: source.id,
|
||||
type: "source",
|
||||
sourceSpot: emptySpot
|
||||
type: 'source',
|
||||
sourceSpot: emptySpot,
|
||||
};
|
||||
return
|
||||
return;
|
||||
}
|
||||
|
||||
console.log(`Creep ${creep.name} could not find a valid source.`);
|
||||
}
|
||||
|
||||
private static onSourceDestination(creep: Creep, state: GameState) {
|
||||
if (!creep.memory.destination || creep.memory.destination.type !== "source") {
|
||||
private static onSourceDestination(creep: Creep, _state: GameState) {
|
||||
if (
|
||||
!creep.memory.destination ||
|
||||
creep.memory.destination.type !== 'source'
|
||||
) {
|
||||
console.log(`Creep ${creep.name} has no valid destination set.`);
|
||||
delete creep.memory.destination;
|
||||
return;
|
||||
@@ -111,18 +123,26 @@ class HarvesterHandler extends RoleHandler {
|
||||
|
||||
if (creep.harvest(source) === ERR_NOT_IN_RANGE) {
|
||||
const sourceSpotPosition = getPositionWithDelta(
|
||||
source.pos, creep.memory.destination.sourceSpot
|
||||
)
|
||||
creep.moveTo(sourceSpotPosition, { reusePath: 10, visualizePathStyle: { stroke: '#ffffff', lineStyle: 'dashed', strokeWidth: 0.1 } });
|
||||
source.pos,
|
||||
creep.memory.destination.sourceSpot
|
||||
);
|
||||
creep.moveTo(sourceSpotPosition, {
|
||||
reusePath: 10,
|
||||
visualizePathStyle: {
|
||||
stroke: '#ffffff',
|
||||
lineStyle: 'dashed',
|
||||
strokeWidth: 0.1,
|
||||
},
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
private static onSpawnDestination(creep: Creep, state: GameState) {
|
||||
private static onSpawnDestination(creep: Creep, _state: GameState) {
|
||||
if (creep.memory.destination === undefined) {
|
||||
creep.memory.destination = {
|
||||
id: creep.memory.spawnId,
|
||||
type: "spawn"
|
||||
}
|
||||
type: 'spawn',
|
||||
};
|
||||
}
|
||||
|
||||
const spawn = getSpawnById(creep.memory.destination.id);
|
||||
@@ -132,23 +152,31 @@ class HarvesterHandler extends RoleHandler {
|
||||
}
|
||||
|
||||
if (creep.transfer(spawn, RESOURCE_ENERGY) === ERR_NOT_IN_RANGE) {
|
||||
creep.moveTo(spawn, { reusePath: 10, visualizePathStyle: { stroke: '#ffffff', lineStyle: 'dashed', strokeWidth: 0.1 } });
|
||||
creep.moveTo(spawn, {
|
||||
reusePath: 10,
|
||||
visualizePathStyle: {
|
||||
stroke: '#ffffff',
|
||||
lineStyle: 'dashed',
|
||||
strokeWidth: 0.1,
|
||||
},
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
private static findClosestSource(creep: Creep, state: GameState): Source[] {
|
||||
const sources = Object.keys(state.sourcesStates)
|
||||
.map(sourceId => getSourceById(sourceId))
|
||||
.filter(source => source !== null)
|
||||
.map((sourceId) => getSourceById(sourceId))
|
||||
.filter((source) => source !== null)
|
||||
.sort((a, b) => creep.pos.getRangeTo(a) - creep.pos.getRangeTo(b));
|
||||
|
||||
return sources as Source[];
|
||||
}
|
||||
|
||||
private static releaseSourceSpot(destination: SourceDestination, state: GameState) {
|
||||
if (!destination || destination.type !== "source") {
|
||||
private static releaseSourceSpot(
|
||||
destination: SourceDestination,
|
||||
state: GameState
|
||||
) {
|
||||
if (!destination || destination.type !== 'source') {
|
||||
return; // Not a source destination, nothing to release
|
||||
}
|
||||
|
||||
@@ -161,13 +189,9 @@ class HarvesterHandler extends RoleHandler {
|
||||
setSpotStatus(
|
||||
sourceState.spots,
|
||||
destination.sourceSpot,
|
||||
SourceSpotStatus.EMPTY
|
||||
PositionSpotStatus.EMPTY
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
export default HarvesterHandler;
|
||||
|
||||
@@ -1,9 +1,5 @@
|
||||
import { RoleHandler } from "./base.handler.interface";
|
||||
|
||||
import HarvesterHandler from "./harvester.handler";
|
||||
import UpgraderHandler from "./upgrader.handler";
|
||||
|
||||
|
||||
|
||||
import { RoleHandler } from './BaseHandler.interface';
|
||||
import HarvesterHandler from './harvester.handler';
|
||||
import UpgraderHandler from './upgrader.handler';
|
||||
|
||||
export { RoleHandler, HarvesterHandler, UpgraderHandler };
|
||||
|
||||
@@ -1,16 +1,20 @@
|
||||
import { getControllerById, getSourceById } from "utils/funcs/get_by_id";
|
||||
import { RoleHandler } from "./base.handler.interface";
|
||||
import { getNextEmptySpot, getPositionWithDelta, setSpotStatus, SourceSpotStatus } from "types/source";
|
||||
|
||||
|
||||
import { RoleHandler } from './BaseHandler.interface';
|
||||
import { SourceDestination } from 'types/creeps';
|
||||
import { getControllerById, getSourceById } from 'utils/funcs/getById';
|
||||
import {
|
||||
getNextEmptySpot,
|
||||
PositionSpotStatus,
|
||||
setSpotStatus,
|
||||
getPositionWithDelta,
|
||||
} from 'utils/positions';
|
||||
|
||||
class UpgraderHandler extends RoleHandler {
|
||||
public static destroy(creepMemory: CreepMemory, state: GameState): void {
|
||||
if (creepMemory.destination?.type === "source") {
|
||||
if (creepMemory.destination?.type === 'source') {
|
||||
this.releaseSourceSpot(creepMemory.destination, state);
|
||||
delete creepMemory.destination; // Clear destination after releasing the spot
|
||||
}
|
||||
if (creepMemory.previousDestination?.type === "source") {
|
||||
if (creepMemory.previousDestination?.type === 'source') {
|
||||
this.releaseSourceSpot(creepMemory.previousDestination, state);
|
||||
delete creepMemory.previousDestination; // Clear previous destination after releasing the spot
|
||||
}
|
||||
@@ -20,10 +24,10 @@ class UpgraderHandler extends RoleHandler {
|
||||
this.validateCreepMemory(creep, state);
|
||||
|
||||
switch (creep.memory.destination?.type) {
|
||||
case "controller":
|
||||
case 'controller':
|
||||
this.onControllerDestination(creep, state);
|
||||
break;
|
||||
case "source":
|
||||
case 'source':
|
||||
this.onSourceDestination(creep, state);
|
||||
break;
|
||||
default:
|
||||
@@ -35,11 +39,14 @@ class UpgraderHandler extends RoleHandler {
|
||||
}
|
||||
|
||||
private static validateCreepMemory(creep: Creep, state: GameState) {
|
||||
if (!!creep.memory.previousDestination && creep.memory.previousDestination.type === "source") {
|
||||
if (
|
||||
!!creep.memory.previousDestination &&
|
||||
creep.memory.previousDestination.type === 'source'
|
||||
) {
|
||||
setSpotStatus(
|
||||
state.sourcesStates[creep.memory.previousDestination.id].spots,
|
||||
creep.memory.previousDestination.sourceSpot,
|
||||
SourceSpotStatus.EMPTY
|
||||
PositionSpotStatus.EMPTY
|
||||
);
|
||||
delete creep.memory.previousDestination;
|
||||
}
|
||||
@@ -48,23 +55,31 @@ class UpgraderHandler extends RoleHandler {
|
||||
return; // No destination set, nothing to validate
|
||||
}
|
||||
|
||||
if (creep.memory.destination.type === "source" && !creep.store.getFreeCapacity(RESOURCE_ENERGY)) {
|
||||
if (
|
||||
creep.memory.destination.type === 'source' &&
|
||||
!creep.store.getFreeCapacity(RESOURCE_ENERGY)
|
||||
) {
|
||||
creep.memory.previousDestination = creep.memory.destination;
|
||||
|
||||
if (!creep.room.controller) {
|
||||
console.log(`Creep ${creep.name} has no valid controller to upgrade.`);
|
||||
console.log(
|
||||
`Creep ${creep.name} has no valid controller to upgrade.`
|
||||
);
|
||||
delete creep.memory.destination;
|
||||
return;
|
||||
}
|
||||
|
||||
creep.memory.destination = {
|
||||
id: creep.room.controller.id,
|
||||
type: "controller"
|
||||
type: 'controller',
|
||||
};
|
||||
return;
|
||||
}
|
||||
|
||||
if (creep.memory.destination.type === "controller" && creep.store.getUsedCapacity(RESOURCE_ENERGY) === 0) {
|
||||
if (
|
||||
creep.memory.destination.type === 'controller' &&
|
||||
creep.store.getUsedCapacity(RESOURCE_ENERGY) === 0
|
||||
) {
|
||||
delete creep.memory.destination; // Clear destination if no energy is available
|
||||
return;
|
||||
}
|
||||
@@ -89,21 +104,24 @@ class UpgraderHandler extends RoleHandler {
|
||||
setSpotStatus(
|
||||
sourceState.spots,
|
||||
emptySpot,
|
||||
SourceSpotStatus.OCCUPIED
|
||||
PositionSpotStatus.OCCUPIED
|
||||
);
|
||||
creep.memory.destination = {
|
||||
id: source.id,
|
||||
type: "source",
|
||||
sourceSpot: emptySpot
|
||||
type: 'source',
|
||||
sourceSpot: emptySpot,
|
||||
};
|
||||
return
|
||||
return;
|
||||
}
|
||||
|
||||
console.log(`Creep ${creep.name} could not find a valid source.`);
|
||||
}
|
||||
|
||||
private static onSourceDestination(creep: Creep, state: GameState) {
|
||||
if (!creep.memory.destination || creep.memory.destination.type !== "source") {
|
||||
private static onSourceDestination(creep: Creep, _state: GameState) {
|
||||
if (
|
||||
!creep.memory.destination ||
|
||||
creep.memory.destination.type !== 'source'
|
||||
) {
|
||||
console.log(`Creep ${creep.name} has no valid destination set.`);
|
||||
delete creep.memory.destination;
|
||||
return;
|
||||
@@ -117,23 +135,33 @@ class UpgraderHandler extends RoleHandler {
|
||||
|
||||
if (creep.harvest(source) === ERR_NOT_IN_RANGE) {
|
||||
const sourceSpotPosition = getPositionWithDelta(
|
||||
source.pos, creep.memory.destination.sourceSpot
|
||||
)
|
||||
creep.moveTo(sourceSpotPosition, { reusePath: 10, visualizePathStyle: { stroke: '#ffffff', lineStyle: 'dashed', strokeWidth: 0.1 } });
|
||||
source.pos,
|
||||
creep.memory.destination.sourceSpot
|
||||
);
|
||||
creep.moveTo(sourceSpotPosition, {
|
||||
reusePath: 10,
|
||||
visualizePathStyle: {
|
||||
stroke: '#ffffff',
|
||||
lineStyle: 'dashed',
|
||||
strokeWidth: 0.1,
|
||||
},
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
private static onControllerDestination(creep: Creep, state: GameState) {
|
||||
private static onControllerDestination(creep: Creep, _state: GameState) {
|
||||
if (creep.memory.destination === undefined) {
|
||||
if (!creep.room.controller) {
|
||||
console.log(`Creep ${creep.name} has no valid controller to upgrade.`);
|
||||
console.log(
|
||||
`Creep ${creep.name} has no valid controller to upgrade.`
|
||||
);
|
||||
delete creep.memory.destination;
|
||||
return;
|
||||
}
|
||||
creep.memory.destination = {
|
||||
id: creep.room.controller.id,
|
||||
type: "controller"
|
||||
}
|
||||
type: 'controller',
|
||||
};
|
||||
}
|
||||
|
||||
const controller = getControllerById(creep.memory.destination.id);
|
||||
@@ -143,23 +171,31 @@ class UpgraderHandler extends RoleHandler {
|
||||
}
|
||||
|
||||
if (creep.upgradeController(controller) === ERR_NOT_IN_RANGE) {
|
||||
creep.moveTo(controller, { reusePath: 10, visualizePathStyle: { stroke: '#ffffff', lineStyle: 'dashed', strokeWidth: 0.1 } });
|
||||
creep.moveTo(controller, {
|
||||
reusePath: 10,
|
||||
visualizePathStyle: {
|
||||
stroke: '#ffffff',
|
||||
lineStyle: 'dashed',
|
||||
strokeWidth: 0.1,
|
||||
},
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
private static findClosestSource(creep: Creep, state: GameState): Source[] {
|
||||
const sources = Object.keys(state.sourcesStates)
|
||||
.map(sourceId => getSourceById(sourceId))
|
||||
.filter(source => source !== null)
|
||||
.map((sourceId) => getSourceById(sourceId))
|
||||
.filter((source) => source !== null)
|
||||
.sort((a, b) => creep.pos.getRangeTo(a) - creep.pos.getRangeTo(b));
|
||||
|
||||
return sources as Source[];
|
||||
}
|
||||
|
||||
private static releaseSourceSpot(destination: SourceDestination, state: GameState) {
|
||||
if (!destination || destination.type !== "source") {
|
||||
private static releaseSourceSpot(
|
||||
destination: SourceDestination,
|
||||
state: GameState
|
||||
) {
|
||||
if (!destination || destination.type !== 'source') {
|
||||
return; // Not a source destination, nothing to release
|
||||
}
|
||||
|
||||
@@ -172,13 +208,9 @@ class UpgraderHandler extends RoleHandler {
|
||||
setSpotStatus(
|
||||
sourceState.spots,
|
||||
destination.sourceSpot,
|
||||
SourceSpotStatus.EMPTY
|
||||
PositionSpotStatus.EMPTY
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
export default UpgraderHandler;
|
||||
|
||||
@@ -1,154 +0,0 @@
|
||||
import { CreepRequisition, CreepRole, CreepRoles, RoleDefinition } from "types/creeps";
|
||||
import { DEFAULT_GAME_CONFIG } from "types/gameConfig";
|
||||
import { createSourcePositionMatrix, forEachMatrixSpot, getPositionWithDelta, setSpotStatus, SourceSpotStatus } from "types/source";
|
||||
import { checkPositionWalkable } from "utils/funcs/check_position";
|
||||
import { get_role_const as get_role_cost } from "utils/funcs/get_role_const";
|
||||
|
||||
class SpawnHandler {
|
||||
constructor(private spawn: StructureSpawn) {}
|
||||
|
||||
public get spawnName(): string {
|
||||
return this.spawn.name;
|
||||
}
|
||||
|
||||
public run(state: GameState): GameState {
|
||||
this.updateSpawnState(state);
|
||||
|
||||
for(const name in Memory.creeps) {
|
||||
if (!Game.creeps[name]) {
|
||||
console.log(`Creep ${name} is dead, cleaning up memory.`);
|
||||
|
||||
const roleDefinition = CreepRoles[Memory.creeps[name].role as CreepRole];
|
||||
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);
|
||||
}
|
||||
|
||||
this.validateSpawnState();
|
||||
|
||||
return state;
|
||||
}
|
||||
|
||||
private updateSpawnState(state: GameState) {
|
||||
const sources = this.spawn.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 !== SourceSpotStatus.UNKNOWN) {
|
||||
return; // Skip known spots
|
||||
}
|
||||
const pos = getPositionWithDelta(source.pos, delta);
|
||||
if (checkPositionWalkable(pos)) {
|
||||
setSpotStatus(state.sourcesStates[sourceId].spots, delta, SourceSpotStatus.EMPTY);
|
||||
state.maxHarvesters = state.maxHarvesters + 1;
|
||||
} else {
|
||||
setSpotStatus(state.sourcesStates[sourceId].spots, delta, SourceSpotStatus.INVALID);
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private validateSpawnState() {
|
||||
if (this.spawn.spawning) {
|
||||
// console.log(`Spawn ${this.spawn.name} is currently spawning a creep.`);
|
||||
return;
|
||||
}
|
||||
|
||||
const creepRequisition = this.checksNeedsCreeps();
|
||||
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 >= DEFAULT_GAME_CONFIG.maxCreeps) {
|
||||
// console.log(`Spawn ${this.spawn.name} cannot spawn more creeps, limit reached.`);
|
||||
return;
|
||||
}
|
||||
|
||||
const rolesToSpawn = this.sortCreepRolesByPriority(creepRequisition);
|
||||
|
||||
for (const role of rolesToSpawn) {
|
||||
if (this.spawn.store[RESOURCE_ENERGY] < get_role_cost(role)) {
|
||||
// console.log(`Spawn ${this.spawn.name} does not have enough energy to spawn a ${role.name}.`);
|
||||
continue;
|
||||
}
|
||||
|
||||
const newName = `${role.name}_${Game.time}`;
|
||||
const spawnResult = this.spawn.spawnCreep(role.body, newName, {
|
||||
memory: {
|
||||
role: role.name,
|
||||
room: this.spawn.room.name,
|
||||
spawnId: this.spawn.id,
|
||||
working: false
|
||||
}
|
||||
});
|
||||
if (spawnResult === OK) {
|
||||
console.log(`Spawn ${this.spawn.name} successfully spawned a new ${role.name}: ${newName}.`);
|
||||
return; // Exit after spawning one creep
|
||||
} else {
|
||||
console.error(`Spawn ${this.spawn.name} failed to spawn a new ${role.name}: ${spawnResult}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private checksNeedsCreeps(): CreepRequisition {
|
||||
const creepCounts: Record<string, number> = {};
|
||||
for (const creep of Object.values(Game.creeps)) {
|
||||
const role = creep.memory.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 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);
|
||||
}
|
||||
}
|
||||
|
||||
export default SpawnHandler;
|
||||
@@ -1,5 +1,5 @@
|
||||
import { HarvesterHandler, RoleHandler, UpgraderHandler } from "roleHandlers";
|
||||
import { PositionDelta } from "./source";
|
||||
import { HarvesterHandler, RoleHandler, UpgraderHandler } from 'roleHandlers';
|
||||
import { PositionDelta } from 'utils/positions';
|
||||
|
||||
export type RoleDefinition = {
|
||||
name: string;
|
||||
@@ -10,58 +10,52 @@ export type RoleDefinition = {
|
||||
|
||||
export const CreepRoles = {
|
||||
harvester: {
|
||||
name: "harvester",
|
||||
name: 'harvester',
|
||||
body: [WORK, CARRY, MOVE],
|
||||
handler: HarvesterHandler,
|
||||
priority: 1
|
||||
priority: 1,
|
||||
},
|
||||
upgrader: {
|
||||
name: "upgrader",
|
||||
name: 'upgrader',
|
||||
body: [WORK, CARRY, MOVE],
|
||||
handler: UpgraderHandler,
|
||||
priority: 2
|
||||
priority: 2,
|
||||
},
|
||||
builder: {
|
||||
name: "builder",
|
||||
name: 'builder',
|
||||
body: [WORK, CARRY, MOVE],
|
||||
handler: HarvesterHandler,
|
||||
priority: 3
|
||||
}
|
||||
priority: 3,
|
||||
},
|
||||
} satisfies Record<string, RoleDefinition>;
|
||||
|
||||
export type CreepRole = keyof typeof CreepRoles;
|
||||
|
||||
export type CreepRequisition = Record<CreepRole, number>;
|
||||
|
||||
|
||||
|
||||
|
||||
export type SpawnDestination = {
|
||||
id: string; // ID of the spawn
|
||||
type: "spawn";
|
||||
}
|
||||
type: 'spawn';
|
||||
};
|
||||
|
||||
export type SourceDestination = {
|
||||
id: string; // ID of the source
|
||||
type: "source";
|
||||
type: 'source';
|
||||
sourceSpot: PositionDelta; // Position delta for the source spot
|
||||
}
|
||||
};
|
||||
|
||||
export type ControllerDestination = {
|
||||
id: string; // ID of the controller
|
||||
type: "controller";
|
||||
}
|
||||
type: 'controller';
|
||||
};
|
||||
|
||||
export type ConstructionSiteDestination = {
|
||||
id: string; // ID of the construction site
|
||||
type: "constructionSite";
|
||||
}
|
||||
|
||||
|
||||
export type CreepDestination = (
|
||||
SpawnDestination |
|
||||
SourceDestination |
|
||||
ControllerDestination |
|
||||
ConstructionSiteDestination
|
||||
);
|
||||
type: 'constructionSite';
|
||||
};
|
||||
|
||||
export type CreepDestination =
|
||||
| SpawnDestination
|
||||
| SourceDestination
|
||||
| ControllerDestination
|
||||
| ConstructionSiteDestination;
|
||||
|
||||
@@ -1,13 +1,10 @@
|
||||
import { CreepRequisition } from "./creeps";
|
||||
import { CreepRequisition } from './creeps';
|
||||
|
||||
/**
|
||||
* Configuration for the game, defining limits and minimum requirements for creeps.
|
||||
* Used to manage the overall game state and ensure proper role distribution.
|
||||
*/
|
||||
export type GameConfig = {
|
||||
/** The maximum number of creeps allowed in the game. */
|
||||
maxCreeps: number;
|
||||
|
||||
/**
|
||||
* The minimum number of creeps required for each role.
|
||||
* Creeps will be spawned to meet these minimums before allocating new roles.
|
||||
@@ -22,10 +19,9 @@ export type GameConfig = {
|
||||
* @type {GameConfig}
|
||||
*/
|
||||
export const DEFAULT_GAME_CONFIG: GameConfig = {
|
||||
maxCreeps: 10,
|
||||
minCreepsPerRole: {
|
||||
harvester: 3,
|
||||
upgrader: 7,
|
||||
builder: 0
|
||||
}
|
||||
builder: 0,
|
||||
},
|
||||
};
|
||||
|
||||
@@ -1,81 +0,0 @@
|
||||
export const SourceSpotStatus = {
|
||||
INVALID: "-2",
|
||||
CENTER: "-1",
|
||||
UNKNOWN: "0",
|
||||
EMPTY: "1",
|
||||
OCCUPIED: "2",
|
||||
} as const;
|
||||
|
||||
|
||||
export type SourceSpotStatus = (typeof SourceSpotStatus)[keyof typeof SourceSpotStatus];
|
||||
|
||||
|
||||
export type PositionDeltaValue = -1 | 0 | 1;
|
||||
|
||||
export type PositionDelta = 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9;
|
||||
|
||||
export type SourcePositionMatrix = {
|
||||
locked: boolean;
|
||||
data: [
|
||||
SourceSpotStatus, SourceSpotStatus, SourceSpotStatus,
|
||||
SourceSpotStatus, SourceSpotStatus, SourceSpotStatus,
|
||||
SourceSpotStatus, SourceSpotStatus, SourceSpotStatus
|
||||
];
|
||||
}
|
||||
|
||||
|
||||
type MatrixPoint = {
|
||||
x: PositionDeltaValue;
|
||||
y: PositionDeltaValue;
|
||||
}
|
||||
|
||||
|
||||
const indexToMatrixPoint = (index: number): MatrixPoint => {
|
||||
// where the 0,0 point is the center of the matrix and -1, -1 is the top-left corner
|
||||
const x = ((index % 3) - 1) as PositionDeltaValue; // Convert index to x coordinate (-1, 0, 1)
|
||||
const y = (Math.floor(index / 3) - 1) as PositionDeltaValue; // Convert index to y coordinate (-1, 0, 1)
|
||||
return { x, y };
|
||||
}
|
||||
|
||||
export const createSourcePositionMatrix = () : SourcePositionMatrix => {
|
||||
return {
|
||||
locked: false,
|
||||
data: [
|
||||
SourceSpotStatus.UNKNOWN, SourceSpotStatus.UNKNOWN, SourceSpotStatus.UNKNOWN,
|
||||
SourceSpotStatus.UNKNOWN, SourceSpotStatus.CENTER, SourceSpotStatus.UNKNOWN,
|
||||
SourceSpotStatus.UNKNOWN, SourceSpotStatus.UNKNOWN, SourceSpotStatus.UNKNOWN
|
||||
]
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
export const getNextEmptySpot = (matrix: SourcePositionMatrix): PositionDelta | null => {
|
||||
const index = matrix.data.findIndex( status => status === SourceSpotStatus.EMPTY);
|
||||
|
||||
if (index === -1) {
|
||||
return null; // No empty spot found
|
||||
}
|
||||
|
||||
return index as PositionDelta; // Convert index to PositionDelta
|
||||
};
|
||||
|
||||
|
||||
export const setSpotStatus = (matrix: SourcePositionMatrix, delta: PositionDelta, status: SourceSpotStatus): void => {
|
||||
matrix.data[delta as number] = status;
|
||||
}
|
||||
|
||||
|
||||
export const getPositionWithDelta = (pos: RoomPosition, delta: PositionDelta): RoomPosition => {
|
||||
const matrixPoint = indexToMatrixPoint(delta as number);
|
||||
return new RoomPosition(
|
||||
pos.x + matrixPoint.x,
|
||||
pos.y + matrixPoint.y,
|
||||
pos.roomName
|
||||
);
|
||||
}
|
||||
|
||||
export const forEachMatrixSpot = (matrix: SourcePositionMatrix, callback: (delta: PositionDelta, status: SourceSpotStatus) => void): void => {
|
||||
for (const index in matrix.data) {
|
||||
callback(index as PositionDelta, matrix.data[index]);
|
||||
}
|
||||
};
|
||||
@@ -1,5 +1,5 @@
|
||||
export const checkPositionWalkable = (pos: RoomPosition) => {
|
||||
// Check if the position is not obstructed by a wall
|
||||
const terrain = pos.lookFor(LOOK_TERRAIN);
|
||||
return terrain.length === 0 || terrain[0] !== 'wall'
|
||||
}
|
||||
return terrain.length === 0 || terrain[0] !== 'wall';
|
||||
};
|
||||
@@ -1,6 +1,8 @@
|
||||
export const getSourceById = (sourceId: string): Source | null => {
|
||||
if (!sourceId) {
|
||||
console.log("getSourceById called with an empty or undefined sourceId.");
|
||||
console.log(
|
||||
'getSourceById called with an empty or undefined sourceId.'
|
||||
);
|
||||
return null;
|
||||
}
|
||||
|
||||
@@ -11,12 +13,11 @@ export const getSourceById = (sourceId: string): Source | null => {
|
||||
}
|
||||
|
||||
return source;
|
||||
}
|
||||
|
||||
};
|
||||
|
||||
export const getSpawnById = (spawnId: string): StructureSpawn | null => {
|
||||
if (!spawnId) {
|
||||
console.log("getSpawnById called with an empty or undefined spawnId.");
|
||||
console.log('getSpawnById called with an empty or undefined spawnId.');
|
||||
return null;
|
||||
}
|
||||
|
||||
@@ -27,12 +28,15 @@ export const getSpawnById = (spawnId: string): StructureSpawn | null => {
|
||||
}
|
||||
|
||||
return spawn;
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
export const getControllerById = (controllerId: string): StructureController | null => {
|
||||
export const getControllerById = (
|
||||
controllerId: string
|
||||
): StructureController | null => {
|
||||
if (!controllerId) {
|
||||
console.log("getControllerById called with an empty or undefined controllerId.");
|
||||
console.log(
|
||||
'getControllerById called with an empty or undefined controllerId.'
|
||||
);
|
||||
return null;
|
||||
}
|
||||
|
||||
@@ -43,4 +47,4 @@ export const getControllerById = (controllerId: string): StructureController | n
|
||||
}
|
||||
|
||||
return controller;
|
||||
}
|
||||
};
|
||||
@@ -1,6 +1,6 @@
|
||||
import { RoleDefinition } from "types/creeps";
|
||||
import { RoleDefinition } from 'types/creeps';
|
||||
|
||||
export const get_role_const = (role: RoleDefinition) => {
|
||||
export const get_role_cost = (role: RoleDefinition) => {
|
||||
return role.body.reduce((cost, part) => {
|
||||
cost += BODYPART_COST[part] || 0;
|
||||
return cost;
|
||||
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);
|
||||
};
|
||||
25
src/utils/positions/index.ts
Normal file
25
src/utils/positions/index.ts
Normal file
@@ -0,0 +1,25 @@
|
||||
import {
|
||||
createSourcePositionMatrix,
|
||||
forEachMatrixSpot,
|
||||
getNextEmptySpot,
|
||||
setSpotStatus,
|
||||
getPositionWithDelta,
|
||||
} from './position.funcs';
|
||||
import {
|
||||
PositionSpotStatus,
|
||||
PositionDeltaValue,
|
||||
PositionMatrix,
|
||||
PositionDelta,
|
||||
} from './position.types';
|
||||
|
||||
export {
|
||||
PositionSpotStatus,
|
||||
PositionDeltaValue,
|
||||
PositionMatrix,
|
||||
PositionDelta,
|
||||
createSourcePositionMatrix,
|
||||
forEachMatrixSpot,
|
||||
getNextEmptySpot,
|
||||
setSpotStatus,
|
||||
getPositionWithDelta,
|
||||
};
|
||||
112
src/utils/positions/position.funcs.ts
Normal file
112
src/utils/positions/position.funcs.ts
Normal file
@@ -0,0 +1,112 @@
|
||||
import {
|
||||
PositionDelta,
|
||||
PositionDeltaValue,
|
||||
PositionMatrix,
|
||||
PositionSpotStatus,
|
||||
} from './position.types';
|
||||
|
||||
/**
|
||||
* Represents a point in the matrix with x and y coordinates.
|
||||
*/
|
||||
type MatrixPoint = {
|
||||
x: PositionDeltaValue;
|
||||
y: PositionDeltaValue;
|
||||
};
|
||||
|
||||
/**
|
||||
* Converts a matrix index to a matrix point.
|
||||
*/
|
||||
const indexToMatrixPoint = (index: number): MatrixPoint => {
|
||||
// where the 0,0 point is the center of the matrix and -1, -1 is the top-left corner
|
||||
const x = ((index % 3) - 1) as PositionDeltaValue; // Convert index to x coordinate (-1, 0, 1)
|
||||
const y = (Math.floor(index / 3) - 1) as PositionDeltaValue; // Convert index to y coordinate (-1, 0, 1)
|
||||
return { x, y };
|
||||
};
|
||||
|
||||
/**
|
||||
* Creates a source position matrix with a default value.
|
||||
* The center of the matrix is always `PositionSpotStatus.CENTER`.
|
||||
* The default value is used for all other spots.
|
||||
*/
|
||||
export const createSourcePositionMatrix = (
|
||||
default_value?: PositionSpotStatus
|
||||
): PositionMatrix => {
|
||||
const center_value = PositionSpotStatus.CENTER;
|
||||
|
||||
default_value = default_value || PositionSpotStatus.UNKNOWN;
|
||||
|
||||
return [
|
||||
default_value,
|
||||
default_value,
|
||||
default_value,
|
||||
default_value,
|
||||
center_value,
|
||||
default_value,
|
||||
default_value,
|
||||
default_value,
|
||||
default_value,
|
||||
];
|
||||
};
|
||||
|
||||
/**
|
||||
* Gets the next empty spot in the matrix.
|
||||
*/
|
||||
export const getNextEmptySpot = (
|
||||
matrix: PositionMatrix
|
||||
): PositionDelta | null => {
|
||||
const index = matrix.findIndex(
|
||||
(status) => status === PositionSpotStatus.EMPTY
|
||||
);
|
||||
|
||||
if (index === -1) {
|
||||
return null; // No empty spot found
|
||||
}
|
||||
|
||||
return index as PositionDelta; // Convert index to PositionDelta
|
||||
};
|
||||
|
||||
/**
|
||||
* Sets the status of a spot in the matrix.
|
||||
* Throws an error if the delta is out of bounds.
|
||||
*/
|
||||
export const setSpotStatus = (
|
||||
matrix: PositionMatrix,
|
||||
delta: PositionDelta,
|
||||
status: PositionSpotStatus
|
||||
): void => {
|
||||
if (delta < 0 || delta >= matrix.length) {
|
||||
throw new Error(
|
||||
`Invalid delta: ${delta}. Must be between 0 and ${matrix.length - 1}.`
|
||||
);
|
||||
}
|
||||
matrix[delta] = status;
|
||||
};
|
||||
|
||||
/**
|
||||
* Gets the position with a delta applied to the given RoomPosition.
|
||||
*/
|
||||
export const getPositionWithDelta = (
|
||||
pos: RoomPosition,
|
||||
delta: PositionDelta
|
||||
): RoomPosition => {
|
||||
const matrixPoint = indexToMatrixPoint(delta as number);
|
||||
return new RoomPosition(
|
||||
pos.x + matrixPoint.x,
|
||||
pos.y + matrixPoint.y,
|
||||
pos.roomName
|
||||
);
|
||||
};
|
||||
|
||||
/**
|
||||
* Iterates over each spot in the matrix and applies the callback function.
|
||||
* The callback receives the delta (index) and the status of the spot.
|
||||
*/
|
||||
export const forEachMatrixSpot = (
|
||||
matrix: PositionMatrix,
|
||||
callback: (delta: PositionDelta, status: PositionSpotStatus) => void
|
||||
): void => {
|
||||
for (const index in matrix) {
|
||||
const positionIndex = Number(index);
|
||||
callback(positionIndex as PositionDelta, matrix[positionIndex]);
|
||||
}
|
||||
};
|
||||
38
src/utils/positions/position.types.ts
Normal file
38
src/utils/positions/position.types.ts
Normal file
@@ -0,0 +1,38 @@
|
||||
/**
|
||||
* Represents the status of a position spot
|
||||
*/
|
||||
export const PositionSpotStatus = {
|
||||
INVALID: '-2',
|
||||
CENTER: '-1',
|
||||
UNKNOWN: '0',
|
||||
EMPTY: '1',
|
||||
OCCUPIED: '2',
|
||||
} as const;
|
||||
|
||||
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.
|
||||
*/
|
||||
export type PositionDeltaValue = -1 | 0 | 1;
|
||||
|
||||
/**
|
||||
* Represents a matrix of positions around a source or a point of interest.
|
||||
* The matrix is a 3x3 grid where the center is the point of interest.
|
||||
* The center should always be `PositionSpotStatus.CENTER`.
|
||||
*/
|
||||
export type PositionMatrix = [
|
||||
PositionSpotStatus,
|
||||
PositionSpotStatus,
|
||||
PositionSpotStatus,
|
||||
PositionSpotStatus,
|
||||
PositionSpotStatus,
|
||||
PositionSpotStatus,
|
||||
PositionSpotStatus,
|
||||
PositionSpotStatus,
|
||||
PositionSpotStatus,
|
||||
];
|
||||
|
||||
// Valid indices for the 3x3 matrix (0-8)
|
||||
export type PositionDelta = 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8;
|
||||
0
src/utils/positions/positionMatrix.ts
Normal file
0
src/utils/positions/positionMatrix.ts
Normal file
@@ -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: {}
|
||||
};
|
||||
@@ -1,23 +1,23 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"target": "ES6",
|
||||
"lib": ["ES2015", "DOM"],
|
||||
"module": "commonjs",
|
||||
"moduleResolution": "node",
|
||||
"outDir": "dist",
|
||||
"rootDir": "src",
|
||||
"baseUrl": "src",
|
||||
"strict": true,
|
||||
"noImplicitReturns": true,
|
||||
"noUnusedLocals": true,
|
||||
"noUnusedParameters": true,
|
||||
"noFallthroughCasesInSwitch": true,
|
||||
"allowUnreachableCode": false,
|
||||
"sourceMap": true,
|
||||
"experimentalDecorators": true,
|
||||
"allowSyntheticDefaultImports": true,
|
||||
"types": ["screeps"]
|
||||
},
|
||||
"include": ["src/**/*"],
|
||||
"exclude": ["node_modules", "dist"]
|
||||
"compilerOptions": {
|
||||
"target": "ES6",
|
||||
"lib": ["ES2017", "DOM"],
|
||||
"module": "commonjs",
|
||||
"moduleResolution": "node",
|
||||
"outDir": "dist",
|
||||
"rootDir": "src",
|
||||
"baseUrl": "src",
|
||||
"strict": true,
|
||||
"noImplicitReturns": true,
|
||||
"noUnusedLocals": true,
|
||||
"noUnusedParameters": true,
|
||||
"noFallthroughCasesInSwitch": true,
|
||||
"allowUnreachableCode": false,
|
||||
"sourceMap": true,
|
||||
"experimentalDecorators": true,
|
||||
"allowSyntheticDefaultImports": true,
|
||||
"types": ["node", "screeps"]
|
||||
},
|
||||
"include": ["src/*.ts", "src/**/*.ts"],
|
||||
"exclude": ["node_modules", "dist"]
|
||||
}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"extends": "./tsconfig.json",
|
||||
"compilerOptions": {
|
||||
"module": "CommonJs"
|
||||
}
|
||||
"extends": "./tsconfig.json",
|
||||
"compilerOptions": {
|
||||
"module": "CommonJs"
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user