Skip to content

Instantly share code, notes, and snippets.

@yogthos
Created June 10, 2011 20:51
Show Gist options
  • Save yogthos/1019750 to your computer and use it in GitHub Desktop.
Save yogthos/1019750 to your computer and use it in GitHub Desktop.
Playing with actors
package main
import scala.util.Random
import scala.collection.immutable.HashMap
import java.awt._
import javax.swing._
import scala.actors._
import scala.actors.Actor._
object Cellular extends Canvas {
val WIDTH = 500
val HEIGHT = 500
val PIXEL_SIZE = 50;
setBounds(0, 0, WIDTH, HEIGHT)
setBackground(Color.BLACK)
val frame = new JFrame("Cellular Automata")
frame.setSize(new Dimension(WIDTH, HEIGHT))
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE)
frame.getContentPane.add(this)
frame.setResizable(false)
frame.setVisible(true)
createBufferStrategy(2)
val buffer = getBufferStrategy
val graphics = buffer.getDrawGraphics
class Message(val x: Int, val y: Int, val status: Boolean)
def drawPixel(x0: Int, y0: Int, color: Color): Unit = {
graphics.setColor(color)
graphics.fillRect(x0 + 1, y0 + 1, PIXEL_SIZE - 1, PIXEL_SIZE - 1)
if (!buffer.contentsLost) buffer.show
}
class Cell(var leftCell: Cell, var rightCell: Cell, var topCell: Cell, var bottomCell: Cell, val x: Int, val y: Int) extends Actor {
var aliveNeighbours = 0
var active = Random.nextInt(2) > 0
def act() {
behave
Thread.sleep(300)
loop {
react {
case alive: Boolean => {
if (alive) aliveNeighbours += 1 else aliveNeighbours -= 1
behave
}
}
}
}
def behave = {
drawPixel(x, y, if (active) Color.red else Color.black)
if (leftCell != null) leftCell ! active
if (rightCell != null) rightCell ! active
if (topCell != null) topCell ! active
if (bottomCell != null) bottomCell ! active
active = aliveNeighbours > 0
}
}
def main(args: Array[String]) {
var cells = HashMap[(Int, Int), Cell]()
var xPos = 0
for (x <- 1 to WIDTH / PIXEL_SIZE) {
var yPos = 0
for (y <- 1 to HEIGHT / PIXEL_SIZE) {
cells += (xPos, yPos) -> new Cell(null, null, null, null, xPos, yPos)
yPos += PIXEL_SIZE
}
xPos += PIXEL_SIZE
}
for (((x, y), cell) <- cells) {
cells.get(cell.x - PIXEL_SIZE, cell.y) match { case Some(leftCell) => cell.leftCell = leftCell; case None => Unit }
cells.get(cell.x + PIXEL_SIZE, cell.y) match { case Some(rightCell) => cell.rightCell = rightCell; case None => Unit }
cells.get(cell.x, cell.y - PIXEL_SIZE) match { case Some(topCell) => cell.topCell = topCell; case None => Unit }
cells.get(cell.x, cell.y + PIXEL_SIZE) match { case Some(bottomCell) => cell.bottomCell = bottomCell; case None => Unit }
}
for (cell <- cells.values) {
cell.start
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment