Created
December 9, 2012 02:46
-
-
Save katzchang/4243084 to your computer and use it in GitHub Desktop.
ライフゲーム実装例
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 coderetreat | |
import org.scalatest.Assertions | |
import org.junit.Test | |
class GameOfLifeSuite extends Assertions { | |
@Test def game_of_life() { | |
assert(new Board(3, 4, Set()).toString === "000,000,000,000") | |
assert(new Board(3, 4, Set((0, 0), (0, 1), (1, 1))).toString === "110,010,000,000") | |
assert(new Board(3, 4, Set()).neighbersOf((1, 1)) | |
=== Set((0, 0), (0, 1), (0, 2), (1, 0), (1, 2), (2, 0), (2, 1), (2, 2))) | |
assert(new Board(3, 4, Set((0, 0), (0, 1), (1, 1))).aliveNext((0, 1)) === true) | |
assert(new Board(3, 4, Set((0, 0), (0, 1), (1, 1))).next.toString | |
=== "110,110,000,000") | |
assert(new Board(3, 4, Set((0, 0), (0, 1), (1, 1))).next.next.toString | |
=== "110,110,000,000") | |
} | |
} | |
class Board(val width: Int, val height: Int, val alivePoints: Set[(Int, Int)]) { | |
val allPoints: Seq[Seq[(Int, Int)]] = | |
(0.to(height - 1)).map((row) => | |
(0.to(width - 1)).map((col) => | |
(row, col))) | |
override val toString: String = | |
allPoints.map((row) => | |
row.map((p) => | |
alive(p) match { | |
case true => "1" | |
case false => "0" | |
}).mkString).mkString(",") | |
lazy val next: Board = new Board(width, height, nextAlivePoints) | |
lazy val nextAlivePoints: Set[(Int, Int)] = | |
allPoints.flatMap((row) => | |
row).filter((p) => | |
aliveNext(p)).toSet | |
def alive(p: (Int, Int)): Boolean = alivePoints.contains(p) | |
def aliveNext(p: (Int, Int)): Boolean = | |
(alive(p), neighbersOf(p).count((q) => alive(q))) match { | |
case (true, 2) => true | |
case (_, 3) => true | |
case _ => false | |
} | |
def neighbersOf(p: (Int, Int)): Set[(Int, Int)] = Set( | |
(p._1 - 1, p._2 - 1), | |
(p._1 - 1, p._2 - 0), | |
(p._1 - 1, p._2 + 1), | |
(p._1 - 0, p._2 - 1), | |
(p._1 - 0, p._2 + 1), | |
(p._1 + 1, p._2 - 1), | |
(p._1 + 1, p._2 - 0), | |
(p._1 + 1, p._2 + 1)) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment