<!-- // replay.html -->
<canvas class="box" id="canvas" width="500" height="500"></canvas>
<div>
<button type="button" id="start">start</button>
<button type="button" id="over">over</button>
<button type="button" id="replay">replay</button>
</div>
<script>
// replay.js
// 初始化相关数据
var rect = {
x: 225,
y: 225,
w: 50,
h: 50
},
delay = 0,
commandStack = [],
ctx = document.getElementById('canvas').getContext('2d');
// 创建角色动作集合
var role = {
clear: function (x, y, w, h) {
ctx.clearRect(x, y, w, h);
},
drawInit: function (x, y, w, h) {
rect = {
x: x,
y: y,
w: w,
h: h
};
this.clear(0, 0, 500, 500);
ctx.fillStyle = "#bcf";
ctx.strokeStyle = "#888";
ctx.fillRect(x, y, w, h);
},
up: function (range) {
rect.y -= range;
this.drawInit(rect.x, rect.y, rect.w, rect.h);
},
down: function (range) {
rect.y += range;
this.drawInit(rect.x, rect.y, rect.w, rect.h);
},
left: function (range) {
rect.x -= range;
this.drawInit(rect.x, rect.y, rect.w, rect.h);
},
right: function (range) {
rect.x += range;
this.drawInit(rect.x, rect.y, rect.w, rect.h);
}
}
// 创建任务集合, 抽象为可携带参数
var commands = {
'119': {
fn: 'up',
args: [2]
},
'115': {
fn: 'down',
args: [2]
},
'97': {
fn: 'left',
args: [2]
},
'100': {
fn: 'right',
args: [2]
},
'drawInit': {
fn: 'drawInit',
args: [rect.x, rect.y, rect.w, rect.h]
},
'clear': {
fn: 'clear',
args: [0, 0, 500, 500]
}
}
// 利用闭包存储任务并赋予角色动作
var makeCommand = function (receiver, state) {
return function () {
receiver[state].apply(role, arguments)
}
}
// 执行角色任务及将存储的任务压入回放任务队列
function runAndPushStack (key) {
var command = makeCommand(role, commands[key]['fn']),
args = commands[key]['args'];
if (command) {
commandStack.push({
fn: command,
args: args || [],
delay: (new Date()).getTime() - delay // 传入每次动作距离开始时间延迟
});
command.apply(role, args);
}
}
// 初始化数据函数
function initConfig () {
delay = (new Date()).getTime();
commandStack = [];
rect = {
x: 225,
y: 225,
w: 50,
h: 50
};
}
// 监控键盘事件
document.onkeypress = function (e) {
var keyCode = e.keyCode;
runAndPushStack(keyCode);
}
// 开始录制
document.getElementById('start').onclick = function () {
initConfig();
document.getElementById('over').disabled = false;
runAndPushStack('drawInit');
}
// 结束录制
document.getElementById('over').onclick = function () {
this.disabled = true;
commandStack.push({
fn: function () {
alert('结束了!');
},
delay: (new Date()).getTime() - delay // 传入每次动作距离开始时间延迟
});
}
// 开始回放
document.getElementById('replay').onclick = function () {
if (!document.getElementById('over').disabled) {
alert('请先停止录制');
return 0;
}
var command;
for (var i = 0; i < commandStack.length; i++) {
(function (command) {
setTimeout(function () {
command.fn.apply(role, command.args);
}, command.delay || 0);
})(commandStack[i]);
}
}
</script>
学习游戏demo(函数式编程、命令模式、工厂模式)
最新推荐文章于 2021-02-22 03:45:21 发布