Logic Puzzle
by egon
HTML
<div id="center">
<canvas id="canvas"></canvas>
<hr />
<div id="logDiv"></div>
<script type="text/javascript">
canvas = document.getElementById("canvas");
W=400; H=400;
canvas.width = W;
canvas.height = H,
canvas2D = canvas.getContext("2d");
log = (function(){
var logDiv = document.getElementById("logDiv");
return function(){
var args = [];
for(var i=0; i < arguments.length; i++)
args.push( arguments[i] );
logDiv.innerHTML = "<p>" + JSON.stringify(args) + "</p>" + logDiv.innerHTML;
};
})();
</script>
</div>
CSS
body {
margin : 0 0;
width : 100%;
background: #000;
}
#center {
align : center;
margin : 0 auto;
margin-top : 30px;
width : 400px;
}
hr {
color: #fff;
}
#logDiv {
font:normal 12px/16px Courier New, monospace;
color: #fff;
height: 200px;
overflow: scroll;
}
JavaScript
ct = {
Wall : "#",
Start : "x",
Point : "o",
Empty : " "
};
function NewBoard(field){
var b = {};
b.size = [field[0].length, field.length];
b.field = [];
for(var y = 0; y < b.size[1]; y++){
var row = field[y].split("");
if( b.size[0] != row.length )
log("Wrong row length!", b.size[0], row.length);
b.field.push( row );
}
return b;
}
function CloneBoard(board){
var b = {};
b.size = board.size.slice();
b.field = [];
for(var y = 0; y < b.size[1]; y++)
b.field.push( board.field[y].slice() );
return b;
}
board = NewBoard(
["######",
"#x #",
"# #",
"# ##",
"######"]);
function CountNeighborsX( board, x, y, type){
var count = 0;
if( board.field[y - 1][x - 1] == type ) count++;
if( board.field[y + 1][x - 1] == type ) count++;
if( board.field[y - 1][x + 1] == type ) count++;
if( board.field[y + 1][x + 1] == type ) count++;
return count;
}
function CountNeighbors4( board, x, y, type ){
var count = 0;
if( board.field[y + 0][x - 1] == type ) count++;
if( board.field[y + 0][x + 1] == type ) count++;
if( board.field[y - 1][x + 0] == type ) count++;
if( board.field[y + 1][x + 0] == type ) count++;
return count;
}
function CountNeighbors8( board, x, y, type ){
var count = 0;
for(var dy = -1; dy < 1; dy++){
for(var dx = -1; dx < 1; dx++){
if( (dx == 0) && (dy == 0) ) continue;
if( board.field[y + dy][x + dx] == type )
count++;
}
}
return count;
};
function UpdateBoard( board ){
var b = CloneBoard(board);
var added = 0;
for(var y = 1; y < board.size[1] - 1; y++){
for(var x = 1; x < board.size[0] - 1; x++){
if( board.field[y][x] == ct.Wall) continue;
var sc = CountNeighbors4( board, x, y, ct.Start ),
pc = CountNeighborsX( board, x, y, ct.Point );
if( (sc > 0)...