Friday, February 29, 2008

Minesweeper in Javascript

http://www.geocities.jp/teruakigemma/nikoniko/minesweeper.html


var field;
var closed_field;

function field_onclick(p) {
switch(field[p]) {
case '*':
field.each(function(x,i) {
if (x == '*') {
$('img' + i).src = 'mine.png';
new Effect.Shake('img' + i);
}
});
alert('Game Over');
main();
break;
case 0:
zero_region(p).map(neighbor).flatten().uniq().each(function(x) {
closed_field[x] = null;
$('img' + x).src = 'mine' + field[x] + '.png';
$('' + x).disabled = 'disabled';
});
break;
default:
closed_field[p] = null;
$('img' + p).src = 'mine' + field[p] + '.png';
$('' + p).disabled = 'disabled';
break;
}
if (closed_field.compact().length == 10) {
field.each(function(x,i) {
if (x == '*') {
$('img' + i).src = 'mine.png';
new Effect.Puff('img' + i);
}
});
alert('Congratulation!');
}
}

function zero_region(p) {
var result = [];
var f = function(n) {
var l = [].without.apply(neighbor(n).select(function(x) {return (field[x] == 0)}),result);
if (l.length != 0) {
result = result.concat(l);
l.each(f);
}
}
f(p);
return result;
}

function neighbor(p) {
var x = Math.floor(p / 9);
var y = p % 9;
var f = function(i,j) {
if (i < 0 || i > 8 || j < 0 || j > 8)
return null;
else
return i * 9 + j;
};
return [f(x-1,y-1),f(x,y-1),f(x+1,y-1),
f(x-1,y),f(x,y),f(x+1,y),
f(x-1,y+1),f(x,y+1),f(x+1,y+1)].compact();
}

function make_mine_field() {
field = $R(0,81,true).map(function(x) {return 0});
closed_field = $R(0,81,true).map(function(x) {return true});
var i = 0;
while(i < 10) {
var p = Math.floor(Math.random() * 81);
if (field[p] != '*') {
field[p] = '*';
i++;
}
}
field.each(function(x,i) {
if (x != '*')
field[i] = neighbor(i).select(function(y) {
return (field[y] == '*')}).length});
}

function main() {
make_mine_field();
Builder.dump();
var e = $('main');
while (e.firstChild) e.removeChild(e.firstChild);
field.inGroupsOf(9).each(function(x,i){
x.each(function(y,j) {
var num = i * 9 + j;
e.appendChild(BUTTON({id: num, onclick: 'field_onclick(' + num + ')'},
IMG({id: 'img' + num, src: 'field.png'})))});
e.appendChild(BR())});
}

window.onload = main;

No comments: