Screeps как играть


Screeps on Steam

Reviews

“It was fun while it lasted, and probably the best thing is that I really feel like my Javascript and Node fluency has gone through the roof compared to what it was. As I said at the start, this isn’t a game to learn coding in. But if you already know a bit, it’s a fun way to get from beginner to intermediate.”Kotaku Australia

“Screeps is a fun game and has a unique angle to it. Using actual programming instead of a pseudo-language actually allows the players to focus on better coding habits and makes practice fun.”8/10 – GameSkinny

“We use Screeps as a key part of our recruitment process at fleetster. Screeps is useful because it throws candidates into an unknown environment where the number of "right" solutions are very numerous.”fleetster

Why subscription?

Note: everything below is about the official MMO world only. The single-player mode and unofficial private servers are available without subscribing.

Screeps is an unusual MMO game that has no counterparts at the moment. There are numerous online games where your character exists in the game world only while you’re online and disappears after you exit the game. There are fewer games that have your character or units continue some defined automatic activity even after logging out. But only Screeps runs your scripts in full continuously, on the 24/7 basis, and you are allowed to use them for anything JavaScript allows.

This makes Screeps more like a hosting or cloud computing service rather than a traditional online game. We offer you server CPU time and fixed amount of memory that you can use as you wish (though it’s still preferable to use it in relation with the game!). Though a new player gets a quite low initial CPU limit, after upgrading your game level you can end up with your limit up to 300 ms per game tick which is quite a serious hosting asset.

As we designed the game, we were considering numerous options and finally came to a conclusion that justification of such expenses requires only one model: game time (or, in our case, CPU time) subscription. And note that we don’t offer multiple subscription options: the subscription cost is the same for all players. Thus we avoid creating game advantages for certain groups of players since all are provided with equal opportunities to use server resources.

If you don’t wish to use such resources on general terms, you can just confine yourself to purchasing a starter kit on Steam. A minimum 10 CPU amount will be reserved for you on the official MMO server, but it won’t grow following your game level. Such a mode is not suitable for a full competitive playing but is still enough for those who are fine with 2-3 game rooms in the game world to have some fun of the game.

Subscription Tokens

Subscription Token is a special in-game item that allows its owner to activate 60 days of CPU subscription. You can buy a subscription token the same way as a regular CPU subscription, but these items are tradeable, you can sell them to another player or buy for game resources.

Hence, those players who want to share their resources with others can play Screeps as a free-to-play game! Subscription tokens trading is possible via the in-game market or Steam Community Market allowing to trade purchased tokens for real currency using your Steam Wallet.

About This Game

Screeps is about scripting your creeps.

It is an open source MMO RTS sandbox game for programmers, wherein the core mechanic is programming your units AI. With all the attributes of a full-fledged strategy game, you control your colony by writing real JavaScript which operate 24/7 in the single persistent world filled by other players on par with you.

Your colony can harvest resources, build units, conquer territory, trade with another colonies. As you conquer more territory, your influence in the game world grows, as well as your abilities to expand your footprint. However, it requires a lot of effort on your part, since multiple players may aim at the same territory.

Screeps is developed for people with programming skills. Unlike some other RTS games, your units in Screeps can react to events without your participation – provided that you have programmed them properly. And, unlike other MMO, you do not have to play Screeps constantly to play well. It is quite enough just to check once in a while to see if everything goes well.

Features:

  • You play by writing JavaScript AI which controls your units 24/7 even while you're offline.
  • Units of all players coexist in the same real-time huge persistent world and obey the same rules.
  • Many kinds of units, base building, mining resources, territory control, economy, manufacturing, transporting, logistics, trading – all the attributes of a real strategy game which you need to program!
  • The better your scripts, the better your game — irrespective of the time played. Your creeps will mine, build, defend, and conquer as you just work, sleep, or walk your dog.
  • Only basic programming skills are required. However, if you are a pro developer, now is the chance to put your skills to the limit!
  • Edit your scripts from the in-game editor, or using your favorite external IDE.
  • Lifetime MMO access with 10 CPU limit included in the starter package. Raise your CPU limit to the point depending on your game level by purchasing a CPU subscription plan or via in-game items called Subscription Tokens. The subscription cost is the same for all players, there is no way to pay more to gain more advantages.
  • Host your own server, modify games rules and play with your friends via LAN or on the Internet. No subscription required. The server is an open source project.
  • And many more features to come! (see Roadmap)

store.steampowered.com

Поиграл == покодил / Блог компании Edison / Хабрахабр

Мой рекорд скорости написания кода «на C» был в консоли Quake II. Причем абсолютно без ошибок. В темноте, не глядя, трясущимися руками надо было набрать примерно такое:bind SHIFT "+snipe" alias +snipe "sensitivity 2.5; fov 30" alias -snipe "fov 90; sensitivity 4" Боги умели прописывать RocketJump.RocketJumpbind t "superrjr" bind a "superrjn" alias superrjr "echo SuperRocketJump enabled; bind a +srj; bind t superrjc" alias superrjn "echo SuperRocketJump disabled" alias superrjc "echo SuperRocketJump disabled; bind a superrjn; bind t superrjr" alias +srj "lookdown1;hand 2;rjump" alias -srj "lookdown2" alias lookdown1 "cl_pitchspeed 999999;+lookdown" alias lookdown2 "-lookdown;cl_pitchspeed 200;-attack;-moveup;wait;wait;wait;centerview;hand 2;cl_maxfps 80" alias rjump "+moveup;+attack;wait;wait;wait;wait;cl_maxfps 0" alias +QLD "+lookdown;cl_pitchspeed 999" alias -QLD "-lookdown;cl_pitchspeed 200" alias +RocketJump "hand 2;+QLD;wait;wait;+attack;+moveup" alias -RocketJump "hand 2;-QLD;-attack;-moveup" alias SuperRocketJump "hand 2;+QLD;wait;wait;wait;wait;+attack;+moveup;wait;cl_maxfps 0;LWX3;cl_maxfps 90;-QLD;-attack;-moveup;hand 2" Под катом — подборка дюжины проектов, которые заточены на то, чтобы играючи повысить кодерское мастерство.Поддержка публикации — компания Edison, которая разрабатывает веб-интерфейс для управления радио-релейной станцией, а так же проектирует и разрабатывает ПО для записи и анализа вариабельности сердечного ритма. Решаем задачки. Прогаем ИИ ботов. Развлекаемся. Поддержка многих многих языков программирования.

Еще видосы про CodinGame

CodeCombat платформа для студентов, изучающих computer science посредством игры. Активное сообщество, волонтеры создают уровни игры. Поддержка Java, JavaScript, Python, Lua, CoffeeScript.

Еще видосы про Code Combat

Изучаем JavaScript играя в первую в мире MMO-стратегию-песочницу для программистов.

Еще видосы про Screeps

Check iO — браузерная игра, где надо решать задачки на Python.

Еще видосы про Check iO

Изучаем Vim играя в игру.

Cyber-dojo тренировочный зал, где оттачивают программистские навыки. Получите черный пояс по JavaScript, Java, Python, PHP, Ruby и пр. (Cyber DoJo используют даже на собеседованиях.)

→ Open source LinkЕще видосы про Cyber DoJo

Учим код, пытаясь ловить бананы. Для детишек. Платно.

Программируем лифт. Решаем задачки шаг за шагом. Задача #1: Перевезти 15 человек за 60 секунд или быстрее. Open Source Link

Достигаем мастерства на «макеварах» и реальных задачах. Поддержка JavaScript, Python, C#, Java, Python и др.

Ruby Quiz — еженедельные задачки Ruby-прогеров, по аналогии с Perl Quiz of the Week. Насчитывает 156 заданий. Изучаем крутые фичи git scm (source control management). Используйте команды git’а чтобы найти подсказки и решить головоломку.

Hacker.org — это серия головоломок, ребусов и тестов, чтобы проверить ваши хакерские способности.

habrahabr.ru

Screeps Documentation

The main global game object containing all the game play information.

Game.constructionSitesobject<string, ConstructionSite>

A hash containing all your construction sites with their id as hash keys.

Game.cpuobject

An object containing information about your CPU usage with the following properties:

parametertypedescription
limitnumber

Your assigned CPU limit for the current shard.

tickLimitnumber

An amount of available CPU time at the current game tick.Usually it is higher than Game.cpu.limit. Learn more

bucketnumber

An amount of unused CPU accumulated in your bucket.

shardLimitsobject<string,number>

An object with limits for each shard with shard names as keys. You can use setShardLimits method to re-assign them.

Game.creepsobject<string, Creep>

for(const i in Game.creeps) { Game.creeps[i].moveTo(flag); }

A hash containing all your creeps with creep names as hash keys.

Game.flagsobject<string, Flag>

creep.moveTo(Game.flags.Flag1);

A hash containing all your flags with flag names as hash keys.

Game.gclobject

Your Global Control Level, an object with the following properties :

parametertypedescription
levelnumber

The current level.

progressnumber

The current progress to the next level.

progressTotalnumber

The progress required to reach the next level.

Game.mapobject

A global object representing world map. See the documentation below.

Game.marketobject

A global object representing the in-game market. See the documentation below.

Game.resourcesobject

An object with your global resources that are bound to the account, like subscription tokens. Each object key is a resource constant, values are resources amounts.

Game.roomsobject<string, Room>

A hash containing all the rooms available to you with room names as hash keys. A room is visible if you have a creep or an owned structure in it.

Game.shardobject

An object describing the world shard where your script is currently being executed in.

parametertypedescription
namestring

The name of the shard.

typestring

Currently always equals to normal.

ptrboolean

Whether this shard belongs to the PTR.

for(const i in Game.spawns) { Game.spawns[i].createCreep(body); }

A hash containing all your spawns with spawn names as hash keys.

Game.structuresobject<string, Structure>

A hash containing all your structures with structure id as hash keys.

Game.timenumber

console.log(Game.time);

System game tick counter. It is automatically incremented on every tick. Learn more

Game.cpu.getUsed()

if(Game.cpu.getUsed() > Game.cpu.tickLimit / 2) { console.log("Used half of CPU already!"); }for(const name in Game.creeps) { const startCpu = Game.cpu.getUsed(); const elapsed = Game.cpu.getUsed() - startCpu; console.log('Creep '+name+' has used '+elapsed+' CPU time'); }

Get amount of CPU time used from the beginning of the current game tick. Always returns 0 in the Simulation mode.

Return value

Returns currently used CPU time as a float number.

Game.cpu.setShardLimits(limits)

Game.cpu.setShardLimits({shard0: 20, shard1: 10});

Allocate CPU limits to different shards. Total amount of CPU should remain equal to Game.cpu.shardLimits. This method can be used only once per 12 hours.

parametertypedescription
limitsobject<string, number>

An object with CPU values for each shard in the same format as Game.cpu.shardLimits.

Return value

One of the following codes:

constantvaluedescription
OK0

The operation has been scheduled successfully.

ERR_BUSY-4

12-hours cooldown period is not over yet.

ERR_INVALID_ARGS-10

The argument is not a valid shard limits object.

Game.getObjectById(id)

creep.memory.sourceId = creep.pos.findClosestByRange(FIND_SOURCES).id; const source = Game.getObjectById(creep.memory.sourceId);

Get an object with the specified unique ID. It may be a game object of any type. Only objects from the rooms which are visible to you can be accessed.

parametertypedescription
idstring

The unique identificator.

Return value

Returns an object instance or null if it cannot be found.

Game.notify(message, [groupInterval])

if(creep.hits < creep.memory.lastHits) { Game.notify('Creep '+creep+' has been attacked at '+creep.pos+'!'); } creep.memory.lastHits = creep.hits;if(Game.spawns['Spawn1'].energy == 0) { Game.notify( 'Spawn1 is out of energy', 180 ); }

Send a custom message at your profile email. This way, you can set up notifications to yourself on any occasion within the game. You can schedule up to 20 notifications during one game tick. Not available in the Simulation Room.

parametertypedescription
messagestring

Custom text which will be sent in the message. Maximum length is 1000 characters.

groupIntervalnumber

If set to 0 (default), the notification will be scheduled immediately. Otherwise, it will be grouped with other notifications and mailed out later using the specified time in minutes.

A global object representing world map. Use it to navigate between rooms.

Game.map.describeExits(roomName)

const exits = Game.map.describeExits('W8N3');

List all exits available from the room with the given name.

parametertypedescription
roomNamestring

The room name.

Return value

The exits information in the following format, or null if the room not found.

Game.map.findExit(fromRoom, toRoom, [opts])

if(creep.room != anotherRoomName) { const exitDir = Game.map.findExit(creep.room, anotherRoomName); const exit = creep.pos.findClosestByRange(exitDir); creep.moveTo(exit); } else { }creep.moveTo(new RoomPosition(25, 25, anotherRoomName));

Find the exit direction from the given room en route to another room.

parametertypedescription
fromRoomstring, Room

Start room name or room object.

toRoomstring, Room

Finish room name or room object.

optsoptionalobject

An object with the pathfinding options. See findRoute.

Return value

The room direction constant, one of the following:

  • FIND_EXIT_TOP
  • FIND_EXIT_RIGHT
  • FIND_EXIT_BOTTOM
  • FIND_EXIT_LEFT

Or one of the following error codes:

constantvaluedescription
ERR_NO_PATH-2

Path can not be found.

ERR_INVALID_ARGS-10

The location is incorrect.

Game.map.findRoute(fromRoom, toRoom, [opts])

const route = Game.map.findRoute(creep.room, anotherRoomName); if(route.length > 0) { console.log('Now heading to room '+route[0].room); const exit = creep.pos.findClosestByRange(route[0].exit); creep.moveTo(exit); }const route = Game.map.findRoute(creep.room, anotherRoomName, { routeCallback(roomName, fromRoomName) { if(roomName == 'W10S10') { return Infinity; } return 1; }});let from = new RoomPosition(25, 25, 'E1N1'); let to = new RoomPosition(25, 25, 'E4N1'); let allowedRooms = { [ from.roomName ]: true }; Game.map.findRoute(from.roomName, to.roomName, { routeCallback(roomName) { let parsed = /^[WE]([0-9]+)[NS]([0-9]+)$/.exec(roomName); let isHighway = (parsed[1] % 10 === 0) || (parsed[2] % 10 === 0); let isMyRoom = Game.rooms[roomName] && Game.rooms[roomName].controller && Game.rooms[roomName].controller.my; if (isHighway || isMyRoom) { return 1; } else { return 2.5; } } }).forEach(function(info) { allowedRooms[info.room] = true; }); let ret = PathFinder.search(from, to, { roomCallback(roomName) { if (allowedRooms[roomName] === undefined) { return false; } } }); console.log(ret.path);

Find route from the given room to another room.

parametertypedescription
fromRoomstring, Room

Start room name or room object.

toRoomstring, Room

Finish room name or room object.

optsoptionalobject

An object with the following options:

  • routeCallback

    function

    This callback accepts two arguments: function(roomName, fromRoomName). It can be used to calculate the cost of entering that room. You can use this to do things like prioritize your own rooms, or avoid some rooms. You can return a floating point cost or Infinity to block the room.

Return value

The route array in the following format:

Or one of the following error codes:

constantvaluedescription
ERR_NO_PATH-2

Path can not be found.

Game.map.getRoomLinearDistance(roomName1, roomName2, [continuous])

Game.map.getRoomLinearDistance('W1N1', 'W4N2'); Game.map.getRoomLinearDistance('E65S55','W65S55', false) Game.map.getRoomLinearDistance('E65S55','W65S55', true)

Get the linear distance (in rooms) between two rooms. You can use this function to estimate the energy cost of sending resources through terminals, or using observers and nukes.

parametertypedescription
roomName1string

The name of the first room.

roomName2string

The name of the second room.

continuousoptionalboolean

Whether to treat the world map continuous on borders. Set to true if you want to calculate the trade or terminal send cost. Default is false.

Return value

A number of rooms between the given two rooms.

Game.map.getTerrainAt(x, y, roomName)(pos)

