Created
November 19, 2014 03:58
-
-
Save natec425/18e268c08829a21a4bfd to your computer and use it in GitHub Desktop.
Nate's Conway
This file contains 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
import util.Random | |
// not necessary, but my original idea | |
// class Field(val width: Int, val height: Int, factory: (Int, Int) => Boolean) { | |
// val grid = tabulate(width, height)(factory) | |
// more reasonable thing (like what you did) | |
class Field(val height : Int, val width : Int) { | |
// kinda funky to read, but its a 2d vector of random booleans | |
var grid = for ( _ <- 0 until height ) | |
yield (for ( _ <- 0 until width ) yield Random.nextBoolean) | |
def isInBounds(row : Int, col : Int) : Boolean = | |
(0 <= row && row < height) && (0 <= col && col < width) | |
def isOccupied(row : Int, col : Int) : Boolean = | |
isInBounds(row, col) && grid(row)(col) | |
def liveNeighbors(row : Int, col : Int) : Int = | |
((for ( | |
d_row <- -1 to 1; | |
d_col <- -1 to 1 | |
) yield if (isOccupied(row + d_row, col + d_col)) 1 else 0).sum) - ( if (isOccupied(row, col)) 1 else 0) | |
// I added the function argument for debugging purposes and just didn't bother to take it out | |
def print(f : (Int, Int) => String) = | |
for ( i <- 0 until height) { | |
for ( j <- 0 until width ) { | |
Console.print(f(i, j)) | |
} | |
Console.println | |
} | |
def nextGeneration ={ | |
def lives(row : Int, col : Int) : Boolean = | |
(grid(row)(col), liveNeighbors(row, col)) match { | |
case (state, 2) => state | |
case (_, 3) => true | |
case _ => false | |
} | |
grid = for ( i <- 0 until height ) | |
yield ( for ( j <- 0 until width ) yield lives(i, j)) | |
} | |
} | |
object NateConway extends App { | |
val life = new Field(50, 50) | |
while (true) { | |
life.print((i, j) => if (life.grid(i)(j)) "0" else ".") | |
println | |
Thread.sleep(250) | |
life.nextGeneration | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment