[JavaScript]Screeps入门1:移动creep到资源并收获

教程的第一个脚本代码

module.exports.loop = function () {
    var creep = Game.creeps['Harvester1'];
    var sources = creep.room.find(FIND_SOURCES);
    if(creep.harvest(sources[0]) == ERR_NOT_IN_RANGE) {
        creep.moveTo(sources[0]);
    }
}

作用:找到资源,移动creep过去并收获


Game.creeps

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

Game.creeps['Harvester1'];

表示当前名为Harvester1的creeps


creep.room.find(FIND_SOURCES);

寻找所有的sources


creep.harvest(target) == ERR_NOT_FOUND;

Harvest energy from the source or resources from minerals and deposits. 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.

ERR_NOT_IN_RANGE: The target is too far away.


creeps.moveTo(sources[0]);

Find the optimal[a.最适的] path to the target within the same room and move to it.

后面可以跟两种变量形式

  1. (x, y, [opts])
    x, y为横纵坐标
  2. (target, [opts])
    target: Can be a RoomPosition object or any object containing RoomPosition. The position doesn’t have to be in the same room with the creep.
    在这里target为creep.room.find(FIND_SOURCES)所寻找到的soueces(放在了sources[]数组里, sources[0]第一个找到的source)
    opts: 暂时用不到,我也看不懂0.0[JavaScript]Screeps入门1:移动creep到资源并收获_第1张图片

if(creep.harvest(sources[0]) == ERR_NOT_IN_RANGE) {
        creep.moveTo(sources[0]);

意思即为如果在收割资源的时候,source is too far away了(这时候返回ERR_NOT_IN_RANGE)那就移动过去


没看过JS,API文档还是纯英文的,对小白来说简直折磨T_T

你可能感兴趣的:(Screeps,JavaScript,javascript)