Created
September 15, 2013 18:48
-
-
Save vim13/6573361 to your computer and use it in GitHub Desktop.
ライフゲーム
This file contains 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
var SCREEN_WIDTH = 848; | |
var SCREEN_HEIGHT = 576; | |
var SIDE_CELLS = 300; | |
var CELL_SIZE = SCREEN_WIDTH / SIDE_CELLS; | |
var FPS = 10; | |
var canvas; | |
var context; | |
window.onload = function() { | |
var n = SIDE_CELLS * Math.floor(SIDE_CELLS * (SCREEN_HEIGHT/SCREEN_WIDTH) ); | |
var field = new Array(n); | |
var tempField = new Array(n); | |
for (var i = 0; i < field.length; i++) field[i] = Math.floor(Math.random()*2); | |
canvas = document.getElementById('ocean'); | |
canvas.width = SCREEN_WIDTH; | |
canvas.height = SCREEN_HEIGHT; | |
context = canvas.getContext('2d'); | |
context.fillStyle = 'rgb(73,102,45)'; | |
update(field, tempField); | |
} | |
function update(field, tempField) { | |
var n = 0; | |
tempField = field.slice(); | |
for (var i = 0; i < tempField.length; i++) { | |
n = 0; | |
for (var x = -1; x < 2; x++) { | |
for (var y = -1; y < 2; y++) { | |
if (x==0 && y==0) continue; | |
var c = i + x*SIDE_CELLS + y; | |
if (c>=0 && c<tempField.length) { | |
if (i<c && c%SIDE_CELLS != 0 || i>c && c%SIDE_CELLS != SIDE_CELLS-1) { | |
if (tempField[c]) n++; | |
} | |
} | |
} | |
} | |
if (tempField[i] && (n==2 || n==3)) { | |
field[i] = 1; | |
} else if (!tempField[i] && n==3) { | |
field[i] = 1; | |
} else field[i] = 0; | |
} | |
draw(field); | |
setTimeout(update, 1000/FPS, field, tempField); | |
} | |
function draw(field) { | |
context.clearRect(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT); | |
for (var i = 0; i < field.length; i++) { | |
if (field[i]) context.fillRect( (i%SIDE_CELLS)*CELL_SIZE, Math.floor((i/SIDE_CELLS))*CELL_SIZE, CELL_SIZE, CELL_SIZE); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment