├── .gitignore ├── .gitmodules ├── README.md ├── build.gradle ├── gradle └── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── gradlew ├── gradlew.bat ├── settings.gradle └── src └── main └── kotlin ├── Main.kt ├── screeps └── game │ └── one │ ├── ApiExtensions.kt │ ├── ColonizeMission.kt │ ├── GameLoop.kt │ ├── KreepMemory.kt │ ├── Mission.kt │ ├── Spawning.kt │ ├── Stats.kt │ ├── Task.kt │ ├── UpgradeMission.kt │ ├── Utils.kt │ ├── behaviours │ ├── Behaviours.kt │ └── RefillEnergy.kt │ ├── building │ └── build.kt │ └── kreeps │ └── BodyDefinition.kt └── traveler ├── CreepExtension.kt └── Traveler.kt /.gitignore: -------------------------------------------------------------------------------- 1 | .idea/ 2 | *.iml 3 | .gradle/ 4 | out/ 5 | build/ 6 | 7 | gradle.properties 8 | -------------------------------------------------------------------------------- /.gitmodules: -------------------------------------------------------------------------------- 1 | [submodule "traveler"] 2 | path = traveler 3 | url = https://github.com/bonzaiferroni/Traveler.git 4 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Playing screeps using Kotlin 2 | 3 | **start here**: https://github.com/exaV/screeps-kotlin-starter 4 | 5 | Standalone types as a library are available too: https://github.com/exaV/screeps-kotlin-types 6 | 7 | Join the official screeps slack on https://chat.screeps.com/ and join #kotlin for help and general screeps kotlin chat. 8 | 9 | ## Contribute 10 | If you want to contribute you should definitely checkout out the two repos above and create a PR! 11 | 12 | ## Using this repo 13 | clone: `git clone --recurse-submodules https://github.com/exaV/screeps-kotlin` 14 | 15 | 16 | ### Deployment 17 | 18 | Deployment is automated with gradle. 19 | Use the 'deploy' task to push to sceeps.com. 20 | The branch 'kotlin' is used by default, make sure it exists. 21 | 22 | Credentials can be provided with a 'gradle.properties' file. 23 | 24 | screepsUser= 25 | screepsPassword= 26 | 27 | 28 | ### Usage 29 | 30 | Call your main function from Main.loop 31 | 32 | Have a look at the [tutorials](https://github.com/exaV/screeps-kotlin/tree/master/src/main/kotlin/screeps/game/tutorials). Call the tutorials gameloop() in Main.loop to test them. 33 | -------------------------------------------------------------------------------- /build.gradle: -------------------------------------------------------------------------------- 1 | import groovy.json.internal.LazyMap 2 | import groovyx.net.http.HttpResponseDecorator 3 | import groovyx.net.http.RESTClient 4 | import org._10ne.gradle.rest.RestTask 5 | 6 | buildscript { 7 | ext.kotlin_version = '1.3.30' 8 | 9 | repositories { 10 | repositories { jcenter() } 11 | 12 | } 13 | dependencies { 14 | classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version" 15 | classpath "org.jetbrains.kotlin:kotlin-serialization:$kotlin_version" 16 | } 17 | } 18 | 19 | plugins { 20 | id "org.tenne.rest" version "0.4.2" 21 | } 22 | 23 | group 'screeps.game' 24 | version '1.0-SNAPSHOT' 25 | 26 | apply plugin: 'kotlin2js' 27 | apply plugin: 'kotlinx-serialization' 28 | apply plugin: 'kotlin-dce-js' 29 | 30 | runDceKotlinJs.dceOptions.devMode = false 31 | runDceTestKotlinJs.dceOptions.devMode = true 32 | 33 | repositories { 34 | jcenter() 35 | maven { 36 | url "https://dl.bintray.com/exav/screeps-kotlin" 37 | } 38 | mavenLocal() 39 | maven { url "https://kotlin.bintray.com/kotlinx" } 40 | maven { url 'https://jitpack.io' } 41 | } 42 | 43 | dependencies { 44 | compile 'org.jetbrains.kotlin:kotlin-stdlib-js:$kotlin_version' 45 | compile "org.jetbrains.kotlinx:kotlinx-serialization-runtime-js:0.11.0" 46 | compile "ch.delconte.screeps-kotlin:screeps-kotlin-types:1.3.0" 47 | 48 | testCompile "org.jetbrains.kotlin:kotlin-test-js:$kotlin_version" 49 | } 50 | 51 | compileKotlin2Js { 52 | kotlinOptions.outputFile = "${buildDir}/screeps/main.js" 53 | kotlinOptions.moduleKind = "commonjs" 54 | kotlinOptions.sourceMap = true 55 | kotlinOptions.freeCompilerArgs = ["-Xuse-experimental=kotlin.Experimental,kotlinx.serialization.ImplicitReflectionSerializer"] 56 | 57 | runDceKotlinJs.keep "main.loop", "main.Traveler", "Traveler" 58 | } 59 | 60 | 61 | task('deploy', type: RestTask) { 62 | group 'screeps' 63 | dependsOn build 64 | 65 | def modules = [:] 66 | 67 | httpMethod = "post" 68 | uri = "https://screeps.com/api/user/code" 69 | requestHeaders = ["X-Token": "$screepsToken"] 70 | contentType = groovyx.net.http.ContentType.JSON 71 | requestBody = ["branch": "kotlin", "modules": modules] 72 | 73 | doFirst { 74 | println "uploading code to screeps.com" 75 | 76 | modules.put('main', file("$buildDir/kotlin-js-min/main/main.js").getText('UTF-8')) 77 | modules.put('screeps-kotlin-types', file("$buildDir/kotlin-js-min/main/screeps-kotlin-types.js").getText('UTF-8')) 78 | modules.put('kotlin', file("$buildDir/kotlin-js-min/main/kotlin.js").getText('UTF-8')) 79 | modules.put('kotlinx-serialization-runtime-js', file("$buildDir/kotlin-js-min/main/kotlinx-serialization-runtime-js.js").getText('UTF-8')) 80 | modules.put('Traveler', file("traveler/Traveler.js").getText('UTF-8')) 81 | } 82 | 83 | } -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/exaV/screeps-kotlin/554ee88e0135082ca1346b298457d05ec60c08bd/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | distributionBase=GRADLE_USER_HOME 2 | distributionPath=wrapper/dists 3 | distributionUrl=https\://services.gradle.org/distributions/gradle-5.3-all.zip 4 | zipStoreBase=GRADLE_USER_HOME 5 | zipStorePath=wrapper/dists 6 | -------------------------------------------------------------------------------- /gradlew: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env sh 2 | 3 | ############################################################################## 4 | ## 5 | ## Gradle start up script for UN*X 6 | ## 7 | ############################################################################## 8 | 9 | # Attempt to set APP_HOME 10 | # Resolve links: $0 may be a link 11 | PRG="$0" 12 | # Need this for relative symlinks. 13 | while [ -h "$PRG" ] ; do 14 | ls=`ls -ld "$PRG"` 15 | link=`expr "$ls" : '.*-> \(.*\)$'` 16 | if expr "$link" : '/.*' > /dev/null; then 17 | PRG="$link" 18 | else 19 | PRG=`dirname "$PRG"`"/$link" 20 | fi 21 | done 22 | SAVED="`pwd`" 23 | cd "`dirname \"$PRG\"`/" >/dev/null 24 | APP_HOME="`pwd -P`" 25 | cd "$SAVED" >/dev/null 26 | 27 | APP_NAME="Gradle" 28 | APP_BASE_NAME=`basename "$0"` 29 | 30 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 31 | DEFAULT_JVM_OPTS="" 32 | 33 | # Use the maximum available, or set MAX_FD != -1 to use that value. 34 | MAX_FD="maximum" 35 | 36 | warn () { 37 | echo "$*" 38 | } 39 | 40 | die () { 41 | echo 42 | echo "$*" 43 | echo 44 | exit 1 45 | } 46 | 47 | # OS specific support (must be 'true' or 'false'). 48 | cygwin=false 49 | msys=false 50 | darwin=false 51 | nonstop=false 52 | case "`uname`" in 53 | CYGWIN* ) 54 | cygwin=true 55 | ;; 56 | Darwin* ) 57 | darwin=true 58 | ;; 59 | MINGW* ) 60 | msys=true 61 | ;; 62 | NONSTOP* ) 63 | nonstop=true 64 | ;; 65 | esac 66 | 67 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar 68 | 69 | # Determine the Java command to use to start the JVM. 70 | if [ -n "$JAVA_HOME" ] ; then 71 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 72 | # IBM's JDK on AIX uses strange locations for the executables 73 | JAVACMD="$JAVA_HOME/jre/sh/java" 74 | else 75 | JAVACMD="$JAVA_HOME/bin/java" 76 | fi 77 | if [ ! -x "$JAVACMD" ] ; then 78 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME 79 | 80 | Please set the JAVA_HOME variable in your environment to match the 81 | location of your Java installation." 82 | fi 83 | else 84 | JAVACMD="java" 85 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 86 | 87 | Please set the JAVA_HOME variable in your environment to match the 88 | location of your Java installation." 89 | fi 90 | 91 | # Increase the maximum file descriptors if we can. 92 | if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then 93 | MAX_FD_LIMIT=`ulimit -H -n` 94 | if [ $? -eq 0 ] ; then 95 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then 96 | MAX_FD="$MAX_FD_LIMIT" 97 | fi 98 | ulimit -n $MAX_FD 99 | if [ $? -ne 0 ] ; then 100 | warn "Could not set maximum file descriptor limit: $MAX_FD" 101 | fi 102 | else 103 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" 104 | fi 105 | fi 106 | 107 | # For Darwin, add options to specify how the application appears in the dock 108 | if $darwin; then 109 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" 110 | fi 111 | 112 | # For Cygwin, switch paths to Windows format before running java 113 | if $cygwin ; then 114 | APP_HOME=`cygpath --path --mixed "$APP_HOME"` 115 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` 116 | JAVACMD=`cygpath --unix "$JAVACMD"` 117 | 118 | # We build the pattern for arguments to be converted via cygpath 119 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` 120 | SEP="" 121 | for dir in $ROOTDIRSRAW ; do 122 | ROOTDIRS="$ROOTDIRS$SEP$dir" 123 | SEP="|" 124 | done 125 | OURCYGPATTERN="(^($ROOTDIRS))" 126 | # Add a user-defined pattern to the cygpath arguments 127 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then 128 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" 129 | fi 130 | # Now convert the arguments - kludge to limit ourselves to /bin/sh 131 | i=0 132 | for arg in "$@" ; do 133 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` 134 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option 135 | 136 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition 137 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` 138 | else 139 | eval `echo args$i`="\"$arg\"" 140 | fi 141 | i=$((i+1)) 142 | done 143 | case $i in 144 | (0) set -- ;; 145 | (1) set -- "$args0" ;; 146 | (2) set -- "$args0" "$args1" ;; 147 | (3) set -- "$args0" "$args1" "$args2" ;; 148 | (4) set -- "$args0" "$args1" "$args2" "$args3" ;; 149 | (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; 150 | (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; 151 | (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; 152 | (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; 153 | (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; 154 | esac 155 | fi 156 | 157 | # Escape application args 158 | save () { 159 | for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done 160 | echo " " 161 | } 162 | APP_ARGS=$(save "$@") 163 | 164 | # Collect all arguments for the java command, following the shell quoting and substitution rules 165 | eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS" 166 | 167 | # by default we should be in the correct project dir, but when run from Finder on Mac, the cwd is wrong 168 | if [ "$(uname)" = "Darwin" ] && [ "$HOME" = "$PWD" ]; then 169 | cd "$(dirname "$0")" 170 | fi 171 | 172 | exec "$JAVACMD" "$@" 173 | -------------------------------------------------------------------------------- /gradlew.bat: -------------------------------------------------------------------------------- 1 | @if "%DEBUG%" == "" @echo off 2 | @rem ########################################################################## 3 | @rem 4 | @rem Gradle startup script for Windows 5 | @rem 6 | @rem ########################################################################## 7 | 8 | @rem Set local scope for the variables with windows NT shell 9 | if "%OS%"=="Windows_NT" setlocal 10 | 11 | set DIRNAME=%~dp0 12 | if "%DIRNAME%" == "" set DIRNAME=. 13 | set APP_BASE_NAME=%~n0 14 | set APP_HOME=%DIRNAME% 15 | 16 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 17 | set DEFAULT_JVM_OPTS= 18 | 19 | @rem Find java.exe 20 | if defined JAVA_HOME goto findJavaFromJavaHome 21 | 22 | set JAVA_EXE=java.exe 23 | %JAVA_EXE% -version >NUL 2>&1 24 | if "%ERRORLEVEL%" == "0" goto init 25 | 26 | echo. 27 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 28 | echo. 29 | echo Please set the JAVA_HOME variable in your environment to match the 30 | echo location of your Java installation. 31 | 32 | goto fail 33 | 34 | :findJavaFromJavaHome 35 | set JAVA_HOME=%JAVA_HOME:"=% 36 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe 37 | 38 | if exist "%JAVA_EXE%" goto init 39 | 40 | echo. 41 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 42 | echo. 43 | echo Please set the JAVA_HOME variable in your environment to match the 44 | echo location of your Java installation. 45 | 46 | goto fail 47 | 48 | :init 49 | @rem Get command-line arguments, handling Windows variants 50 | 51 | if not "%OS%" == "Windows_NT" goto win9xME_args 52 | 53 | :win9xME_args 54 | @rem Slurp the command line arguments. 55 | set CMD_LINE_ARGS= 56 | set _SKIP=2 57 | 58 | :win9xME_args_slurp 59 | if "x%~1" == "x" goto execute 60 | 61 | set CMD_LINE_ARGS=%* 62 | 63 | :execute 64 | @rem Setup the command line 65 | 66 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar 67 | 68 | @rem Execute Gradle 69 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% 70 | 71 | :end 72 | @rem End local scope for the variables with windows NT shell 73 | if "%ERRORLEVEL%"=="0" goto mainEnd 74 | 75 | :fail 76 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of 77 | rem the _cmd.exe /c_ return code! 78 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 79 | exit /b 1 80 | 81 | :mainEnd 82 | if "%OS%"=="Windows_NT" endlocal 83 | 84 | :omega 85 | -------------------------------------------------------------------------------- /settings.gradle: -------------------------------------------------------------------------------- 1 | rootProject.name = 'kotlin-screeps' 2 | 3 | -------------------------------------------------------------------------------- /src/main/kotlin/Main.kt: -------------------------------------------------------------------------------- 1 | import screeps.game.one.gameLoop 2 | 3 | @Suppress("unused") 4 | private object Traveler { 5 | init { 6 | js("var Traveler = require('Traveler');") 7 | println("global reset!") 8 | println("============================================================================================") 9 | println("imported traveler") 10 | } 11 | } 12 | /** 13 | * Entry point 14 | * is called by screeps 15 | * 16 | * must not be removed by DCE 17 | */ 18 | @Suppress("unused") 19 | fun loop() { 20 | Traveler 21 | gameLoop() 22 | } -------------------------------------------------------------------------------- /src/main/kotlin/screeps/game/one/ApiExtensions.kt: -------------------------------------------------------------------------------- 1 | package screeps.game.one 2 | 3 | import screeps.api.* 4 | import screeps.api.structures.Structure 5 | import screeps.api.structures.StructureSpawn 6 | 7 | fun Room.findStructures() = find(FIND_STRUCTURES) 8 | fun Room.findMyConstructionSites() = find(FIND_MY_CONSTRUCTION_SITES) 9 | fun Room.findMySpawns() = find(FIND_MY_SPAWNS) 10 | fun Room.findEnergy() = find(FIND_SOURCES) 11 | fun Room.findCreeps() = find(FIND_CREEPS) 12 | fun Room.findMyCreeps() = find(FIND_MY_CREEPS) 13 | fun Room.findConstructionSites() = find(FIND_CONSTRUCTION_SITES) 14 | fun Room.findDroppedEnergy() = find(FIND_DROPPED_ENERGY) -------------------------------------------------------------------------------- /src/main/kotlin/screeps/game/one/ColonizeMission.kt: -------------------------------------------------------------------------------- 1 | package screeps.game.one 2 | 3 | import kotlinx.serialization.Serializable 4 | import screeps.api.* 5 | import screeps.game.one.kreeps.BodyDefinition 6 | import traveler.travelTo 7 | 8 | class ColonizeMission(val memory: ColonizeMissionMemory) : Mission() { 9 | 10 | override var complete = memory.isComplete() 11 | override val missionId: String = memory.missionId 12 | val pos = RoomPosition(memory.x, memory.y, memory.roomName) 13 | 14 | enum class State { 15 | SPAWNING_CLAIMER, 16 | CLAIM, 17 | DONE_CLAIM, 18 | SPAWNING_BUILDER, 19 | BUILD_SPAWN, 20 | NO_SPAWN_LOCATION, 21 | DONE_BUILD, 22 | DONE 23 | } 24 | 25 | init { 26 | 27 | } 28 | 29 | var claimerName: String? = null 30 | val workernames: MutableList = mutableListOf() 31 | 32 | 33 | override fun update() { 34 | when (memory.state) { 35 | State.SPAWNING_CLAIMER -> { 36 | val claimer = Context.creeps.values.find { 37 | it.memory.missionId == missionId && it.memory.state == CreepState.CLAIM 38 | } 39 | if (claimer == null) { 40 | requestCreepOnce(BodyDefinition.CLAIMER, KreepSpawnOptions(CreepState.CLAIM, missionId)) 41 | } else { 42 | this.claimerName = claimer.name 43 | memory.state = State.CLAIM 44 | } 45 | } 46 | 47 | State.CLAIM -> { 48 | if (claimerName == null || claimerName !in Context.creeps) { 49 | memory.state = State.SPAWNING_CLAIMER 50 | return 51 | } 52 | 53 | val claimer = Context.creeps[claimerName!!]!! 54 | if (claimer.pos.inRangeTo(pos, 1)) { 55 | if (claimer.room.controller?.my == true) { 56 | memory.state == State.BUILD_SPAWN 57 | claimer.memory.state = CreepState.IDLE 58 | claimer.memory.missionId = null 59 | } else { 60 | claimer.claimController(claimer.room.controller!!) 61 | //claimer.reserveController(claimer.room.controller!!) 62 | } 63 | } else { 64 | val res = claimer.travelTo(pos) 65 | if (res != OK) { 66 | println("claimer could not move to room ${pos.roomName} because of $res") 67 | } 68 | } 69 | } 70 | 71 | State.SPAWNING_BUILDER -> { 72 | val workers = Context.creeps.values.filter { 73 | it.memory.missionId == missionId && it.name.startsWith(BodyDefinition.BASIC_WORKER.name) 74 | } 75 | 76 | if (workers.size < MIN_WORKERS) { 77 | requestCreepOnce(BodyDefinition.BASIC_WORKER, KreepSpawnOptions(CreepState.REFILL, missionId)) 78 | } else { 79 | this.workernames.addAll(workers.map { it.name }) 80 | memory.state = State.BUILD_SPAWN 81 | } 82 | } 83 | 84 | State.BUILD_SPAWN -> { 85 | if (workernames.count { it in Context.creeps } < MIN_WORKERS) { 86 | memory.state = State.SPAWNING_BUILDER 87 | workernames.clear() 88 | } 89 | 90 | for (workerName in workernames) { 91 | if (workerName !in Context.creeps) continue 92 | val worker = Context.creeps[workerName]!! 93 | buildSpawn(worker) 94 | } 95 | } 96 | 97 | State.DONE_BUILD -> { 98 | 99 | workernames.map { Context.creeps[it] }.filterNotNull().forEach { 100 | it.memory.state = CreepState.IDLE 101 | it.memory.missionId = null 102 | } 103 | memory.state = State.DONE 104 | } 105 | 106 | else -> { 107 | } 108 | } 109 | 110 | } 111 | 112 | private fun buildSpawn(worker: Creep) { 113 | if (worker.carry.energy < worker.carryCapacity) return 114 | worker.memory.state = CreepState.MISSION 115 | 116 | if (worker.pos.roomName == pos.roomName) { 117 | if (worker.memory.targetId == null) { 118 | val constructionSite = findSpawnPosition(Context.rooms[memory.roomName]!!) 119 | if (constructionSite == null) { 120 | if (worker.room.findMySpawns().isNotEmpty()) { 121 | memory.state = State.DONE_BUILD 122 | } else { 123 | memory.state = State.NO_SPAWN_LOCATION 124 | } 125 | return 126 | 127 | } else { 128 | worker.memory.targetId = constructionSite.id 129 | } 130 | } 131 | if (worker.memory.state != CreepState.REFILL && worker.memory.state != CreepState.CONSTRUCTING) { 132 | worker.memory.state = CreepState.CONSTRUCTING 133 | } 134 | } else { 135 | val res = worker.travelTo(pos) 136 | if (res != OK) { 137 | println("worker ${worker.name} could not move to room ${pos.roomName} because of $res") 138 | } 139 | } 140 | } 141 | 142 | private fun findSpawnPosition(room: Room): ConstructionSite? { 143 | val constructionSite = room.findMyConstructionSites().firstOrNull { it.structureType == STRUCTURE_SPAWN } 144 | 145 | if (constructionSite == null) { 146 | for ((name, flag) in Game.flags) { 147 | if (name == "spawn" && flag.pos.roomName == pos.roomName) { 148 | room.createConstructionSite(flag.pos, STRUCTURE_SPAWN) 149 | return null 150 | } 151 | } 152 | return null 153 | } else return constructionSite 154 | } 155 | 156 | companion object { 157 | private const val MIN_WORKERS = 2 158 | fun forRoom(room: Room): ColonizeMission { 159 | val controller = room.controller ?: throw IllegalStateException("Room $room has no controller") 160 | return forRoom(controller.pos) 161 | } 162 | 163 | fun forRoom(room: RoomPosition): ColonizeMission { 164 | val memory = ColonizeMissionMemory(room.x, room.y, room.roomName) 165 | val mission = ColonizeMission(memory) 166 | Missions.missionMemory.colonizeMissionMemory.add(memory) 167 | Missions.activeMissions.add(mission) 168 | println("spawning persistent ColonizeMission for room ${room.roomName}") 169 | 170 | return mission 171 | } 172 | } 173 | } 174 | 175 | @Serializable 176 | class ColonizeMissionMemory(var x: Int, var y: Int, val roomName: String) : MissionMemory() { 177 | 178 | override val missionId: String 179 | get() = "colonize_$roomName" 180 | 181 | override fun restoreMission(): ColonizeMission { 182 | return ColonizeMission(this) 183 | } 184 | 185 | var state: ColonizeMission.State = ColonizeMission.State.CLAIM 186 | 187 | override fun isComplete() = state == ColonizeMission.State.DONE 188 | } 189 | 190 | sealed class ColonizeSubMission() { 191 | abstract fun update() 192 | } 193 | 194 | class ClaimMission(val claimer: Creep, val position: RoomPosition) : ColonizeSubMission() { 195 | override fun update() { 196 | claimer.travelTo(position) 197 | } 198 | } 199 | -------------------------------------------------------------------------------- /src/main/kotlin/screeps/game/one/GameLoop.kt: -------------------------------------------------------------------------------- 1 | package screeps.game.one 2 | 3 | 4 | import screeps.api.* 5 | import screeps.api.structures.Structure 6 | import screeps.api.structures.StructureController 7 | import screeps.api.structures.StructureSpawn 8 | import screeps.api.structures.StructureTower 9 | import screeps.game.one.behaviours.BusyBehaviour 10 | import screeps.game.one.behaviours.IdleBehaviour 11 | import screeps.game.one.behaviours.RefillEnergy 12 | import screeps.game.one.building.buildStorage 13 | import screeps.game.one.building.buildTowers 14 | import screeps.game.one.kreeps.BodyDefinition 15 | import screeps.utils.lazyPerTick 16 | import screeps.utils.toMap 17 | import kotlin.collections.component1 18 | import kotlin.collections.component2 19 | 20 | object Context { 21 | //built-in 22 | val creeps: Map by lazyPerTick { Game.creeps.toMap() } 23 | //val rooms: Map by lazyPerTick { Game.rooms.toMap() } 24 | val rooms: Map = Game.rooms.toMap() 25 | val myStuctures: Map by lazyPerTick { Game.structures.toMap() } 26 | val constructionSites: Map by lazyPerTick { Game.constructionSites.toMap() } 27 | 28 | //synthesized 29 | val targets: Map by lazyPerTick { creepsByTarget() } 30 | //val towers: List by lazyPerTick { 31 | // myStuctures.values.filter { it.structureType == STRUCTURE_TOWER }.map { it as StructureTower } 32 | //} 33 | val towers: List by lazyPerTick { myStuctures.values.filter { it.structureType == STRUCTURE_TOWER } as List } 34 | 35 | private fun creepsByTarget(): Map { 36 | return Context.creeps.filter { it.value.memory.targetId != null } 37 | .mapKeys { (_, creep) -> creep.memory.targetId!! } 38 | } 39 | } 40 | 41 | fun Iterable.filterIsStrucure(structureType: StructureConstant): List { 42 | return this.filter { it.structureType == structureType } 43 | 44 | } 45 | 46 | 47 | fun gameLoop() { 48 | Stats.tickStarts() 49 | 50 | if (Game.time % 100 == 0) { // TODO modulo seems expensive. Use something else 51 | houseKeeping() 52 | } 53 | 54 | val mainSpawn: StructureSpawn = (Game.spawns["Spawn1"])!! 55 | val secondarySpawn: StructureSpawn? = (Game.spawns["Spawn5"]) //FIXME 56 | secondarySpawn?.also { 57 | val creeps = secondarySpawn.room.find(FIND_MY_CREEPS) 58 | if (creeps.count { it.name.startsWith(BodyDefinition.BASIC_WORKER.name) } < 3) { 59 | secondarySpawn.spawn(BodyDefinition.BASIC_WORKER) 60 | } 61 | 62 | } 63 | 64 | val energySources = mainSpawn.room.findEnergy() 65 | val minWorkers = energySources.size * 2 66 | val minMiners = energySources.size 67 | 68 | val minerCount = Context.creeps.count { it.key.startsWith(BodyDefinition.MINER.name) } 69 | val workerCount = Context.creeps.count { it.key.startsWith(BodyDefinition.BASIC_WORKER.name) } 70 | val haulerCount = Context.creeps.count { it.key.startsWith(BodyDefinition.HAULER.name) } 71 | if (minerCount < minMiners) { 72 | if (GlobalSpawnQueue.spawnQueue.count { it.bodyDefinition.name.startsWith(BodyDefinition.MINER.name) } < minMiners - minerCount) { 73 | // TODO we cannot spawn small miners 74 | GlobalSpawnQueue.push(BodyDefinition.MINER_BIG, KreepSpawnOptions(CreepState.REFILL)) 75 | } 76 | } 77 | if (workerCount < minWorkers) { 78 | if (GlobalSpawnQueue.spawnQueue.count { it.bodyDefinition == BodyDefinition.BASIC_WORKER } < minWorkers - workerCount) { 79 | GlobalSpawnQueue.push(BodyDefinition.BASIC_WORKER) 80 | } 81 | } 82 | if (haulerCount < minMiners && mainSpawn.room.storage != null) { 83 | if (GlobalSpawnQueue.spawnQueue.count { it.bodyDefinition == BodyDefinition.HAULER } < minMiners - haulerCount) { 84 | GlobalSpawnQueue.push(BodyDefinition.HAULER) 85 | } 86 | } 87 | 88 | 89 | // if (Missions.activeMissions.isEmpty() && Missions.missionMemory.upgradeMissions.isEmpty()) { 90 | // val q = RoomUpgradeMission(mainSpawn.room.controller!!.missionId) 91 | // Missions.missionMemory.upgradeMissions.add(q.memory) 92 | // Missions.activeMissions.add(q) 93 | // } 94 | 95 | 96 | GlobalSpawnQueue.spawnCreeps(listOf(mainSpawn)) 97 | 98 | for ((_, room) in Context.rooms) { 99 | Stats.write(room) 100 | 101 | 102 | buildStorage(room) 103 | buildTowers(room) 104 | 105 | val hostiles = room.find(FIND_HOSTILE_CREEPS) 106 | for (tower in Context.towers) { 107 | if (tower.room.name != room.name) continue 108 | if (hostiles.isNotEmpty() && tower.energy > 0) { 109 | tower.attack(hostiles.minBy { it.hits }!!) 110 | } 111 | } 112 | } 113 | 114 | val refillEnergy = RefillEnergy() 115 | val idleBehaviour = IdleBehaviour() 116 | 117 | // remove completed mission TODO do this with mission.complete = true 118 | val removed = Missions.missionMemory.upgradeMissionMemory.removeAll { 119 | val controller = Game.getObjectById(it.controllerId) 120 | controller == null || !controller.my 121 | } 122 | if (removed) { 123 | println("removed a mission") 124 | Missions.activeMissions.clear() 125 | Missions.save() 126 | } 127 | 128 | Missions.load() 129 | 130 | for ((name, flag) in Game.flags) { 131 | if (name == "colonize" && Missions.activeMissions.none { it is ColonizeMission && it.pos.roomName == flag.pos.roomName }) { 132 | ColonizeMission.forRoom(flag.pos) 133 | } 134 | } 135 | for ((name, spawn) in Game.spawns) { 136 | if (spawn.my && spawn.room.controller!!.my && Missions.missionMemory.upgradeMissionMemory.none { it.controllerId == spawn.room.controller!!.id }) { 137 | RoomUpgradeMission.forRoom(spawn.room) 138 | } 139 | } 140 | 141 | Missions.update() 142 | 143 | for ((_, creep) in Context.creeps) { 144 | if (creep.spawning) continue 145 | 146 | when (creep.memory.state) { 147 | CreepState.UNKNOWN -> { 148 | println("creep ${creep.name} was in UKNOWN state. Resuming from IDLE") 149 | idleBehaviour.run(creep, mainSpawn) 150 | } 151 | CreepState.IDLE -> idleBehaviour.run(creep, mainSpawn) 152 | CreepState.REFILL -> refillEnergy.run(creep) 153 | else -> BusyBehaviour.run(creep) //TODO make dis better 154 | } 155 | } 156 | 157 | GlobalSpawnQueue.save() 158 | Missions.save() 159 | 160 | Stats.tickEnds() 161 | sandbox() 162 | } 163 | 164 | fun sandbox() { 165 | 166 | 167 | } 168 | 169 | public fun houseKeeping() { 170 | js( 171 | """ 172 | for (var name in Memory.creeps) { 173 | if (!Game.creeps[name]) { 174 | delete Memory.creeps[name]; 175 | console.log('Clearing non-existing creep memory:', name); 176 | } 177 | } 178 | """ 179 | ) 180 | } 181 | -------------------------------------------------------------------------------- /src/main/kotlin/screeps/game/one/KreepMemory.kt: -------------------------------------------------------------------------------- 1 | package screeps.game.one 2 | 3 | import screeps.api.CreepMemory 4 | import screeps.utils.memory.memory 5 | 6 | var CreepMemory.state by memory(CreepState.UNKNOWN) 7 | var CreepMemory.targetId: String? by memory() 8 | var CreepMemory.assignedEnergySource: String? by memory() 9 | var CreepMemory.missionId: String? by memory() 10 | 11 | enum class CreepState { 12 | UNKNOWN, IDLE, BUSY, REFILL, TRANSFERRING_ENERGY, CONSTRUCTING, UPGRADING, REPAIR, CLAIM, MISSION 13 | } 14 | -------------------------------------------------------------------------------- /src/main/kotlin/screeps/game/one/Mission.kt: -------------------------------------------------------------------------------- 1 | package screeps.game.one 2 | 3 | import kotlinx.serialization.ImplicitReflectionSerializer 4 | import kotlinx.serialization.Serializable 5 | import kotlinx.serialization.json.Json 6 | import kotlinx.serialization.parse 7 | import kotlinx.serialization.stringify 8 | import screeps.api.Memory 9 | 10 | abstract class Mission(open val parent: Mission? = null) { 11 | abstract val missionId: String 12 | abstract fun update() 13 | 14 | open var complete = false 15 | protected set 16 | } 17 | 18 | 19 | @Serializable 20 | data class ActiveMissionMemory( 21 | /* 22 | Rightnow there is no polymorphic serializer for kotlin-js so we have to resort to this 23 | */ 24 | val upgradeMissionMemory: MutableList = mutableListOf(), 25 | val colonizeMissionMemory: MutableList = mutableListOf() 26 | ) 27 | 28 | object Missions { 29 | val missionMemory: ActiveMissionMemory 30 | val activeMissions: MutableList = mutableListOf() 31 | 32 | init { 33 | missionMemory = Memory.activeMissionMemory ?: ActiveMissionMemory(mutableListOf()) 34 | } 35 | 36 | fun load() = profiled("missions.load") { 37 | for (memory in missionMemory.upgradeMissionMemory) { 38 | if (activeMissions.none { it.missionId == memory.missionId }) { 39 | activeMissions.add(memory.restoreMission()) 40 | } 41 | } 42 | for (memory in missionMemory.colonizeMissionMemory) { 43 | if (activeMissions.none { it.missionId == memory.missionId }) { 44 | activeMissions.add(memory.restoreMission()) 45 | } 46 | } 47 | } 48 | 49 | fun update() = profiled("missions.update") { 50 | for (mission in activeMissions) { 51 | mission.update() 52 | } 53 | activeMissions.removeAll { it.complete } 54 | missionMemory.colonizeMissionMemory.removeAll { it.isComplete() } 55 | } 56 | 57 | fun save() = profiled("missions.save") { 58 | Memory.activeMissionMemory = missionMemory 59 | } 60 | 61 | @UseExperimental(ImplicitReflectionSerializer::class) 62 | private var Memory.activeMissionMemory: ActiveMissionMemory? 63 | get() { 64 | val internal = this.asDynamic()._missionMemory 65 | return if (internal == null) null else Json.parse(internal) 66 | } 67 | set(value) { 68 | val stringyfied = if (value == null) null else Json.stringify(value) 69 | this.asDynamic()._missionMemory = stringyfied 70 | } 71 | } 72 | 73 | abstract class MissionMemory { 74 | abstract val missionId: String 75 | abstract fun restoreMission(): T 76 | 77 | open fun isComplete(): Boolean = false 78 | } -------------------------------------------------------------------------------- /src/main/kotlin/screeps/game/one/Spawning.kt: -------------------------------------------------------------------------------- 1 | package screeps.game.one 2 | 3 | import kotlinx.serialization.ImplicitReflectionSerializer 4 | import kotlinx.serialization.Serializable 5 | import kotlinx.serialization.json.Json 6 | import kotlinx.serialization.parse 7 | import kotlinx.serialization.stringify 8 | import screeps.api.* 9 | import screeps.api.structures.SpawnOptions 10 | import screeps.api.structures.StructureSpawn 11 | import screeps.game.one.kreeps.BodyDefinition 12 | 13 | fun StructureSpawn.spawn(bodyDefinition: BodyDefinition, spawnOptions: KreepSpawnOptions? = null): ScreepsReturnCode { 14 | if (room.energyAvailable < bodyDefinition.cost) return ERR_NOT_ENOUGH_ENERGY 15 | 16 | val body = bodyDefinition.getBiggest(room.energyAvailable) 17 | val newName = "${bodyDefinition.name}_T${body.tier}_${Game.time}" 18 | 19 | val actualSpawnOptions = spawnOptions ?: GlobalSpawnQueue.defaultSpawnOptions 20 | println("actual mission = ${actualSpawnOptions.toSpawnOptions().memory?.missionId}") 21 | val code = this.spawnCreep( 22 | body.body.toTypedArray(), 23 | newName, 24 | actualSpawnOptions.toSpawnOptions() 25 | ) 26 | 27 | if (code == OK) println("spawning $newName with spawnOptions $actualSpawnOptions") 28 | return code 29 | } 30 | 31 | object GlobalSpawnQueue { 32 | 33 | @Serializable 34 | private val queue: MutableList 35 | val spawnQueue: List 36 | get() = queue 37 | 38 | private var modified: Boolean = false 39 | val defaultSpawnOptions = KreepSpawnOptions(state = CreepState.IDLE) 40 | 41 | init { 42 | // load from memory 43 | queue = try { 44 | Memory.globalSpawnQueue?.queue?.toMutableList() ?: ArrayList() 45 | } catch (e: Error) { 46 | println("Error while initializing GlobalSpawnQueue: $e") 47 | ArrayList() 48 | } 49 | println("spawnqueue initialized to $queue") 50 | } 51 | 52 | fun push(bodyDefinition: BodyDefinition, spawnOptions: KreepSpawnOptions? = null) { 53 | queue.add(SpawnInfo(bodyDefinition, spawnOptions ?: defaultSpawnOptions)) 54 | modified = true 55 | } 56 | 57 | fun spawnCreeps(spawns: List) { 58 | if (queue.isEmpty()) return 59 | if (queue.size > 5) println("spawnqueue has size ${queue.size} with first 10 ${queue.take(10)}") 60 | for (spawn in spawns) { 61 | if (queue.isEmpty() || spawn.spawning != null) continue 62 | 63 | val (bodyDefinition, spawnOptions) = queue.first() 64 | val code = spawn.spawn(bodyDefinition, spawnOptions) 65 | 66 | when (code) { 67 | OK -> { 68 | queue.removeAt(0) 69 | modified = true 70 | } 71 | 72 | ERR_NOT_ENOUGH_ENERGY -> { 73 | if (bodyDefinition.cost > spawn.room.energyCapacityAvailable) { 74 | println("creep ${bodyDefinition.name} with body ${bodyDefinition.body} (cost ${bodyDefinition.cost}) is to expensive for ${spawn.name}") 75 | } 76 | 77 | val creep = queue.removeAt(0) 78 | queue.add(creep) 79 | modified = true 80 | } 81 | 82 | else -> println("Unexpected return code $code when spawning creep ${bodyDefinition.name} with $spawnOptions") 83 | } 84 | } 85 | } 86 | 87 | /** 88 | * Save content of the queue to memory 89 | */ 90 | fun save() { 91 | if (modified) Memory.globalSpawnQueue = CreepSpawnList(queue) 92 | modified = false 93 | } 94 | 95 | 96 | @UseExperimental(ImplicitReflectionSerializer::class) 97 | private var Memory.globalSpawnQueue: CreepSpawnList? 98 | get() { 99 | val internal = this.asDynamic().globalSpawnQueue 100 | return if (internal == null) null else Json.parse(internal) 101 | } 102 | set(value) { 103 | val stringyfied = if (value == null) null else Json.stringify(value) 104 | this.asDynamic().globalSpawnQueue = stringyfied 105 | } 106 | } 107 | 108 | fun requestCreep(bodyDefinition: BodyDefinition, spawnOptions: KreepSpawnOptions) { 109 | 110 | val candidate = 111 | Context.creeps.values.firstOrNull { it.memory.state == CreepState.IDLE && it.body.contentEquals(bodyDefinition.body) } 112 | if (candidate != null) { 113 | spawnOptions.transfer(candidate.memory) 114 | } else { 115 | GlobalSpawnQueue.push(bodyDefinition, spawnOptions) 116 | } 117 | 118 | } 119 | 120 | fun requestCreepOnce(bodyDefinition: BodyDefinition, spawnOptions: KreepSpawnOptions) { 121 | 122 | if (GlobalSpawnQueue.spawnQueue.none { it.spawnOptions == spawnOptions && it.bodyDefinition == bodyDefinition }) { 123 | requestCreep(bodyDefinition, spawnOptions) 124 | } 125 | } 126 | 127 | @Serializable 128 | data class SpawnInfo(val bodyDefinition: BodyDefinition, val spawnOptions: KreepSpawnOptions) 129 | 130 | @Serializable 131 | data class CreepSpawnList(val queue: List) 132 | 133 | @Serializable 134 | data class KreepSpawnOptions( 135 | val state: CreepState = CreepState.IDLE, 136 | val missionId: String? = null, 137 | val targetId: String? = null, 138 | val assignedEnergySource: String? = null 139 | ) { 140 | fun toSpawnOptions(): SpawnOptions = options { 141 | memory = object : CreepMemory {}.apply { transfer(this) } 142 | } 143 | 144 | fun transfer(memory: CreepMemory) { 145 | memory.state = state 146 | memory.missionId = missionId 147 | memory.targetId = targetId 148 | memory.assignedEnergySource = assignedEnergySource 149 | } 150 | } 151 | 152 | 153 | -------------------------------------------------------------------------------- /src/main/kotlin/screeps/game/one/Stats.kt: -------------------------------------------------------------------------------- 1 | package screeps.game.one 2 | 3 | import screeps.api.Game 4 | import screeps.api.Memory 5 | import screeps.api.Room 6 | 7 | object Stats { 8 | 9 | const val FN_PREFIX = "cpu.usage.fn." 10 | private const val RESET_TICK_TIMEOUT = 19 // 60s / 3.2 (s/tick) = 19 ticks 11 | private var globalreset = true // is initialized on global reset 12 | private var resetInTicks = RESET_TICK_TIMEOUT 13 | 14 | var Memory.stats: dynamic 15 | get() = this.asDynamic().stats 16 | set(value) = run { this.asDynamic().stats = value } 17 | 18 | init { 19 | if (Memory.stats == null) { 20 | Memory.stats = Any() 21 | } 22 | } 23 | 24 | fun write(room: Room) { 25 | 26 | val r = "rooms.${room.name}" 27 | 28 | Memory.stats["$r.mine"] = room.controller?.level ?: 0 29 | Memory.stats["$r.energyAvailable"] = room.energyAvailable 30 | Memory.stats["$r.energyCapacityAvailable"] = room.energyCapacityAvailable 31 | room.storage?.let { 32 | Memory.stats["$r.storage"] = it.store 33 | } 34 | room.controller?.let { 35 | val r = "$r.controller" 36 | Memory.stats["$r.level"] = it.level 37 | Memory.stats["$r.progress"] = it.progress 38 | Memory.stats["$r.progressTotal"] = it.progressTotal 39 | } 40 | } 41 | 42 | fun write(key: String, value: Any) { 43 | Memory.stats[key] = value 44 | } 45 | 46 | fun tickStarts() { 47 | resetInTicks -= 1 48 | if (resetInTicks < 0) { 49 | resetInTicks = RESET_TICK_TIMEOUT 50 | Memory.stats = Any() 51 | } 52 | } 53 | 54 | fun tickEnds() { 55 | Memory.stats["cpu.used"] = Game.cpu.getUsed() 56 | Memory.stats["cpu.limit"] = Game.cpu.limit 57 | Memory.stats["cpu.bucket"] = Game.cpu.bucket 58 | 59 | if (globalreset) { 60 | Memory.stats["globalreset"] = Game.time 61 | globalreset = false 62 | } 63 | } 64 | 65 | fun profiled(name: String, prefix: String? = null, block: () -> R): R { 66 | val key = FN_PREFIX + if (prefix != null) ".$prefix." else "" + name 67 | val cpuBefore = Game.cpu.getUsed() 68 | 69 | val result = block() 70 | 71 | val cpuUsed = Game.cpu.getUsed() - cpuBefore 72 | Memory.stats[key] = cpuUsed 73 | return result 74 | } 75 | } 76 | 77 | fun profiled(name: String, prefix: String? = null, block: () -> R) = Stats.profiled(name, prefix, block) -------------------------------------------------------------------------------- /src/main/kotlin/screeps/game/one/Task.kt: -------------------------------------------------------------------------------- 1 | package screeps.game.one 2 | 3 | abstract class Task { 4 | abstract val priorityThreshold: Int 5 | abstract val priority: Int 6 | open val minCreeps = 0 7 | } 8 | 9 | class RefillTask : Task() { 10 | 11 | override val priorityThreshold: Int 12 | get() = 0 13 | override val priority: Int 14 | get() = 0 15 | override val minCreeps = 1 16 | 17 | } -------------------------------------------------------------------------------- /src/main/kotlin/screeps/game/one/UpgradeMission.kt: -------------------------------------------------------------------------------- 1 | package screeps.game.one 2 | 3 | import kotlinx.serialization.Serializable 4 | import screeps.api.Creep 5 | import screeps.api.Game 6 | import screeps.api.Room 7 | import screeps.api.structures.StructureController 8 | import screeps.game.one.kreeps.BodyDefinition 9 | 10 | //sealed class UpgradeMission1 11 | //class RoomUpgradeMission : UpgradeMission1() 12 | //sealed class RunningUpgradeMission : UpgradeMission1() 13 | //class EasyUpgradeMission : RunningUpgradeMission() 14 | //class LinkUpgradeMission : RunningUpgradeMission() 15 | //class RCL8UpgradeMission : RunningUpgradeMission() 16 | 17 | 18 | /** 19 | * Mission to upgrade a controller using multiple creeps to carry energy 20 | * Can be cached safely 21 | * 22 | * @throws IllegalStateException if it can't be initialized 23 | */ 24 | abstract class UpgradeMission(val controllerId: String) : Mission() { 25 | val controller: StructureController 26 | get() = Game.getObjectById(controllerId) ?: throw IllegalStateException("could not find controller $controllerId probably due to lack of vision") 27 | 28 | abstract fun abort() 29 | } 30 | 31 | 32 | class RoomUpgradeMission(private val memory: UpgradeMissionMemory) : UpgradeMission(memory.controllerId) { 33 | 34 | companion object { 35 | const val maxLevel = 8 36 | fun forRoom(room: Room, state: State = State.EARLY): RoomUpgradeMission { 37 | val controller = room.controller ?: throw IllegalStateException("Roomcontroller null") 38 | val memory = UpgradeMissionMemory(controller.id, state) 39 | val mission = RoomUpgradeMission(memory) 40 | Missions.missionMemory.upgradeMissionMemory.add(memory) 41 | Missions.activeMissions.add(mission) 42 | println("spawning persistent RoomUpgradeMission for room ${room.name}") 43 | return mission 44 | } 45 | } 46 | 47 | enum class State { 48 | EARLY, LINK, RCL8_MAINTENANCE, RCL8_IDLE 49 | } 50 | 51 | override val missionId: String = memory.missionId 52 | var mission: UpgradeMission? 53 | 54 | init { 55 | when (memory.state) { 56 | State.RCL8_IDLE -> mission = null 57 | else -> mission = EarlyGameUpgradeMission(this, memory.controllerId, if (controller.level == 8) 1 else 3) 58 | } 59 | } 60 | 61 | override fun update() { 62 | if (controller.level == maxLevel) { 63 | if (memory.state == State.EARLY) { 64 | memory.state = State.RCL8_MAINTENANCE 65 | } 66 | 67 | if (memory.state == State.RCL8_IDLE && controller.ticksToDowngrade < 100_000) { 68 | memory.state = State.RCL8_MAINTENANCE 69 | mission = EarlyGameUpgradeMission(this, controller.id, 1) 70 | } else if (memory.state == State.RCL8_MAINTENANCE && controller.ticksToDowngrade > 140_000) { 71 | memory.state = State.RCL8_IDLE 72 | mission?.abort() 73 | mission = null 74 | } 75 | } 76 | 77 | mission?.update() 78 | } 79 | 80 | override fun abort() { 81 | if (controller.my) throw IllegalStateException("stopping to upgrade my controller in Room ${controller.room}") 82 | else { 83 | mission = null 84 | complete = true 85 | } 86 | } 87 | } 88 | 89 | class EarlyGameUpgradeMission( 90 | override val parent: UpgradeMission, 91 | controllerId: String, 92 | private val minWorkerCount: Int 93 | ) : UpgradeMission(controllerId) { 94 | 95 | override val missionId: String 96 | get() = parent.missionId 97 | 98 | // TODO must not cache workers!! 99 | private val workers: MutableList = mutableListOf() 100 | 101 | init { 102 | workers.addAll(Context.creeps.values.filter { it.memory.missionId == missionId }) 103 | } 104 | 105 | override fun update() { 106 | 107 | if (workers.size < minWorkerCount) { 108 | workers.clear() 109 | workers.addAll(Context.creeps.values.filter { it.memory.missionId == missionId }) 110 | 111 | if (workers.size < minWorkerCount 112 | && workers.size + GlobalSpawnQueue.spawnQueue.count { it.spawnOptions.missionId == missionId } < minWorkerCount 113 | ) { 114 | requestCreep(BodyDefinition.BASIC_WORKER, KreepSpawnOptions(CreepState.UPGRADING, missionId)) 115 | println("requested creep for EarlyGameUpgradeMission $missionId in ${controller.room}") 116 | } 117 | } 118 | 119 | for (worker in workers) { 120 | if (worker.memory.state == CreepState.IDLE) { 121 | worker.memory.state = CreepState.UPGRADING 122 | worker.memory.targetId = controller.id 123 | } 124 | } 125 | workers.clear() // TODO do this more efficiently 126 | } 127 | 128 | override fun abort() { 129 | // return workers to pool 130 | for (worker in workers) { 131 | worker.memory.missionId = null 132 | worker.memory.state = CreepState.IDLE 133 | } 134 | } 135 | } 136 | 137 | @Serializable 138 | class UpgradeMissionMemory(val controllerId: String, var state: RoomUpgradeMission.State) : MissionMemory() { 139 | override val missionId: String 140 | get() = "upgrade_$controllerId" 141 | 142 | override fun restoreMission(): RoomUpgradeMission { 143 | return RoomUpgradeMission(this) 144 | } 145 | } -------------------------------------------------------------------------------- /src/main/kotlin/screeps/game/one/Utils.kt: -------------------------------------------------------------------------------- 1 | package screeps.game.one 2 | 3 | import screeps.api.Creep 4 | import screeps.api.RoomObject 5 | 6 | fun Creep.findClosest(roomObjects: Collection): T? { 7 | 8 | var closest: T? = null 9 | var minDistance = Int.MAX_VALUE 10 | for (roomObject in roomObjects) { 11 | val dist = (roomObject.pos.x - this.pos.x) * (roomObject.pos.x - this.pos.x) + 12 | (roomObject.pos.y - this.pos.y) * (roomObject.pos.y - this.pos.y) 13 | 14 | if (dist < minDistance) { 15 | minDistance = dist 16 | closest = roomObject 17 | } 18 | } 19 | return closest 20 | } 21 | 22 | fun Creep.findClosest(roomObjects: Array): T? { 23 | var closest: T? = null 24 | var minDistance = Int.MAX_VALUE 25 | for (roomObject in roomObjects) { 26 | val dist = (roomObject.pos.x - this.pos.x) * (roomObject.pos.x - this.pos.x) + 27 | (roomObject.pos.y - this.pos.y) * (roomObject.pos.y - this.pos.y) 28 | 29 | if (dist < minDistance) { 30 | minDistance = dist 31 | closest = roomObject 32 | } 33 | } 34 | return closest 35 | } 36 | 37 | fun Creep.findClosestNotEmpty(roomObjects: Array): T { 38 | require(roomObjects.isNotEmpty()) 39 | return findClosest(roomObjects)!! 40 | } -------------------------------------------------------------------------------- /src/main/kotlin/screeps/game/one/behaviours/Behaviours.kt: -------------------------------------------------------------------------------- 1 | package screeps.game.one.behaviours 2 | 3 | import screeps.api.* 4 | import screeps.api.structures.Structure 5 | import screeps.api.structures.StructureController 6 | import screeps.api.structures.StructureRoad 7 | import screeps.api.structures.StructureSpawn 8 | import screeps.game.one.* 9 | import screeps.game.one.building.buildRoads 10 | import screeps.game.one.kreeps.BodyDefinition 11 | import traveler.travelTo 12 | import kotlin.random.Random 13 | 14 | class IdleBehaviour { 15 | fun structuresThatNeedRepairing(): List { 16 | val room = Game.rooms.values.firstOrNull { it.storage != null } 17 | 18 | return room?.findStructures().orEmpty().filterNot { Context.targets.containsKey(it.id) } 19 | .filter { it.hits < it.hitsMax / 2 && it.hits < 2_000_000 } 20 | .sortedBy { it.hits } 21 | .take(5) //TODO only repairing 5 is arbitrary 22 | } 23 | 24 | val structureThatNeedRepairing = structuresThatNeedRepairing() 25 | var structureThatNeedRepairingIndex = 0 26 | 27 | fun run(creep: Creep, spawn: StructureSpawn) { 28 | if (creep.memory.missionId != null) return // we do not care about creeps on a mission 29 | creep.memory.targetId = null //just making sure it is reset 30 | 31 | 32 | val constructionSite = creep.findClosest(creep.room.findMyConstructionSites()) 33 | val controller = creep.room.controller 34 | 35 | val towersInNeedOfRefill = Context.towers.filter { it.room == creep.room && it.energy < it.energyCapacity } 36 | when { 37 | //make sure spawn does not dry up 38 | notEnoughtSpawnEnergy(creep.room) -> { 39 | creep.memory.state = CreepState.TRANSFERRING_ENERGY 40 | } 41 | 42 | //make sure towe does not dry up 43 | towersInNeedOfRefill.isNotEmpty() -> { 44 | creep.memory.state = CreepState.TRANSFERRING_ENERGY 45 | creep.memory.targetId = towersInNeedOfRefill.first().id 46 | } 47 | 48 | creep.name.startsWith(BodyDefinition.HAULER.name) && creep.room.storage != null -> { 49 | creep.memory.state = CreepState.TRANSFERRING_ENERGY 50 | creep.memory.targetId = creep.room.storage!!.id 51 | } 52 | 53 | //check if we need to construct something 54 | constructionSite != null -> { 55 | creep.memory.state = CreepState.CONSTRUCTING 56 | creep.memory.targetId = constructionSite.id 57 | } 58 | //check if we need to upgrade the controller 59 | controller != null && controller.level < 8 && Context.creeps.none { it.value.memory.state == CreepState.UPGRADING } -> { 60 | creep.memory.state = CreepState.UPGRADING 61 | creep.memory.targetId = controller.id 62 | } 63 | structureThatNeedRepairing.isNotEmpty() && structureThatNeedRepairingIndex < structureThatNeedRepairing.size -> { 64 | val structure = structureThatNeedRepairing[structureThatNeedRepairingIndex++] 65 | creep.memory.state = CreepState.REPAIR 66 | creep.memory.targetId = structure.id 67 | println("repairing ${structure.structureType} (${structure.id})") 68 | } 69 | 70 | controller?.level == 8 && controller.ticksToDowngrade < 10_000 && Context.creeps.none { it.value.memory.state == CreepState.UPGRADING } -> { 71 | creep.memory.state = CreepState.UPGRADING 72 | creep.memory.targetId = controller.id 73 | } 74 | 75 | creep.room.energyAvailable < creep.room.energyCapacityAvailable -> { 76 | creep.memory.state = CreepState.TRANSFERRING_ENERGY 77 | 78 | } 79 | //if still idle upgrade controller 80 | controller != null && controller.level < 8 -> { 81 | creep.memory.state = CreepState.UPGRADING 82 | creep.memory.targetId = controller.id 83 | } 84 | else -> { //get out of the way 85 | if (creep.pos.look().any { it.structure is StructureRoad }) { 86 | // println("${creep.name}! Quit stadning on a road like a dumbass!") 87 | creep.moveInRandomDirection() 88 | } 89 | } 90 | 91 | } 92 | 93 | } 94 | 95 | fun Creep.moveInRandomDirection() { 96 | val rand = Random.nextDouble() 97 | 98 | val direction = when { 99 | rand < 0.125 -> TOP 100 | rand < 0.25 -> TOP_RIGHT 101 | rand < 0.375 -> RIGHT 102 | rand < 0.5 -> BOTTOM_RIGHT 103 | rand < 0.625 -> BOTTOM 104 | rand < 0.75 -> BOTTOM_LEFT 105 | rand < 0.875 -> LEFT 106 | else -> TOP_LEFT 107 | } 108 | move(direction) 109 | } 110 | 111 | private fun notEnoughtSpawnEnergy(room: Room) = 112 | room.energyAvailable < BodyDefinition.BASIC_WORKER.cost 113 | // or at least 2/3 of energy available 114 | || room.energyCapacityAvailable > BodyDefinition.BASIC_WORKER.cost 115 | && room.energyAvailable < room.energyCapacityAvailable * 2.0 / 3.0 116 | } 117 | 118 | 119 | object BusyBehaviour { 120 | fun run(creep: Creep) { 121 | 122 | if (creep.carry.energy == 0) { 123 | creep.memory.state = CreepState.REFILL 124 | creep.memory.targetId = null 125 | return 126 | } 127 | 128 | 129 | if (creep.memory.state == CreepState.TRANSFERRING_ENERGY) { 130 | fun findTarget(): Structure? { 131 | val targets = creep.room.findStructures() 132 | .filter { (it.structureType == STRUCTURE_EXTENSION || it.structureType == STRUCTURE_SPAWN) } 133 | .filter { it.unsafeCast().energy < it.unsafeCast().energyCapacity } 134 | 135 | return creep.findClosest(targets) 136 | } 137 | 138 | val target = if (creep.memory.targetId != null) { 139 | Game.getObjectById(creep.memory.targetId) 140 | } else findTarget() 141 | 142 | if (target != null) { 143 | val code = creep.transfer(target, RESOURCE_ENERGY) 144 | when (code) { 145 | OK -> kotlin.run { } 146 | ERR_NOT_IN_RANGE -> creep.travelTo(target.pos) 147 | else -> creep.memory.state = CreepState.IDLE 148 | } 149 | } else { 150 | creep.memory.state = CreepState.IDLE 151 | creep.memory.targetId = null 152 | } 153 | } 154 | 155 | 156 | if (creep.memory.state == CreepState.UPGRADING) { 157 | val controller = 158 | creep.memory.targetId?.let { Game.getObjectById(it) as? StructureController } 159 | ?: creep.room.controller!! 160 | if (creep.upgradeController(controller) == ERR_NOT_IN_RANGE) { 161 | creep.travelTo(controller.pos) 162 | } 163 | } 164 | 165 | if (creep.memory.state == CreepState.CONSTRUCTING) { 166 | val constructionSite = Context.constructionSites[creep.memory.targetId!!] 167 | if (constructionSite != null) { 168 | if (creep.build(constructionSite) == ERR_NOT_IN_RANGE) { 169 | creep.travelTo(constructionSite.pos); 170 | } 171 | } else { 172 | println("construction of ${creep.memory.targetId} is done") 173 | creep.memory.targetId = null 174 | creep.memory.state = CreepState.IDLE 175 | buildRoads(creep.room) 176 | } 177 | } 178 | 179 | if (creep.memory.state == CreepState.REPAIR) { 180 | require(creep.memory.targetId != null) 181 | val structure = Game.getObjectById(creep.memory.targetId!!) 182 | 183 | fun done() { 184 | println("finished repairing ${creep.memory.targetId}") 185 | creep.memory.state = CreepState.IDLE 186 | creep.memory.targetId = null 187 | } 188 | if (structure == null || structure.hits == structure.hitsMax) { 189 | done() 190 | } else { 191 | if (creep.repair(structure) == ERR_NOT_IN_RANGE) { 192 | creep.travelTo(structure.pos) 193 | } 194 | } 195 | } 196 | 197 | } 198 | } -------------------------------------------------------------------------------- /src/main/kotlin/screeps/game/one/behaviours/RefillEnergy.kt: -------------------------------------------------------------------------------- 1 | package screeps.game.one.behaviours 2 | 3 | import screeps.api.* 4 | import screeps.api.structures.Structure 5 | import screeps.api.structures.StructureContainer 6 | import screeps.api.structures.StructureStorage 7 | import screeps.game.one.* 8 | import screeps.game.one.kreeps.BodyDefinition 9 | import screeps.utils.lazyPerTick 10 | import traveler.travelTo 11 | 12 | class RefillEnergy { 13 | companion object { 14 | const val MAX_MINER_WORK_PARTS_PER_SOURCE = 5 15 | const val MAX_CREEP_PER_DROPPED_ENERGY = 1 16 | } 17 | 18 | val droppedEnergyByRoom: MutableMap> = mutableMapOf() 19 | val minersByRoom: MutableMap> = mutableMapOf() 20 | 21 | val usedSourcesWithCreepWORKCounts: MutableMap by lazyPerTick { 22 | 23 | val sources = Context.creeps.values.mapNotNull { it.memory.assignedEnergySource } 24 | val m = mutableMapOf() 25 | for (source in sources) { 26 | m[source] = Context.creeps.values.filter { it.memory.assignedEnergySource == source } 27 | .sumBy { it.body.count { it.type == WORK } } 28 | } 29 | m 30 | } 31 | 32 | fun run(creep: Creep) { 33 | if (creep.name.startsWith(BodyDefinition.MINER.name)) { 34 | miner(creep) 35 | } else { 36 | val canWork = worker(creep) 37 | miner(creep) 38 | } 39 | } 40 | 41 | private fun worker(creep: Creep): Boolean { 42 | /* 43 | workers can be assigned to a 44 | * miner 45 | * container 46 | * source 47 | * in the future... carry 48 | 49 | */ 50 | if (shouldContinueMininig(creep)) { 51 | val source: Identifiable? = getSourceFromMemory(creep) ?: creep.requestEnergy() 52 | 53 | if (source == null) { 54 | println("no energy available for worker ${creep.name}") 55 | return false 56 | } else { 57 | creep.memory.assignedEnergySource = source.id 58 | } 59 | 60 | when (source) { 61 | is Creep -> refillFromMinerCreep(creep, source) 62 | is Source -> run {} //println("my source is Source") 63 | is Resource -> refillFromResource(creep, source) 64 | is StructureContainer -> refillFromStructure(creep, source) 65 | is StructureStorage -> refillFromStructure(creep, source) 66 | else -> println("dont know the type of my source") 67 | } 68 | 69 | return true 70 | } else { 71 | creep.memory.state = CreepState.IDLE 72 | return true 73 | } 74 | } 75 | 76 | private fun getSourceFromMemory(creep: Creep): Identifiable? { 77 | val assigned = Game.getObjectById(creep.memory.assignedEnergySource) 78 | if (assigned == null) { 79 | creep.memory.assignedEnergySource = null 80 | } 81 | return assigned 82 | } 83 | 84 | private fun refillFromStructure(creep: Creep, source: Structure) { 85 | when (creep.withdraw(source, RESOURCE_ENERGY)) { 86 | OK -> kotlin.run { } 87 | ERR_NOT_IN_RANGE -> creep.travelTo(source.pos) 88 | ERR_NOT_ENOUGH_RESOURCES -> creep.memory.assignedEnergySource = null 89 | else -> { 90 | println("${creep.name} could now withdraw from (${source.id})") 91 | creep.say("could now withdraw from (${source.id})") 92 | creep.memory.assignedEnergySource = null 93 | } 94 | } 95 | } 96 | 97 | private fun refillFromResource(creep: Creep, resource: Resource) { 98 | if (creep.pickup(resource) == ERR_NOT_IN_RANGE) { 99 | creep.travelTo(resource.pos) 100 | } 101 | } 102 | 103 | private fun refillFromMinerCreep(creep: Creep, miner: Creep) { 104 | require(miner.name.startsWith(BodyDefinition.MINER.name)) 105 | 106 | val minerTile = miner.room.lookAt(miner.pos).firstOrNull() 107 | 108 | when { 109 | minerTile == null -> println("assigned miner ${miner.id} is not yet mining") 110 | 111 | minerTile.type == LOOK_RESOURCES && minerTile.resource!!.resourceType == RESOURCE_ENERGY -> { 112 | refillFromResource(creep, minerTile.resource!!) 113 | } 114 | 115 | minerTile.type == LOOK_STRUCTURES && minerTile.structure!!.structureType == STRUCTURE_CONTAINER -> { 116 | refillFromStructure(creep, minerTile.structure as StructureContainer) 117 | } 118 | } 119 | 120 | 121 | } 122 | 123 | private fun Creep.requestEnergy(): Identifiable? { 124 | 125 | val isHauler = name.startsWith(BodyDefinition.HAULER.name) 126 | 127 | val droppedEnergy = droppedEnergyByRoom.getOrPut(room) { 128 | room.findDroppedEnergy().sortedBy { it.amount } 129 | } 130 | 131 | //find a source that is close and has some free spots 132 | for (energy in droppedEnergy) { 133 | if (energy.amount >= carryCapacity && 134 | usedSourcesWithCreepWORKCounts.getOrElse(energy.id, { 0 }) < MAX_CREEP_PER_DROPPED_ENERGY 135 | ) { 136 | return energy 137 | } 138 | } 139 | 140 | //assign to storage if not a hauler (hauling from storage to storage is a bit useless) 141 | val storage = room.storage 142 | if (!isHauler && storage != null && storage.my && storage.store.energy > carryCapacity) { 143 | return storage 144 | } 145 | 146 | //assign to a miner 147 | val miners = minersByRoom.getOrPut(this.room) { 148 | Context.creeps.filter { it.key.startsWith(BodyDefinition.MINER.name) && it.value.room.name == this.room.name } //TODO assign to miners in other rooms that serve the same colony 149 | .values.toTypedArray() 150 | } 151 | if (miners.isNotEmpty()) { 152 | //biggest miner first 153 | // TODO this could be bad because usedSourcesWithCreepWORKCounts only updated in the beginning of the tick 154 | // and many could be assigned to same miner 155 | 156 | if (isHauler) { 157 | val haulers: Map by lazyPerTick { 158 | Context.creeps.filter { 159 | it.value.name.startsWith( 160 | BodyDefinition.HAULER.name 161 | ) 162 | } 163 | } 164 | val minerWithoutHauler = 165 | miners.filterNot { miner -> haulers.any { hauler -> hauler.value.memory.assignedEnergySource == miner.id } } 166 | .firstOrNull() 167 | if (minerWithoutHauler != null) return minerWithoutHauler 168 | 169 | } else return miners.maxBy { 170 | val creepsAssignedToMiner = usedSourcesWithCreepWORKCounts[it.id] ?: 0 171 | val minerOutput = it.body.count { it.type == WORK } * 2 172 | minerOutput.toDouble() / (creepsAssignedToMiner + 1) 173 | } 174 | } 175 | 176 | val containers = room.findStructures() 177 | .filter { it.structureType == STRUCTURE_CONTAINER } 178 | .filter { (it as StructureContainer).store.energy > 0 } 179 | if (containers.isNotEmpty()) { 180 | println("assigning creep $name's energysource to a container") 181 | } 182 | return findClosest(containers) 183 | } 184 | 185 | private fun miner(creep: Creep) { 186 | if (shouldContinueMininig(creep)) { 187 | var assignedSource = creep.memory.assignedEnergySource 188 | if (assignedSource == null) { 189 | val energySources = creep.room.findEnergy() 190 | val source = creep.requestSource(energySources) 191 | if (source == null) { 192 | println("no energy sources available for creep ${creep.name} in ${creep.room}") 193 | return 194 | } 195 | creep.memory.assignedEnergySource = source.id 196 | assignedSource = source.id 197 | } 198 | 199 | val source = Game.getObjectById(assignedSource) 200 | if (source == null) { 201 | creep.memory.assignedEnergySource = null 202 | return 203 | } 204 | 205 | val useContainerMining = 206 | creep.room.controller?.level ?: 0 >= 3 && creep.name.startsWith(BodyDefinition.MINER_BIG.name) 207 | if (useContainerMining) { 208 | containerMining(creep, source) 209 | } else { 210 | val code = creep.harvest(source) 211 | when (code) { 212 | ERR_NOT_IN_RANGE -> { 213 | val moveCode = creep.travelTo(source.pos) 214 | when (moveCode) { 215 | OK, ERR_TIRED -> { 216 | } 217 | //TODO handle no path 218 | else -> println("unexpected code $moveCode when moving $creep to ${source.pos}") 219 | } 220 | } 221 | } 222 | } 223 | 224 | 225 | } else { 226 | creep.memory.state = CreepState.IDLE 227 | creep.memory.assignedEnergySource = null 228 | } 229 | } 230 | 231 | private fun containerMining(creep: Creep, source: Source) { 232 | val sourceToContainerMaxRange = 3 233 | 234 | //TODO 235 | /*Container mining: 236 | If RCL > 3 we can place containers to reduce loss to decay of dropped resources. 237 | The miner needs to stand exactly on the container and repair it from time to time 238 | Obviously this is only beneficial if we already have a big miner 239 | */ 240 | 241 | //TODO make sure the computations happen not all the time 242 | //TODO this assumes the container can be built by workers -> workers must be present 243 | data class Pos(val x: Int, val y: Int) 244 | 245 | val pathToSource = source.room.findPath(creep.pos, source.pos) 246 | 247 | //figure out where to place the container 248 | val containertile: Pos = if (pathToSource.size < 2) { 249 | Pos(creep.pos.x, creep.pos.y) 250 | } else { 251 | creep.moveByPath(pathToSource) //mov to location 252 | val tileBeforeLast = pathToSource[pathToSource.lastIndex] 253 | Pos(tileBeforeLast.x, tileBeforeLast.y) 254 | } 255 | 256 | //check if there is already a container for this source 257 | val containers = source.pos.findInRange(FIND_STRUCTURES, sourceToContainerMaxRange) 258 | .filter { it.structureType == STRUCTURE_CONTAINER } 259 | when (containers.size) { 260 | 0 -> { 261 | if (source.room.lookAt(containertile.x, containertile.y) 262 | .any { it.type == LOOK_CONSTRUCTION_SITES && it.constructionSite!!.structureType == STRUCTURE_CONTAINER } 263 | ) { 264 | return 265 | } 266 | 267 | val code = source.room.createConstructionSite( 268 | containertile.x, containertile.y, 269 | STRUCTURE_CONTAINER 270 | ) 271 | when (code) { 272 | OK -> println("building container for source ${source.id}]") 273 | else -> println("error placing construction site for source ${source.id}") 274 | } 275 | 276 | } 277 | 1 -> { 278 | val container = containers.single() 279 | //set target and move to 280 | if (creep.pos.x != container.pos.x || creep.pos.y != container.pos.y) { 281 | creep.travelTo(container.pos) //TODO deal with return 282 | } else { 283 | creep.harvest(source) 284 | } 285 | } 286 | else -> { 287 | //TODO what? 288 | println("Error! multiple containers within $sourceToContainerMaxRange range of source ${source.id}") 289 | } 290 | } 291 | 292 | } 293 | 294 | 295 | private fun Creep.requestSource(energySources: Array): Source? { 296 | 297 | println("usedSourcesWithCreepWORKCounts=$usedSourcesWithCreepWORKCounts") 298 | 299 | //find a source that is close and has some free spots 300 | energySources.sort({ a, b -> (dist2(this.pos, a.pos) - dist2(this.pos, b.pos)) }) 301 | 302 | for (energySource in energySources) { 303 | val bodyPartsUsed = usedSourcesWithCreepWORKCounts.getOrElse(energySource.id, { 0 }) 304 | if (bodyPartsUsed < MAX_MINER_WORK_PARTS_PER_SOURCE) { 305 | //assign creep to energy source 306 | usedSourcesWithCreepWORKCounts[energySource.id] = bodyPartsUsed + body.count { it.type == WORK } 307 | return energySource 308 | } 309 | } 310 | 311 | return null 312 | } 313 | 314 | private fun shouldContinueMininig(creep: Creep): Boolean { 315 | if (creep.name.startsWith(BodyDefinition.MINER.name)) { 316 | return true 317 | } else { 318 | return creep.carry.energy < creep.carryCapacity 319 | } 320 | } 321 | 322 | fun dist2(from: RoomPosition, to: RoomPosition) = 323 | (to.x - from.x) * (to.x - from.x) + (to.y - from.y) * (to.y - from.y) 324 | 325 | 326 | } -------------------------------------------------------------------------------- /src/main/kotlin/screeps/game/one/building/build.kt: -------------------------------------------------------------------------------- 1 | package screeps.game.one.building 2 | 3 | import screeps.api.* 4 | import screeps.api.structures.Structure 5 | import screeps.api.structures.StructureController 6 | import screeps.api.structures.StructureSpawn 7 | import screeps.game.one.Context 8 | import screeps.game.one.findEnergy 9 | import screeps.utils.copy 10 | 11 | val StructureController.availableStorage 12 | get() = when { 13 | level >= 4 -> 1 14 | else -> 0 15 | } 16 | 17 | val StructureController.availableTowers 18 | get() = when (level) { 19 | 3, 4 -> 1 20 | 5, 6 -> 2 21 | 7 -> 3 22 | 8 -> 6 23 | else -> 0 24 | } 25 | 26 | val StructureController.availableExtensions 27 | get() = when (level) { 28 | 1 -> 0 29 | 2 -> 5 30 | 3 -> 10 31 | 4 -> 20 32 | 5 -> 30 33 | 6 -> 40 34 | 7 -> 50 35 | 8 -> 60 36 | else -> 0 //will not happen 37 | } 38 | 39 | fun buildRoads(room: Room) { 40 | val controller = room.controller 41 | if (controller == null || !controller.my) { 42 | println("cannot buildRoads() in room which is not under our control") 43 | return 44 | } 45 | println("building roads in room $room") 46 | 47 | val spawns = room.find(FIND_MY_SPAWNS) 48 | val energySources = room.findEnergy() 49 | 50 | fun buildRoadBetween(a: RoomPosition, b: RoomPosition) { 51 | val path = room.findPath(a, b, options { ignoreCreeps = true }) 52 | for (tile in path) { 53 | val stuff = room.lookAt(tile.x, tile.y) 54 | val roadExistsAtTile = stuff.any { 55 | (it.type == LOOK_STRUCTURES && it.structure!!.structureType == STRUCTURE_ROAD) 56 | || (it.type == LOOK_CONSTRUCTION_SITES && it.constructionSite!!.structureType == STRUCTURE_ROAD) 57 | } 58 | if (roadExistsAtTile) continue 59 | 60 | val code = room.createConstructionSite(tile.x, tile.y, STRUCTURE_ROAD) 61 | when (code) { 62 | OK -> run { } 63 | else -> println("could not place road at [x=${tile.x},y=${tile.y}] code=($code)") 64 | } 65 | } 66 | } 67 | //build roads from controller to each spawn 68 | for (spawn in spawns) { 69 | buildRoadBetween(controller.pos, spawn.pos) 70 | 71 | //build roads from each spawn to each source 72 | for (source in energySources) { 73 | buildRoadBetween(source.pos, spawn.pos) 74 | } 75 | } 76 | 77 | } 78 | 79 | 80 | fun buildStorage(room: Room) { 81 | if (room.controller == null || room.controller?.my == false) return //not our room 82 | if (room.controller!!.availableStorage != 1) return //cannot build storage yet 83 | 84 | val hasStorage = room.storage != null 85 | || Context.constructionSites.values.any { it.structureType == STRUCTURE_STORAGE && it.room?.name == room.name } 86 | if (hasStorage) return //already built or being built 87 | 88 | val spawn = room.find(FIND_MY_SPAWNS).first() 89 | 90 | var placed = false 91 | var pos = spawn.pos.copy(spawn.pos.x - 2) 92 | while (!placed) { 93 | val code = room.createConstructionSite(pos, STRUCTURE_STORAGE) 94 | when (code) { 95 | OK -> placed = true 96 | ERR_INVALID_TARGET -> pos = pos.copy(x = pos.x - 1) 97 | else -> println("unexpected return value $code when attempting to place storage") 98 | } 99 | } 100 | } 101 | 102 | fun buildTowers(room: Room) { 103 | if (room.controller?.my != true) return //not under control 104 | 105 | val numberOfTowers = 106 | Context.constructionSites.values.count { it.room?.name == room.name && it.structureType == STRUCTURE_TOWER } + Context.myStuctures.values.count { it.room.name == room.name && it.structureType == STRUCTURE_TOWER } 107 | val towersToPlace = room.controller!!.availableTowers - numberOfTowers 108 | if (towersToPlace == 0) return //no need to place towers 109 | 110 | val spawn = room.find(FIND_MY_SPAWNS).first() 111 | 112 | var placed = 0 113 | 114 | var x = spawn.pos.x 115 | var y = spawn.pos.y + 1 116 | 117 | while (placed < towersToPlace) { 118 | y += 1 119 | val success = room.createConstructionSite(x, y, STRUCTURE_TOWER) 120 | when (success) { 121 | OK -> placed += 1 122 | ERR_INVALID_TARGET -> run { } 123 | else -> println("unexpected return value $success when attempting to place tower") 124 | } 125 | } 126 | 127 | } 128 | 129 | fun buildExtensions(room: Room) { 130 | require(room.controller?.my == true) 131 | 132 | val spawn = room.find(FIND_MY_SPAWNS).first() 133 | 134 | val startPos = spawn.pos 135 | val numberOfExtensions: Int = 136 | room.find(FIND_STRUCTURES).count { it.structureType == STRUCTURE_EXTENSION } 137 | val toPlace = room.controller!!.availableExtensions - numberOfExtensions 138 | var placed = 0 139 | 140 | val energySources = room.findEnergy() 141 | 142 | require(toPlace >= 0) 143 | val constructionSites = ArrayList() 144 | while (placed < toPlace) { 145 | //find a road from spawn to energy source 146 | for (source in energySources) { 147 | 148 | } 149 | } 150 | } 151 | -------------------------------------------------------------------------------- /src/main/kotlin/screeps/game/one/kreeps/BodyDefinition.kt: -------------------------------------------------------------------------------- 1 | package screeps.game.one.kreeps 2 | 3 | import screeps.api.* 4 | 5 | enum class BodyDefinition(val body: Array, val maxSize: Int = 0) { 6 | BASIC_WORKER(arrayOf(WORK, CARRY, MOVE), maxSize = 5), 7 | MINER(arrayOf(WORK, WORK, MOVE), maxSize = 2), 8 | MINER_BIG( 9 | arrayOf( 10 | WORK, 11 | WORK, 12 | WORK, 13 | WORK, 14 | WORK, 15 | MOVE, 16 | MOVE 17 | ), maxSize = 1 18 | ), //completely drains a Source 19 | BIG_WORKER( 20 | arrayOf( 21 | WORK, 22 | WORK, 23 | WORK, 24 | WORK, 25 | CARRY, 26 | MOVE, 27 | MOVE 28 | ) 29 | ), 30 | HAULER(arrayOf(CARRY, CARRY, MOVE), maxSize = 5), 31 | SCOUT(arrayOf(MOVE), maxSize = 1), 32 | 33 | CLAIMER(arrayOf(CLAIM, MOVE), maxSize = 1); 34 | 35 | val cost: Int 36 | get() = body.sumBy { BODYPART_COST[it]!! } 37 | 38 | data class Body(val tier: Int, val body: List) 39 | 40 | fun getBiggest(availableEnergy: Int): Body { 41 | var energyCost = availableEnergy 42 | val cost = cost 43 | val body = mutableListOf() 44 | var size = 0 45 | 46 | while (energyCost - cost >= 0 && (maxSize == 0 || size < maxSize)) { 47 | energyCost -= cost 48 | body.addAll(this.body) 49 | size += 1 50 | } 51 | body.sortBy { it.value } 52 | 53 | return Body(size, body) 54 | } 55 | 56 | } -------------------------------------------------------------------------------- /src/main/kotlin/traveler/CreepExtension.kt: -------------------------------------------------------------------------------- 1 | package traveler 2 | 3 | import screeps.api.Creep 4 | import screeps.api.RoomPosition 5 | import screeps.api.ScreepsReturnCode 6 | 7 | /** 8 | * Use Traveler to travel to target destination. 9 | */ 10 | fun Creep.travelTo(target: RoomPosition, travelToOptions: TravelToOptions? = null): ScreepsReturnCode { 11 | return if (travelToOptions == null) { 12 | (this.unsafeCast()).travelTo(target) 13 | } else { 14 | (this.unsafeCast()).travelTo(target, travelToOptions) 15 | } 16 | } -------------------------------------------------------------------------------- /src/main/kotlin/traveler/Traveler.kt: -------------------------------------------------------------------------------- 1 | @file:Suppress( 2 | "INTERFACE_WITH_SUPERCLASS", 3 | "OVERRIDING_FINAL_MEMBER", 4 | "RETURN_TYPE_MISMATCH_ON_OVERRIDE", 5 | "CONFLICTING_OVERLOADS", 6 | "EXTERNAL_DELEGATION", 7 | "NESTED_CLASS_IN_EXTERNAL_INTERFACE" 8 | ) 9 | 10 | package traveler 11 | 12 | import screeps.api.PathFinder 13 | import screeps.api.RoomPosition 14 | import screeps.api.ScreepsReturnCode 15 | 16 | external interface PathfinderReturn { 17 | var path: Array 18 | var ops: Number 19 | var cost: Number 20 | var incomplete: Boolean 21 | } 22 | 23 | external interface TravelToReturnData { 24 | var nextPos: RoomPosition? get() = definedExternally; set(value) = definedExternally 25 | var pathfinderReturn: PathfinderReturn? get() = definedExternally; set(value) = definedExternally 26 | var state: TravelState? get() = definedExternally; set(value) = definedExternally 27 | var path: String? get() = definedExternally; set(value) = definedExternally 28 | } 29 | 30 | 31 | external interface TravelToOptions { 32 | 33 | /** 34 | * Creeps won't prefer roads above plains (will still prefer them to swamps). Default is false. 35 | */ 36 | var ignoreRoads: Boolean? get() = definedExternally; set(value) = definedExternally 37 | 38 | /** 39 | * Will not path around other creeps. Default is true. 40 | */ 41 | var ignoreCreeps: Boolean? get() = definedExternally; set(value) = definedExternally 42 | 43 | /** 44 | * Will not path around structures. Default is false. 45 | */ 46 | var ignoreStructures: Boolean? get() = definedExternally; set(value) = definedExternally 47 | 48 | /** 49 | * Creep prefer to travel along highway (empty rooms in between sectors). Default is false. 50 | */ 51 | var preferHighway: Boolean? get() = definedExternally; set(value) = definedExternally 52 | 53 | var highwayBias: Number? get() = definedExternally; set(value) = definedExternally 54 | 55 | /** 56 | * Hostile rooms will be included in path. Default is false. 57 | */ 58 | var allowHostile: Boolean? get() = definedExternally; set(value) = definedExternally 59 | /** 60 | * SourceKeeper rooms will be included in path. (if false, SK rooms will still be taken if they are they only viable path). 61 | * Default is false. 62 | */ 63 | var allowSK: Boolean? get() = definedExternally; set(value) = definedExternally 64 | /** 65 | * Range to goal before it is considered reached. The default is 1. 66 | */ 67 | var range: Number? get() = definedExternally; set(value) = definedExternally 68 | 69 | /** 70 | * Array of objects with property {pos: RoomPosition} that represent positions to avoid. 71 | */ 72 | var obstacles: Array 73 | 74 | /** 75 | * Callback function that accepts two arguments, roomName (string) and matrix (CostMatrix) and returns a CostMatrix or boolean. 76 | * Used for overriding the default PathFinder callback. 77 | * If it returns false, that room will be excluded. If it returns a matrix, it will be used in place of the default matrix. 78 | * If it returns undefined the default matrix will be used instead. 79 | */ 80 | var roomCallback: ((roomName: String, matrix: PathFinder.CostMatrix) -> dynamic /* CostMatrix | Boolean */)? get() = definedExternally; set(value) = definedExternally 81 | 82 | /** 83 | * Callback function that accepts one argument, roomName (string) and returns a number representing the foundRoute value that roomName. 84 | * Used for overriding the findRoute callback. 85 | * If it returns a number that value will be used to influence the route. If it returns undefined it will use the default value. 86 | */ 87 | var routeCallback: ((roomName: String) -> Number)? get() = definedExternally; set(value) = definedExternally 88 | 89 | /** 90 | * If an empty object literal is provided, the RoomPosition being moved to will be assigned to returnData.nextPos. 91 | */ 92 | var returnData: TravelToReturnData? get() = definedExternally; set(value) = definedExternally 93 | 94 | /** 95 | * Limits the range the findRoute will search. Default is 32. 96 | */ 97 | var restrictDistance: Number? get() = definedExternally; set(value) = definedExternally 98 | 99 | /** 100 | * Can be used to force or prohibit the use of findRoute. 101 | * If undefined it will use findRoute only for paths that span a larger number of rooms (linear distance >2). 102 | */ 103 | var useFindRoute: Boolean? get() = definedExternally; set(value) = definedExternally 104 | 105 | /** 106 | * Limits the ops (CPU) that PathFinder will use. Default is 20000. (~20 CPU) 107 | */ 108 | var maxOps: Number? get() = definedExternally; set(value) = definedExternally 109 | 110 | /** 111 | * Allows you to avoid making a new pathfinding call when your destination is only 1 position away from what it was previously. 112 | * The new direction is just added to the path. Default is false. 113 | */ 114 | var movingTarget: Boolean? get() = definedExternally; set(value) = definedExternally 115 | 116 | /** 117 | * Will guarantee that a new structure matrix is generated. 118 | * This might be necessary if structures are likely to change often. Default is false. 119 | */ 120 | var freshMatrix: Boolean 121 | 122 | /** 123 | * Creeps won't prefer plains or roads over swamps, all costs will be 1. Default is false. 124 | */ 125 | var offRoad: Boolean? get() = definedExternally; set(value) = definedExternally 126 | 127 | /** 128 | * Number of ticks of non-movement before a creep considers itself stuck. Default is 2. 129 | */ 130 | var stuckValue: Int? get() = definedExternally; set(value) = definedExternally 131 | 132 | /** 133 | * Limit how many rooms can be searched by PathFinder. Default is undefined. 134 | */ 135 | var maxRooms: Number? get() = definedExternally; set(value) = definedExternally 136 | 137 | /** 138 | * Float value between 0 and 1 representing the probability that creep will randomly invalidate its current path. 139 | * Setting it to 1 would cause the creep to repath every tick. Default is undefined. 140 | */ 141 | var repath: Double? get() = definedExternally; set(value) = definedExternally 142 | 143 | /** 144 | * Supply the route to be used by PathFinder. Default is undefined. 145 | */ 146 | var route: Any? 147 | 148 | /** 149 | * This can improve the chance of finding a path in certain edge cases where might otherwise fail. 150 | * Default is false. 151 | */ 152 | val ensurePath: Boolean 153 | } 154 | 155 | external interface TravelData { 156 | var state: Array 157 | var path: String 158 | } 159 | 160 | external interface TravelState { 161 | var stuckCount: Number 162 | var lastCoord: Coord 163 | var destination: RoomPosition 164 | var cpu: Number 165 | } 166 | 167 | external interface TravelerCreep { 168 | fun travelTo(destination: HasPos, ops: TravelToOptions? = definedExternally /* null */): ScreepsReturnCode 169 | fun travelTo(destination: RoomPosition, ops: TravelToOptions? = definedExternally /* null */): ScreepsReturnCode 170 | } 171 | 172 | external interface Coord { 173 | var x: Number 174 | var y: Number 175 | } 176 | 177 | external interface HasPos { 178 | var pos: RoomPosition 179 | } 180 | --------------------------------------------------------------------------------