來自Java,我正在學習Scala。我對遊戲和虛擬世界的編程感興趣,所以我決定將我的第一個程序作爲一個小遊戲世界模擬器。在我看來,所有遊戲元素通常都處於以下階段:創建,更新,刪除。在Java或其他OOP中,對我來說這絕對是清楚的。現在我來到Scala ......到目前爲止我已經實現的,只是一個應該改變每個週期的許多單元的容器。下面是代碼: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()
}
}
首先 - 我的問題是 - 如何makу的「版本()」在AUX構造函數的工作?在Java中沒有問題。什麼是Scala解決這個問題的方法?其次,您可以從斯卡拉功能方法的角度評論我的錯誤嗎?
更新:我將不勝感激重寫這段代碼,因爲您會以純Scala的方式編寫它。
您可能會對這些文章[「純功能Retrogames」](http://prog21.dadgum.com/23.html)感興趣,其中涵蓋了一些更一般的問題。 – Howard 2011-12-23 13:59:27
哇,謝謝!我現在就讀它! – noncom 2011-12-23 14:04:05
更好的代碼審查地點是http://codereview.stackexchange.com/。 – 2011-12-23 14:07:31