日期:2014-05-16 浏览次数:20552 次
/*--
标题:围堵
设计:王集鹄
博客:http://blog.csdn.net/zswang
日期:2009年12月5日
--*/
//2009年12月6日 王集鹄 添加 地图参数、马和象的走法、操作次数、图像样式的兼容
function Box(options) {
options = options || {};
var self = this;
this.rowCount = options.rowCount || 15; // 行数
this.colCount = options.colCount || 15; // 列数
this.kickCount = options.kickCount || 1; // 玩家操作多少次一个周期
this.parent = options.parent || document.body; // 容器
this.caption = options.caption || "Replay"; // 标题
this.map = (options.map || "").replace(/\s+/g, ""); // 地图数据
this.button = document.createElement("input");
this.button.type = "button";
this.button.value = this.caption;
this.button.onclick = function() {
self.replay();
};
this.parent.appendChild(this.button);
this.table_back = document.createElement("table");
this.table_back.className = "table_back";
this.table_back.cellPadding = "0px";
this.table_back.cellSpacing = "0px";
this.playing = false; // 是否在进行中
this.floors = {}; // 矩阵地板矩阵 [y,x]
for (var i = 0; i < this.rowCount; i++) {
var tr = this.table_back.insertRow(-1);
for (var j = 0; j < this.colCount; j++) {
var td = tr.insertCell(-1);
this.floors[i + "," + j] = new Floor({
td: td
, box: this
, pos: { x: j, y: i }
});
}
}
this.parent.appendChild(this.table_back);
this.replay();
}
// 重新开始
Box.prototype.replay = function() {
this.playing = true;
this.mickeys = [];
this.step = 0;
var k = 0;
for (var i = 0; i < this.rowCount; i++) {
for (var j = 0; j < this.colCount; j++) {
var name = this.map.substr(k++, 1);
switch(name) {
case "1": case "x": case "w": case "c":
this.floors[i + "," + j].setState("closed");
break;
case "r": case "b": case "n": case "q":
var mickey = new Mickey({name: name, box: this, pos: {x: j, y: i}});
this.mickeys.push(mickey);
break;
default:
this.floors[i + "," + j].setState("blank");
break;
}
}
}
};
// 下一个周期
Box.prototype.kick = function() {
if (!this.playing) return;
this.step++;
if (this.step % this.kickCount != 0) return;
var count = 0;
var freedom = false;
for (var i = 0; i < this.mickeys.length; i++) {
if (this.mickeys[i].run()) count++;
if (this.mickeys[i].freedom) freedom = true;
}
if (freedom) // 有老鼠跑了
this.gameover();
else if (!count) this.win();
};
// 游戏结束
Box.prototype.gameover = function() {
if (!this.playing) return;
this.playing = false;
if (this.ongameover)
this.ongameover();
else alert(this.caption + "跑掉了。o(╯□╰)o");
};
Box.prototype.win = function() {
if (!this.playing) return;
this.playing = false;
if (this.onwin)
this.onwin();
else alert(this.caption + "O(∩_∩)O成功!");
};
// 地板
function Floor(options) {
options = options || {};
var self = this;
this.td = options.td || {};
this.td.innerHTML = " ";
this.td.onclick = function() {
if (!self.box.playing) return; // 游戏已经结束
if (self.state != "blank") return;
self.setState("closed"