Life-Canvas/life.html

124 lines
2.5 KiB
HTML
Raw Normal View History

2011-06-16 06:30:30 +00:00
<html>
<head>
<title>The Game of Life: HTML Canvas Demo</title>
<script language="javascript">
var size;
2011-06-20 05:39:10 +00:00
var hertz;
2011-06-16 06:30:30 +00:00
var height;
var width;
2011-06-16 14:15:21 +00:00
var cells;
2011-06-16 06:30:30 +00:00
function btn_control_set_name(name) {
var btn = document.getElementById('control-btn');
btn.value = name;
}
2011-06-20 05:39:10 +00:00
function gen_cells() {
2011-06-16 14:15:21 +00:00
var hcells = height/size;
var wcells = width/size;
2011-06-20 05:39:10 +00:00
var new_cells = new Array(hcells);
2011-06-16 14:15:21 +00:00
for(var i = 0; i < hcells; i++) {
2011-06-20 05:39:10 +00:00
new_cells[i] = new Array(wcells);
2011-06-16 14:15:21 +00:00
}
for (var y = 0; y < hcells; y++) {
for (var x = 0; x < wcells; x++) {
2011-06-20 05:39:10 +00:00
new_cells[y][x] = false;
2011-06-16 14:15:21 +00:00
}
}
2011-06-20 05:39:10 +00:00
return new_cells;
}
function init_cells() {
cells = gen_cells();
2011-06-16 14:15:21 +00:00
}
2011-06-16 06:30:30 +00:00
function board_init() {
2011-06-16 14:15:21 +00:00
var canvas = document.getElementById('board');
width = canvas.width;
height = canvas.height;
2011-06-16 06:30:30 +00:00
btn_control_set_name('Start');
size = 10;
2011-06-20 05:39:10 +00:00
hertz = 4;
2011-06-16 14:15:21 +00:00
init_cells();
2011-06-16 06:30:30 +00:00
redraw();
}
function redraw() {
var canvas = document.getElementById('board');
var c = canvas.getContext('2d');
draw_grid(c);
2011-06-16 14:15:21 +00:00
c.stroke();
cells[1][2] = true;
cells[3][4] = true;
cells[5][5] = true;
draw_cells(c);
c.stroke();
c.fill();
}
function draw_cells(c) {
var hcells = height/size;
var wcells = width/size;
for (var y = 0; y < hcells; y++) {
for (var x =0; x < wcells; x ++) {
if (cells[y][x] == true) {
c.moveTo(x*size, y*size);
c.lineTo(x*size+ size, y*size);
c.lineTo(x*size+ size, y*size + size);
c.lineTo(x*size, y*size + size);
// auto return home?
}
}
}
2011-06-16 06:30:30 +00:00
}
function draw_grid(c) {
// Horizontal lines
for (var y = 0; y <= height; y += size) {
c.moveTo(0, y);
c.lineTo(width, y);
}
// Vertical lines
for (var x = 0; x <= width; x += size) {
c.moveTo(x, 0);
c.lineTo(x, height);
}
}
window.onload = board_init;
2011-06-20 05:39:10 +00:00
function step() {
var new_cells = gen_cells();
for(var y=0; y <= height; y++) {
for(var x =0 ; x <= width; x++) {
var n = num_neighbours(x, y);
if (cells[y][x] == true) {
if (n < 2 || n > 3) {
new_cells[y][x] = false;
} else {
new_cells[y][x] = true;
}
} else if (n == 3) {
new_cells[y][x] = true;
} else {
new_cells[y][x] = false;
}
}
}
}
2011-06-16 06:30:30 +00:00
</script>
</head>
<body>
<input type="button" id="control-btn"/>
<br/>
<canvas width="800" height="400" id="board" ></canvas>
</body>
</html>