【问题标题】:Game Screeps - find filter and static typed languages (Scala) - how to facade correctly?Game Screeps - 查找过滤器和静态类型语言 (Scala) - 如何正确外观?
【发布时间】:2017-10-05 01:54:56
【问题描述】:

我正在尝试将 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
}

【问题讨论】:

    标签: javascript scala screeps


    【解决方案1】:

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

      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 外观中存在错误。 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
    }
    

    【讨论】:

      猜你喜欢
      • 2016-09-26
      • 2011-02-11
      • 1970-01-01
      • 1970-01-01
      • 2011-02-09
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多