悔棋功能通过一个栈结构来实现:每走一步,就将当前棋盘状态 push 进栈;需要悔棋时,从栈中 pop 出上一步的状态并恢复。

/**
 * map stack is provide a stack to regret
 */



MAX_STEP = 4;// max step of stack save map
// you can change value to modify the stack capacity

var MapStack = cc.Class.extend({
    stack: null,//inner data structrue
    index: null,// cursor of stack
    ctor: function () {
        this.stack = new Array(MAX_STEP);
        this.index = 0;
        for (var i = 0; i < MAX_STEP; i++) this.stack[i] = 0;

    },

    /** clear the stack
     * @warning this will not remove data so,please use pop or
         * push to operation this stack not use this.stack...
     * */
    clear: function () {
        this.index = 0;
    },

    /** push a member into stack
     * @param arg the member
     * @warning please use deep copy to push member
     */
    push: function (arg) {
        if (this.index == MAX_STEP) {// full
            for (var i = 0; i < MAX_STEP - 1; i++) {
                this.stack[i] = this.stack[i + 1];
            }
            this.index = MAX_STEP - 1;
        }

        this.stack[this.index] = arg;
        this.index++;
        cc.log("map stack push:" + arg);

    },
    /**pop a member and return the member which is pop
     * @return member which is pop
     */
    pop: function () {
        if (this.index > 0) {
            var ret = this.stack[this.index - 1];
            this.index--;
            return ret;
        }
        return null;
    },
    /**return the stack'stop member
     * @return the top member of the stack's top
     */
    top: function () {
        if (this.index > 0) return this.stack[this.index - 1];
        return null;
    }
});