js数据结构之栈、队列(数据结构与拉火车游戏)
1.js实现队列的数据结构(先进先出)
function Queue (array) { if(Object.prototype.toString.call(array)!="[object Array]") { throw "target is not an Array !" } this.queue = array; this.pushQueue = function (ele) { this.queue.push(ele) } this.delQueue = function () { this.queue.shift() } this.getFirst = function () { return this.queue[0] } this.getLast = function () { return this.queue[this.queue.length] } this.isEmpty = function () { return this.queue.length?false:true } this.getArray = function () { return this.queue } // 出队列并获取出队列的元素 this.delGet = function () { var last = this.getFirst(); this.delQueue(); return last; } }
2. js实现栈(先进后出)
function Stack (array) { if(Object.prototype.toString.call(array)!="[object Array]") throw "target is not an Array !" this.stack = array; this.addStack = function (ele) { this.stack.push(ele) } this.delStack = function () { this.stack.pop(); } // 出栈并获取出栈的元素 this.delGet = function () { var last = this.getLast(); this.delStack(); return last; } this.getFirst = function () { return this.stack[0] } this.getLast = function () { return this.stack[this.stack.length-1] } this.getArray = function () { return this.stack } }
***** 实现拉火车游戏
游戏约定如下:
1.首先给定相同数量的牌
2. 不同玩家轮流出牌
3.当出牌后,两张最近的相同牌之间的所有牌可以被当前玩家获取,获取后放在尾部
4.先出完牌的玩家输
*****定义玩家类
// name: 玩家名字 queue:队列数据结构 playGround:游戏台,用于存放玩家出的牌 function dragTrainPlayer (name, queue, playGround) { if(Object.prototype.toString.call(array) !== "[object Array]") throw "target is not an Array !" this.name = name; this.cards = queue; this.getName = function () { return this.name } this.getArray = function () { return this.cards.getArray(); } // 每次出牌需检查一次 this.giveCard = function () { if(this.cards.getArray().length==0) return 0 playGround.push(this.cards.delGet()) this.check() } // 检查是否可获取牌 this.check = function () { // 依次比对,最近相同牌之间的牌截取下来,与玩家当前手中的牌拼接 for (var i=playGround-1; i>0; i--) { if(playGround[playGround.length-1] === playGround[i]) { this.cards.getArray().concat(this.cards.slice(i)) return } } } }
******* 定义游戏开始函数
function gameStart (player) { var flag = 1; // 如果没有出现玩家手中无牌的情况,则一直执行下去 while (flag) { for(var i = 0; i<arguments.length; i++) { if(arguments[i].getArray().length === 0) { flag = 0; // 返回第一个出完牌的玩家的名字 return arguments[i].getName(); } arguments[i].giveCard(); // 以下代码块用于每次出牌的测试 console.log("---------"); for(var i=0;i<arguments.length; i++) { console.log(arguments[i].getName()); console.log(arguments[i].getArray()); console.log(playGround); }; console.log("---------"); } } }
*******创建对象并执行
var playGround = [];
var stack1 = new Queue([5,8,6,9,8]); var stack2 = new Queue([9,9,6,5,3]); var stack3 = new Queue([7,4,2,5,1]); var player1 = new dragTrainPlayer("player1", stack1, playGround) var player2 = new dragTrainPlayer("player2", stack2, playGround) var player3 = new dragTrainPlayer("player3", stack2, playGround) console.log(gameStart(player1, player2, player3))