console.log(Game.map.getTerrainAt(25,20,'W10N10'));console.log(Game.map.getTerrainAt(new RoomPosition(25,20,'W10N10'));

Get terrain type at the specified room position. This method works for any room in the world even if you have no access to it.

parametertypedescription
xnumber

X position in the room.

ynumber

Y position in the room.

roomNamestring

The room name.

posRoomPosition

The position object.

Return value

One of the following string values:

Game.map.getWorldSize()

Returns the world size as a number of rooms between world corners. For example, for a world with rooms from W50N50 to E50S50 this method will return 102.

Game.map.isRoomAvailable(roomName)

if(Game.map.isRoomAvailable(room.name)) { creep.moveTo(room.getPositionAt(25,25)); }

Check if the room is available to move into.

parametertypedescription
roomNamestring

The room name.

Return value

A boolean value.

A global object representing the in-game market. You can use this object to track resource transactions to/from your terminals, and your buy/sell orders.

Learn more about the market system from this article.

Game.market.creditsnumber

Your current credits balance.

Game.market.incomingTransactionsarray

[{ transactionId : "56dec546a180ce641dd65960", time : 10390687, sender : {username: "Sender"}, recipient : {username: "Me"}, resourceType : "U", amount : 100, from : "W0N0", to : "W10N10", description : "trade contract #1", order: { id : "55c34a6b5be41a0a6e80c68b", type : "sell", price : 2.95 } }]

An array of the last 100 incoming transactions to your terminals with the following format:

Game.market.outgoingTransactionsarray

[{ transactionId : "56dec546a180ce641dd65960", time : 10390687, sender : {username: "Me"}, recipient : {username: "Recipient"}, resourceType : "U", amount : 100, from : "W0N0", to : "W10N10", description : "trade contract #1", order: { id : "55c34a6b5be41a0a6e80c68b", type : "sell", price : 2.95 } }]

An array of the last 100 outgoing transactions from your terminals with the following format:

Game.market.ordersobject

{ "55c34a6b5be41a0a6e80c68b": { id : "55c34a6b5be41a0a6e80c68b", created : 13131117, active: true, type : "sell" resourceType : "OH", roomName : "W1N1", amount : 15821, remainingAmount : 30000, totalAmount : 50000, price : 2.95 }, "55c34a6b52411a0a6e80693a": { id : "55c34a6b52411a0a6e80693a", created : 13134122, active: true, type : "buy" resourceType : "energy", roomName : "W1N1", amount : 94000, remainingAmount : 94000, totalAmount : 94000 price : 0.45 }, "55c34a6b5be41a0a6e80c123": { id : "55c34a6b5be41a0a6e80c123", created : 13105123, active: false, type : "sell" resourceType : "token", amount : 0, remainingAmount : 10, totalAmount : 10, price : 50000 } }

An object with your active and inactive buy/sell orders on the market.

Game.market.calcTransactionCost(amount, roomName1, roomName2)

const cost = Game.market.calcTransactionCost(1000, 'W0N0', 'W10N5');

Estimate the energy transaction cost of StructureTerminal.send and Game.market.deal methods. The formula:

parametertypedescription
amountnumber

Amount of resources to be sent.

roomName1string

The name of the first room.

roomName2string

The name of the second room.

Return value

The amount of energy required to perform the transaction.

Game.market.cancelOrder(orderId)

for(const id in Game.market.orders) { Game.market.cancelOrder(id); }

Cancel a previously created order. The 5% fee is not returned.

parametertypedescription
orderIdstring

The order ID as provided in Game.market.orders.

Return value

One of the following codes:

constantvaluedescription
OK0

The operation has been scheduled successfully.

ERR_INVALID_ARGS-10

The order ID is not valid.

Game.market.changeOrderPrice(orderId, newPrice)

Game.market.changeOrderPrice('57bec1bf77f4d17c4c011960', 9.95);

Change the price of an existing order. If newPrice is greater than old price, you will be charged (newPrice-oldPrice)*remainingAmount*0.05 credits.

parametertypedescription
orderIdstring

The order ID as provided in Game.market.orders.

newPricenumber

The new order price.

Return value

One of the following codes:

constantvaluedescription
OK0

The operation has been scheduled successfully.

ERR_NOT_OWNER-1

You are not the owner of the room's terminal or there is no terminal.

ERR_NOT_ENOUGH_RESOURCES-6

You don't have enough credits to pay a fee.

ERR_INVALID_ARGS-10

The arguments provided are invalid.

Game.market.createOrder(type, resourceType, price, totalAmount, [roomName])

Game.market.createOrder(ORDER_SELL, RESOURCE_GHODIUM, 9.95, 10000, "W1N1");

Create a market order in your terminal. You will be charged price*amount*0.05 credits when the order is placed. The maximum orders count is 50 per player. You can create an order at any time with any amount, it will be automatically activated and deactivated depending on the resource/credits availability.

parametertypedescription
typestring

The order type, either ORDER_SELL or ORDER_BUY.

resourceTypestring

Either one of the RESOURCE_* constants or SUBSCRIPTION_TOKEN. If your Terminal doesn't have the specified resource, the order will be temporary inactive.

pricenumber

The price for one resource unit in credits. Can be a decimal number.

totalAmountnumber

The amount of resources to be traded in total.

roomNameoptionalstring

The room where your order will be created. You must have your own Terminal structure in this room, otherwise the created order will be temporary inactive. This argument is not used when resourceType equals to SUBSCRIPTION_TOKEN.

Return value

One of the following codes:

constantvaluedescription
OK0

The operation has been scheduled successfully.

ERR_NOT_OWNER-1

You are not the owner of the room's terminal or there is no terminal.

ERR_NOT_ENOUGH_RESOURCES-6

You don't have enough credits to pay a fee.

ERR_FULL-8

You cannot create more than 50 orders.

ERR_INVALID_ARGS-10

The arguments provided are invalid.

Game.market.deal(orderId, amount, [yourRoomName])

Game.market.deal('57cd2b12cda69a004ae223a3', 1000, "W1N1");const amountToBuy = 2000, maxTransferEnergyCost = 500; const orders = Game.market.getAllOrders({type: ORDER_SELL, resourceType: RESOURCE_GHODIUM}); for(let i=0; i<orders.length; i++) { const transferEnergyCost = Game.market.calcTransactionCost( amountToBuy, 'W1N1', orders[i].roomName); if(transferEnergyCost < maxTransferEnergyCost) { Game.market.deal(orders[i].id, amountToBuy, "W1N1"); break; } }

Execute a trade deal from your Terminal in yourRoomName to another player's Terminal using the specified buy/sell order. Your Terminal will be charged energy units of transfer cost regardless of the order resource type. You can use Game.market.calcTransactionCost method to estimate it. When multiple players try to execute the same deal, the one with the shortest distance takes precedence. You cannot execute more than 10 deals during one tick.

parametertypedescription
orderIdstring

The order ID as provided in Game.market.getAllOrders.

amountnumber

The amount of resources to transfer.

yourRoomNameoptionalstring

The name of your room which has to contain an active Terminal with enough amount of energy. This argument is not used when the order resource type equals to SUBSCRIPTION_TOKEN.

Return value

One of the following codes:

constantvaluedescription
OK0

The operation has been scheduled successfully.

ERR_NOT_OWNER-1

You don't have a terminal in the target room.

ERR_NOT_ENOUGH_RESOURCES-6

You don't have enough credits or resource units.

ERR_FULL-8

You cannot execute more than 10 deals during one tick.

ERR_INVALID_ARGS-10

The arguments provided are invalid.

ERR_TIRED-11

The target terminal is still cooling down.

Game.market.extendOrder(orderId, addAmount)

Game.market.extendOrder('57bec1bf77f4d17c4c011960', 10000);

Add more capacity to an existing order. It will affect remainingAmount and totalAmount properties. You will be charged priceaddAmount0.05 credits.

parametertypedescription
orderIdstring

The order ID as provided in Game.market.orders.

addAmountnumber

How much capacity to add. Cannot be a negative value.

Return value

One of the following codes:

constantvaluedescription
OK0

The operation has been scheduled successfully.

ERR_NOT_ENOUGH_RESOURCES-6

You don't have enough credits to pay a fee.

ERR_INVALID_ARGS-10

The arguments provided are invalid.

Game.market.getAllOrders([filter])

Game.market.getAllOrders();Game.market.getAllOrders({type: ORDER_SELL, resourceType: RESOURCE_GHODIUM});const targetRoom = "W1N1"; Game.market.getAllOrders(order => order.resourceType == RESOURCE_GHODIUM && order.type == ORDER_SELL && Game.market.calcTransactionCost(1000, targetRoom, order.roomName) < 500); [{ id : "55c34a6b5be41a0a6e80c68b", created : 13131117, type : "sell" resourceType : "OH", roomName : "W1N1", amount : 15821, remainingAmount : 30000, price : 2.95 }, { id : "55c34a6b52411a0a6e80693a", created : 13134122, type : "buy" resourceType : "energy", roomName : "W1N1", amount : 94000, remainingAmount : 94000, price : 0.45 }, { id : "55c34a6b5be41a0a6e80c123", created : 13105123, type : "sell" resourceType : "token", amount : 3, remainingAmount : 10, price : 50000 }]

Get other players' orders currently active on the market.

parametertypedescription
filteroptionalobject, function

An object or function that will filter the resulting list using the lodash.filter method.

Return value

An orders array in the following form:

property description
id The unique order ID.
created The order creation time in game ticks.
type Either ORDER_SELL or ORDER_BUY.
resourceType Either one of the RESOURCE_* constants or SUBSCRIPTION_TOKEN.
roomName The room where this order is placed.
amount Currently available amount to trade.
remainingAmount How many resources are left to trade via this order.
price The current price per unit.

Game.market.getOrderById(id)

const order = Game.market.getOrderById('55c34a6b5be41a0a6e80c123');

Retrieve info for specific market order.

parametertypedescription
idstring

The order ID.

Return value

An object with the order info. See getAllOrders for properties explanation.

A global plain object which can contain arbitrary data. You can access it both using the API and the Memory UI in the game editor. Learn how to work with memory from this article.

Contains powerful methods for pathfinding in the game world. This module is written in fast native C++ code and supports custom navigation costs and paths which span multiple rooms.

PathFinder.search(origin, goal, [opts])

let creep = Game.creeps.John; let goals = _.map(creep.room.find(FIND_SOURCES), function(source) { return { pos: source.pos, range: 1 }; }); let ret = PathFinder.search( creep.pos, goals, { plainCost: 2, swampCost: 10, roomCallback: function(roomName) { let room = Game.rooms[roomName]; if (!room) return; let costs = new PathFinder.CostMatrix; room.find(FIND_STRUCTURES).forEach(function(struct) { if (struct.structureType === STRUCTURE_ROAD) { costs.set(struct.pos.x, struct.pos.y, 1); } else if (struct.structureType !== STRUCTURE_CONTAINER && (struct.structureType !== STRUCTURE_RAMPART || !struct.my)) { costs.set(struct.pos.x, struct.pos.y, 0xff); } }); room.find(FIND_CREEPS).forEach(function(creep) { costs.set(creep.pos.x, creep.pos.y, 0xff); }); return costs; }, } ); let pos = ret.path[0]; creep.move(creep.pos.getDirectionTo(pos));

Find an optimal path between origin and goal.

parametertypedescription
originRoomPosition

The start position.

goalobject

A goal or an array of goals. If more than one goal is supplied then the cheapest path found out of all the goals will be returned. A goal is either a RoomPosition or an object as defined below.

Important: Please note that if your goal is not walkable (for instance, a source) then you should set range to at least 1 or else you will waste many CPU cycles searching for a target that you can't walk on.

optsoptionalobject

An object containing additional pathfinding flags.

  • roomCallback

    function

    Request from the pathfinder to generate a CostMatrix for a certain room. The callback accepts one argument, roomName. This callback will only be called once per room per search. If you are running multiple pathfinding operations in a single room and in a single tick you may consider caching your CostMatrix to speed up your code. Please read the CostMatrix documentation below for more information on CostMatrix. If you return false from the callback the requested room will not be searched, and it won't count against maxRooms
  • plainCost

    number

    Cost for walking on plain positions. The default is 1.

  • swampCost

    number

    Cost for walking on swamp positions. The default is 5.

  • flee

    boolean

    Instead of searching for a path to the goals this will search for a path away from the goals. The cheapest path that is out of range of every goal will be returned. The default is false.

  • maxOps

    number

    The maximum allowed pathfinding operations. You can limit CPU time used for the search based on ratio 1 op ~ 0.001 CPU. The default value is 2000.

  • maxRooms

    number

    The maximum allowed rooms to search. The default (and maximum) is 16.

  • maxCost

    number

    The maximum allowed cost of the path returned. If at any point the pathfinder detects that it is impossible to find a path with a cost less than or equal to maxCost it will immediately halt the search. The default is Infinity.

  • heuristicWeight

    number

    Weight to apply to the heuristic in the A* formula F = G + weight * H. Use this option only if you understand the underlying A* algorithm mechanics! The default value is 1.2.

Return value

An object containing the following properties:

property description
path An array of RoomPosition objects.
ops Total number of operations performed before this path was calculated.
cost The total cost of the path as derived from plainCost, swampCost and any given CostMatrix instances.
incomplete If the pathfinder fails to find a complete path, this will be true. Note that path will still be populated with a partial path which represents the closest path it could find given the search parameters.

PathFinder.use(isEnabled)

This method is deprecated and will be removed soon.

PathFinder.use(true); Game.creeps.John.moveTo(Game.spawns['Spawn1']);

Specify whether to use this new experimental pathfinder in game objects methods. This method should be invoked every tick. It affects the following methods behavior: Room.findPath, RoomPosition.findPathTo, RoomPosition.findClosestByPath, Creep.moveTo.

parametertypedescription
isEnabledboolean

Whether to activate the new pathfinder or deactivate. The default is true.

RawMemory object allows to implement your own memory stringifier instead of built-in serializer based on JSON.stringify. It also allows to request up to 10 MB of additional memory using asynchronous memory segments feature.

You can also access memory segments of other players using methods below.

RawMemory.segmentsobject

RawMemory.setActiveSegments([0,3]); console.log(RawMemory.segments[0]); console.log(RawMemory.segments[3]); RawMemory.segments[3] = '{"foo": "bar", "counter": 15}';

An object with asynchronous memory segments available on this tick. Each object key is the segment ID with data in string values. Use setActiveSegments to fetch segments on the next tick. Segments data is saved automatically in the end of the tick. The maximum size per segment is 100 KB.

RawMemory.foreignSegmentobject

RawMemory.setActiveForeignSegment('player'); console.log(RawMemory.foreignSegment);

An object with a memory segment of another player available on this tick. Use setActiveForeignSegment to fetch segments on the next tick. The object consists of the following properties:

parametertypedescription
usernamestring

Another player's name.

idnumber

The ID of the requested memory segment.

datastring

The segment contents.

RawMemory.interShardSegmentstring

RawMemory.interShardSegment = JSON.stringify({ creeps: { Bob: {role: 'claimer'} } }); var interShardData = JSON.parse(RawMemory.interShardSegment); if(interShardData.creeps[creep.name]) { creep.memory = interShardData[creep.name]; delete interShardData.creeps[creep.name]; } RawMemory.interShardSegment = JSON.stringify(interShardData);

A string with a shared memory segment available on every world shard. Maximum string length is 100 KB.

Warning: this segment is not safe for concurrent usage! All shards have shared access to the same instance of data. When the segment contents is changed by two shards simultaneously, you may lose some data, since the segment string value is written all at once atomically. You must implement your own system to determine when each shard is allowed to rewrite the inter-shard memory, e.g. based on mutual exclusions.

RawMemory.get()

const myMemory = JSON.parse(RawMemory.get());

Get a raw string representation of the Memory object.

Return value

Returns a string value.

RawMemory.set(value)

RawMemory.set(JSON.stringify(myMemory));

Set new Memory value.

parametertypedescription
valuestring

New memory value as a string.

RawMemory.setActiveSegments(ids)

RawMemory.setActiveSegments([0,3]);

Request memory segments using the list of their IDs. Memory segments will become available on the next tick in segments object.

parametertypedescription
idsarray

An array of segment IDs. Each ID should be a number from 0 to 99. Maximum 10 segments can be active at the same time. Subsequent calls of setActiveSegments override previous ones.

RawMemory.setActiveForeignSegment(username, [id])

RawMemory.setActiveForeignSegment('player');RawMemory.setActiveForeignSegment('player', 10);RawMemory.setActiveForeignSegment(null);

Request a memory segment of another user. The segment should be marked by its owner as public using setPublicSegments. The segment data will become available on the next tick in foreignSegment object. You can only have access to one foreign segment at the same time.

parametertypedescription
usernamestring | null

The name of another user. Pass null to clear the foreign segment.

idoptionalnumber

The ID of the requested segment from 0 to 99. If undefined, the user's default public segment is requested as set by setDefaultPublicSegment.

RawMemory.setDefaultPublicSegment(id)

RawMemory.setPublicSegments([5,20,21]); RawMemory.setDefaultPublicSegment(5);RawMemory.setDefaultPublicSegment(null);

Set the specified segment as your default public segment. It will be returned if no id parameter is passed to setActiveForeignSegment by another user.

parametertypedescription
idnumber | null

The ID of the memory segment from 0 to 99. Pass null to remove your default public segment.

RawMemory.setPublicSegments(ids)

RawMemory.setPublicSegments([5,3]);RawMemory.setPublicSegments([]);

Set specified segments as public. Other users will be able to request access to them using setActiveForeignSegment.

parametertypedescription
idsarray

An array of segment IDs. Each ID should be a number from 0 to 99. Subsequent calls of setPublicSegments override previous ones.

All the following constant names are available in the global scope:

A site of a structure which is currently under construction. A construction site can be created using the 'Construct' button at the left of the game field or the Room.createConstructionSite method.

To build a structure on the construction site, give a worker creep some amount of energy and perform Creep.build action.

You can remove enemy construction sites by moving a creep on it.

An object representing the position of this object in the room.

The link to the Room object. May be undefined in case if an object is a flag or a construction site and is placed in a room that is not visible to you.

idstring

A unique object identificator. You can use Game.getObjectById method to retrieve an object instance by its id.

myboolean

Whether this is your own construction site.

ownerobject

An object with the structure’s owner info containing the following properties:

parametertypedescription
usernamestring

The name of the owner user.

progressnumber

The current construction progress.

progressTotalnumber

The total construction progress needed for the structure to be built.

structureTypestring

One of the STRUCTURE_* constants.

remove()

Remove the construction site.

Return value

One of the following codes:

constantvaluedescription
OK0

The operation has been scheduled successfully.

ERR_NOT_OWNER-1

You are not the owner of this construction site.

Creeps are your units. Creeps can move, harvest energy, construct structures, attack another creeps, and perform other actions. Each creep consists of up to 50 body parts with the following possible types:

Body part Build cost Effect per one body part
MOVE 50 Decreases fatigue by 2 points per tick.
WORK 100

Harvests 2 energy units from a source per tick.

Harvests 1 mineral unit from a deposit per tick.

Builds a structure for 5 energy units per tick.

Repairs a structure for 100 hits per tick consuming 1 energy unit per tick.

Dismantles a structure for 50 hits per tick returning 0.25 energy unit per tick.

Upgrades a controller for 1 energy unit per tick.

CARRY 50 Can contain up to 50 resource units.
ATTACK 80 Attacks another creep/structure with 30 hits per tick in a short-ranged attack.
RANGED_ATTACK 150

Attacks another single creep/structure with 10 hits per tick in a long-range attack up to 3 squares long.

Attacks all hostile creeps/structures within 3 squares range with 1-4-10 hits (depending on the range).

HEAL 250 Heals self or another creep restoring 12 hits per tick in short range or 4 hits per tick at a distance.
CLAIM 600

Claims a neutral room controller.

Reserves a neutral room controller for 1 tick per body part.

Attacks a hostile room controller downgrade or reservation timer with 1 tick per 5 body parts.

A creep with this body part will have a reduced life time of 500 ticks and cannot be renewed.

TOUGH 10 No effect, just additional hit points to the creep's body. Can be boosted to resist damage.

An object representing the position of this object in the room.

The link to the Room object. May be undefined in case if an object is a flag or a construction site and is placed in a room that is not visible to you.

bodyarray

An array describing the creep’s body. Each element contains the following properties:

parametertypedescription
booststring | undefined

If the body part is boosted, this property specifies the mineral type which is used for boosting. One of the RESOURCE_* constants. Learn more

typestring

One of the body part types constants.

hitsnumber

The remaining amount of hit points of this body part.

carryobject

const total = _.sum(creep.carry);

An object with the creep's cargo contents. Each object key is one of the RESOURCE_* constants, values are resources amounts. Use lodash.sum to get the total amount of contents:

carryCapacitynumber

The total amount of resources the creep can carry.

fatiguenumber

The movement fatigue indicator. If it is greater than zero, the creep cannot move.

hitsnumber

The current amount of hit points of the creep.

hitsMaxnumber

The maximum amount of hit points of the creep.

idstring

A unique object identificator. You can use Game.getObjectById method to retrieve an object instance by its id.

memoryany

creep.memory.task = 'building';

A shorthand to Memory.creeps[creep.name]. You can use it for quick access the creep’s specific memory data object. Learn more about memory

myboolean

Whether it is your creep or foe.

namestring

Creep’s name. You can choose the name while creating a new creep, and it cannot be changed later. This name is a hash key to access the creep via the Game.creeps object.

ownerobject

An object with the creep’s owner info containing the following properties:

parametertypedescription
usernamestring

The name of the owner user.

sayingstring

The text message that the creep was saying at the last tick.

spawningboolean

Whether this creep is still being spawned.

ticksToLivenumber

The remaining amount of game ticks after which the creep will die.

attack(target)

const target = creep.pos.findClosestByRange(FIND_HOSTILE_CREEPS); if(target) { if(creep.attack(target) == ERR_NOT_IN_RANGE) { creep.moveTo(target); } }

Attack another creep or structure in a short-ranged attack. Requires the ATTACK body part. If the target is inside a rampart, then the rampart is attacked instead. The target has to be at adjacent square to the creep. If the target is a creep with ATTACK body parts and is not inside a rampart, it will automatically hit back at the attacker.

parametertypedescription
targetCreep, Structure

The target object to be attacked.

Return value

One of the following codes:

constantvaluedescription
OK0

The operation has been scheduled successfully.

ERR_NOT_OWNER-1

You are not the owner of this creep.

ERR_BUSY-4

The creep is still being spawned.

ERR_INVALID_TARGET-7

The target is not a valid attackable object.

ERR_NOT_IN_RANGE-9

The target is too far away.

ERR_NO_BODYPART-12

There are no ATTACK body parts in this creep’s body.

attackController(target)

if(creep.room.controller && !creep.room.controller.my) { if(creep.attackController(creep.room.controller) == ERR_NOT_IN_RANGE) { creep.moveTo(creep.room.controller); } }

Decreases the controller's downgrade or reservation timer for 300 ticks per every CLAIM body part. The controller under attack cannot be upgraded or attacked again for the next 1,000 ticks. The target has to be at adjacent square to the creep.

parametertypedescription
targetStructure

The target controller object.

Return value

One of the following codes:

constantvaluedescription
OK0

The operation has been scheduled successfully.

ERR_NOT_OWNER-1

You are not the owner of this creep.

ERR_BUSY-4

The creep is still being spawned.

ERR_INVALID_TARGET-7

The target is not a valid owned or reserved controller object.

ERR_NOT_IN_RANGE-9

The target is too far away.

ERR_TIRED-11

You have to wait until the next attack is possible.

ERR_NO_BODYPART-12

There are not enough CLAIM body parts in this creep’s body.

build(target)

const target = creep.pos.findClosestByRange(FIND_CONSTRUCTION_SITES); if(target) { if(creep.build(target) == ERR_NOT_IN_RANGE) { creep.moveTo(target); } }

Build a structure at the target construction site using carried energy. Requires WORK and CARRY body parts. The target has to be within 3 squares range of the creep.

parametertypedescription
targetConstructionSite

The target construction site to be built.

Return value

One of the following codes:

constantvaluedescription
OK0

The operation has been scheduled successfully.

ERR_NOT_OWNER-1

You are not the owner of this creep.

ERR_BUSY-4

The creep is still being spawned.

ERR_NOT_ENOUGH_RESOURCES-6

The creep does not have any carried energy.

ERR_INVALID_TARGET-7

The target is not a valid construction site object or the structure cannot be built here (probably because of a creep at the same square).

ERR_NOT_IN_RANGE-9

The target is too far away.

ERR_NO_BODYPART-12

There are no WORK body parts in this creep’s body.

ERR_RCL_NOT_ENOUGH-14

Room Controller Level insufficient. Learn more

cancelOrder(methodName)

creep.move(LEFT); creep.cancelOrder('move');

Cancel the order given during the current game tick.

parametertypedescription
methodNamestring

The name of a creep's method to be cancelled.

Return value

One of the following codes:

constantvaluedescription
OK0

The operation has been cancelled successfully.

ERR_NOT_FOUND-5

The order with the specified name is not found.

claimController(target)

if(creep.room.controller) { if(creep.claimController(creep.room.controller) == ERR_NOT_IN_RANGE) { creep.moveTo(creep.room.controller); } }

Claims a neutral controller under your control. Requires the CLAIM body part. The target has to be at adjacent square to the creep. You need to have the corresponding Global Control Level in order to claim a new room. If you don't have enough GCL, consider reserving this room instead. Learn more

Return value

One of the following codes:

constantvaluedescription
OK0

The operation has been scheduled successfully.

ERR_NOT_OWNER-1

You are not the owner of this creep.

ERR_BUSY-4

The creep is still being spawned.

ERR_INVALID_TARGET-7

The target is not a valid neutral controller object.

ERR_FULL-8

You cannot claim more than 3 rooms in the Novice Area.

ERR_NOT_IN_RANGE-9

The target is too far away.

ERR_NO_BODYPART-12

There are no CLAIM body parts in this creep’s body.

ERR_GCL_NOT_ENOUGH-15

Your Global Control Level is not enough.

dismantle(target)

const target = creep.pos.findClosestByRange(FIND_STRUCTURES, {filter: {structureType: STRUCTURE_WALL}}); if(target) { if(creep.dismantle(target) == ERR_NOT_IN_RANGE) { creep.moveTo(target); } }

Dismantles any (even hostile) structure returning 50% of the energy spent on its repair. Requires the WORK body part. If the creep has an empty CARRY body part, the energy is put into it; otherwise it is dropped on the ground. The target has to be at adjacent square to the creep.

parametertypedescription
targetStructure

The target structure.

Return value

One of the following codes:

constantvaluedescription
OK0

The operation has been scheduled successfully.

ERR_NOT_OWNER-1

You are not the owner of this creep.

ERR_BUSY-4

The creep is still being spawned.

ERR_INVALID_TARGET-7

The target is not a valid creep object.

ERR_NOT_IN_RANGE-9

The target is too far away.

ERR_NO_BODYPART-12

There are no WORK body parts in this creep’s body.

drop(resourceType, [amount])

creep.drop(RESOURCE_ENERGY); for(const resourceType in creep.carry) { creep.drop(resourceType); }

Drop this resource on the ground.

parametertypedescription
resourceTypestring

One of the RESOURCE_* constants.

amountoptionalnumber

The amount of resource units to be dropped. If omitted, all the available carried amount is used.

Return value

One of the following codes:

constantvaluedescription
OK0

The operation has been scheduled successfully.

ERR_NOT_OWNER-1

You are not the owner of this creep.

ERR_BUSY-4

The creep is still being spawned.

ERR_NOT_ENOUGH_RESOURCES-6

The creep does not have the given amount of energy.

generateSafeMode(controller)

if(creep.generateSafeMode(creep.room.controller) == ERR_NOT_IN_RANGE) { creep.moveTo(creep.room.controller); }

Add one more available safe mode activation to a room controller. The creep has to be at adjacent square to the target room controller and have 1000 ghodium resource.

Return value

One of the following codes:

constantvaluedescription
OK0

The operation has been scheduled successfully.

ERR_NOT_OWNER-1

You are not the owner of this creep.

ERR_BUSY-4

The creep is still being spawned.

ERR_NOT_ENOUGH_RESOURCES-6

The creep does not have enough ghodium.

ERR_INVALID_TARGET-7

The target is not a valid controller object.

ERR_NOT_IN_RANGE-9

The target is too far away.

getActiveBodyparts(type)

const target = creep.pos.findClosestByRange(FIND_HOSTILE_CREEPS, { filter: function(object) { return object.getActiveBodyparts(ATTACK) == 0; } }); if(target) { creep.moveTo(target); }

Get the quantity of live body parts of the given type. Fully damaged parts do not count.

parametertypedescription
typestring

A body part type, one of the following body part constants:

  • MOVE
  • WORK
  • CARRY
  • ATTACK
  • RANGED_ATTACK
  • HEAL
  • TOUGH

Return value

A number representing the quantity of body parts.

harvest(target)

const target = creep.pos.findClosestByRange(FIND_SOURCES_ACTIVE); if(target) { if(creep.harvest(target) == ERR_NOT_IN_RANGE) { creep.moveTo(target); } }

Harvest energy from the source or minerals from the mineral deposit. Requires the WORK body part. If the creep has an empty CARRY body part, the harvested resource is put into it; otherwise it is dropped on the ground. The target has to be at an adjacent square to the creep.

parametertypedescription
targetSource, Mineral

The object to be harvested.

Return value

One of the following codes:

constantvaluedescription
OK0

The operation has been scheduled successfully.

ERR_NOT_OWNER-1

You are not the owner of this creep, or the room controller is owned or reserved by another player.

ERR_BUSY-4

The creep is still being spawned.

ERR_NOT_FOUND-5

Extractor not found. You must build an extractor structure to harvest minerals. Learn more

ERR_NOT_ENOUGH_RESOURCES-6

The target source does not contain any harvestable energy.

ERR_INVALID_TARGET-7

The target is not a valid source object.

ERR_NOT_IN_RANGE-9

The target is too far away.

ERR_NO_BODYPART-12

There are no WORK body parts in this creep’s body.

heal(target)

const target = creep.pos.findClosestByRange(FIND_MY_CREEPS, { filter: function(object) { return object.hits < object.hitsMax; } }); if(target) { if(creep.heal(target) == ERR_NOT_IN_RANGE) { creep.moveTo(target); } }

Heal self or another creep. It will restore the target creep’s damaged body parts function and increase the hits counter. Requires the HEAL body part. The target has to be at adjacent square to the creep.

parametertypedescription
targetCreep

The target creep object.

Return value

One of the following codes:

constantvaluedescription
OK0

The operation has been scheduled successfully.

ERR_NOT_OWNER-1

You are not the owner of this creep.

ERR_BUSY-4

The creep is still being spawned.

ERR_INVALID_TARGET-7

The target is not a valid creep object.

ERR_NOT_IN_RANGE-9

The target is too far away.

ERR_NO_BODYPART-12

There are no HEAL body parts in this creep’s body.

move(direction)

creep.move(RIGHT);const path = creep.pos.findPathTo(Game.flags.Flag1); if(path.length > 0) { creep.move(path[0].direction); }

Move the creep one square in the specified direction. Requires the MOVE body part.

parametertypedescription
directionnumber

One of the following constants:

  • TOP
  • TOP_RIGHT
  • RIGHT
  • BOTTOM_RIGHT
  • BOTTOM
  • BOTTOM_LEFT
  • LEFT
  • TOP_LEFT

Return value

One of the following codes:

constantvaluedescription
OK0

The operation has been scheduled successfully.

ERR_NOT_OWNER-1

You are not the owner of this creep.

ERR_BUSY-4

The creep is still being spawned.

ERR_INVALID_ARGS-10

The provided direction is incorrect.

ERR_TIRED-11

The fatigue indicator of the creep is non-zero.

ERR_NO_BODYPART-12

There are no MOVE body parts in this creep’s body.

moveByPath(path)

const path = spawn.room.findPath(spawn, source); creep.moveByPath(path);if(!creep.memory.path) { creep.memory.path = creep.pos.findPathTo(target); } creep.moveByPath(creep.memory.path);

Move the creep using the specified predefined path. Requires the MOVE body part.

Return value

One of the following codes:

constantvaluedescription
OK0

The operation has been scheduled successfully.

ERR_NOT_OWNER-1

You are not the owner of this creep.

ERR_BUSY-4

The creep is still being spawned.

ERR_NOT_FOUND-5

The specified path doesn't match the creep's location.

ERR_INVALID_ARGS-10

path is not a valid path array.

ERR_TIRED-11

The fatigue indicator of the creep is non-zero.

ERR_NO_BODYPART-12

There are no MOVE body parts in this creep’s body.

moveTo(x, y, [opts])(target, [opts])

creep.moveTo(10, 20);creep.moveTo(Game.flags.Flag1);creep.moveTo(new RoomPosition(25, 20, 'W10N5'));creep.moveTo(pos, {reusePath: 50}); for(const name in Game.creeps) { Game.creeps[name].moveTo(target, {noPathFinding: true}); } if(Game.cpu.tickLimit - Game.cpu.getUsed() > 20) { for(const name in Game.creeps) { Game.creeps[name].moveTo(target); } }

Find the optimal path to the target within the same room and move to it. A shorthand to consequent calls of pos.findPathTo() and move() methods. If the target is in another room, then the corresponding exit will be used as a target. Requires the MOVE body part.

parametertypedescription
xnumber

X position of the target in the same room.

ynumber

Y position of the target in the same room.

targetobject

Can be a RoomPosition object or any object containing RoomPosition. The position doesn't have to be in the same room with the creep.

optsoptionalobject

An object containing additional options:

  • reusePath

    number

    This option enables reusing the path found along multiple game ticks. It allows to save CPU time, but can result in a slightly slower creep reaction behavior. The path is stored into the creep's memory to the _move property. The reusePath value defines the amount of ticks which the path should be reused for. The default value is 5. Increase the amount to save more CPU, decrease to make the movement more consistent. Set to 0 if you want to disable path reusing.

  • serializeMemory

    boolean

    If reusePath is enabled and this option is set to true, the path will be stored in memory in the short serialized form using Room.serializePath. The default value is true.
  • noPathFinding

    boolean

    If this option is set to true, moveTo method will return ERR_NOT_FOUND if there is no memorized path to reuse. This can significantly save CPU time in some cases. The default value is false.

  • visualizePathStyle

    object

    Draw a line along the creep’s path using RoomVisual.poly. You can provide either an empty object or custom style parameters. The default style is equivalent to: { fill: 'transparent', stroke: '#fff', lineStyle: 'dashed', strokeWidth: .15, opacity: .1 }
  • Any options supported by Room.findPath method.

Return value

One of the following codes:

constantvaluedescription
OK0

The operation has been scheduled successfully.

ERR_NOT_OWNER-1

You are not the owner of this creep.

ERR_NO_PATH-2

No path to the target could be found.

ERR_BUSY-4

The creep is still being spawned.

ERR_INVALID_TARGET-7

The target provided is invalid.

ERR_TIRED-11

The fatigue indicator of the creep is non-zero.

ERR_NO_BODYPART-12

There are no MOVE body parts in this creep’s body.

notifyWhenAttacked(enabled)

if(creep.memory.role == 'scout') { creep.notifyWhenAttacked(false); } else { creep.notifyWhenAttacked(true); }

Toggle auto notification when the creep is under attack. The notification will be sent to your account email. Turned on by default.

parametertypedescription
enabledboolean

Whether to enable notification or disable.

Return value

One of the following codes:

constantvaluedescription
OK0

The operation has been scheduled successfully.

ERR_NOT_OWNER-1

You are not the owner of this creep.

ERR_BUSY-4

The creep is still being spawned.

ERR_INVALID_ARGS-10

enable argument is not a boolean value.

pickup(target)

const target = creep.pos.findClosestByRange(FIND_DROPPED_ENERGY); if(target) { if(creep.pickup(target) == ERR_NOT_IN_RANGE) { creep.moveTo(target); } }

Pick up an item (a dropped piece of energy). Requires the CARRY body part. The target has to be at adjacent square to the creep or at the same square.

parametertypedescription
targetResource

The target object to be picked up.

Return value

One of the following codes:

constantvaluedescription
OK0

The operation has been scheduled successfully.

ERR_NOT_OWNER-1

You are not the owner of this creep.

ERR_BUSY-4

The creep is still being spawned.

ERR_INVALID_TARGET-7

The target is not a valid object to pick up.

ERR_FULL-8

The creep cannot receive any more energy.

ERR_NOT_IN_RANGE-9

The target is too far away.

rangedAttack(target)

const targets = creep.pos.findInRange(FIND_HOSTILE_CREEPS, 3); if(targets.length > 0) { creep.rangedAttack(targets[0]); }

A ranged attack against another creep or structure. Requires the RANGED_ATTACK body part. If the target is inside a rampart, the rampart is attacked instead. The target has to be within 3 squares range of the creep.

parametertypedescription
targetCreep, Structure

The target object to be attacked.

Return value

One of the following codes:

constantvaluedescription
OK0

The operation has been scheduled successfully.

ERR_NOT_OWNER-1

You are not the owner of this creep.

ERR_BUSY-4

The creep is still being spawned.

ERR_INVALID_TARGET-7

The target is not a valid attackable object.

ERR_NOT_IN_RANGE-9

The target is too far away.

ERR_NO_BODYPART-12

There are no RANGED_ATTACK body parts in this creep’s body.

rangedHeal(target)

const target = creep.pos.findClosestByRange(FIND_MY_CREEPS, { filter: function(object) { return object.hits < object.hitsMax; } }); if(target) { creep.moveTo(target); if(creep.pos.isNearTo(target)) { creep.heal(target); } else { creep.rangedHeal(target); } }

Heal another creep at a distance. It will restore the target creep’s damaged body parts function and increase the hits counter. Requires the HEAL body part. The target has to be within 3 squares range of the creep.

parametertypedescription
targetCreep

The target creep object.

Return value

One of the following codes:

constantvaluedescription
OK0

The operation has been scheduled successfully.

ERR_NOT_OWNER-1

You are not the owner of this creep.

ERR_BUSY-4

The creep is still being spawned.

ERR_INVALID_TARGET-7

The target is not a valid creep object.

ERR_NOT_IN_RANGE-9

The target is too far away.

ERR_NO_BODYPART-12

There are no HEAL body parts in this creep’s body.

rangedMassAttack()

const targets = creep.pos.findInRange(FIND_HOSTILE_CREEPS, 3); if(targets.length > 0) { creep.rangedMassAttack(); }

A ranged attack against all hostile creeps or structures within 3 squares range. Requires the RANGED_ATTACK body part. The attack power depends on the range to each target. Friendly units are not affected.

Return value

One of the following codes:

constantvaluedescription
OK0

The operation has been scheduled successfully.

ERR_NOT_OWNER-1

You are not the owner of this creep.

ERR_BUSY-4

The creep is still being spawned.

ERR_NO_BODYPART-12

There are no RANGED_ATTACK body parts in this creep’s body.

repair(target)

const targets = creep.room.find(FIND_STRUCTURES, { filter: object => object.hits < object.hitsMax }); targets.sort((a,b) => a.hits - b.hits); if(targets.length > 0) { if(creep.repair(targets[0]) == ERR_NOT_IN_RANGE) { creep.moveTo(targets[0]); } }

Repair a damaged structure using carried energy. Requires the WORK and CARRY body parts. The target has to be within 3 squares range of the creep.

parametertypedescription
targetStructure

The target structure to be repaired.

Return value

One of the following codes:

constantvaluedescription
OK0

The operation has been scheduled successfully.

ERR_NOT_OWNER-1

You are not the owner of this creep.

ERR_BUSY-4

The creep is still being spawned.

ERR_NOT_ENOUGH_RESOURCES-6

The creep does not carry any energy.

ERR_INVALID_TARGET-7

The target is not a valid creep object.

ERR_NOT_IN_RANGE-9

The target is too far away.

ERR_NO_BODYPART-12

There are no WORK body parts in this creep’s body.

reserveController(target)

if(creep.room.controller) { if(creep.reserveController(creep.room.controller) == ERR_NOT_IN_RANGE) { creep.moveTo(creep.room.controller); } }

Temporarily block a neutral controller from claiming by other players and restore energy sources to their full capacity. Each tick, this command increases the counter of the period during which the controller is unavailable by 1 tick per each CLAIM body part. The maximum reservation period to maintain is 5,000 ticks. The target has to be at adjacent square to the creep.

Return value

One of the following codes:

constantvaluedescription
OK0

The operation has been scheduled successfully.

ERR_NOT_OWNER-1

You are not the owner of this creep.

ERR_BUSY-4

The creep is still being spawned.

ERR_INVALID_TARGET-7

The target is not a valid neutral controller object.

ERR_NOT_IN_RANGE-9

The target is too far away.

ERR_NO_BODYPART-12

There are no CLAIM body parts in this creep’s body.

say(message, [public])

const hostiles = creep.pos.findInRange(FIND_HOSTILE_CREEPS, 10); if(hostiles.length > 0) { creep.say('OMG!😨'); creep.moveTo(Game.spawns['Spawn1']); } else { doWork(creep); }

Display a visual speech balloon above the creep with the specified message. The message will be available for one tick. You can read the last message using the saying property. Any valid Unicode characters are allowed, including emoji.

parametertypedescription
messagestring

The message to be displayed. Maximum length is 10 characters.

publicoptionalboolean

Set to true to allow other players to see this message. Default is false.

Return value

One of the following codes:

constantvaluedescription
OK0

The operation has been scheduled successfully.

ERR_NOT_OWNER-1

You are not the owner of this creep.

ERR_BUSY-4

The creep is still being spawned.

signController(target, text)

if(creep.room.controller) { if(creep.signController(creep.room.controller, "I'm going to claim this room in a few days. I warned ya!") == ERR_NOT_IN_RANGE) { creep.moveTo(creep.room.controller); } }

Sign a controller with an arbitrary text visible to all players. This text will appear in the room UI, in the world map, and can be accessed via the API. You can sign unowned and hostile controllers. The target has to be at adjacent square to the creep. Pass an empty string to remove the sign.

parametertypedescription
targetStructureController

The target controller object to be signed.

textstring

The sign text. The string is cut off after 100 characters.

Return value

One of the following codes:

constantvaluedescription
OK0

The operation has been scheduled successfully.

ERR_BUSY-4

The creep is still being spawned.

ERR_INVALID_TARGET-7

The target is not a valid controller object.

ERR_NOT_IN_RANGE-9

The target is too far away.

suicide()

Kill the creep immediately.

Return value

One of the following codes:

constantvaluedescription
OK0

The operation has been scheduled successfully.

ERR_NOT_OWNER-1

You are not the owner of this creep.

ERR_BUSY-4

The creep is still being spawned.

transfer(target, resourceType, [amount])

if(creep.transfer(storage, RESOURCE_ENERGY) == ERR_NOT_IN_RANGE) { creep.moveTo(storage); } for(const resourceType in creep.carry) { creep.transfer(storage, resourceType); }

Transfer resource from the creep to another object. The target has to be at adjacent square to the creep.

parametertypedescription
targetCreep, Structure

The target object.

resourceTypestring

One of the RESOURCE_* constants.

amountoptionalnumber

The amount of resources to be transferred. If omitted, all the available carried amount is used.

Return value

One of the following codes:

constantvaluedescription
OK0

The operation has been scheduled successfully.

ERR_NOT_OWNER-1

You are not the owner of this creep.

ERR_BUSY-4

The creep is still being spawned.

ERR_NOT_ENOUGH_RESOURCES-6

The creep does not have the given amount of resources.

ERR_INVALID_TARGET-7

The target is not a valid object which can contain the specified resource.

ERR_FULL-8

The target cannot receive any more resources.

ERR_NOT_IN_RANGE-9

The target is too far away.

ERR_INVALID_ARGS-10

The resources amount is incorrect.

upgradeController(target)

if(creep.room.controller) { if(creep.upgradeController(creep.room.controller) == ERR_NOT_IN_RANGE) { creep.moveTo(creep.room.controller); } }

Upgrade your controller to the next level using carried energy. Upgrading controllers raises your Global Control Level in parallel. Requires WORK and CARRY body parts. The target has to be within 3 squares range of the creep.

A fully upgraded level 8 controller can't be upgraded over 15 energy units per tick regardless of creeps abilities. The cumulative effect of all the creeps performing upgradeController in the current tick is taken into account. This limit can be increased by using ghodium mineral boost.

Upgrading the controller raises its ticksToDowngrade timer by 100. The timer must be full in order for controller to be levelled up.

Return value

One of the following codes:

constantvaluedescription
OK0

The operation has been scheduled successfully.

ERR_NOT_OWNER-1

You are not the owner of this creep or the target controller.

ERR_BUSY-4

The creep is still being spawned.

ERR_NOT_ENOUGH_RESOURCES-6

The creep does not have any carried energy.

ERR_INVALID_TARGET-7

The target is not a valid controller object.

ERR_NOT_IN_RANGE-9

The target is too far away.

ERR_NO_BODYPART-12

There are no WORK body parts in this creep’s body.

withdraw(target, resourceType, [amount])

if(creep.withdraw(storage, RESOURCE_ENERGY) == ERR_NOT_IN_RANGE) { creep.moveTo(storage); }

Withdraw resources from a structure. The target has to be at adjacent square to the creep. Multiple creeps can withdraw from the same structure in the same tick. Your creeps can withdraw resources from hostile structures as well, in case if there is no hostile rampart on top of it.

parametertypedescription
targetStructure

The target object.

resourceTypestring

One of the RESOURCE_* constants.

amountoptionalnumber

The amount of resources to be transferred. If omitted, all the available amount is used.

Return value

One of the following codes:

constantvaluedescription
OK0

The operation has been scheduled successfully.

ERR_NOT_OWNER-1

You are not the owner of this creep, or there is a hostile rampart on top of the target.

ERR_BUSY-4

The creep is still being spawned.

ERR_NOT_ENOUGH_RESOURCES-6

The target does not have the given amount of resources.

ERR_INVALID_TARGET-7

The target is not a valid object which can contain the specified resource.

ERR_FULL-8

The creep's carry is full.

ERR_NOT_IN_RANGE-9

The target is too far away.

ERR_INVALID_ARGS-10

The resource amount or type is incorrect.

A flag. Flags can be used to mark particular spots in a room. Flags are visible to their owners only. You cannot have more than 10,000 flags.

An object representing the position of this object in the room.

The link to the Room object. May be undefined in case if an object is a flag or a construction site and is placed in a room that is not visible to you.

colornumber

Flag primary color. One of the COLOR_* constants.

memoryany

A shorthand to Memory.flags[flag.name]. You can use it for quick access the flag's specific memory data object.

namestring

Flag’s name. You can choose the name while creating a new flag, and it cannot be changed later. This name is a hash key to access the flag via the Game.flags object. The maximum name length is 60 charactes.

secondaryColornumber

Flag secondary color. One of the COLOR_* constants.

remove()

Remove the flag.

Return value

Always returns OK .

setColor(color, [secondaryColor])

Game.flags.Flag1.setColor(COLOR_GREEN, COLOR_WHITE);

Set new color of the flag.

parametertypedescription
colorstring

Primary color of the flag. One of the COLOR_* constants.

secondaryColoroptionalstring

Secondary color of the flag. One of the COLOR_* constants.

Return value

One of the following codes:

constantvaluedescription
OK0

The operation has been scheduled successfully.

ERR_INVALID_ARGS-10

color is not a valid color constant.

setPosition(x,y)(pos)

Game.flags.Flag1.setPosition(10,20);Game.flags.Flag1.setPosition( new RoomPosition(10, 20, 'W3S5') );

Set new position of the flag.

parametertypedescription
xnumber

The X position in the room.

ynumber

The Y position in the room.

posobject

Can be a RoomPosition object or any object containing RoomPosition.

Return value

One of the following codes:

constantvaluedescription
OK0

The operation has been scheduled successfully.

ERR_INVALID_TARGET-7

The target provided is invalid.

A mineral deposit. Can be harvested by creeps with a WORK body part using the extractor structure. Learn more about minerals from this article.

Regeneration amount DENSITY_LOW: 15,000 DENSITY_MODERATE: 35,000DENSITY_HIGH: 70,000 DENSITY_ULTRA: 100,000
Regeneration time 50,000 ticks
Density change probability DENSITY_LOW: 100% chance DENSITY_MODERATE: 5% chanceDENSITY_HIGH: 5% chance DENSITY_ULTRA: 100% chance

An object representing the position of this object in the room.

The link to the Room object. May be undefined in case if an object is a flag or a construction site and is placed in a room that is not visible to you.

densitynumber

The density of this mineral deposit, one of the DENSITY_* constants.

mineralAmountnumber

The remaining amount of resources.

mineralTypestring

The resource type, one of the RESOURCE_* constants.

idstring

A unique object identificator. You can use Game.getObjectById method to retrieve an object instance by its id.

ticksToRegenerationnumber

The remaining time after which the deposit will be refilled.

A nuke landing position. This object cannot be removed or modified. You can find incoming nukes in the room using the FIND_NUKES constant.

Landing time 50,000 ticks
Effect All creeps, construction sites and dropped resources in the room are removed immediately, even inside ramparts. Damage to structures:
  • 10,000,000 hits at the landing position;
  • 5,000,000 hits to all structures in 5x5 area.

Note that you can stack multiple nukes from different rooms at the same target position to increase damage.

If the room is in safe mode, then the safe mode is cancelled immediately, and the safe mode cooldown is reset to 0.

The room controller is hit by triggering upgradeBlocked period, which means it is unavailable to activate safe mode again within the next 200 ticks.

An object representing the position of this object in the room.

The link to the Room object. May be undefined in case if an object is a flag or a construction site and is placed in a room that is not visible to you.

idstring

A unique object identificator. You can use Game.getObjectById method to retrieve an object instance by its id.

launchRoomNamestring

The name of the room where this nuke has been launched from.

timeToLandnumber

The remaining landing time.

The base prototype for a structure that has an owner. Such structures can be found using FIND_MY_STRUCTURES and FIND_HOSTILE_STRUCTURES constants.

An object representing the position of this object in the room.

The link to the Room object. May be undefined in case if an object is a flag or a construction site and is placed in a room that is not visible to you.

hitsnumber

The current amount of hit points of the structure.

hitsMaxnumber

The total amount of hit points of the structure.

idstring

A unique object identificator. You can use Game.getObjectById method to retrieve an object instance by its id.

structureTypestring

One of the STRUCTURE_* constants.

destroy()

Destroy this structure immediately.

Return value

One of the following codes:

constantvaluedescription
OK0

The operation has been scheduled successfully.

ERR_NOT_OWNER-1

You are not the owner of this structure.

ERR_BUSY-4

Hostile creeps are in the room.

isActive()

Check whether this structure can be used. If room controller level is insufficient, then this method will return false, and the structure will be highlighted with red in the game.

Return value

A boolean value.

notifyWhenAttacked(enabled)

Toggle auto notification when the structure is under attack. The notification will be sent to your account email. Turned on by default.

parametertypedescription
enabledboolean

Whether to enable notification or disable.

Return value

One of the following codes:

constantvaluedescription
OK0

The operation has been scheduled successfully.

ERR_NOT_OWNER-1

You are not the owner of this structure.

ERR_INVALID_ARGS-10

enable argument is not a boolean value.

myboolean

Whether this is your own structure.

ownerobject

An object with the structure’s owner info containing the following properties:

parametertypedescription
usernamestring

The name of the owner user.

Container for custom navigation cost data. By default PathFinder will only consider terrain data (plain, swamp, wall) — if you need to route around obstacles such as buildings or creeps you must put them into a CostMatrix. Generally you will create your CostMatrix from within roomCallback. If a non-0 value is found in a room's CostMatrix then that value will be used instead of the default terrain cost. You should avoid using large values in your CostMatrix and terrain cost flags. For example, running PathFinder.search with { plainCost: 1, swampCost: 5 } is faster than running it with {plainCost: 2, swampCost: 10 } even though your paths will be the same.

constructor()

let costs = new PathFinder.CostMatrix;

Creates a new CostMatrix containing 0's for all positions.

set(x, y, cost)

let costs = new PathFinder.CostMatrix; let pos = Game.spawns['Spawn1'].pos; costs.set(pos.x, pos.y, 255);

Set the cost of a position in this CostMatrix.

parametertypedescription
xnumber

X position in the room.

ynumber

Y position in the room.

costnumber

Cost of this position. Must be a whole number. A cost of 0 will use the terrain cost for that tile. A cost greater than or equal to 255 will be treated as unwalkable.

get(x, y)

Get the cost of a position in this CostMatrix.

parametertypedescription
xnumber

X position in the room.

ynumber

Y position in the room.

clone()

Copy this CostMatrix into a new CostMatrix with the same data.

Return value

A new CostMatrix instance.

serialize()

let costs = new PathFinder.CostMatrix; Memory.savedMatrix = costs.serialize();

Returns a compact representation of this CostMatrix which can be stored via JSON.stringify.

Return value

An array of numbers. There's not much you can do with the numbers besides store them for later.

PathFinder.CostMatrix.deserialize(val)

let costs = PathFinder.CostMatrix.deserialize(Memory.savedMatrix)

Static method which deserializes a new CostMatrix using the return value of serialize.

parametertypedescription
valobject

Whatever serialize returned

Return value

Returns new CostMatrix instance.

A dropped piece of resource. It will decay after a while if not picked up. Dropped resource pile decays for ceil(amount/1000) units per tick.

An object representing the position of this object in the room.

The link to the Room object. May be undefined in case if an object is a flag or a construction site and is placed in a room that is not visible to you.

amountnumber

The amount of resource units containing.

idstring

A unique object identificator. You can use Game.getObjectById method to retrieve an object instance by its id.

resourceTypestring

One of the RESOURCE_* constants.

An object representing the room in which your units and structures are in. It can be used to look around, find paths, etc. Every RoomObject in the room contains its linked Room instance in the room property.

The Controller structure of this room, if present, otherwise undefined.

energyAvailablenumber

Total amount of energy available in all spawns and extensions in the room.

energyCapacityAvailablenumber

Total amount of energyCapacity of all spawns and extensions in the room.

memoryany

room.memory.stage = 2;

A shorthand to Memory.rooms[room.name]. You can use it for quick access the room’s specific memory data object. Learn more about memory

namestring

The name of the room.

The Storage structure of this room, if present, otherwise undefined.

The Terminal structure of this room, if present, otherwise undefined.

A RoomVisual object for this room. You can use this object to draw simple shapes (lines, circles, text labels) in the room.

Room.serializePath(path)

const path = spawn.pos.findPathTo(source); Memory.path = Room.serializePath(path); creep.moveByPath(Memory.path);

Serialize a path array into a short string representation, which is suitable to store in memory.

parametertypedescription
patharray

A path array retrieved from Room.findPath.

Return value

A serialized string form of the given path.

Room.deserializePath(path)

const path = Room.deserializePath(Memory.path); creep.moveByPath(path);

Deserialize a short string path representation into an array form.

parametertypedescription
pathstring

A serialized path string.

Return value

A path array.

createConstructionSite(x, y, structureType)(pos, structureType)

Game.rooms.sim.createConstructionSite(10, 15, STRUCTURE_ROAD);

Create new ConstructionSite at the specified location.

parametertypedescription
xnumber

The X position.

ynumber

The Y position.

posobject

Can be a RoomPosition object or any object containing RoomPosition.

structureTypestring

One of the STRUCTURE_* constants.

Return value

One of the following codes:

constantvaluedescription
OK0

The operation has been scheduled successfully.

ERR_INVALID_TARGET-7

The structure cannot be placed at the specified location.

ERR_FULL-8

You have too many construction sites. The maximum number of construction sites per player is 100.

ERR_INVALID_ARGS-10

The location is incorrect.

ERR_RCL_NOT_ENOUGH-14

Room Controller Level insufficient. Learn more

createFlag(x, y, [name], [color], [secondaryColor])(pos, [name], [color], [secondaryColor])

Game.rooms.sim.createFlag(5, 12, 'Flag1');

Create new Flag at the specified location.

parametertypedescription
xnumber

The X position.

ynumber

The Y position.

posobject

Can be a RoomPosition object or any object containing RoomPosition.

nameoptionalstring

The name of a new flag. It should be unique, i.e. the Game.flags object should not contain another flag with the same name (hash key). If not defined, a random name will be generated. The maximum length is 60 characters.

coloroptionalstring

The color of a new flag. Should be one of the COLOR_* constants. The default value is COLOR_WHITE.

secondaryColoroptionalstring

The secondary color of a new flag. Should be one of the COLOR_* constants. The default value is equal to color.

Return value

The name of a new flag, or one of the following error codes:

constantvaluedescription
ERR_NAME_EXISTS-3

There is a flag with the same name already.

ERR_INVALID_ARGS-10

The location or the color constant is incorrect.

find(type, [opts])

const targets = creep.room.find(FIND_DROPPED_RESOURCES); if(targets.length) { creep.moveTo(targets[0]); creep.pickup(targets[0]); }const extensions = Game.spawns['Spawn1'].room.find(FIND_MY_STRUCTURES, { filter: { structureType: STRUCTURE_EXTENSION } }); console.log('Spawn has '+extensions.length+' extensions available');const targets = creep.room.find(FIND_HOSTILE_CREEPS, { filter: function(object) { return object.getActiveBodyparts(ATTACK) == 0; } });

Find all objects of the specified type in the room.

parametertypedescription
typenumber

One of the FIND_* constants.

optsoptionalobject

An object with additional options:

  • filter

    object, function, string

Return value

An array with the objects found.

findExitTo(room)

const exitDir = creep.room.findExitTo(anotherCreep.room); const exit = creep.pos.findClosestByRange(exitDir); creep.moveTo(exit); creep.moveTo(anotherCreep); creep.moveTo(new RoomPosition(25,25, anotherCreep.pos.roomName));

Find the exit direction en route to another room. Please note that this method is not required for inter-room movement, you can simply pass the target in another room into Creep.moveTo method.

parametertypedescription
roomstring, Room

Another room name or room object.

Return value

The room direction constant, one of the following:

  • FIND_EXIT_TOP
  • FIND_EXIT_RIGHT
  • FIND_EXIT_BOTTOM
  • FIND_EXIT_LEFT

Or one of the following error codes:

constantvaluedescription
ERR_NO_PATH-2

Path can not be found.

ERR_INVALID_ARGS-10

The location is incorrect.

findPath(fromPos, toPos, [opts])

const path = creep.room.findPath(creep.pos, targetPos); creep.move(path[0].direction);PathFinder.use(true); const path = creep.room.findPath(creep.pos, targetPos, { costCallback: function(roomName, costMatrix) { if(roomName == 'W1N5') { costMatrix.set(anotherCreep.pos.x, anotherCreep.pos.y, 0); costMatrix.set(flag.pos.x, flag.pos.y, 255); costMatrix.set(25, 20, 50); } } });let path = creep.room.findPath(creep.pos, targetPos, {maxOps: 200}); if( !path.length || !targetPos.isEqualTo(path[path.length - 1]) ) { path = creep.room.findPath(creep.pos, targetPos, { maxOps: 1000, ignoreDestructibleStructures: true }); } if( path.length ) { creep.move(path[0].direction); }

Find an optimal path inside the room between fromPos and toPos using Jump Point Search algorithm.

parametertypedescription
fromPosRoomPosition

The start position.

toPosRoomPosition

The end position.

optsoptionalobject

An object containing additonal pathfinding flags:

  • ignoreCreeps

    boolean

    Treat squares with creeps as walkable. Can be useful with too many moving creeps around or in some other cases. The default value is false.

  • ignoreDestructibleStructures

    boolean

    Treat squares with destructible structures (constructed walls, ramparts, spawns, extensions) as walkable. The default value is false.

  • ignoreRoads

    boolean

    Ignore road structures. Enabling this option can speed up the search. The default value is false. This is only used when the new PathFinder is enabled.
  • costCallback

    function(string, CostMatrix)

    You can use this callback to modify a CostMatrix for any room during the search. The callback accepts two arguments, roomName and costMatrix. Use the costMatrix instance to make changes to the positions costs. If you return a new matrix from this callback, it will be used instead of the built-in cached one. This option is only used when the new PathFinder is enabled.
  • ignore

    array

    An array of the room's objects or RoomPosition objects which should be treated as walkable tiles during the search. This option cannot be used when the new PathFinder is enabled (use costCallback option instead).
  • avoid

    array

    An array of the room's objects or RoomPosition objects which should be treated as obstacles during the search. This option cannot be used when the new PathFinder is enabled (use costCallback option instead).
  • maxOps

    number

    The maximum limit of possible pathfinding operations. You can limit CPU time used for the search based on ratio 1 op ~ 0.001 CPU. The default value is 2000.

  • heuristicWeight

    number

    Weight to apply to the heuristic in the A formula F = G + weight H. Use this option only if you understand the underlying A* algorithm mechanics! The default value is 1.2.

  • serialize

    boolean

    If true, the result path will be serialized using Room.serializePath. The default is false.
  • maxRooms

    number

    The maximum allowed rooms to search. The default (and maximum) is 16. This is only used when the new PathFinder is enabled.

Return value

An array with path steps in the following format:

getPositionAt(x, y)

const pos = Game.rooms.sim.getPositionAt(5,12); const source = pos.findClosestByRange(FIND_SOURCES_ACTIVE);

Creates a RoomPosition object at the specified location.

parametertypedescription
xnumber

The X position.

ynumber

The Y position.

Return value

A RoomPosition object or null if it cannot be obtained.

lookAt(x, y)(target)

const look = creep.room.lookAt(target); look.forEach(function(lookObject) { if(lookObject.type == LOOK_CREEPS && lookObject[LOOK_CREEPS].getActiveBodyparts(ATTACK) == 0) { creep.moveTo(lookObject.creep); } });

Get the list of objects at the specified room position.

parametertypedescription
xnumber

X position in the room.

ynumber

Y position in the room.

targetobject

Can be a RoomPosition object or any object containing RoomPosition.

Return value

An array with objects at the specified position in the following format:

lookAtArea(top, left, bottom, right, [asArray])

const look = creep.room.lookAtArea(10,5,11,7);

Get the list of objects at the specified room area.

parametertypedescription
topnumber

The top Y boundary of the area.

leftnumber

The left X boundary of the area.

bottomnumber

The bottom Y boundary of the area.

rightnumber

The right X boundary of the area.

asArrayoptionalboolean

Set to true if you want to get the result as a plain array.

Return value

If asArray is set to false or undefined, the method returns an object with all the objects in the specified area in the following format:

If asArray is set to true, the method returns an array in the following format:

lookForAt(type, x, y)(type, target)

const found = creep.room.lookForAt(LOOK_CREEPS, target); if(found.length && found[0].getActiveBodyparts(ATTACK) == 0) { creep.moveTo(found[0]); }

Get an object with the given type at the specified room position.

parametertypedescription
typestring

One of the LOOK_* constants.

xnumber

X position in the room.

ynumber

Y position in the room.

targetobject

Can be a RoomPosition object or any object containing RoomPosition.

Return value

An array of objects of the given type at the specified position if found.

lookForAtArea(type, top, left, bottom, right, [asArray])

const look = creep.room.lookForAtArea(LOOK_STRUCTURES,10,5,11,7);

Get the list of objects with the given type at the specified room area.

parametertypedescription
typestring

One of the LOOK_* constants.

topnumber

The top Y boundary of the area.

leftnumber

The left X boundary of the area.

bottomnumber

The bottom Y boundary of the area.

rightnumber

The right X boundary of the area.

asArrayoptionalboolean

Set to true if you want to get the result as a plain array.

Return value

If asArray is set to false or undefined, the method returns an object with all the objects of the given type in the specified area in the following format:

If asArray is set to true, the method returns an array in the following format:

Any object with a position in a room. Almost all game objects prototypes are derived from RoomObject.

An object representing the position of this object in the room.

The link to the Room object. May be undefined in case if an object is a flag or a construction site and is placed in a room that is not visible to you.

An object representing the specified position in the room. Every RoomObject in the room contains RoomPosition as the pos property. The position object of a custom location can be obtained using the Room.getPositionAt method or using the constructor.

constructor(x, y, roomName)

const pos = new RoomPosition(10, 25, 'sim');

You can create new RoomPosition object using its constructor.

parametertypedescription
xnumber

X position in the room.

ynumber

Y position in the room.

roomNamestring

The room name.

roomNamestring

The name of the room.

xnumber

X position in the room.

ynumber

Y position in the room.

createConstructionSite(structureType)

Game.flags.Flag1.pos.createConstructionSite(STRUCTURE_ROAD);

Create new ConstructionSite at the specified location.

parametertypedescription
structureTypestring

One of the STRUCTURE_* constants.

Return value

One of the following codes:

constantvaluedescription
OK0

The operation has been scheduled successfully.

ERR_INVALID_TARGET-7

The structure cannot be placed at the specified location.

ERR_FULL-8

You have too many construction sites. The maximum number of construction sites per player is 100.

ERR_INVALID_ARGS-10

The location is incorrect.

ERR_RCL_NOT_ENOUGH-14

Room Controller Level insufficient. Learn more

createFlag([name], [color], [secondaryColor])

creep.pos.createFlag('Flag1');

Create new Flag at the specified location.

parametertypedescription
nameoptionalstring

The name of a new flag. It should be unique, i.e. the Game.flags object should not contain another flag with the same name (hash key). If not defined, a random name will be generated.

coloroptionalstring

The color of a new flag. Should be one of the COLOR_* constants. The default value is COLOR_WHITE.

secondaryColoroptionalstring

The secondary color of a new flag. Should be one of the COLOR_* constants. The default value is equal to color.

Return value

The name of a new flag, or one of the following error codes:

constantvaluedescription
ERR_NAME_EXISTS-3

There is a flag with the same name already.

ERR_INVALID_ARGS-10

The location or the color constant is incorrect.

findClosestByPath(type, [opts])(objects, [opts])

const target = creep.pos.findClosestByPath(FIND_MY_SPAWNS); creep.moveTo(target);const target = creep.pos.findClosestByPath(FIND_MY_SPAWNS, {maxOps: 500}); creep.moveTo(target);const target = creep.pos.findClosestByPath(FIND_HOSTILE_CREEPS, { filter: function(object) { return object.getActiveBodyparts(ATTACK) == 0; } });const target = creep.pos.findClosestByPath(FIND_HOSTILE_CREEPS, { filter: { owner: { username: 'Invader' } } });const targets = [ Game.creeps.John, Game.creeps.Mike, room.getPositionAt(10,10) ]; const closest = creep.pos.findClosestByPath(targets);

Find an object with the shortest path from the given position. Uses Jump Point Search algorithm and Dijkstra's algorithm.

parametertypedescription
typenumber

See Room.find.

objectsarray

An array of room's objects or RoomPosition objects that the search should be executed against.

optsoptionalobject

An object containing pathfinding options (see Room.findPath), or one of the following:

  • filter

    object, function, string

    Only the objects which pass the filter using the Lodash.filter method will be used.
  • algorithm

    string

    One of the following constants:
    • astar is faster when there are relatively few possible targets;
    • dijkstra is faster when there are a lot of possible targets or when the closest target is nearby.
    The default value is determined automatically using heuristics.

Return value

The closest object if found, null otherwise.

findClosestByRange(type, [opts])(objects, [opts])

const target = creep.pos.findClosestByRange(FIND_MY_SPAWNS); creep.moveTo(target);const target = creep.pos.findClosestByRange(FIND_HOSTILE_CREEPS, { filter: function(object) { return object.getActiveBodyparts(ATTACK) == 0; } });const target = creep.pos.findClosestByRange(FIND_HOSTILE_CREEPS, { filter: { owner: { username: 'Invader' } } });const targets = [ Game.creeps.John, Game.creeps.Mike, room.getPositionAt(10,10) ]; const closest = creep.pos.findClosestByRange(targets);

Find an object with the shortest linear distance from the given position.

parametertypedescription
typenumber

See Room.find.

objectsarray

An array of room's objects or RoomPosition objects that the search should be executed against.

optsoptionalobject

An object containing one of the following options:

  • filter

    object, function, string

    Only the objects which pass the filter using the Lodash.filter method will be used.

Return value

The closest object if found, null otherwise.

findInRange(type, range, [opts])(objects, range, [opts])

const targets = creep.pos.findInRange(FIND_HOSTILE_CREEPS, 3); if(targets.length > 0) { creep.rangedAttack(targets[0]); }const targets = [ Game.creeps.John, Game.creeps.Mike, room.getPositionAt(10,10) ]; const inRangeTargets = creep.pos.findInRange(targets, 3);

Find all objects in the specified linear range.

parametertypedescription
typenumber

See Room.find.

objectsarray

An array of room's objects or RoomPosition objects that the search should be executed against.

rangenumber

The range distance.

optsoptionalobject

See Room.find.

Return value

An array with the objects found.

findPathTo(x, y, [opts])(target, [opts])

const path = creep.pos.findPathTo(target); creep.move(path[0].direction);let path = creep.pos.findPathTo(target, {maxOps: 200}); if( !path.length || !target.equalsTo(path[path.length - 1]) ) { path = creep.pos.findPathTo(target, {maxOps: 1000, ignoreDestructibleStructures: true}); } if( path.length ) { creep.move(path[0].direction); }

Find an optimal path to the specified position using Jump Point Search algorithm. This method is a shorthand for Room.findPath. If the target is in another room, then the corresponding exit will be used as a target.

parametertypedescription
xnumber

X position in the room.

ynumber

Y position in the room.

targetobject

Can be a RoomPosition object or any object containing RoomPosition.

optsoptionalobject

An object containing pathfinding options flags (see Room.findPath for more details).

Return value

An array with path steps in the following format:

getDirectionTo(x,y)(target)

const direction = creep.pos.getDirectionTo(target); creep.move(direction);

Get linear direction to the specified position.

parametertypedescription
xnumber

X position in the room.

ynumber

Y position in the room.

targetobject

Can be a RoomPosition object or any object containing RoomPosition.

Return value

A number representing one of the direction constants.

getRangeTo(x,y)(target)

const range = creep.pos.getRangeTo(target); if(range <= 3) { creep.rangedAttack(target); }

Get linear range to the specified position.

parametertypedescription
xnumber

X position in the room.

ynumber

Y position in the room.

targetobject

Can be a RoomPosition object or any object containing RoomPosition.

Return value

A number of squares to the given position.

inRangeTo(x, y, range)(target, range)

if(creep.pos.inRangeTo(target, 3)) { creep.rangedAttack(target); }

Check whether this position is in the given range of another position.

parametertypedescription
xnumber

X position in the same room.

ynumber

Y position in the same room.

targetRoomPosition

The target position.

rangenumber

The range distance.

Return value

A boolean value.

isEqualTo(x,y)(target)

if(creep.pos.isEqualTo(10,25)) { creep.move(RIGHT); }if(creep.pos.isEqualTo(Game.flags.Flag1)) { creep.move(RIGHT); }

Check whether this position is the same as the specified position.

parametertypedescription
xnumber

X position in the room.

ynumber

Y position in the room.

targetobject

Can be a RoomPosition object or any object containing RoomPosition.

Return value

A boolean value.

isNearTo(x,y)(target)

if(creep.pos.isNearTo(target)) { creep.transferEnergy(target); }

Check whether this position is on the adjacent square to the specified position. The same as inRangeTo(target, 1).

parametertypedescription
xnumber

X position in the room.

ynumber

Y position in the room.

targetobject

Can be a RoomPosition object or any object containing RoomPosition.

Return value

A boolean value.

look()

const look = Game.flags.Flag1.pos.look(); look.forEach(function(lookObject) { if(lookObject.type == LOOK_CREEPS && lookObject[LOOK_CREEPS].getActiveBodyparts(ATTACK) == 0) { creep.moveTo(lookObject.creep); } });

Get the list of objects at the specified room position.

Return value

An array with objects at the specified position in the following format:

lookFor(type)

const found = Game.flags.Flag1.pos.lookFor(LOOK_CREEPS); if(found.length && found[0].getActiveBodyparts(ATTACK) == 0) { creep.moveTo(found[0]); }

Get an object with the given type at the specified room position.

parametertypedescription
typestring

One of the LOOK_* constants.

Return value

An array of objects of the given type at the specified position if found.

Room visuals provide a way to show various visual debug info in game rooms. You can use the RoomVisual object to draw simple shapes that are visible only to you. Every existing Room object already contains the visual property, but you also can create new RoomVisual objects for any room (even without visibility) using the constructor.

Room visuals are not stored in the database, their only purpose is to display something in your browser. All drawings will persist for one tick and will disappear if not updated. All RoomVisual API calls have no added CPU cost (their cost is natural and mostly related to simple JSON.serialize calls). However, there is a usage limit: you cannot post more than 500 KB of serialized data per one room (see getSize method).

All draw coordinates are measured in game coordinates and centered to tile centers, i.e. (10,10) will point to the center of the creep at x:10; y:10 position. Fractional coordinates are allowed.

constructor([roomName])

Game.rooms['W10N10'].visual.circle(10,20).line(0,0,10,20); new RoomVisual('W10N10').circle(10,20).line(0,0,10,20); new RoomVisual().text('Some text', 1, 1, {align: 'left'});

You can directly create new RoomVisual object in any room, even if it's invisible to your script.

parametertypedescription
roomNameoptionalstring

The room name. If undefined, visuals will be posted to all rooms simultaneously.

roomNamestring

The name of the room.

line(x1, y1, x2, y2, [style])(pos1, pos2, [style])

new RoomVisual('W1N1').line(10,15, 20,20);creep.room.visual.line(creep.pos, target.pos, {color: 'red', style: 'dashed'});

Draw a line.

parametertypedescription
x1number

The start X coordinate.

y1number

The start Y coordinate.

x2number

The finish X coordinate.

y2number

The finish Y coordinate.

pos1RoomPosition

The start position object.

pos2RoomPosition

The finish position object.

styleoptionalobject

An object with the following properties:

  • width

    number

    Line width, default is 0.1.

  • color

    string

    Line color in any web format, default is #ffffff (white).

  • opacity

    number

    Opacity value, default is 0.5.

  • lineStyle

    string

    Either undefined (solid line), dashed, or dotted. Default is undefined.

Return value

The RoomVisual object itself, so that you can chain calls.

circle(x, y, [style])(pos, [style])

new RoomVisual('W1N1').circle(10,15);creep.room.visual.circle(creep.pos, {fill: 'transparent', radius: 0.55, stroke: 'red'});

Draw a circle.

parametertypedescription
xnumber

The X coordinate of the center.

ynumber

The Y coordinate of the center.

posRoomPosition

The position object of the center.

styleoptionalobject

An object with the following properties:

  • radius

    number

    Circle radius, default is 0.15.

  • fill

    string

    Fill color in any web format, default is #ffffff (white).

  • opacity

    number

    Opacity value, default is 0.5.

  • stroke

    string

    Stroke color in any web format, default is undefined (no stroke).

  • strokeWidth

    number

    Stroke line width, default is 0.1.

  • lineStyle

    string

    Either undefined (solid line), dashed, or dotted. Default is undefined.

Return value

The RoomVisual object itself, so that you can chain calls.

rect(x, y, width, hheight, [style])(topLeftPos, width, height, [style])

new RoomVisual('W1N1').rect(1.5, 1.5, 9, 9); creep.room.visual.rect(creep.pos.x - 0.6, creep.pos.y - 0.6, 1.2, 1.2, {fill: 'transparent', stroke: '#f00'});

Draw a rectangle.

parametertypedescription
xnumber

The X coordinate of the top-left corner.

ynumber

The Y coordinate of the top-left corner.

topLeftPosRoomPosition

The position object of the top-left corner.

widthnumber

The width of the rectangle.

heightnumber

The height of the rectangle.

styleoptionalobject

An object with the following properties:

  • fill

    string

    Fill color in any web format, default is #ffffff (white).

  • opacity

    number

    Opacity value, default is 0.5.

  • stroke

    string

    Stroke color in any web format, default is undefined (no stroke).

  • strokeWidth

    number

    Stroke line width, default is 0.1.

  • lineStyle

    string

    Either undefined (solid line), dashed, or dotted. Default is undefined.

Return value

The RoomVisual object itself, so that you can chain calls.

poly(points, [style])

const points = []; points.push(creep1.pos); points.push([10,15]); points.push(new RoomPosition(20,21,'W1N1')); new RoomVisual('W1N1').poly(points, {fill: 'aqua'}); const path = Game.rooms['W1N1'].findPath(from, to); new RoomVisual('W1N1').poly(path, {stroke: '#fff', strokeWidth: .15, opacity: .2, lineStyle: 'dashed'});

Draw a polyline.

parametertypedescription
pointsarray

An array of points. Every item should be either an array with 2 numbers (i.e. [10,15]), or a RoomPosition object.

styleoptionalobject

An object with the following properties:

  • fill

    string

    Fill color in any web format, default is undefined (no fill).

  • opacity

    number

    Opacity value, default is 0.5.

  • stroke

    string

    Stroke color in any web format, default is #ffffff (white).

  • strokeWidth

    number

    Stroke line width, default is 0.1.

  • lineStyle

    string

    Either undefined (solid line), dashed, or dotted. Default is undefined.

Return value

The RoomVisual object itself, so that you can chain calls.

text(text, x, y, [style])(text, pos, [style])

new RoomVisual('W1N1').text("Target💥", 10, 15, {color: 'green', font: 0.8});

Draw a text label. You can use any valid Unicode characters, including emoji.

parametertypedescription
textstring

The text message.

xnumber

The X coordinate of the label baseline point.

ynumber

The Y coordinate of the label baseline point.

posRoomPosition

The position object of the label baseline.

styleoptionalobject

An object with the following properties:

  • color

    string

    Font color in any web format, default is #ffffff (white).

  • font

    number, string

    Either a number or a string in one of the following forms:
    • 0.7 - relative size in game coordinates
    • 20px - absolute size in pixels
    • 0.7 serif
    • bold italic 1.5 Times New Roman
  • stroke

    string

    Stroke color in any web format, default is undefined (no stroke).

  • strokeWidth

    number

    Stroke width, default is 0.15.

  • backgroundColor

    string

    Background color in any web format, default is undefined (no background). When background is enabled, text vertical align is set to middle (default is baseline).

  • backgroundPadding

    number

    Background rectangle padding, default is 0.3.

  • align

    string

    Text align, either center, left, or right. Default is center.

  • opacity

    number

    Opacity value, default is 1.0.

Return value

The RoomVisual object itself, so that you can chain calls.

clear()

new RoomVisual('W1N1').clear();

Remove all visuals from the room.

Return value

The RoomVisual object itself, so that you can chain calls.

getSize()

if(creep.room.visual.getSize() >= 512000) { }

Get the stored size of all visuals added in the room in the current tick. It must not exceed 512,000 (500 KB).

Return value

The size of the visuals in bytes.

An energy source object. Can be harvested by creeps with a WORK body part.

Energy amount 4000 in center rooms3000 in an owned or reserved room1500 in an unreserved room
Energy regeneration Every 300 game ticks

An object representing the position of this object in the room.

The link to the Room object. May be undefined in case if an object is a flag or a construction site and is placed in a room that is not visible to you.

energynumber

The remaining amount of energy.

energyCapacitynumber

The total amount of energy in the source.

idstring

A unique object identificator. You can use Game.getObjectById method to retrieve an object instance by its id.

ticksToRegenerationnumber

The remaining time after which the source will be refilled.

The base prototype object of all structures.

An object representing the position of this object in the room.

The link to the Room object. May be undefined in case if an object is a flag or a construction site and is placed in a room that is not visible to you.

hitsnumber

The current amount of hit points of the structure.

hitsMaxnumber

The total amount of hit points of the structure.

idstring

A unique object identificator. You can use Game.getObjectById method to retrieve an object instance by its id.

structureTypestring

One of the STRUCTURE_* constants.

destroy()

Destroy this structure immediately.

Return value

One of the following codes:

constantvaluedescription
OK0

The operation has been scheduled successfully.

ERR_NOT_OWNER-1

You are not the owner of this structure.

ERR_BUSY-4

Hostile creeps are in the room.

isActive()

Check whether this structure can be used. If room controller level is insufficient, then this method will return false, and the structure will be highlighted with red in the game.

Return value

A boolean value.

notifyWhenAttacked(enabled)

Toggle auto notification when the structure is under attack. The notification will be sent to your account email. Turned on by default.

parametertypedescription
enabledboolean

Whether to enable notification or disable.

Return value

One of the following codes:

constantvaluedescription
OK0

The operation has been scheduled successfully.

ERR_NOT_OWNER-1

You are not the owner of this structure.

ERR_INVALID_ARGS-10

enable argument is not a boolean value.

A small container that can be used to store resources. This is a walkable structure. All dropped resources automatically goes to the container at the same tile.

Controller level Any (including neutral rooms)
Available per room 5
Capacity 2,000
Cost 5,000
Hits 250,000
Decay Loses 5,000 hits every 500 ticks in an owned room, and every 100 ticks in an unowned room.

An object representing the position of this object in the room.

The link to the Room object. May be undefined in case if an object is a flag or a construction site and is placed in a room that is not visible to you.

hitsnumber

The current amount of hit points of the structure.

hitsMaxnumber

The total amount of hit points of the structure.

idstring

A unique object identificator. You can use Game.getObjectById method to retrieve an object instance by its id.

structureTypestring

One of the STRUCTURE_* constants.

destroy()

Destroy this structure immediately.

Return value

One of the following codes:

constantvaluedescription
OK0

The operation has been scheduled successfully.

ERR_NOT_OWNER-1

You are not the owner of this structure.

ERR_BUSY-4

Hostile creeps are in the room.

isActive()

Check whether this structure can be used. If room controller level is insufficient, then this method will return false, and the structure will be highlighted with red in the game.

Return value

A boolean value.

notifyWhenAttacked(enabled)

Toggle auto notification when the structure is under attack. The notification will be sent to your account email. Turned on by default.

parametertypedescription
enabledboolean

Whether to enable notification or disable.

Return value

One of the following codes:

constantvaluedescription
OK0

The operation has been scheduled successfully.

ERR_NOT_OWNER-1

You are not the owner of this structure.

ERR_INVALID_ARGS-10

enable argument is not a boolean value.

storeobject

const containersWithEnergy = room.find(FIND_STRUCTURES, { filter: (i) => i.structureType == STRUCTURE_CONTAINER && i.store[RESOURCE_ENERGY] > 0 });const total = _.sum(container.store);

An object with the structure contents. Each object key is one of the RESOURCE_* constants, values are resources amounts. RESOURCE_ENERGY is always defined and equals to 0 when empty, other resources are undefined when empty. You can use lodash.sum to get the total amount of contents.

storeCapacitynumber

The total amount of resources the structure can contain.

ticksToDecaynumber

The amount of game ticks when this container will lose some hit points.

transfer(target, resourceType, [amount])

This method is deprecated and will be removed soon. Please use Creep.withdraw instead.

const containers = creep.pos.findInRange(FIND_STRUCTURES, 1, {filter: {structureType: STRUCTURE_CONTAINER}}); containers[0].transfer(creep, RESOURCE_ENERGY);

Transfer resource from this structure to a creep. The target has to be at adjacent square.

parametertypedescription
targetCreep

The target object.

resourceTypestring

One of the RESOURCE_* constants.

amountoptionalnumber

The amount of resources to be transferred. If omitted, all the available amount is used.

Return value

One of the following codes:

constantvaluedescription
OK0

The operation has been scheduled successfully.

ERR_NOT_ENOUGH_RESOURCES-6

The structure does not have the given amount of energy.

ERR_INVALID_TARGET-7

The target is not a valid object which can contain energy.

ERR_FULL-8

The target cannot receive any more energy.

ERR_NOT_IN_RANGE-9

The target is too far away.

ERR_INVALID_ARGS-10

The energy amount is incorrect.

Claim this structure to take control over the room. The controller structure cannot be damaged or destroyed.

It can be addressed by Room.controller property.

Level Upgrade to next level Downgrade timer
1 200 energy 20,000 ticks
2 45,000 energy 5,000 ticks
3 135,000 energy 10,000 ticks
4 405,000 energy 20,000 ticks
5 1,215,000 energy 40,000 ticks
6 3,645,000 energy 60,000 ticks
7 10,935,000 energy 100,000 ticks
8 150,000 ticks

Safe mode

Effect Blocks attack, rangedAttack, rangedMassAttack, dismantle, heal, rangedHeal, attackController and withdraw methods of all hostile creeps in the room. Only one room can be in safe mode at the same time.When safe mode is active, all hostile creeps become visually transparent and passable - your creeps can move through them freely (but not vice versa).
Duration 20,000 ticks
Cooldown 50,000 ticks (no cooldown in Novice Areas)
Generation
  • Each new controller level generates one available activation
  • Can be generated by creeps using 1,000 ghodium
  • All available activations are reset if the controller is downgraded

An object representing the position of this object in the room.

The link to the Room object. May be undefined in case if an object is a flag or a construction site and is placed in a room that is not visible to you.

hitsnumber

The current amount of hit points of the structure.

hitsMaxnumber

The total amount of hit points of the structure.

idstring

A unique object identificator. You can use Game.getObjectById method to retrieve an object instance by its id.

structureTypestring

One of the STRUCTURE_* constants.

destroy()

Destroy this structure immediately.

Return value

One of the following codes:

constantvaluedescription
OK0

The operation has been scheduled successfully.

ERR_NOT_OWNER-1

You are not the owner of this structure.

ERR_BUSY-4

Hostile creeps are in the room.

isActive()

Check whether this structure can be used. If room controller level is insufficient, then this method will return false, and the structure will be highlighted with red in the game.

Return value

A boolean value.

notifyWhenAttacked(enabled)

Toggle auto notification when the structure is under attack. The notification will be sent to your account email. Turned on by default.

parametertypedescription
enabledboolean

Whether to enable notification or disable.

Return value

One of the following codes:

constantvaluedescription
OK0

The operation has been scheduled successfully.

ERR_NOT_OWNER-1

You are not the owner of this structure.

ERR_INVALID_ARGS-10

enable argument is not a boolean value.

Whether this is your own structure.

An object with the structure’s owner info containing the following properties:

parametertypedescription
usernamestring

The name of the owner user.

levelnumber

Current controller level, from 0 to 8.

progressnumber

The current progress of upgrading the controller to the next level.

progressTotalnumber

The progress needed to reach the next level.

reservationobject

An object with the controller reservation info if present:

parametertypedescription
usernamestring

The name of a player who reserved this controller.

ticksToEndnumber

The amount of game ticks when the reservation will end.

safeModenumber

How many ticks of safe mode remaining, or undefined.

safeModeAvailablenumber

Safe mode activations available to use.

safeModeCooldownnumber

During this period in ticks new safe mode activations will be blocked, undefined if cooldown is inactive.

signobject

An object with the controller sign info if present:

parametertypedescription
usernamestring

The name of a player who signed this controller.

textstring

The sign text.

timenumber

The sign time in game ticks.

datetimeDate

The sign real date.

ticksToDowngradenumber

The amount of game ticks when this controller will lose one level. This timer can be reset by using Creep.upgradeController.

upgradeBlockednumber

The amount of game ticks while this controller cannot be upgraded due to attack. Safe mode is also unavailable during this period.

activateSafeMode()

room.controller.activateSafeMode();

Activate safe mode if available.

Return value

One of the following codes:

constantvaluedescription
OK0

The operation has been scheduled successfully.

ERR_NOT_OWNER-1

You are not the owner of this controller.

ERR_BUSY-4

There is another room in safe mode already.

ERR_NOT_ENOUGH_RESOURCES-6

There is no safe mode activations available.

ERR_TIRED-11

The previous safe mode is still cooling down, or the controller is upgradeBlocked, or the controller is downgraded for 5000 ticks or more.

unclaim()

room.controller.unclaim();

Make your claimed controller neutral again.

Return value

One of the following codes:

constantvaluedescription
OK0

The operation has been scheduled successfully.

ERR_NOT_OWNER-1

You are not the owner of this controller.

Contains energy which can be spent on spawning bigger creeps. Extensions can be placed anywhere in the room, any spawns will be able to use them regardless of distance.

Controller level
1
2 5 extensions (50 capacity)
3 10 extensions (50 capacity)
4 20 extensions (50 capacity)
5 30 extensions (50 capacity)
6 40 extensions (50 capacity)
7 50 extensions (100 capacity)
8 60 extensions (200 capacity)
Cost 3,000
Hits 1,000

An object representing the position of this object in the room.

The link to the Room object. May be undefined in case if an object is a flag or a construction site and is placed in a room that is not visible to you.

hitsnumber

The current amount of hit points of the structure.

hitsMaxnumber

The total amount of hit points of the structure.

idstring

A unique object identificator. You can use Game.getObjectById method to retrieve an object instance by its id.

structureTypestring

One of the STRUCTURE_* constants.

destroy()

Destroy this structure immediately.

Return value

One of the following codes:

constantvaluedescription
OK0

The operation has been scheduled successfully.

ERR_NOT_OWNER-1

You are not the owner of this structure.

ERR_BUSY-4

Hostile creeps are in the room.

isActive()

Check whether this structure can be used. If room controller level is insufficient, then this method will return false, and the structure will be highlighted with red in the game.

Return value

A boolean value.

notifyWhenAttacked(enabled)

Toggle auto notification when the structure is under attack. The notification will be sent to your account email. Turned on by default.

parametertypedescription
enabledboolean

Whether to enable notification or disable.

Return value

One of the following codes:

constantvaluedescription
OK0

The operation has been scheduled successfully.

ERR_NOT_OWNER-1

You are not the owner of this structure.

ERR_INVALID_ARGS-10

enable argument is not a boolean value.

Whether this is your own structure.

An object with the structure’s owner info containing the following properties:

parametertypedescription
usernamestring

The name of the owner user.

energynumber

The amount of energy containing in the extension.

energyCapacitynumber

The total amount of energy the extension can contain.

transferEnergy(target, [amount])

This method is deprecated and will be removed soon. Please use Creep.withdraw instead.

Transfer the energy from the extension to a creep. You can transfer resources to your creeps from hostile structures as well.

parametertypedescription
targetCreep

The creep object which energy should be transferred to.

amountoptionalnumber

The amount of energy to be transferred. If omitted, all the remaining amount of energy will be used.

Return value

One of the following codes:

constantvaluedescription
OK0

The operation has been scheduled successfully.

ERR_NOT_OWNER-1

You are not the owner of the target creep, or there is a hostile rampart on top of the structure.

ERR_NOT_ENOUGH_RESOURCES-6

The extension contains less energy than the given amount.

ERR_INVALID_TARGET-7

The specified target object is not a creep.

ERR_FULL-8

The target creep can not carry the given amount of energy.

ERR_NOT_IN_RANGE-9

The target creep is too far away.

Allows to harvest a mineral deposit. Learn more about minerals from this article.

Controller level 6
Cost 5,000
Hits 500
Cooldown 5 ticks on each harvest action

An object representing the position of this object in the room.

The link to the Room object. May be undefined in case if an object is a flag or a construction site and is placed in a room that is not visible to you.

hitsnumber

The current amount of hit points of the structure.

hitsMaxnumber

The total amount of hit points of the structure.

idstring

A unique object identificator. You can use Game.getObjectById method to retrieve an object instance by its id.

structureTypestring

One of the STRUCTURE_* constants.

destroy()

Destroy this structure immediately.

Return value

One of the following codes:

constantvaluedescription
OK0

The operation has been scheduled successfully.

ERR_NOT_OWNER-1

You are not the owner of this structure.

ERR_BUSY-4

Hostile creeps are in the room.

isActive()

Check whether this structure can be used. If room controller level is insufficient, then this method will return false, and the structure will be highlighted with red in the game.

Return value

A boolean value.

notifyWhenAttacked(enabled)

Toggle auto notification when the structure is under attack. The notification will be sent to your account email. Turned on by default.

parametertypedescription
enabledboolean

Whether to enable notification or disable.

Return value

One of the following codes:

constantvaluedescription
OK0

The operation has been scheduled successfully.

ERR_NOT_OWNER-1

You are not the owner of this structure.

ERR_INVALID_ARGS-10

enable argument is not a boolean value.

Whether this is your own structure.

An object with the structure’s owner info containing the following properties:

parametertypedescription
usernamestring

The name of the owner user.

cooldownnumber

The amount of game ticks until the next harvest action is possible.

Non-player structure. Spawns NPC Source Keepers that guards energy sources and minerals in some rooms. This structure cannot be destroyed.

An object representing the position of this object in the room.

The link to the Room object. May be undefined in case if an object is a flag or a construction site and is placed in a room that is not visible to you.

hitsnumber

The current amount of hit points of the structure.

hitsMaxnumber

The total amount of hit points of the structure.

idstring

A unique object identificator. You can use Game.getObjectById method to retrieve an object instance by its id.

structureTypestring

One of the STRUCTURE_* constants.

destroy()

Destroy this structure immediately.

Return value

One of the following codes:

constantvaluedescription
OK0

The operation has been scheduled successfully.

ERR_NOT_OWNER-1

You are not the owner of this structure.

ERR_BUSY-4

Hostile creeps are in the room.

isActive()

Check whether this structure can be used. If room controller level is insufficient, then this method will return false, and the structure will be highlighted with red in the game.

Return value

A boolean value.

notifyWhenAttacked(enabled)

Toggle auto notification when the structure is under attack. The notification will be sent to your account email. Turned on by default.

parametertypedescription
enabledboolean

Whether to enable notification or disable.

Return value

One of the following codes:

constantvaluedescription
OK0

The operation has been scheduled successfully.

ERR_NOT_OWNER-1

You are not the owner of this structure.

ERR_INVALID_ARGS-10

enable argument is not a boolean value.

Whether this is your own structure.

An object with the structure’s owner info containing the following properties:

parametertypedescription
usernamestring

The name of the owner user.

ticksToSpawnnumber

Time to spawning of the next Source Keeper.

Produces mineral compounds from base minerals and boosts creeps. Learn more about minerals from this article.

Controller level
1-5
6 3 labs
7 6 labs
8 10 labs
Cost 50,000
Hits 500
Capacity 3000 mineral units, 2000 energy units
Produce 5 mineral compound units per reaction
Reaction cooldown 10 ticks
Distance to input labs 2 squares
Boost cost 30 mineral units, 20 energy units per body part

An object representing the position of this object in the room.

The link to the Room object. May be undefined in case if an object is a flag or a construction site and is placed in a room that is not visible to you.

hitsnumber

The current amount of hit points of the structure.

hitsMaxnumber

The total amount of hit points of the structure.

idstring

A unique object identificator. You can use Game.getObjectById method to retrieve an object instance by its id.

structureTypestring

One of the STRUCTURE_* constants.

destroy()

Destroy this structure immediately.

Return value

One of the following codes:

constantvaluedescription
OK0

The operation has been scheduled successfully.

ERR_NOT_OWNER-1

You are not the owner of this structure.

ERR_BUSY-4

Hostile creeps are in the room.

isActive()

Check whether this structure can be used. If room controller level is insufficient, then this method will return false, and the structure will be highlighted with red in the game.

Return value

A boolean value.

notifyWhenAttacked(enabled)

Toggle auto notification when the structure is under attack. The notification will be sent to your account email. Turned on by default.

parametertypedescription
enabledboolean

Whether to enable notification or disable.

Return value

One of the following codes:

constantvaluedescription
OK0

The operation has been scheduled successfully.

ERR_NOT_OWNER-1

You are not the owner of this structure.

ERR_INVALID_ARGS-10

enable argument is not a boolean value.

Whether this is your own structure.

An object with the structure’s owner info containing the following properties:

parametertypedescription
usernamestring

The name of the owner user.

cooldownnumber

The amount of game ticks the lab has to wait until the next reaction is possible.

energynumber

The amount of energy containing in the lab. Energy is used for boosting creeps.

energyCapacitynumber

The total amount of energy the lab can contain.

mineralAmountnumber

The amount of mineral resources containing in the lab.

mineralTypestring

The type of minerals containing in the lab. Labs can contain only one mineral type at the same time.

mineralCapacitynumber

The total amount of minerals the lab can contain.

boostCreep(creep, [bodyPartsCount])

Boosts creep body parts using the containing mineral compound. The creep has to be at adjacent square to the lab.

parametertypedescription
creepCreep

The target creep.

bodyPartsCountoptionalnumber

The number of body parts of the corresponding type to be boosted. Body parts are always counted left-to-right for TOUGH, and right-to-left for other types. If undefined, all the eligible body parts are boosted.

Return value

One of the following codes:

constantvaluedescription
OK0

The operation has been scheduled successfully.

ERR_NOT_OWNER-1

You are not the owner of this lab.

ERR_NOT_FOUND-5

The mineral containing in the lab cannot boost any of the creep's body parts.

ERR_NOT_ENOUGH_RESOURCES-6

The lab does not have enough energy or minerals.

ERR_INVALID_TARGET-7

The targets is not valid creep object.

ERR_NOT_IN_RANGE-9

The targets are too far away.

runReaction(lab1, lab2)

Produce mineral compounds using reagents from two other labs. The same input labs can be used by many output labs.

Return value

One of the following codes:

constantvaluedescription
OK0

The operation has been scheduled successfully.

ERR_NOT_OWNER-1

You are not the owner of this lab.

ERR_NOT_ENOUGH_RESOURCES-6

The source lab do not have enough resources.

ERR_INVALID_TARGET-7

The targets are not valid lab objects.

ERR_FULL-8

The target cannot receive any more energy.

ERR_NOT_IN_RANGE-9

The targets are too far away.

ERR_INVALID_ARGS-10

The reaction cannot be run using this resources.

ERR_TIRED-11

The lab is still cooling down.

transfer(target, resourceType, [amount])

This method is deprecated and will be removed soon. Please use Creep.withdraw instead.

Transfer resource from this structure to a creep. The target has to be at adjacent square. You can transfer resources to your creeps from hostile structures as well.

parametertypedescription
targetCreep

The target object.

resourceTypestring

One of the RESOURCE_* constants.

amountoptionalnumber

The amount of resources to be transferred. If omitted, all the available amount is used.

Return value

One of the following codes:

constantvaluedescription
OK0

The operation has been scheduled successfully.

ERR_NOT_OWNER-1

You are not the owner of the target creep, or there is a hostile rampart on top of the structure.

ERR_NOT_ENOUGH_RESOURCES-6

The creep does not have the given amount of resources.

ERR_INVALID_TARGET-7

The target is not a valid Creep object.

ERR_FULL-8

The target cannot receive any more energy.

ERR_NOT_IN_RANGE-9

The target is too far away.

ERR_INVALID_ARGS-10

The amount or resource type is incorrect.

Remotely transfers energy to another Link in the same room.

Controller level
1-4
5 2 links
6 3 links
7 4 links
8 6 links
Cost 5,000
Hits 1,000
Capacity 800
Cooldown time 1 tick per tile of the linear distance to the target
Energy loss 3%

An object representing the position of this object in the room.

The link to the Room object. May be undefined in case if an object is a flag or a construction site and is placed in a room that is not visible to you.

hitsnumber

The current amount of hit points of the structure.

hitsMaxnumber

The total amount of hit points of the structure.

idstring

A unique object identificator. You can use Game.getObjectById method to retrieve an object instance by its id.

structureTypestring

One of the STRUCTURE_* constants.

destroy()

Destroy this structure immediately.

Return value

One of the following codes:

constantvaluedescription
OK0

The operation has been scheduled successfully.

ERR_NOT_OWNER-1

You are not the owner of this structure.

ERR_BUSY-4

Hostile creeps are in the room.

isActive()

Check whether this structure can be used. If room controller level is insufficient, then this method will return false, and the structure will be highlighted with red in the game.

Return value

A boolean value.

notifyWhenAttacked(enabled)

Toggle auto notification when the structure is under attack. The notification will be sent to your account email. Turned on by default.

parametertypedescription
enabledboolean

Whether to enable notification or disable.

Return value

One of the following codes:

constantvaluedescription
OK0

The operation has been scheduled successfully.

ERR_NOT_OWNER-1

You are not the owner of this structure.

ERR_INVALID_ARGS-10

enable argument is not a boolean value.

Whether this is your own structure.

An object with the structure’s owner info containing the following properties:

parametertypedescription
usernamestring

The name of the owner user.

cooldownnumber

The amount of game ticks the link has to wait until the next transfer is possible.

energynumber

The amount of energy containing in the link.

energyCapacitynumber

The total amount of energy the link can contain.

transferEnergy(target, [amount])

const linkFrom = Game.rooms['W1N1'].lookForAt('structure', 10, 25)[0]; const linkTo = linkFrom.pos.findInRange(FIND_MY_STRUCTURES, 2, {filter: {structureType: STRUCTURE_LINK}})[0]; linkFrom.transferEnergy(linkTo);

Remotely transfer energy to another link at any location in the same room.

parametertypedescription
targetStructureLink

The target object.

amountoptionalnumber

The amount of energy to be transferred. If omitted, all the available energy is used.

Return value

One of the following codes:

constantvaluedescription
OK0

The operation has been scheduled successfully.

ERR_NOT_OWNER-1

You are not the owner of this link.

ERR_NOT_ENOUGH_RESOURCES-6

The structure does not have the given amount of energy.

ERR_INVALID_TARGET-7

The target is not a valid StructureLink object.

ERR_FULL-8

The target cannot receive any more energy.

ERR_INVALID_ARGS-10

The energy amount is incorrect.

ERR_TIRED-11

The link is still cooling down.

ERR_RCL_NOT_ENOUGH-14

Room Controller Level insufficient to use this link.

Launches a nuke to another room dealing huge damage to the landing area. Each launch has a cooldown and requires energy and ghodium resources. Launching creates a Nuke object at the target room position which is visible to any player until it is landed. Incoming nuke cannot be moved or cancelled. Nukes cannot be launched from or to novice rooms. Resources placed into a StructureNuker cannot be withdrawn.

Controller level
1-7
8 1 nuke
Cost 100,000
Hits 1,000
Range 10 rooms
Launch cost 300,000 energy5,000 ghodium
Launch cooldown 100,000 ticks
Landing time 50,000 ticks
Effect All creeps, construction sites and dropped resources in the room are removed immediately, even inside ramparts. Damage to structures:
  • 10,000,000 hits at the landing position;
  • 5,000,000 hits to all structures in 5x5 area.

Note that you can stack multiple nukes from different rooms at the same target position to increase damage.

If the room is in safe mode, then the safe mode is cancelled immediately, and the safe mode cooldown is reset to 0.

The room controller is hit by triggering upgradeBlocked period, which means it is unavailable to activate safe mode again within the next 200 ticks.

An object representing the position of this object in the room.

The link to the Room object. May be undefined in case if an object is a flag or a construction site and is placed in a room that is not visible to you.

hitsnumber

The current amount of hit points of the structure.

hitsMaxnumber

The total amount of hit points of the structure.

idstring

A unique object identificator. You can use Game.getObjectById method to retrieve an object instance by its id.

structureTypestring

One of the STRUCTURE_* constants.

destroy()

Destroy this structure immediately.

Return value

One of the following codes:

constantvaluedescription
OK0

The operation has been scheduled successfully.

ERR_NOT_OWNER-1

You are not the owner of this structure.

ERR_BUSY-4

Hostile creeps are in the room.

isActive()

Check whether this structure can be used. If room controller level is insufficient, then this method will return false, and the structure will be highlighted with red in the game.

Return value

A boolean value.

notifyWhenAttacked(enabled)

Toggle auto notification when the structure is under attack. The notification will be sent to your account email. Turned on by default.

parametertypedescription
enabledboolean

Whether to enable notification or disable.

Return value

One of the following codes:

constantvaluedescription
OK0

The operation has been scheduled successfully.

ERR_NOT_OWNER-1

You are not the owner of this structure.

ERR_INVALID_ARGS-10

enable argument is not a boolean value.

Whether this is your own structure.

An object with the structure’s owner info containing the following properties:

parametertypedescription
usernamestring

The name of the owner user.

energynumber

The amount of energy containing in this structure.

energyCapacitynumber

The total amount of energy this structure can contain.

ghodiumnumber

The amount of ghodium containing in this structure.

ghodiumCapacitynumber

The total amount of ghodium this structure can contain.

cooldownnumber

The amount of game ticks until the next launch is possible.

launchNuke(pos)

nuker.launchNuke(new RoomPosition(20,30, 'W1N1'));

Launch a nuke to the specified position.

parametertypedescription
posRoomPosition

The target room position.

Return value

One of the following codes:

constantvaluedescription
OK0

The operation has been scheduled successfully.

ERR_NOT_OWNER-1

You are not the owner of this structure.

ERR_NOT_ENOUGH_RESOURCES-6

The structure does not have enough energy and/or ghodium.

ERR_INVALID_TARGET-7

The target is not a valid RoomPosition.

ERR_NOT_IN_RANGE-9

The target room is out of range.

ERR_TIRED-11

This structure is still cooling down.

ERR_RCL_NOT_ENOUGH-14

Room Controller Level insufficient to use this structure.

Provides visibility into a distant room from your script.

Controller level
1-7
8 1 observer
Cost 8,000
Hits 500
Range 10 rooms

An object representing the position of this object in the room.

The link to the Room object. May be undefined in case if an object is a flag or a construction site and is placed in a room that is not visible to you.

hitsnumber

The current amount of hit points of the structure.

hitsMaxnumber

The total amount of hit points of the structure.

idstring

A unique object identificator. You can use Game.getObjectById method to retrieve an object instance by its id.

structureTypestring

One of the STRUCTURE_* constants.

destroy()

Destroy this structure immediately.

Return value

One of the following codes:

constantvaluedescription
OK0

The operation has been scheduled successfully.

ERR_NOT_OWNER-1

You are not the owner of this structure.

ERR_BUSY-4

Hostile creeps are in the room.

isActive()

Check whether this structure can be used. If room controller level is insufficient, then this method will return false, and the structure will be highlighted with red in the game.

Return value

A boolean value.

notifyWhenAttacked(enabled)

Toggle auto notification when the structure is under attack. The notification will be sent to your account email. Turned on by default.

parametertypedescription
enabledboolean

Whether to enable notification or disable.

Return value

One of the following codes:

constantvaluedescription
OK0

The operation has been scheduled successfully.

ERR_NOT_OWNER-1

You are not the owner of this structure.

ERR_INVALID_ARGS-10

enable argument is not a boolean value.

Whether this is your own structure.

An object with the structure’s owner info containing the following properties:

parametertypedescription
usernamestring

The name of the owner user.

observeRoom(roomName)

Provide visibility into a distant room from your script. The target room object will be available on the next tick.

parametertypedescription
roomNamestring

The name of the target room.

Return value

One of the following codes:

constantvaluedescription
OK0

The operation has been scheduled successfully.

ERR_NOT_IN_RANGE-9

Room roomName is not in observing range.

ERR_INVALID_ARGS-10

roomName argument is not a valid room name value.

ERR_RCL_NOT_ENOUGH-14

Room Controller Level insufficient to use this structure.

Non-player structure. Contains power resource which can be obtained by destroying the structure. Hits the attacker creep back on each attack. Learn more about power from this article.

Hits 2,000,000
Return damage 50%
Capacity 500 — 10,000
Decay 5,000 ticks

An object representing the position of this object in the room.

The link to the Room object. May be undefined in case if an object is a flag or a construction site and is placed in a room that is not visible to you.

hitsnumber

The current amount of hit points of the structure.

hitsMaxnumber

The total amount of hit points of the structure.

idstring

A unique object identificator. You can use Game.getObjectById method to retrieve an object instance by its id.

structureTypestring

One of the STRUCTURE_* constants.

destroy()

Destroy this structure immediately.

Return value

One of the following codes:

constantvaluedescription
OK0

The operation has been scheduled successfully.

ERR_NOT_OWNER-1

You are not the owner of this structure.

ERR_BUSY-4

Hostile creeps are in the room.

isActive()

Check whether this structure can be used. If room controller level is insufficient, then this method will return false, and the structure will be highlighted with red in the game.

Return value

A boolean value.

notifyWhenAttacked(enabled)

Toggle auto notification when the structure is under attack. The notification will be sent to your account email. Turned on by default.

parametertypedescription
enabledboolean

Whether to enable notification or disable.

Return value

One of the following codes:

constantvaluedescription
OK0

The operation has been scheduled successfully.

ERR_NOT_OWNER-1

You are not the owner of this structure.

ERR_INVALID_ARGS-10

enable argument is not a boolean value.

powernumber

The amount of power containing.

ticksToDecaynumber

The amount of game ticks when this structure will disappear.

Processes power into your account, and spawns power creeps with special unique powers (in development). Learn more about power from this article.

Controller level
1-7
8 1 power spawn
Cost 100,000
Hits 5,000
Capacity 5,000 energy units, 100 power units
Processing cost 50 energy units per 1 power unit
Processing speed 1 power unit per tick

An object representing the position of this object in the room.

The link to the Room object. May be undefined in case if an object is a flag or a construction site and is placed in a room that is not visible to you.

hitsnumber

The current amount of hit points of the structure.

hitsMaxnumber

The total amount of hit points of the structure.

idstring

A unique object identificator. You can use Game.getObjectById method to retrieve an object instance by its id.

structureTypestring

One of the STRUCTURE_* constants.

destroy()

Destroy this structure immediately.

Return value

One of the following codes:

constantvaluedescription
OK0

The operation has been scheduled successfully.

ERR_NOT_OWNER-1

You are not the owner of this structure.

ERR_BUSY-4

Hostile creeps are in the room.

isActive()

Check whether this structure can be used. If room controller level is insufficient, then this method will return false, and the structure will be highlighted with red in the game.

Return value

A boolean value.

notifyWhenAttacked(enabled)

Toggle auto notification when the structure is under attack. The notification will be sent to your account email. Turned on by default.

parametertypedescription
enabledboolean

Whether to enable notification or disable.

Return value

One of the following codes:

constantvaluedescription
OK0

The operation has been scheduled successfully.

ERR_NOT_OWNER-1

You are not the owner of this structure.

ERR_INVALID_ARGS-10

enable argument is not a boolean value.

Whether this is your own structure.

An object with the structure’s owner info containing the following properties:

parametertypedescription
usernamestring

The name of the owner user.

energynumber

The amount of energy containing in this structure.

energyCapacitynumber

The total amount of energy this structure can contain.

powernumber

The amount of power containing in this structure.

powerCapacitynumber

The total amount of power this structure can contain.

createPowerCreep(name)

Create a power creep. This method is under development.

parametertypedescription
roomNamestring

The name of the power creep.

processPower()

Register power resource units into your account. Registered power allows to develop power creeps skills.

Return value

One of the following codes:

constantvaluedescription
OK0

The operation has been scheduled successfully.

ERR_NOT_ENOUGH_RESOURCES-6

The structure does not have enough energy or power resource units.

ERR_RCL_NOT_ENOUGH-14

Room Controller Level insufficient to use this structure.

transferEnergy(target, [amount])

This method is deprecated and will be removed soon. Please use Creep.withdraw instead.

Transfer the energy from this structure to a creep. You can transfer resources to your creeps from hostile structures as well.

parametertypedescription
targetCreep

The creep object which energy should be transferred to.

amountoptionalnumber

The amount of energy to be transferred. If omitted, all the remaining amount of energy will be used.

Return value

One of the following codes:

constantvaluedescription
OK0

The operation has been scheduled successfully.

ERR_NOT_OWNER-1

You are not the owner of the target creep, or there is a hostile rampart on top of the structure.

ERR_NOT_ENOUGH_RESOURCES-6

This structure less energy than the given amount.

ERR_INVALID_TARGET-7

The specified target object is not a creep.

ERR_FULL-8

The target creep can not carry the given amount of energy.

ERR_NOT_IN_RANGE-9

The target creep is too far away.

A non-player structure. Instantly teleports your creeps to a distant room acting as a room exit tile. Portals appear randomly in the central room of each sector.

Stable time 10 days
Decay time 30,000 ticks

An object representing the position of this object in the room.

The link to the Room object. May be undefined in case if an object is a flag or a construction site and is placed in a room that is not visible to you.

hitsnumber

The current amount of hit points of the structure.

hitsMaxnumber

The total amount of hit points of the structure.

idstring

A unique object identificator. You can use Game.getObjectById method to retrieve an object instance by its id.

structureTypestring

One of the STRUCTURE_* constants.

destroy()

Destroy this structure immediately.

Return value

One of the following codes:

constantvaluedescription
OK0

The operation has been scheduled successfully.

ERR_NOT_OWNER-1

You are not the owner of this structure.

ERR_BUSY-4

Hostile creeps are in the room.

isActive()

Check whether this structure can be used. If room controller level is insufficient, then this method will return false, and the structure will be highlighted with red in the game.

Return value

A boolean value.

notifyWhenAttacked(enabled)

Toggle auto notification when the structure is under attack. The notification will be sent to your account email. Turned on by default.

parametertypedescription
enabledboolean

Whether to enable notification or disable.

Return value

One of the following codes:

constantvaluedescription
OK0

The operation has been scheduled successfully.

ERR_NOT_OWNER-1

You are not the owner of this structure.

ERR_INVALID_ARGS-10

enable argument is not a boolean value.

If this is an inter-room portal, then this property contains a RoomPosition object leading to the point in the destination room.

If this is an inter-shard portal, then this property contains an object with shard and room string properties. Exact coordinates are undetermined, the creep will appear at any free spot in the destination room.

ticksToDecaynumber

The amount of game ticks when the portal disappears, or undefined when the portal is stable.

Blocks movement of hostile creeps, and defends your creeps and structures on the same tile. Can be used as a controllable gate.

Controller level
1
2 300,000 max hits
3 1,000,000 max hits
4 3,000,000 max hits
5 10,000,000 max hits
6 30,000,000 max hits
7 100,000,000 max hits
8 300,000,000 max hits
Cost 1
Hits when constructed 1
Decay Loses 300 hits every 100 ticks

An object representing the position of this object in the room.

The link to the Room object. May be undefined in case if an object is a flag or a construction site and is placed in a room that is not visible to you.

hitsnumber

The current amount of hit points of the structure.

hitsMaxnumber

The total amount of hit points of the structure.

idstring

A unique object identificator. You can use Game.getObjectById method to retrieve an object instance by its id.

structureTypestring

One of the STRUCTURE_* constants.

destroy()

Destroy this structure immediately.

Return value

One of the following codes:

constantvaluedescription
OK0

The operation has been scheduled successfully.

ERR_NOT_OWNER-1

You are not the owner of this structure.

ERR_BUSY-4

Hostile creeps are in the room.

isActive()

Check whether this structure can be used. If room controller level is insufficient, then this method will return false, and the structure will be highlighted with red in the game.

Return value

A boolean value.

notifyWhenAttacked(enabled)

Toggle auto notification when the structure is under attack. The notification will be sent to your account email. Turned on by default.

parametertypedescription
enabledboolean

Whether to enable notification or disable.

Return value

One of the following codes:

constantvaluedescription
OK0

The operation has been scheduled successfully.

ERR_NOT_OWNER-1

You are not the owner of this structure.

ERR_INVALID_ARGS-10

enable argument is not a boolean value.

Whether this is your own structure.

An object with the structure’s owner info containing the following properties:

parametertypedescription
usernamestring

The name of the owner user.

isPublicboolean

If false (default), only your creeps can step on the same square. If true, any hostile creeps can pass through.

ticksToDecaynumber

The amount of game ticks when this rampart will lose some hit points.

setPublic(isPublic)

Make this rampart public to allow other players' creeps to pass through.

parametertypedescription
isPublicboolean

Whether this rampart should be public or non-public.

Return value

One of the following codes:

constantvaluedescription
OK0

The operation has been scheduled successfully.

ERR_NOT_OWNER-1

You are not the owner of this structure.

Decreases movement cost to 1. Using roads allows creating creeps with less MOVE body parts.

Controller level Any (including neutral rooms)
Cost
  • 300 at plain land
  • 1,500 at swamp
Hits
  • 5,000 at plain land
  • 25,000 at swamp
Decay
  • Loses 100 hits every 1,000 ticks at plain land
  • Loses 500 hits every 1,000 ticks at swamp
Note: every creep step decreases the decay timer for 1 tick per each creep body part

An object representing the position of this object in the room.

The link to the Room object. May be undefined in case if an object is a flag or a construction site and is placed in a room that is not visible to you.

hitsnumber

The current amount of hit points of the structure.

hitsMaxnumber

The total amount of hit points of the structure.

idstring

A unique object identificator. You can use Game.getObjectById method to retrieve an object instance by its id.

structureTypestring

One of the STRUCTURE_* constants.

destroy()

Destroy this structure immediately.

Return value

One of the following codes:

constantvaluedescription
OK0

The operation has been scheduled successfully.

ERR_NOT_OWNER-1

You are not the owner of this structure.

ERR_BUSY-4

Hostile creeps are in the room.

isActive()

Check whether this structure can be used. If room controller level is insufficient, then this method will return false, and the structure will be highlighted with red in the game.

Return value

A boolean value.

notifyWhenAttacked(enabled)

Toggle auto notification when the structure is under attack. The notification will be sent to your account email. Turned on by default.

parametertypedescription
enabledboolean

Whether to enable notification or disable.

Return value

One of the following codes:

constantvaluedescription
OK0

The operation has been scheduled successfully.

ERR_NOT_OWNER-1

You are not the owner of this structure.

ERR_INVALID_ARGS-10

enable argument is not a boolean value.

ticksToDecaynumber

The amount of game ticks when this road will lose some hit points.

Spawn is your colony center. This structure can create, renew, and recycle creeps. All your spawns are accessible through Game.spawns hash list. Spawns auto-regenerate a little amount of energy each tick, so that you can easily recover even if all your creeps died.

Controller level
1-6 1 spawn
7 2 spawns
8 3 spawns
Cost 15,000
Hits 5,000
Capacity 300
Spawn time 3 ticks per each body part
Energy auto-regeneration 1 energy unit per tick while energy available in the room (in all spawns and extensions) is less than 300

An object representing the position of this object in the room.

The link to the Room object. May be undefined in case if an object is a flag or a construction site and is placed in a room that is not visible to you.

hitsnumber

The current amount of hit points of the structure.

hitsMaxnumber

The total amount of hit points of the structure.

idstring

A unique object identificator. You can use Game.getObjectById method to retrieve an object instance by its id.

structureTypestring

One of the STRUCTURE_* constants.

destroy()

Destroy this structure immediately.

Return value

One of the following codes:

constantvaluedescription
OK0

The operation has been scheduled successfully.

ERR_NOT_OWNER-1

You are not the owner of this structure.

ERR_BUSY-4

Hostile creeps are in the room.

isActive()

Check whether this structure can be used. If room controller level is insufficient, then this method will return false, and the structure will be highlighted with red in the game.

Return value

A boolean value.

notifyWhenAttacked(enabled)

Toggle auto notification when the structure is under attack. The notification will be sent to your account email. Turned on by default.

parametertypedescription
enabledboolean

Whether to enable notification or disable.

Return value

One of the following codes:

constantvaluedescription
OK0

The operation has been scheduled successfully.

ERR_NOT_OWNER-1

You are not the owner of this structure.

ERR_INVALID_ARGS-10

enable argument is not a boolean value.

Whether this is your own structure.

An object with the structure’s owner info containing the following properties:

parametertypedescription
usernamestring

The name of the owner user.

energynumber

The amount of energy containing in the spawn.

energyCapacitynumber

The total amount of energy the spawn can contain

memoryany

spawn.memory.queue = [];

A shorthand to Memory.spawns[spawn.name]. You can use it for quick access the spawn’s specific memory data object. Learn more about memory

namestring

Spawn’s name. You choose the name upon creating a new spawn, and it cannot be changed later. This name is a hash key to access the spawn via the Game.spawns object.

spawningobject, null

If the spawn is in process of spawning a new creep, this object will contain the new creep’s information, or null otherwise.

parametertypedescription
namestring

The name of a new creep.

needTimenumber

Time needed in total to complete the spawning.

remainingTimenumber

Remaining time to go.

canCreateCreep(body, [name])

if(spawn.canCreateCreep(body, name) == OK) { spawn.createCreep(body, name); }

Check if a creep can be created.

parametertypedescription
bodyarray<string>

An array describing the new creep’s body. Should contain 1 to 50 elements with one of these constants:

  • WORK
  • MOVE
  • CARRY
  • ATTACK
  • RANGED_ATTACK
  • HEAL
  • TOUGH
  • CLAIM
nameoptionalstring

The name of a new creep. It should be unique creep name, i.e. the Game.creeps object should not contain another creep with the same name (hash key). If not defined, a random name will be generated.

Return value

One of the following codes:

constantvaluedescription
OK0

A creep with the given body and name can be created.

ERR_NOT_OWNER-1

You are not the owner of this spawn.

ERR_NAME_EXISTS-3

There is a creep with the same name already.

ERR_BUSY-4

The spawn is already in process of spawning another creep.

ERR_NOT_ENOUGH_ENERGY-6

The spawn and its extensions contain not enough energy to create a creep with the given body.

ERR_INVALID_ARGS-10

Body is not properly described.

ERR_RCL_NOT_ENOUGH-14

Your Room Controller level is insufficient to use this spawn.

createCreep(body, [name], [memory])

Game.spawns['Spawn1'].createCreep([WORK, CARRY, MOVE], 'Worker1');Game.spawns['Spawn1'].createCreep([WORK, CARRY, MOVE], null, {role: 'harvester'});const result = Game.spawns['Spawn1'].createCreep([WORK, CARRY, MOVE]); if(_.isString(result)) { console.log('The name is: '+result); } else { console.log('Spawn error: '+result); }

Start the creep spawning process. The required energy amount can be withdrawn from all spawns and extensions in the room.

parametertypedescription
bodyarray<string>

An array describing the new creep’s body. Should contain 1 to 50 elements with one of these constants:

  • WORK
  • MOVE
  • CARRY
  • ATTACK
  • RANGED_ATTACK
  • HEAL
  • TOUGH
  • CLAIM
nameoptionalstring

The name of a new creep. It should be unique creep name, i.e. the Game.creeps object should not contain another creep with the same name (hash key). If not defined, a random name will be generated.

memoryoptionalany

The memory of a new creep. If provided, it will be immediately stored into Memory.creeps[name].

Return value

The name of a new creep or one of these error codes:

constantvaluedescription
ERR_NOT_OWNER-1

You are not the owner of this spawn.

ERR_NAME_EXISTS-3

There is a creep with the same name already.

ERR_BUSY-4

The spawn is already in process of spawning another creep.

ERR_NOT_ENOUGH_ENERGY-6

The spawn and its extensions contain not enough energy to create a creep with the given body.

ERR_INVALID_ARGS-10

Body is not properly described.

ERR_RCL_NOT_ENOUGH-14

Your Room Controller level is insufficient to use this spawn.

spawnCreep(body, name, [opts])

Game.spawns['Spawn1'].spawnCreep([WORK, CARRY, MOVE], 'Worker1');Game.spawns['Spawn1'].spawnCreep([WORK, CARRY, MOVE], 'Worker1', { memory: {role: 'harvester'} });Game.spawns['Spawn1'].spawnCreep([WORK, CARRY, MOVE], 'Worker1', { energyStructures: [ Game.spawns['Spawn1'], Game.getObjectById('anExtensionId') ] });var testIfCanSpawn = Game.spawns['Spawn1'].spawnCreep([WORK, CARRY, MOVE], 'Worker1', { dryRun: true });

Start the creep spawning process. The required energy amount can be withdrawn from all spawns and extensions in the room.

parametertypedescription
bodyarray<string>

An array describing the new creep’s body. Should contain 1 to 50 elements with one of these constants:

  • WORK
  • MOVE
  • CARRY
  • ATTACK
  • RANGED_ATTACK
  • HEAL
  • TOUGH
  • CLAIM
namestring

The name of a new creep. It must be a unique creep name, i.e. the Game.creeps object should not contain another creep with the same name (hash key).

optsoptionalobject

An object with additional options for the spawning process.

  • memory

    any

    Memory of the new creep. If provided, it will be immediately stored into Memory.creeps[name].

  • energyStructures

    array

    Array of spawns/extensions from which to draw energy for the spawning process. Structures will be used according to the array order.

  • dryRun

    boolean

    If dryRun is true, the operation will only check if it is possible to create a creep.

Return value

One of the following codes:

constantvaluedescription
OK0

The operation has been scheduled successfully.

ERR_NOT_OWNER-1

You are not the owner of this spawn.

ERR_NAME_EXISTS-3

There is a creep with the same name already.

ERR_BUSY-4

The spawn is already in process of spawning another creep.

ERR_NOT_ENOUGH_ENERGY-6

The spawn and its extensions contain not enough energy to create a creep with the given body.

ERR_INVALID_ARGS-10

Body is not properly described or name was not provided.

ERR_RCL_NOT_ENOUGH-14

Your Room Controller level is insufficient to use this spawn.

recycleCreep(target)

Kill the creep and drop up to 100% of resources spent on its spawning and boosting depending on remaining life time. The target should be at adjacent square.

parametertypedescription
targetCreep

The target creep object.

Return value

One of the following codes:

constantvaluedescription
OK0

The operation has been scheduled successfully.

ERR_NOT_OWNER-1

You are not the owner of this spawn or the target creep.

ERR_INVALID_TARGET-7

The specified target object is not a creep.

ERR_NOT_IN_RANGE-9

The target creep is too far away.

renewCreep(target)

Increase the remaining time to live of the target creep. The target should be at adjacent square. The spawn should not be busy with the spawning process. Each execution increases the creep's timer by amount of ticks according to this formula:

Energy required for each execution is determined using this formula:

Renewing a creep removes all of its boosts.

parametertypedescription
targetCreep

The target creep object.

Return value

One of the following codes:

constantvaluedescription
OK0

The operation has been scheduled successfully.

ERR_NOT_OWNER-1

You are not the owner of the spawn, or the creep.

ERR_BUSY-4

The spawn is spawning another creep.

ERR_NOT_ENOUGH_ENERGY-6

The spawn does not have enough energy.

ERR_INVALID_TARGET-7

The specified target object is not a creep.

ERR_FULL-8

The target creep's time to live timer is full.

ERR_NOT_IN_RANGE-9

The target creep is too far away.

transferEnergy(target, [amount])

This method is deprecated and will be removed soon. Please use Creep.withdraw instead.

Transfer the energy from the spawn to a creep.

parametertypedescription
targetCreep

The creep object which energy should be transferred to.

amountoptionalnumber

The amount of energy to be transferred. If omitted, all the remaining amount of energy will be used.

Return value

One of the following codes:

constantvaluedescription
OK0

The operation has been scheduled successfully.

ERR_NOT_OWNER-1

You are not the owner of this spawn.

ERR_NOT_ENOUGH_ENERGY-6

The spawn contains less energy than the given amount.

ERR_INVALID_TARGET-7

The specified target object is not a creep.

ERR_FULL-8

The target creep can not carry the given amount of energy.

ERR_NOT_IN_RANGE-9

The target creep is too far away.

A structure that can store huge amount of resource units. Only one structure per room is allowed that can be addressed by Room.storage property.

Controller level
1-3
4-8 1 storage
Cost 30,000
Hits 10,000
Capacity 1,000,000

An object representing the position of this object in the room.

The link to the Room object. May be undefined in case if an object is a flag or a construction site and is placed in a room that is not visible to you.

hitsnumber

The current amount of hit points of the structure.

hitsMaxnumber

The total amount of hit points of the structure.

idstring

A unique object identificator. You can use Game.getObjectById method to retrieve an object instance by its id.

structureTypestring

One of the STRUCTURE_* constants.

destroy()

Destroy this structure immediately.

Return value

One of the following codes:

constantvaluedescription
OK0

The operation has been scheduled successfully.

ERR_NOT_OWNER-1

You are not the owner of this structure.

ERR_BUSY-4

Hostile creeps are in the room.

isActive()

Check whether this structure can be used. If room controller level is insufficient, then this method will return false, and the structure will be highlighted with red in the game.

Return value

A boolean value.

notifyWhenAttacked(enabled)

Toggle auto notification when the structure is under attack. The notification will be sent to your account email. Turned on by default.

parametertypedescription
enabledboolean

Whether to enable notification or disable.

Return value

One of the following codes:

constantvaluedescription
OK0

The operation has been scheduled successfully.

ERR_NOT_OWNER-1

You are not the owner of this structure.

ERR_INVALID_ARGS-10

enable argument is not a boolean value.

Whether this is your own structure.

An object with the structure’s owner info containing the following properties:

parametertypedescription
usernamestring

The name of the owner user.

storeobject

if(creep.room.storage.store[RESOURCE_ENERGY] == 0) { }if( !(RESOURCE_UTRIUM in creep.room.storage.store) ) { }const total = _.sum(Game.rooms['W1N1'].storage.store);

An object with the storage contents. Each object key is one of the RESOURCE_* constants, values are resources amounts. RESOURCE_ENERGY is always defined and equals to 0 when empty, other resources are undefined when empty. You can use lodash.sum to get the total amount of contents.

storeCapacitynumber

The total amount of resources the storage can contain.

transfer(target, resourceType, [amount])

This method is deprecated and will be removed soon. Please use Creep.withdraw instead.

storage.transfer(creep, RESOURCE_ENERGY);

Transfer resource from this storage to a creep. The target has to be at adjacent square. You can transfer resources to your creeps from hostile structures as well.

parametertypedescription
targetCreep

The target object.

resourceTypestring

One of the RESOURCE_* constants.

amountoptionalnumber

The amount of resources to be transferred. If omitted, all the available amount is used.

Return value

One of the following codes:

constantvaluedescription
OK0

The operation has been scheduled successfully.

ERR_NOT_OWNER-1

You are not the owner of the target creep, or there is a hostile rampart on top of the structure.

ERR_NOT_ENOUGH_RESOURCES-6

The structure does not have the given amount of energy.

ERR_INVALID_TARGET-7

The target is not a valid object which can contain energy.

ERR_FULL-8

The target cannot receive any more energy.

ERR_NOT_IN_RANGE-9

The target is too far away.

ERR_INVALID_ARGS-10

The energy amount is incorrect.

Sends any resources to a Terminal in another room. The destination Terminal can belong to any player. Each transaction requires additional energy (regardless of the transfer resource type) that can be calculated using Game.market.calcTransactionCost method. For example, sending 1000 mineral units from W0N0 to W10N5 will consume 742 energy units. You can track your incoming and outgoing transactions using the Game.market object. Only one Terminal per room is allowed that can be addressed by Room.terminal property.

Terminals are used in the Market system.

Controller level
1-5
6-8 1 terminal
Cost 100,000
Hits 3,000
Capacity 300,000
Cooldown on send 10 ticks

An object representing the position of this object in the room.

The link to the Room object. May be undefined in case if an object is a flag or a construction site and is placed in a room that is not visible to you.

hitsnumber

The current amount of hit points of the structure.

hitsMaxnumber

The total amount of hit points of the structure.

idstring

A unique object identificator. You can use Game.getObjectById method to retrieve an object instance by its id.

structureTypestring

One of the STRUCTURE_* constants.

destroy()

Destroy this structure immediately.

Return value

One of the following codes:

constantvaluedescription
OK0

The operation has been scheduled successfully.

ERR_NOT_OWNER-1

You are not the owner of this structure.

ERR_BUSY-4

Hostile creeps are in the room.

isActive()

Check whether this structure can be used. If room controller level is insufficient, then this method will return false, and the structure will be highlighted with red in the game.

Return value

A boolean value.

notifyWhenAttacked(enabled)

Toggle auto notification when the structure is under attack. The notification will be sent to your account email. Turned on by default.

parametertypedescription
enabledboolean

Whether to enable notification or disable.

Return value

One of the following codes:

constantvaluedescription
OK0

The operation has been scheduled successfully.

ERR_NOT_OWNER-1

You are not the owner of this structure.

ERR_INVALID_ARGS-10

enable argument is not a boolean value.

Whether this is your own structure.

An object with the structure’s owner info containing the following properties:

parametertypedescription
usernamestring

The name of the owner user.

cooldownnumber

The remaining amount of ticks while this terminal cannot be used to make StructureTerminal.send or Game.market.deal calls.

storeobject

if( !(RESOURCE_UTRIUM in Game.rooms['W1N1'].terminal.store) ) { }const total = _.sum(Game.rooms['W1N1'].terminal.store);

An object with the storage contents. Each object key is one of the RESOURCE_* constants, values are resources amounts. RESOURCE_ENERGY is always defined and equals to 0 when empty, other resources are undefined when empty. You can use lodash.sum to get the total amount of contents.

storeCapacitynumber

The total amount of resources the storage can contain.

send(resourceType, amount, destination, [description])

Game.rooms['W1N1'].terminal.send(RESOURCE_UTRIUM, 100, 'W2N3', 'trade contract #1');

Sends resource to a Terminal in another room with the specified name.

parametertypedescription
resourceTypestring

One of the RESOURCE_* constants.

amountnumber

The amount of resources to be sent. The minimum amount is 100.

destinationstring

The name of the target room. You don't have to gain visibility in this room.

descriptionoptionalstring

The description of the transaction. It is visible to the recipient. The maximum length is 100 characters.

Return value

One of the following codes:

constantvaluedescription
OK0

The operation has been scheduled successfully.

ERR_NOT_OWNER-1

You are not the owner of this structure.

ERR_NOT_ENOUGH_RESOURCES-6

The structure does not have the required amount of resources.

ERR_INVALID_ARGS-10

The arguments provided are incorrect.

ERR_TIRED-11

The terminal is still cooling down.

transfer(target, resourceType, [amount])

This method is deprecated and will be removed soon. Please use Creep.withdraw instead.

Game.rooms['W1N1'].terminal.transfer(creep, RESOURCE_ENERGY);

Transfer resource from this terminal to a creep. The target has to be at adjacent square. You can transfer resources to your creeps from hostile structures as well.

parametertypedescription
targetCreep

The target object.

resourceTypestring

One of the RESOURCE_* constants.

amountoptionalnumber

The amount of resources to be transferred. If omitted, all the available amount is used.

Return value

One of the following codes:

constantvaluedescription
OK0

The operation has been scheduled successfully.

ERR_NOT_OWNER-1

You are not the owner of the target creep, or there is a hostile rampart on top of the structure.

ERR_NOT_ENOUGH_RESOURCES-6

The structure does not have the given amount of energy.

ERR_INVALID_TARGET-7

The target is not a valid object which can contain energy.

ERR_FULL-8

The target cannot receive any more energy.

ERR_NOT_IN_RANGE-9

The target is too far away.

ERR_INVALID_ARGS-10

The energy amount is incorrect.

Remotely attacks or heals creeps, or repairs structures. Can be targeted to any object in the room. However, its effectiveness linearly depends on the distance. Each action consumes energy.

Controller level
1-2
3-4 1 tower
5-6 2 towers
7 3 towers
8 6 towers
Cost 5,000
Hits 3,000
Capacity 1,000
Energy per action 10
Attack effectiveness 600 hits at range ≤5 to 150 hits at range ≥20
Heal effectiveness 400 hits at range ≤5 to 100 hits at range ≥20
Repair effectiveness 800 hits at range ≤5 to 200 hits at range ≥20

An object representing the position of this object in the room.

The link to the Room object. May be undefined in case if an object is a flag or a construction site and is placed in a room that is not visible to you.

hitsnumber

The current amount of hit points of the structure.

hitsMaxnumber

The total amount of hit points of the structure.

idstring

A unique object identificator. You can use Game.getObjectById method to retrieve an object instance by its id.

structureTypestring

One of the STRUCTURE_* constants.

destroy()

Destroy this structure immediately.

Return value

One of the following codes:

constantvaluedescription
OK0

The operation has been scheduled successfully.

ERR_NOT_OWNER-1

You are not the owner of this structure.

ERR_BUSY-4

Hostile creeps are in the room.

isActive()

Check whether this structure can be used. If room controller level is insufficient, then this method will return false, and the structure will be highlighted with red in the game.

Return value

A boolean value.

notifyWhenAttacked(enabled)

Toggle auto notification when the structure is under attack. The notification will be sent to your account email. Turned on by default.

parametertypedescription
enabledboolean

Whether to enable notification or disable.

Return value

One of the following codes:

constantvaluedescription
OK0

The operation has been scheduled successfully.

ERR_NOT_OWNER-1

You are not the owner of this structure.

ERR_INVALID_ARGS-10

enable argument is not a boolean value.

Whether this is your own structure.

An object with the structure’s owner info containing the following properties:

parametertypedescription
usernamestring

The name of the owner user.

energynumber

The amount of energy containing in this structure.

energyCapacitynumber

The total amount of energy this structure can contain.

attack(target)

Remotely attack any creep in the room.

parametertypedescription
targetCreep

The target creep.

Return value

One of the following codes:

constantvaluedescription
OK0

The operation has been scheduled successfully.

ERR_NOT_ENOUGH_RESOURCES-6

The tower does not have enough energy.

ERR_INVALID_TARGET-7

The target is not a valid attackable object.

ERR_RCL_NOT_ENOUGH-14

Room Controller Level insufficient to use this structure.

heal(target)

Remotely heal any creep in the room.

parametertypedescription
targetCreep

The target creep.

Return value

One of the following codes:

constantvaluedescription
OK0

The operation has been scheduled successfully.

ERR_NOT_ENOUGH_RESOURCES-6

The tower does not have enough energy.

ERR_INVALID_TARGET-7

The target is not a valid creep object.

ERR_RCL_NOT_ENOUGH-14

Room Controller Level insufficient to use this structure.

repair(target)

Remotely repair any structure in the room.

parametertypedescription
targetStructure

The target structure.

Return value

One of the following codes:

constantvaluedescription
OK0

The operation has been scheduled successfully.

ERR_NOT_ENOUGH_RESOURCES-6

The tower does not have enough energy.

ERR_INVALID_TARGET-7

The target is not a valid repairable object.

ERR_RCL_NOT_ENOUGH-14

Room Controller Level insufficient to use this structure.

transferEnergy(target, [amount])

This method is deprecated and will be removed soon. Please use Creep.withdraw instead.

Transfer energy from the structure to a creep. The target has to be at adjacent square.

parametertypedescription
targetCreep

The creep object which energy should be transferred to.

amountoptionalnumber

The amount of energy to be transferred. If omitted, all the remaining amount of energy will be used.

Return value

One of the following codes:

constantvaluedescription
OK0

The operation has been scheduled successfully.

ERR_NOT_OWNER-1

You are not the owner of the target creep, or there is a hostile rampart on top of the structure.

ERR_NOT_ENOUGH_RESOURCES-6

The structure contains less energy than the given amount.

ERR_INVALID_TARGET-7

The specified target object is not a creep.

ERR_FULL-8

The target creep can not carry the given amount of energy.

ERR_NOT_IN_RANGE-9

The target creep is too far away.

Blocks movement of all creeps. Players can build destructible walls in controlled rooms. Some rooms also contain indestructible walls separating novice and respawn areas from the rest of the world or dividing novice / respawn areas into smaller sections. Indestructible walls have no hits property.

Controller level 2
Cost 1
Hits when constructed 1
Max hits 300,000,000

An object representing the position of this object in the room.

The link to the Room object. May be undefined in case if an object is a flag or a construction site and is placed in a room that is not visible to you.

hitsnumber

The current amount of hit points of the structure.

hitsMaxnumber

The total amount of hit points of the structure.

idstring

A unique object identificator. You can use Game.getObjectById method to retrieve an object instance by its id.

structureTypestring

One of the STRUCTURE_* constants.

destroy()

Destroy this structure immediately.

Return value

One of the following codes:

constantvaluedescription
OK0

The operation has been scheduled successfully.

ERR_NOT_OWNER-1

You are not the owner of this structure.

ERR_BUSY-4

Hostile creeps are in the room.

isActive()

Check whether this structure can be used. If room controller level is insufficient, then this method will return false, and the structure will be highlighted with red in the game.

Return value

A boolean value.

notifyWhenAttacked(enabled)

Toggle auto notification when the structure is under attack. The notification will be sent to your account email. Turned on by default.

parametertypedescription
enabledboolean

Whether to enable notification or disable.

Return value

One of the following codes:

constantvaluedescription
OK0

The operation has been scheduled successfully.

ERR_NOT_OWNER-1

You are not the owner of this structure.

ERR_INVALID_ARGS-10

enable argument is not a boolean value.

docs.screeps.com

5 игр, которые научат вас программировать / Полезное / FREELANCE.TODAY

Трудно ли научиться программированию? Наверное, да. По крайней мере, спрос на услуги программистов остается стабильным всегда, даже во время экономического спада, что говорит о том, что программистов относительно мало и они постоянно востребованы. Но решение начать изучение основ программирования очень часто пропадает из-за слишком высокого входного барьера. Мало того, что нужно иметь определенный багаж знаний – нужно уметь усваивать материал, а вот с этим у многих проблемы. Программирование – сфера специфическая и многим на первом этапе трудно начать мыслить новыми категориями.

 

Однако, когда грызть гранит науки не получается или уже нет сил, можно пойти другим путем. Как это ни удивительно, но научиться писать код можно просто играя в игры. Да-да, именно так. FreelanceToday предлагает вашему вниманию 5 игр, которые научат вас программировать.

 

CODECOMBAT

 

СodeCombat – это ролевая HTML5-игра, которая научит вас основным понятиям программирования. В CodeCombat вам нужно провести своего персонажа через несколько уровней игры, в каждом из которых героя ждут интересные приключения. Первый уровень, «Подземелье Китгарда», охватывает основные концепции программирования. На протяжении всего путешествия игрок все время сталкивается с проблемами кодирования и, если он успешно их преодолеет, то переходит на следующий уровень. За успешное прохождение уровня игроку начисляются очки, которые он может использовать для прокачки своего героя.

 

CodeCombat рассчитан на молодых людей, которые хотели бы стать программистами. Согласно данным опроса, проведенного владельцами игрового сайта, 62% пользователей CodeCombat – это молодежь возрасте до 18 лет.

 

Игра поддерживает несколько языков программирования: JavaScript, CoffeeScript, Lua, и Python. CodeCombat охватывает множество аспектов создания кода: строки, переменные, вызов метода, векторную графику и многое другое.

 

CODE HUNT

 

Code Hunt – это научно-фантастическая HTML5-игра, созданная компанией Microsoft Research. В этой игре нужно попытаться исправить неправильный код для того, чтобы программа начала работать. Игра насчитывает 14 уровней, которые называются секторами. Пойдя все сектора, игрок получает некоторое представление о том, как пишется и работает код.

 

Code Hunt поддерживает языки Java и C#, так что начать изучение программирования можно на одном из выбранных. Пройдя игру, пользователь подтянет знание арифметики, познакомится с петлями и условными выражениями.

 

CODINGAME

 

CodinGame представляет собой большой набор сложных игр для программистов. Если вы хотите улучшить свои навыки программирования, то игры CodinGame – это как раз то, что нужно, для того, чтобы совместить приятное с полезным. Игра поддерживает свыше 20 языков, в частности можно отметить PHP, C и JavaScript.

Пользовательский интерфейс многофункциональный и может быть изменен по желанию игрока. К примеру, можно выбрать стиль редактора кода. По умолчанию используется тема Classic, но стиль можно поменять на Emacs или Vim. В CodinGame можно играть как одному, так и с другими программистами – игра поддерживает многопользовательский режим, в котором можно совместно с другими игроками решать возникшие проблемы.

 

SCREEPS

 

Screeps – это многопользовательская для программистов, работающих с JavaScript. Это открытый игровой мир, где участник управляет юнитами, которые называются крипами. Тип игры – стратегия: крипы добывают ресурсы, захватывают территорию и так далее. Так как Screeps является многопользовательской игрой, нужно быть готовым к тому, что вашим юнитам придется взаимодействовать с крипами других игроков.

 

Контролировать крипов нужно с помощью JavaScript, о чем недвусмысленно намекает название игры: Screeps – это скрипт (сценарий) для ваших крипов.

 

FIGHTCODE

 

Правила игры FightCode очень просты – вам нужно создать робота, который должен победить роботов других игроков. Как создать робота? При помощи JavaScript. К примеру, вы можете использовать метод .rotateCannon () чтобы повернуть оружие вашего робота в нужном направлении, если ему угрожает опасность (происходит событие).

 

Игра может быть непонятной для новичков, поэтому перед тем, как начать строить робота, который покорит виртуальный мир, будет полезным прочитать руководство.

freelance.today


Смотрите также