Appearance
命令者模式
HTML
HTML
<html>
<body>
<button id="replay">播放录像<button>
</body>
</html>
JS
JS
var Ryu = {
attack: function () {
console.log('攻击')
},
defense: function () {
console.log('防御')
},
jump: function () {
console.log('跳跃')
},
crouch: function () {
console.log('蹲下')
}
}
// 保存命令
var makeCommand = function (receive, state) {
return function () {
receive[state]()
}
}
// 命令对应key值
var commands = {
"119": "jump",
"115": 'crouch',
"97": 'defense',
"100": 'attack'
};
// 保存明令
var commandStack = []
document.onkeypress = function(ev) {
var keyCode = ev.keyCode
var command = makeCommand(Ryu, commands[keyCode])
if (command) {
command()
commandStack.push(command)
}
}
// 播放命令录像
document.getElementById('replay').onclick = function() {
var command;
while(command = commandStack.shift()) {
command()
}
}