Created
July 21, 2009 19:57
-
-
Save gclaramunt/151554 to your computer and use it in GitHub Desktop.
Game of Life in Scala
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package gameoflife | |
class Board[T](val b:Array[Array[T]]) { | |
val h=b.size | |
val w=b(0).size | |
def conv(idx:Int,max:Int)=if (idx<0) (max-Math.abs(idx %max) ) else (idx % max ) | |
def apply(x:Int,y:Int)=b(conv(x,h))(conv(y,w)) | |
def update(x:Int,y:Int,value:T)= b(conv(x,h))(conv(y,w))=value | |
def prnt(f:T=>String)= for (i <- 0 until h) { | |
for (j <- 0 until w) print (f(b(i)(j))) | |
println | |
} | |
//build a new board horizontally | |
def +(other:Board[T]):Board[T]={ | |
new Board[T]( b.zip(other.b).map(t=>t._1++t._2)) | |
} | |
//build a new board vertically | |
def ++(other:Board[T]):Board[T]={ | |
new Board[T](b++other.b) | |
} | |
} | |
object Board { | |
type Pos=(Int,Int) | |
def adjacents(x:Int,y:Int):Seq[(Int,Int)]=for( i<- x-1 to x+1; j<- y-1 to y+1 if (i,j)!=(x,y)) yield (i,j) | |
def manhattan(a:Pos,b:Pos)= (a._1-b._1)+(a._2-b._2) | |
} | |
object GameOfLife { | |
type GoLBoard = Board[Boolean] | |
val O=true | |
val o=false | |
def neighbourghs(b:GoLBoard,adj: Seq[(Int,Int)]):Int=adj.filter (t=>b(t._1,t._2)) length | |
def procCell[T](w:GoLBoard, nw:GoLBoard , i:Int, j:Int):Unit= | |
neighbourghs(w,Board.adjacents(i,j)) match { | |
case 2 => nw(i,j)=w(i,j) | |
case 3 => nw(i,j)=true | |
case _ => nw(i,j)=false | |
} | |
def stepImm(world:GoLBoard):GoLBoard={ | |
val newWorld=new Board(new Array[Array[Boolean]](world.h,world.w)) | |
for (i<- 0 to world.h ; j <- 0 to world.w) procCell(world, newWorld,i,j) | |
newWorld | |
} | |
def run(steps:Int, step:GoLBoard=>GoLBoard){ | |
val float=new Board(Array( | |
Array(o,o,o,o,o), | |
Array(o,o,o,o,o), | |
Array(o,O,O,O,o), | |
Array(o,o,o,o,o), | |
Array(o,o,o,o,o) | |
) | |
) | |
var world=(float+float)++(float+float) | |
def p(b:Boolean)=if (b) "O" else "o" | |
for (i<-1 to steps) { | |
world=step(world) | |
world.prnt(p) | |
println | |
} | |
} | |
def main(args:Array[String]):Unit={ | |
run(10,stepImm) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment