「コンウェイのライフゲーム」の実装です。
「コンウェイのライフゲーム」の実装です。
HTML
<canvas id="Canvas"></canvas> <br> <form> <div class="ms"><input type="button" value="初期化" onclick="start();"></div> </form> <script type="text/javascript" src="lifegame.js"></script>
CoffeeScript
width = 30; height = 30 cellwidth = 10; space = 3; margin = 8 wd = cellwidth * width + space * (width - 1) + 2 * margin ht = cellwidth * height + space * (height - 1) + 2 * margin ctx = f = w = id = null Field = (width, height)-> @width = width @height = height @field = [] for i in [0...(@width + 2)] @field[i] = [] for j in [0...(@height + 2)] @field[i][j] = 0 @generate = (n)-> for i in [1..n] @field[Math.floor(Math.random() * @width) + 1][Math.floor(Math.random() * @height) + 1] = 1 @show = -> for x in [1..@width] for y in [1..@height] if @field[x][y] w.set(x, y) else w.reset(x, y) @windowx = (x)-> margin + (x - 1) * cellwidth + (x - 1) * space @windowy = (y)-> margin + (y - 1) * cellwidth + (y - 1) * space @next = -> nxf = [] for i in [0...(@width + 2)] nxf[i] = [] for j in [0...(@height + 2)] nxf[i][j] = 0 for x in [1..@width] for y in [1..@height] n = @alive_cells(x, y) if @field[x][y] nxf[x][y] = 1 if n == 2 or n == 3 else nxf[x][y] = 1 if n == 3 @field = nxf @alive_cells = (x, y)-> @field[x - 1][y - 1] + @field[x][y - 1] + @field[x + 1][y - 1] + @field[x - 1][y] + @field[x + 1][y] + @field[x - 1][y + 1] + @field[x][y + 1] + @field[x + 1][y + 1] null Window = -> @set = (x, y)-> ctx.fillStyle = "rgb(255, 255, 255)" @draw_cell(x, y) @reset = (x, y)-> ctx.fillStyle = "rgb(0, 0, 0)" @draw_cell(x, y) @draw_cell = (x, y)-> ctx.beginPath() ctx.fillRect(f.windowx(x), f.windowy(y), cellwidth, cellwidth) ctx.fill() null mainloop = -> f.show() f.next() return window.start = -> window.clearInterval(id) if id ctx.clearRect(0, 0, wd, ht) f = new Field(width, height) f.generate(150) w = new Window() id = window.setInterval(mainloop, 200) return $(window).load -> cvs = document.getElementById("Canvas"); ctx = cvs.getContext("2d") cvs.width = wd; cvs.height = ht return
クラス定義の最後は必ず null を置くこと。