Skip to content

Instantly share code, notes, and snippets.

@kamiyaowl
Created March 5, 2014 12:15
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 kamiyaowl/9366090 to your computer and use it in GitHub Desktop.
Save kamiyaowl/9366090 to your computer and use it in GitHub Desktop.
ScalaでLifegame
__________________________________________________
## ## ##
## # # ## ##
# # ######
## # #
##
### ##
# # #
# # # # # ##
# # # # ### #
## # # # ## ##
# # # # ##
# # #### ### ###
##### ## ### ### ###
# ## ## ### # #
# ## # #
### # ## ## # #
# ## # ## ##
# ### # # ##
## # ## # # # # ##
### ## # # # #
__________________________________________________
## ## ##
## # # ## ##
# # # #
## # #
#####
# ## #
## ## ##
### # ##
### ## # # #
## # ## ### # # # #
## # # # # # #######
## # # # # # # ## #
##### ## # ## # # # # # #
# # # # ## ##
### # ## ###
### ### ## ### #
# # ### # ##
## #### # ## # ####
# # ## # ## #
## # ##
__________________________________________________
## ##
## # # ## ##
# # ### ###
## # #
#
## ##
## ## # #
# # #
# # # # # ## #
# ## ## # # # #
## # # # ## ### #
# # ## ## # #
# ### ### # ## # ###
# # # # # #
# # # #
# # ##
### # # # #
### # ## # ## ###
# # ## ### # ## ##
import scala.language.postfixOps
import scala.util.Random
object Lifegame {
implicit class RichList[T](self:List[T]){
def shuffle() = (new Random).shuffle(self)
}
implicit class Field(self:Map[(Int,Int),Boolean]) {
def around(p:(Int,Int), d:Int = 1) = self filter(x => Tools.aroundPoint(p,d).contains(x._1))
def isLive(p:(Int,Int)) = {
val lives = around(p) filter(_._2)
//born
if(!self(p)) {
if(lives.size == 3) true else false
} else { //live or death
lives.size match {
case 2 => true
case 3 => true
case _ => false
}
}
}
def next() = self map(x => (x._1._1, x._1._2) -> isLive(x._1))
def show(implicit size:(Int,Int)) = {
println("_" * size._1)
for(j <- 0 until size._2) {
for(i <- 0 until size._1) {
self((i,j)) match {
case true => print("#")
case false => print(" ")
}
}
println("")
}
}
def future() : Stream[Map[(Int,Int),Boolean]] = {
Stream.cons(self, self.next.future)
}
}
object Tools {
def field(implicit size:(Int,Int)) = (for(j <- 0 until size._2 ; i <- 0 until size._1) yield ((i,j) -> false)).toMap
def aroundPoint(x:(Int,Int), d:Int = 1) = List((x._1 - d, x._2 - d), (x._1 - d, x._2 + d), (x._1 + d, x._2 - d), (x._1 + d, x._2 + d), (x._1 - d, x._2), (x._1 + d, x._2), (x._1, x._2 - d), (x._1, x._2 + d))
def create(implicit size:(Int,Int)) = {
val f = field
val t = f.toList.shuffle.take((new Random).nextInt(f.size)) map(x => {((x._1._1,x._1._2) -> true)})
f ++ t
}
}
def main(args:Array[String]) = {
implicit val size = (50,20)
val start = Tools.create
val future = start.future
future foreach(_.show)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment