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