我正在尝试将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 });
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 [HasEnergy结构],它编译,但现在我在运行时收到类型错误 - &gt; TypeError: a.k is not a function
。
My Facades看起来像这样:
@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
}
答案 0 :(得分:0)
好的,这是我提出的解决方案:
$newarray= array();
foreach ($tmparray as $value) {
if (!in_array($value,$newarray)) {
$newarray[ ] = $value;
}
}
var_dump($newarray);
事实证明我的 findClosestByPath Facade中存在错误。每个API的正确版本支持 FindFilter 和 FindFilterAlgorithm - 我的映射中缺少前者。正确的一个现在看起来像这样:
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))))
}
现在通过dot使用成员访问权限,我添加了特征 OwnedStructureWithEnergy :
def findClosestByPath[T](typ: Int, opts: FindFilter[T] | FindFilterAlgorithm[T] = ???): T
@JSName("findClosestByPath")