What is the simplest, yet fully-functioning Screeps code we can possibly write?
To answer this question, we first need to define it well.
Let's start with the fully-functioning part. To me, a fully-functioning Screeps code means code that, if we left it alone and let it run for long enough, we would eventually upgrade our controller all the way to level 8, and we'd continue to gain control points even after that.
So that first part is pretty easy to define, but the second qualifier to my question, the "simplest possible", is a lot more subjective. In my mind, I know what I don’t want "simple" to mean: I don't want it to be the fewest lines of code. There's a lot of crazy tricks we could use to reduce the number of lines needed, but those would actually make our code more confusing to read. Which to me isn't very simple.
Let's just say we want to keep our method calls and our use of control structures to as few as we can, and keep them as basic as we can.
So this is the solution I came up with:
module.exports.loop = function () {
// this is the game loop. during every game tick, it runs the code below one time,
// from top to bottom.
// create a creep
Game.spawns["Spawn1"].spawnCreep([WORK,CARRY,MOVE,MOVE], "My First Creep");
// make an easy reference to my creep
var mycreep = Game.creeps["My First Creep"];
// if my creep is not carrying any energy
if (mycreep.store[RESOURCE_ENERGY] == 0) {
// make an easy reference to the energy source
var source = Game.getObjectById('16c3f93dd468ca9f065fd27c');
// move my creep to the energy source and harvest energy
mycreep.moveTo(source);
mycreep.harvest(source);
} else {
// make an easy reference to the room's controller
var controller = mycreep.room.controller;
// move my creep to the controller and upgrade it
mycreep.moveTo(controller);
mycreep.upgradeController(controller);
}
}
Try it out for yourself in the Screeps simulator: https://screeps.com/a/#!/sim/survival
Remember to change the object id of the source!
If you're a Screeps veteran, let me know what you think of my solution.
If you're brand new to programming or JavaScript, checkout my next video where I'll break down this code and explain exactly how each piece of it works.