Skip to content

Instantly share code, notes, and snippets.

@landon9720
Created June 27, 2012 13:33
Show Gist options
  • Save landon9720/3004092 to your computer and use it in GitHub Desktop.
Save landon9720/3004092 to your computer and use it in GitHub Desktop.
Conway's Game of Life, using Processing, written in Scala
// Conway's Game of Life, using Processing, written in Scala
// see: http://en.wikipedia.org/wiki/Conway's_Game_of_Life
// see: http://processing.org/
// see: http://www.scala-lang.org/
// run using processing-scala-sbt:
// https://github.com/landon9720/processing-scala-sbt
// this code is by Landon Kuhn
package kuhn
import processing.core._
import PConstants._
class Main extends PApplet {
val WIDTH = 1500
val HEIGHT = 1000
override def setup {
size(WIDTH, HEIGHT)
colorMode(HSB, 100)
noStroke
loop
init_world
}
override def draw {
// model
for ((x, y) <- all) {
var n = 0
var hue = 0
for ((dx, dy) <- neighbors) {
if (peek(x+dx, y+dy).state) {
n = n + 1
hue = peek(x+dx, y+dy).hue
}
}
n match {
case 2 =>
case 3 => val cell = poke(x, y); cell.state = true; cell.hue = hue
case _ => val cell = poke(x, y); cell.state = false
}
}
// view
background(10, 10, 10)
for ((x, y) <- all) {
val cell = peek(x, y)
if (cell.state) {
fill(cell.hue, 100, 100)
rect(x*width/W, y*height/H, width/W, height/H)
} else {
fill(cell.hue, 15, 15)
rect(x*width/W+1, y*height/H+1, width/W-2, height/H-2)
}
// copy write world state to read world state
world._1(x)(y).state = world._2(x)(y).state
world._1(x)(y).hue = world._2(x)(y).hue
}
}
// space key starts over
override def keyPressed {
if (key == ' ') init_world
}
val W = (WIDTH / 5) // world size (x)
val H = (HEIGHT / 5) // world size (y)
val all = for (x <- 0 until W; y <- 0 until H) yield (x, y) // seq of coords in world
val world:(Array[Array[Cell]], Array[Array[Cell]]) = (Array.ofDim[Cell](W, H), Array.ofDim[Cell](W, H))
def init_world = {
for ((x, y) <- all) {
world._1(x).update(y, new Cell(random(0, 100) < 70, random(100).toInt))
world._2(x).update(y, new Cell(false, 0)) // is there a better way to update inside a 2D array?
}
}
def X(x:Int) = if (x<0) x+W else x%W // x lookup, with wraparound
def Y(y:Int) = if (y<0) y+H else y%H // y lookup, with wraparound
def peek(x:Int, y:Int) = world._1(X(x))(Y(y)) // read from world 1
def poke(x:Int, y:Int) = world._2(X(x))(Y(y)) // write to world 2
val neighbors = for (dx <- -1 to 1; dy <- -1 to 1 if !(dx == 0 && dy == 0)) yield (dx, dy) // neighbor offsets
}
class Cell(var state:Boolean, var hue:Int)
object Main {
def main(args:Array[String]) {
PApplet.main(Array("--present", "kuhn.Main"))
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment