Last active
December 23, 2015 09:19
-
-
Save torounit/6613937 to your computer and use it in GitHub Desktop.
ライフゲームをCoffeeScriptで書いてみた。CoffeeScriptの練習用。両端でループします。無駄にjQueryプラグインになってます。
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
class Game_of_Life | |
# | |
# @CELL_SIZE セルの大きさ | |
# @BORAD_SIZE マスの数 | |
# @FPS = FPS | |
# | |
constructor:( canvas, @CELL_SIZE = 10,@BORAD_SIZE = 100,@FPS = 50 ) -> | |
@timer | |
@memory = @createMemory() | |
@canvas = @setupCanvas(canvas) | |
@context = @setupContext() | |
@update() | |
# | |
# Canvasのセットアップ | |
# | |
setupCanvas:(canvas) -> | |
canvas.width = canvas.height = @CELL_SIZE * @BORAD_SIZE | |
canvas.style.height = canvas.style.width = @CELL_SIZE * @BORAD_SIZE + "px" | |
canvas | |
# | |
# Canvasのcontextのセットアップ | |
# | |
setupContext:() -> | |
context = @canvas.getContext('2d') | |
context.fillStyle = "rgb(0,0,0)" | |
context | |
# | |
# メモリーに値をセット | |
# | |
setMemory:(func) -> | |
memory = Array() | |
for x in [0..@BORAD_SIZE - 1] | |
memory[x] = Array() | |
for y in [0..@BORAD_SIZE - 1] | |
memory[x][y] = func(x,y); | |
memory | |
# | |
# メモリーにランダムに0か1を。 | |
# | |
createMemory:() -> | |
@setMemory( -> | |
(Math.random() * 3 < 1) + 0 | |
) | |
# | |
# 次の状態をメモリーに。 | |
# | |
nextMemory:() -> | |
@setMemory( (x,y)=> | |
state = @checkState(x,y); | |
if @memory[x][y] == 1 and (state == 2 or state == 3) | |
1 | |
else if(@memory[x][y] == 0 and state == 3) | |
1 | |
else | |
0 | |
) | |
# | |
# 更新処理 | |
# | |
update:() => | |
@render(); | |
@memory = @nextMemory(); | |
clearTimeout(@timer); | |
@timer = setTimeout @update, 1000/@FPS | |
# | |
# レンダリング | |
# | |
render:() -> | |
@context.clearRect(0, 0, @canvas.width, @canvas.height); | |
for x in [0..@BORAD_SIZE - 1] | |
for y in [0..@BORAD_SIZE - 1] | |
if @memory[x][y] | |
@context.fillRect(y * @CELL_SIZE, x * @CELL_SIZE, @CELL_SIZE, @CELL_SIZE) | |
# | |
# 周囲の生きているセルを数える | |
# | |
checkState:(x,y) -> | |
n = @n | |
@memory[n(x-1)][n(y-1)] + | |
@memory[n(x-1)][y] + | |
@memory[n(x-1)][n(y+1)] + | |
@memory[x][n(y-1)] + | |
@memory[x][n(y+1)] + | |
@memory[n(x+1)][n(y-1)] + | |
@memory[n(x+1)][y] + | |
@memory[n(x+1)][n(y+1)] | |
# | |
# bounded grid | |
# | |
n:(num) => | |
if num < 0 | |
num + @BORAD_SIZE | |
else if num >= @BORAD_SIZE | |
num - @BORAD_SIZE | |
else | |
num | |
do ($ = jQuery) -> | |
$.fn.Game_of_Life = (CELL_SIZE, BORAD_SIZE, FPS)-> | |
new Game_of_Life( @.get(0), CELL_SIZE, BORAD_SIZE, FPS) | |
jQuery ($)-> | |
$("canvas").Game_of_Life(3,400,500); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment