来自Java,我正在学习Scala。我对游戏和虚拟世界编程很感兴趣,所以我决定将我的第一个程序变成一个小型的游戏世界模拟器。在我看来,所有游戏元素通常都处于以下阶段:创建,更新,删除。在Java或其他OOP中我绝对清楚。现在我来到Scala ...到目前为止我已经实现了,它只是一个容器,可以容纳每个周期都应该改变的多个单元格。这是代码:
//init
val rand : Random = new Random
//mutation variations
def mutF(f:Int=>Int, v: Int) : Int = {f(v)}
def mutFA(v:Int) : Int = mutF(x => x, v)
def mutFB(v:Int) : Int = mutF(x => x + x, v)
def mutFC(v:Int) : Int = mutF(x => x - x, v)
//mutation variance
val mutFS : List[Int=>Int] = List(mutFA, mutFB, mutFC)
//cycle through mutation functions
def mutFF(f:Int=>Int) : Int=>Int = {
val i = mutFS.indexOf(f)
if(i < mutFS.length) mutFS(i + 1)
else mutFS(0)
}
//objects
class Cell(value:Int)(f:Int => Int){ //TODO: what will be without currying???
def mutate() : Cell = new Cell(f(value))(f)
def output() {
print("[" + value + "]")
}
}
//the main class
class Breed(generation:Int, num:Int, margins:Int, cells: List[Cell]) {
def this(num:Int, margins:Int) = this(0, num, margins, build()) //<<<<<
//make 1 cell
def makeCell() : Cell = {
val mutF:Int=>Int = mutFS(rand.nextInt(mutFS.length))
val v = rand.nextInt(margins)
println("BREED: making cell " + v)
new Cell(v)(mutF)
}
//fill with random cells
def build() : List[Cell] = {
def addCell(acc:Int, list:List[Cell]) : List[Cell] = {
println("BREED: build(), acc= " + acc + " list=" + list)
if(acc <= 0) list
else addCell(acc - 1, makeCell :: list)
}
addCell(num, List())
}
// val cells : List[Cell] = build()
//go several generations ahead, print every generation
def mutate(generations:Int) {
def mutateF(acc:Int, breed : Breed) : Breed = {
if (acc == 0) breed
else {
print("BREED: mutating, ")
breed.output()
mutateF(acc - 1, mutate(breed))
}
}
mutateF(generations, this)
}
//mutate this breed
def mutate(breed : Breed) : Breed = {
def mutateF(l : List[Cell]) : List[Cell] = {
l match {
case Nil => Nil
case y :: yx => y.mutate() :: mutateF(yx)
}
}
new Breed(generation, num, margins, mutateF(build))
}
def output() {
print("BREED: [" + generation + "] ")
for(i <- 0 to num - 1) cells(i).output()
println()
}
}
首先 - 我的问题是 - 如何在aux构造函数中使用'build()'函数?在Java中没有问题。什么是Scala解决这个问题的方法?其次,从Scala的功能方法的角度来看,你能否评论一下我的错误?
更新:我希望重写此代码,因为您将以纯Scala方式编写它。
答案 0 :(得分:1)
由于在初始化该对象之前无法在对象上调用方法,因此必须将build
移动到其他位置。一个自然的地方就是伴侣。请注意,build
使用的num
在您调用build
时尚未初始化,因此您必须将其作为参数传递。