let playerDirector = (function() {
const players = {}, // 保存所有玩家
operations = {} // 中介者可以执行的操作
/****************新增一个玩家***************************/
operations.addPlayer = function(player) {
const teamColor = player.teamColor // 玩家的队伍颜色
players[teamColor] = players[teamColor] || [] // 如果该颜色的玩家还没有成立队伍,则新成立一个队伍
players[teamColor].push(player) // 添加玩家进队伍
}
/****************移除一个玩家***************************/
operations.removePlayer = function(player) {
const 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) {
const 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() // 本队所有玩家 lose
}
for (let color in players) {
if (color !== teamColor) {
const teamPlayers = players[color]
for (let i = 0, player; (player = teamPlayers[i++]); ) {
player.win()
}
}
}
}
}
const reciveMessage = function() {
const message = Array.prototype.shift.call(arguments)
operations[message].apply(this, arguments)
}
return {
reciveMessage: reciveMessage
}
})()