1

我正在尝试将 JavaScript 教程代码移植到 Scala.js 并卡在过滤结构上 - 任何建议都将不胜感激。

原始代码:

// If creep is supposed to transfer energy to a structure
if (creep.memory.working == true) {

    // Find closest spawn, extension or tower which is not full
    var structure = creep.pos.findClosestByPath(FIND_MY_STRUCTURES, {
        filter: (s) => (s.structureType == STRUCTURE_SPAWN
        || s.structureType == STRUCTURE_EXTENSION
        || s.structureType == STRUCTURE_TOWER)
        && s.energy < s.energyCapacity });

Scala.js 中的代码:

val structure = Option[Structure](creep.pos.findClosestByPath[Structure](FIND_MY_STRUCTURES,
FindFilter[Structure](structure => {
   (structure.structureType == STRUCTURE_SPAWN ||
    structure.structureType == STRUCTURE_EXTENSION ||
    structure.structureType == STRUCTURE_TOWER) &&
    structure.energy < structure.energyCapacity })))

问题是不是所有的结构类型都有.energy所以这不会编译,尽管过滤的那些有?

我试图定义一个特征 HasEnergy(类似于 JavaScript 接口)并像 FindFilter[Structure with HasEnergy] 一样使用它,它可以编译,但现在我在运行时遇到类型错误 -> TypeError: a.k is not a function

我的外墙看起来像这样:

@js.native
trait HasEnergy extends js.Object {
  val energy: Int
  val energyCapacity: Int
}

@js.native
trait Structure extends RoomObject with HasID {
  val hits: UndefOr[Int]
  val hitsMax: UndefOr[Int]
  val id: String
  val structureType: String
  def destroy(): Int
  def isActive(): Boolean
  def notifyWhenAttacked(enabled: Boolean): Int
}
4

1 回答 1

0

好的,这是我想出的解决方案:

  val structure = {
    Option(creep.pos.findClosestByPath[OwnedStructureWithEnergy](FIND_MY_STRUCTURES, FindFilter[OwnedStructureWithEnergy](s =>
      ((s.structureType == STRUCTURE_SPAWN) ||
        (s.structureType == STRUCTURE_EXTENSION) ||
        (s.structureType == STRUCTURE_TOWER)) &&
        (s.energy < s.energyCapacity))))
  }

原来我的findClosestByPath Facade 中有一个错误。每个API的正确版本支持FindFilterFindFilterAlgorithm - 我的映射中缺少前者。正确的现在看起来像这样:

  def findClosestByPath[T](typ: Int, opts: FindFilter[T] | FindFilterAlgorithm[T] = ???): T
  @JSName("findClosestByPath")

现在要通过点使用成员访问,我添加了特征OwnedStructureWithEnergy

@js.native
trait OwnedStructureWithEnergy extends OwnedStructure {
  val energy: Int = js.native
  val energyCapacity: Int = js.native
}
于 2017-01-14T10:42:10.813 回答