Skip to content

Instantly share code, notes, and snippets.

@ma2saka
Created February 12, 2017 04:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ma2saka/14a07db2cdff3b862c9de714c9dcc0e6 to your computer and use it in GitHub Desktop.
Save ma2saka/14a07db2cdff3b862c9de714c9dcc0e6 to your computer and use it in GitHub Desktop.
ProcessingでLifeGameをScala実装
import processing.core.PApplet
import processing.core.PConstants._
class App extends PApplet {
private[this] val CELL_SIZE = 10
private[this] val W = 102
private[this] val H = 76
private[this] val arr = new Array[Boolean](W * H)
private[this] val tmp_arr = new Array[Boolean](W * H)
override def settings(): Unit = {
size(W * CELL_SIZE, H * CELL_SIZE, JAVA2D)
}
override def setup(): Unit = {
//frameRate(10)
fill(60)
}
override def mousePressed(): Unit = {
for (x <- 0 to W * H - 1) {
arr(x) = if (random(1.0f) < 0.5f) {
true
} else {
false
}
}
}
override def draw(): Unit = {
background(200)
write_lines()
update_cells()
write_cells()
}
private[this] def write_lines() = {
for (x <- 0 to W * CELL_SIZE by CELL_SIZE) line(x, 0, x, height)
for (y <- 0 to H * CELL_SIZE by CELL_SIZE) line(0, y, width, y)
}
private[this] def update_cells(): Unit = {
for (i <- 0 to W * H - 1) {
var c = 0
// 左側
if (i % W > 0 && arr(i - 1)) {
c += 1
}
// 右側
if (i % W != W - 1 && arr(i + 1)) {
c += 1
}
// 上、右上、左上
if (i / W > 0) {
if (arr(i - W)) c += 1
if (i % W != W - 1 && arr(i + 1 - W)) c += 1
if (i % W > 0 && arr(i - 1 - W)) c += 1
}
// 下、左下、右下
if (i / W < H - 1) {
if (arr(i + W)) c += 1
if (i % W != W - 1 && arr(i + 1 + W)) c += 1
if (i % W > 0 && arr(i - 1 + W)) c += 1
}
// 生存判定
if (arr(i) && (c == 2 || c == 3)) {
tmp_arr(i) = true
} else if (arr(i)) {
tmp_arr(i) = false
} else if (c == 3) {
tmp_arr(i) = true
} else {
tmp_arr(i) = false
}
}
tmp_arr.copyToArray(arr)
}
private[this] def write_cells(): Unit = {
for (i <- 0 to W * H - 1) {
val y = i / W
val x = i % W
if (arr(i)) {
rect(x * CELL_SIZE, y * CELL_SIZE, CELL_SIZE, CELL_SIZE)
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment