1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114
| function Player(name, teamColor) { this.state = "live"; this.name = name; this.teamColor = teamColor; }
Player.prototype.win = function(){ console.log( this.name + ' won ' ); };
Player.prototype.lose = function(){ console.log( this.name +' lost' ); };
Player.prototype.die = function () { this.state = "dead"; playerDirector.receiveMessage("playerDead", this); };
Player.prototype.remove = function () { playerDirector.receiveMessage("removePlayer", this); };
Player.prototype.changeTeam = function (color) { playerDirector.receiveMessage("changeTeam", this, color); };
let playerDirector = (function () { let players = {}, operations = {}; operations.addPlayer = function (player) { let teamColor = player.teamColor; players[teamColor] = players[teamColor] || []; players[teamColor].push(player); }; operations.removePlayer = function (player) { let teamColor = player.teamColor, teamPlayers = players[teamColor] || []; for (let i = teamPlayers.length - 1; i >= 0; i--) { if (teamPlayers[i] === player) { teamPlayers.splice(i, 1); } } }; operations.changeTeam = function (player, newTeamColor) { operations.removePlayer(player); player.teamColor = newTeamColor; operations.addPlayer(player); }; operations.playerDead = function (player) { let teamColor = player.teamColor, teamPlayers = players[teamColor]; let all_dead = true; for (let i = 0, player; player = teamPlayers[i++];) { if (player.state !== "dead") { all_dead = false; break; } } if (all_dead === true) { for (let i = 0, player; player = teamPlayers[i++];) { player.lose(); } for (let color in players) { if (color !== teamColor) { let teamPlayers = players[color]; for (let i = 0, player; player = teamPlayers[i++];) { player.win(); } } } } };
let receiveMessage = function () { let message = Array.prototype.shift.call(arguments); operations[message].apply(this, arguments); }; return { receiveMessage: receiveMessage, }; })();
let playerFactory = function (name, teamColor) { let newPlayer = new Player(name, teamColor); playerDirector.receiveMessage("addPlayer", newPlayer); return newPlayer; };
let player1 = playerFactory("皮蛋", "red"), player2 = playerFactory("小乖", "red"), player3 = playerFactory("宝宝", "red"), player4 = playerFactory("小强", "red");
let player5 = playerFactory("黑妞", "blue"), player6 = playerFactory("葱头", "blue"), player7 = playerFactory("胖墩", "blue"), player8 = playerFactory("海盗", "blue");
player1.die(); player2.die(); player3.die(); player4.die();
|