message (5)
message (5)
/* ROOM */
const scoreLimitClassic = 3;
const scoreLimitBig = 3;
const timeLimitClassic = 4;
const timeLimitBig = 4;
room.setTeamsLock(true);
/* COLORES */
/* TIPO DE LETRAS */
/* STADIUM */
/* OPTIONS */
/* PLAYERS */
/* GAME */
var lastTeamTouched;
var lastPlayersTouched; // These allow to get good goal notifications (it should be
lastPlayersKicked, waiting on a next update to get better track of shots on target)
var countAFK = false; // Created to get better track of activity
var activePlay = false; // Created to get better track of the possession
var goldenGoal = false;
var SMSet = new Set(); // Set created to get slow mode which is useful in
chooseMode
var banList = []; // Getting track of the bans, so we can unban ppl if we want
/* STATS */
var game;
var GKList = ["",""];
var Rposs = 0;
var Bposs = 0;
var point = [{"x": 0, "y": 0}, {"x": 0, "y": 0}]; // created to get ball speed
var ballSpeed;
var lastWinner = Team.SPECTATORS;
var streak = 0;
var allBlues = []; // This is to count the players who should be counted for the
stats. This includes players who left after the game has started, doesn't include
those who came too late or ...
var allReds = []; // ... those who came in a very unequal game.
/* AUXILIARY */
var checkTimeVariable = false; // This is created so the chat doesn't get spammed
when a game is ending via timeLimit
var statNumber = 0; // This allows the room to be given stat information every X
minutes
var endGameVariable = false; // This variable with the one below helps distinguish
the cases where games are stopped because they have finished to the ones where
games are stopped due to player movements or resetting teams
var resettingTeams = false;
var capLeft = false;
var statInterval = 6;
loadMap(aloneMap, 0, 0);
/* OBJECTS */
/* AUXILIARY FUNCTIONS */
/* BUTTONS */
function topBtn() {
if (teamS.length == 0) {
return;
}
else {
if (teamR.length == teamB.length) {
if (teamS.length > 1) {
room.setPlayerTeam(teamS[0].id, Team.RED);
room.setPlayerTeam(teamS[1].id, Team.BLUE);
}
return;
}
else if (teamR.length < teamB.length) {
room.setPlayerTeam(teamS[0].id, Team.RED);
}
else {
room.setPlayerTeam(teamS[0].id, Team.BLUE);
}
}
}
function randomBtn() {
if (teamS.length == 0) {
return;
}
else {
if (teamR.length == teamB.length) {
if (teamS.length > 1) {
var r = getRandomInt(teamS.length);
room.setPlayerTeam(teamS[r].id, Team.RED);
teamS = teamS.filter((spec) => spec.id != teamS[r].id);
room.setPlayerTeam(teamS[getRandomInt(teamS.length)].id,
Team.BLUE);
}
return;
}
else if (teamR.length < teamB.length) {
room.setPlayerTeam(teamS[getRandomInt(teamS.length)].id,
Team.RED);
}
else {
room.setPlayerTeam(teamS[getRandomInt(teamS.length)].id,
Team.BLUE);
}
}
}
function blueToSpecBtn() {
resettingTeams = true;
setTimeout(() => { resettingTeams = false; }, 100);
for (var i = 0; i < teamB.length; i++) {
room.setPlayerTeam(teamB[teamB.length - 1 - i].id, Team.SPECTATORS);
}
}
function redToSpecBtn() {
resettingTeams = true;
setTimeout(() => { resettingTeams = false; }, 100);
for (var i = 0; i < teamR.length; i++) {
room.setPlayerTeam(teamR[teamR.length - 1 - i].id, Team.SPECTATORS);
}
}
function resetBtn() {
resettingTeams = true;
setTimeout(() => { resettingTeams = false; }, 100);
if (teamR.length <= teamB.length) {
for (var i = 0; i < teamR.length; i++) {
room.setPlayerTeam(teamB[teamB.length - 1 - i].id,
Team.SPECTATORS);
room.setPlayerTeam(teamR[teamR.length - 1 - i].id,
Team.SPECTATORS);
}
for (var i = teamR.length; i < teamB.length; i++) {
room.setPlayerTeam(teamB[teamB.length - 1 - i].id,
Team.SPECTATORS);
}
}
else {
for (var i = 0; i < teamB.length; i++) {
room.setPlayerTeam(teamB[teamB.length - 1 - i].id,
Team.SPECTATORS);
room.setPlayerTeam(teamR[teamR.length - 1 - i].id,
Team.SPECTATORS);
}
for (var i = teamB.length; i < teamR.length; i++) {
room.setPlayerTeam(teamR[teamR.length - 1 - i].id,
Team.SPECTATORS);
}
}
}
function blueToRedBtn() {
resettingTeams = true;
setTimeout(() => { resettingTeams = false; }, 100);
for (var i = 0; i < teamB.length; i++) {
room.setPlayerTeam(teamB[i].id, Team.RED);
}
}
/* GAME FUNCTIONS */
function checkTime() {
const scores = room.getScores();
game.scores = scores;
if (Math.abs(scores.time - scores.timeLimit) <= 0.01 && scores.timeLimit !=
0) {
if (scores.red != scores.blue) {
if (checkTimeVariable == false) {
checkTimeVariable = true;
setTimeout(() => { checkTimeVariable = false; }, 3000);
scores.red > scores.blue ? endGame(Team.RED) :
endGame(Team.BLUE);
setTimeout(() => { room.stopGame(); }, 2000);
}
return;
}
goldenGoal = true;
room.sendAnnouncement("⚽ ¡Gol gana! ⚽", null, golescolor, "bold");
}
if (Math.abs(drawTimeLimit * 60 - scores.time - 60) <= 0.01 && players.length
> 2) {
if (checkTimeVariable == false) {
checkTimeVariable = true;
setTimeout(() => { checkTimeVariable = false; }, 10);
room.sendChat("⌛ Quedan 60 segundos para que termine el
partido !");
}
}
if (Math.abs(scores.time - drawTimeLimit * 60) <= 0.01 && players.length > 2)
{
if (checkTimeVariable == false) {
checkTimeVariable = true;
setTimeout(() => { checkTimeVariable = false; }, 10);
endGame(Team.SPECTATORS);
room.stopGame();
goldenGoal = false;
}
}
}
function quickRestart() {
room.stopGame();
setTimeout(() => { room.startGame(); }, 2000);
}
function resumeGame() {
setTimeout(() => { room.startGame(); }, 2000);
setTimeout(() => { room.pauseGame(false); }, 1000);
}
function deactivateChooseMode() {
inChooseMode = false;
clearTimeout(timeOutCap);
if (slowMode != 0) {
slowMode = 0;
room.sendAnnouncement("⚽ Partido iniciado ⚽");
}
redCaptainChoice = "";
blueCaptainChoice = "";
}
/* PLAYER FUNCTIONS */
function updateTeams() { // update the players' list and all the teams' list
players = room.getPlayerList().filter((player) => player.id != 0 && !
getAFK(player));
teamR = players.filter(p => p.team === Team.RED);
teamB = players.filter(p => p.team === Team.BLUE);
teamS = players.filter(p => p.team === Team.SPECTATORS);
}
function getAuth(player) {
return extendedP.filter((a) => a[0] == player.id) != null ?
extendedP.filter((a) => a[0] == player.id)[0][eP.AUTH] : null;
}
function getAFK(player) {
return extendedP.filter((a) => a[0] == player.id) != null ?
extendedP.filter((a) => a[0] == player.id)[0][eP.AFK] : null;
}
function getGK(player) {
return extendedP.filter((a) => a[0] == player.id) != null ?
extendedP.filter((a) => a[0] == player.id)[0][eP.GK] : null;
}
function getMute(player) {
return extendedP.filter((a) => a[0] == player.id) != null ?
extendedP.filter((a) => a[0] == player.id)[0][eP.MUTE] : null;
}
function updateRoleOnPlayerIn() {
updateTeams();
if (inChooseMode) {
if (players.length == 6) {
loadMap(bigMap, scoreLimitBig, timeLimitBig);
}
getSpecList(teamR.length <= teamB.length ? teamR[0] : teamB[0]);
}
balanceTeams();
}
function updateRoleOnPlayerOut() {
updateTeams();
if (room.getScores() != null) {
var scores = room.getScores();
if (players.length >= 2 * maxTeamSize && scores.time >= (5/6) *
game.scores.timeLimit && teamR.length != teamB.length) {
if (teamR.length < teamB.length) {
if (scores.blue - scores.red == 2) {
endGame(Team.BLUE);
room.sendChat("🤖 Abandono detectado. Juego
terminado 🤖");
setTimeout(() => { room.stopGame(); }, 100);
return;
}
}
else {
if (scores.red - scores.blue == 2) {
endGame(Team.RED);
room.sendChat("🤖 Abandono detectado. Juego
terminado 🤖");
setTimeout(() => { room.stopGame(); }, 100);
return;
}
}
}
}
if (inChooseMode) {
if (players.length == 5) {
loadMap(classicMap, scoreLimitClassic, timeLimitClassic);
}
if (teamR.length == 0 || teamB.length == 0) {
teamR.length == 0 ? room.setPlayerTeam(teamS[0].id, Team.RED) :
room.setPlayerTeam(teamS[0].id, Team.BLUE);
return;
}
if (Math.abs(teamR.length - teamB.length) == teamS.length) {
room.sendChat("No hay alternativa, déjame manejar esta
situación ...");
deactivateChooseMode();
resumeGame();
var b = teamS.length;
if (teamR.length > teamB.length) {
for (var i = 0 ; i < b ; i++) {
setTimeout(() => { room.setPlayerTeam(teamS[0].id,
Team.BLUE); }, 5*i);
}
}
else {
for (var i = 0 ; i < b ; i++) {
setTimeout(() => { room.setPlayerTeam(teamS[0].id,
Team.RED); }, 5*i);
}
}
return;
}
if (streak == 0 && room.getScores() == null) {
if (Math.abs(teamR.length - teamB.length) == 2) { // if someone
left a team has 2 more players than the other one, put the last chosen guy back in
his place so it's fair
room.sendChat("🤖 Equilibrando equipos... 🤖");
teamR.length > teamB.length ?
room.setPlayerTeam(teamR[teamR.length - 1].id, Team.SPECTATORS) :
room.setPlayerTeam(teamB[teamB.length - 1].id, Team.SPECTATORS);
}
}
if (teamR.length == teamB.length && teamS.length < 2) {
deactivateChooseMode();
resumeGame();
return;
}
capLeft ? choosePlayer() : getSpecList(teamR.length <= teamB.length ?
teamR[0] : teamB[0]);
}
balanceTeams();
}
function balanceTeams() {
if (!inChooseMode) {
if (players.length == 1 && teamR.length == 0) {
quickRestart();
loadMap(aloneMap, 0, 0);
room.setPlayerTeam(players[0].id, Team.RED);
}
else if (Math.abs(teamR.length - teamB.length) == teamS.length &&
teamS.length > 0) {
const n = Math.abs(teamR.length - teamB.length);
if (players.length == 2) {
quickRestart();
loadMap(classicMap, scoreLimitClassic, timeLimitClassic);
}
if (teamR.length > teamB.length) {
for (var i = 0 ; i < n ; i++) {
room.setPlayerTeam(teamS[i].id, Team.BLUE);
}
}
else {
for (var i = 0 ; i < n ; i++) {
room.setPlayerTeam(teamS[i].id, Team.RED);
}
}
}
else if (Math.abs(teamR.length - teamB.length) > teamS.length) {
const n = Math.abs(teamR.length - teamB.length);
if (players.length == 1) {
quickRestart();
loadMap(aloneMap, 0, 0);
room.setPlayerTeam(players[0].id, Team.RED);
return;
}
else if (players.length == 5) {
quickRestart();
loadMap(classicMap, scoreLimitClassic, timeLimitClassic);
}
if (players.length == maxTeamSize * 2 - 1) {
allReds = [];
allBlues = [];
}
if (teamR.length > teamB.length) {
for (var i = 0 ; i < n ; i++) {
room.setPlayerTeam(teamR[teamR.length - 1 - i].id,
Team.SPECTATORS);
}
}
else {
for (var i = 0 ; i < n ; i++) {
room.setPlayerTeam(teamB[teamB.length - 1 - i].id,
Team.SPECTATORS);
}
}
}
else if (Math.abs(teamR.length - teamB.length) < teamS.length &&
teamR.length != teamB.length) {
room.pauseGame(true);
activateChooseMode();
choosePlayer();
}
else if (teamS.length >= 2 && teamR.length == teamB.length &&
teamR.length < maxTeamSize) {
if (teamR.length == 2) {
quickRestart();
loadMap(bigMap, scoreLimitBig, timeLimitBig);
}
topBtn();
}
}
}
function choosePlayer() {
clearTimeout(timeOutCap);
if (teamR.length <= teamB.length && teamR.length != 0) {
room.sendChat("[PV] Para elegir un jugador, ingrese su número en la
lista dada o use 'top', 'random' o 'bottom'.", teamR[0].id);
timeOutCap = setTimeout(function (player) { room.sendChat("[PV] Date
prisa @" + player.name + ", solo quedan " + Number.parseInt(chooseTime / 2) + "
segundos para elegir !", player.id); timeOutCap = setTimeout(function (player)
{ room.kickPlayer(player.id, "¡No elegiste a tiempo!", false); }, chooseTime * 500,
teamR[0]); }, chooseTime * 1000, teamR[0]);
}
else if (teamB.length < teamR.length && teamB.length != 0) {
room.sendChat("[PV] Para elegir un jugador, ingrese su número en la
lista dada o use 'top', 'random' o 'bottom'.", teamB[0].id);
timeOutCap = setTimeout(function (player) { room.sendChat("[PV] Date
prisa @" + player.name + ", solo quedan " + Number.parseInt(chooseTime / 2) + "
segundos para elegir !", player.id); timeOutCap = setTimeout(function (player)
{ room.kickPlayer(player.id, "¡No elegiste a tiempo!", false); }, chooseTime * 500,
teamB[0]); }, chooseTime * 1000, teamB[0]);
}
if (teamR.length != 0 && teamB.length != 0) getSpecList(teamR.length <=
teamB.length ? teamR[0] : teamB[0]);
}
function getSpecList(player) {
var cstm = "[PV] Jugadores : ";
for (var i = 0 ; i < teamS.length ; i++) {
if (140 - cstm.length < (teamS[i].name + "[" + (i+1) + "], ").length) {
room.sendChat(cstm, player.id);
cstm = "... ";
}
cstm += teamS[i].name + "[" + (i+1) + "], ";
}
cstm = cstm.substring(0,cstm.length - 2);
cstm += ".";
room.sendChat(cstm, player.id);
}
/* STATS FUNCTIONS */
function getLastTouchOfTheBall() {
const ballPosition = room.getBallPosition();
updateTeams();
for (var i = 0; i < players.length; i++) {
if (players[i].position != null) {
var distanceToBall = pointDistance(players[i].position,
ballPosition);
if (distanceToBall < triggerDistance) {
!activePlay ? activePlay = true : null;
if (lastTeamTouched == players[i].team &&
lastPlayersTouched[0] != null && lastPlayersTouched[0].id != players[i].id) {
lastPlayersTouched[1] = lastPlayersTouched[0];
lastPlayersTouched[0] = players[i];
}
lastTeamTouched = players[i].team;
}
}
}
}
function updateStats() {
if (players.length >= 2 * maxTeamSize && (game.scores.time >= (5 / 6) *
game.scores.timeLimit || game.scores.red == game.scores.scoreLimit ||
game.scores.blue == game.scores.scoreLimit) && allReds.length >= maxTeamSize &&
allBlues.length >= maxTeamSize) {
var stats;
for (var i = 0; i < allReds.length; i++) {
localStorage.getItem(getAuth(allReds[i])) ? stats =
JSON.parse(localStorage.getItem(getAuth(allReds[i]))) : stats = [0, 0, 0, 0,
"0.00", 0, 0, 0, 0, "0.00", "player", allReds[i].name];
stats[Ss.GA]++;
lastWinner == Team.RED ? stats[Ss.WI]++ : lastWinner == Team.BLUE
? stats[Ss.LS]++ : stats[Ss.DR]++;
stats[Ss.WR] = (100 * stats[Ss.WI] /
stats[Ss.GA]).toPrecision(3);
localStorage.setItem(getAuth(allReds[i]), JSON.stringify(stats));
}
for (var i = 0; i < allBlues.length; i++) {
localStorage.getItem(getAuth(allBlues[i])) ? stats =
JSON.parse(localStorage.getItem(getAuth(allBlues[i]))) : stats = [0, 0, 0, 0,
"0.00", 0, 0, 0, 0, "0.00", "player", allBlues[i].name];
stats[Ss.GA]++;
lastWinner == Team.BLUE ? stats[Ss.WI]++ : lastWinner == Team.RED
? stats[Ss.LS]++ : stats[Ss.DR]++;
stats[Ss.WR] = (100 * stats[Ss.WI] /
stats[Ss.GA]).toPrecision(3);
localStorage.setItem(getAuth(allBlues[i]),
JSON.stringify(stats));
}
for (var i = 0; i < game.goals.length; i++) {
if (game.goals[i].striker != null) {
if ((allBlues.concat(allReds)).findIndex((player) =>
player.id == game.goals[i].striker.id) != -1) {
stats =
JSON.parse(localStorage.getItem(getAuth(game.goals[i].striker)));
stats[Ss.GL]++;
localStorage.setItem(getAuth(game.goals[i].striker),
JSON.stringify(stats));
}
}
if (game.goals[i].assist != null) {
if ((allBlues.concat(allReds)).findIndex((player) =>
player.name == game.goals[i].assist.name) != -1) {
stats =
JSON.parse(localStorage.getItem(getAuth(game.goals[i].assist)));
stats[Ss.AS]++;
localStorage.setItem(getAuth(game.goals[i].assist),
JSON.stringify(stats));
}
}
}
if (allReds.findIndex((player) => player.id == GKList[0].id) != -1) {
stats = JSON.parse(localStorage.getItem(getAuth(GKList[0])));
stats[Ss.GK]++;
game.scores.blue == 0 ? stats[Ss.CS]++ : null;
stats[Ss.CP] = (100 * stats[Ss.CS] /
stats[Ss.GK]).toPrecision(3);
localStorage.setItem(getAuth(GKList[0]), JSON.stringify(stats));
}
if (allBlues.findIndex((player) => player.id == GKList[1].id) != -1) {
stats = JSON.parse(localStorage.getItem(getAuth(GKList[1])));
stats[Ss.GK]++;
game.scores.red == 0 ? stats[Ss.CS]++ : null;
stats[Ss.CP] = (100 * stats[Ss.CS] /
stats[Ss.GK]).toPrecision(3);
localStorage.setItem(getAuth(GKList[1]), JSON.stringify(stats));
}
}
}
function findGK() {
var tab = [[-1,""], [-1,""]];
for (var i = 0; i < extendedP.length ; i++) {
if (room.getPlayer(extendedP[i][eP.ID]) != null &&
room.getPlayer(extendedP[i][eP.ID]).team == Team.RED) {
if (tab[0][0] < extendedP[i][eP.GK]) {
tab[0][0] = extendedP[i][eP.GK];
tab[0][1] = room.getPlayer(extendedP[i][eP.ID]);
}
}
else if (room.getPlayer(extendedP[i][eP.ID]) != null &&
room.getPlayer(extendedP[i][eP.ID]).team == Team.BLUE) {
if (tab[1][0] < extendedP[i][eP.GK]) {
tab[1][0] = extendedP[i][eP.GK];
tab[1][1] = room.getPlayer(extendedP[i][eP.ID]);
}
}
}
GKList = [tab[0][1], tab[1][1]];
}
setInterval(() => {
var tableau = [];
if (statNumber % 5 == 0) {
Object.keys(localStorage).forEach(function (key) { if (!["player_name",
"view_mode", "geo", "avatar", "player_auth_key"].includes(key))
{ tableau.push([(JSON.parse(localStorage.getItem(key))[Ss.NK]),
(JSON.parse(localStorage.getItem(key))[Ss.GA])]); } });
if (tableau.length < 5) {
return false;
}
tableau.sort(function (a, b) { return b[1] - a[1]; });
room.sendChat("Partidos Jugados> #1 " + tableau[0][0] + ": " +
tableau[0][1] + " #2 " + tableau[1][0] + ": " + tableau[1][1] + " #3 " + tableau[2]
[0] + ": " + tableau[2][1] + " #4 " + tableau[3][0] + ": " + tableau[3][1] + " #5 "
+ tableau[4][0] + ": " + tableau[4][1]);
}
if (statNumber % 5 == 1) {
Object.keys(localStorage).forEach(function (key) { if (!["player_name",
"view_mode", "geo", "avatar", "player_auth_key"].includes(key))
{ tableau.push([(JSON.parse(localStorage.getItem(key))[Ss.NK]),
(JSON.parse(localStorage.getItem(key))[Ss.WI])]); } });
if (tableau.length < 5) {
return false;
}
tableau.sort(function (a, b) { return b[1] - a[1]; });
room.sendChat("Victorias> #1 " + tableau[0][0] + ": " + tableau[0][1] +
" #2 " + tableau[1][0] + ": " + tableau[1][1] + " #3 " + tableau[2][0] + ": " +
tableau[2][1] + " #4 " + tableau[3][0] + ": " + tableau[3][1] + " #5 " + tableau[4]
[0] + ": " + tableau[4][1]);
}
if (statNumber % 5 == 2) {
Object.keys(localStorage).forEach(function (key) { if (!["player_name",
"view_mode", "geo", "avatar", "player_auth_key"].includes(key))
{ tableau.push([(JSON.parse(localStorage.getItem(key))[Ss.NK]),
(JSON.parse(localStorage.getItem(key))[Ss.GL])]); } });
if (tableau.length < 5) {
return false;
}
tableau.sort(function (a, b) { return b[1] - a[1]; });
room.sendChat("Goles> #1 " + tableau[0][0] + ": " + tableau[0][1] + "
#2 " + tableau[1][0] + ": " + tableau[1][1] + " #3 " + tableau[2][0] + ": " +
tableau[2][1] + " #4 " + tableau[3][0] + ": " + tableau[3][1] + " #5 " + tableau[4]
[0] + ": " + tableau[4][1]);
}
if (statNumber % 5 == 3) {
Object.keys(localStorage).forEach(function (key) { if (!["player_name",
"view_mode", "geo", "avatar", "player_auth_key"].includes(key))
{ tableau.push([(JSON.parse(localStorage.getItem(key))[Ss.NK]),
(JSON.parse(localStorage.getItem(key))[Ss.AS])]); } });
if (tableau.length < 5) {
return false;
}
tableau.sort(function (a, b) { return b[1] - a[1]; });
room.sendChat("Asistencias> #1 " + tableau[0][0] + ": " + tableau[0][1]
+ " #2 " + tableau[1][0] + ": " + tableau[1][1] + " #3 " + tableau[2][0] + ": " +
tableau[2][1] + " #4 " + tableau[3][0] + ": " + tableau[3][1] + " #5 " + tableau[4]
[0] + ": " + tableau[4][1]);
}
if (statNumber % 5 == 4) {
Object.keys(localStorage).forEach(function (key) { if (!["player_name",
"view_mode", "geo", "avatar", "player_auth_key"].includes(key))
{ tableau.push([(JSON.parse(localStorage.getItem(key))[Ss.NK]),
(JSON.parse(localStorage.getItem(key))[Ss.CS])]); } });
if (tableau.length < 5) {
return false;
}
tableau.sort(function (a, b) { return b[1] - a[1]; });
room.sendChat("CS> #1 " + tableau[0][0] + ": " + tableau[0][1] + " #2 "
+ tableau[1][0] + ": " + tableau[1][1] + " #3 " + tableau[2][0] + ": " + tableau[2]
[1] + " #4 " + tableau[3][0] + ": " + tableau[3][1] + " #5 " + tableau[4][0] + ": "
+ tableau[4][1]);
}
statNumber++;
}, statInterval * 60 * 1000);
/* EVENTS */
/* PLAYER MOVEMENT */
room.onPlayerJoin = function(player) {
extendedP.push([player.id, player.auth, player.conn, false, 0, 0, false]);
updateRoleOnPlayerIn();
room.sendAnnouncement("👋 Bienvenido " + player.name + ", escribe !help o !
ayuda para ver los comandos.", player.id, bienvenidacolor, "bold");
if (localStorage.getItem(player.auth) != null) {
if (JSON.parse(localStorage.getItem(player.auth))[Ss.RL] != "player") {
room.setPlayerAdmin(player.id, true);
room.sendChat((JSON.parse(localStorage.getItem(player.auth))
[Ss.RL] == "master" ? "Master " : "Admin ") + player.name + " has connected to the
room !");
}
}
}
room.onPlayerLeave = function(player) {
if (teamR.findIndex((red) => red.id == player.id) == 0 && inChooseMode &&
teamR.length <= teamB.length) {
choosePlayer();
capLeft = true; setTimeout(() => { capLeft = false; }, 10);
}
if (teamB.findIndex((blue) => blue.id == player.id) == 0 && inChooseMode &&
teamB.length < teamR.length) {
choosePlayer();
capLeft = true; setTimeout(() => { capLeft = false; }, 10);
}
setActivity(player, 0);
updateRoleOnPlayerOut();
}
/* PLAYER ACTIVITY */
//---------------------------------------------------------------------------------
----------
else if (["!afk"].includes(message[0].toLowerCase())) {
if (players.length != 1 && player.team != Team.SPECTATORS) {
if (player.team == Team.RED && streak > 0 && room.getScores() ==
null) {
room.setPlayerTeam(player.id, Team.SPECTATORS);
}
else {
room.sendChat("No puedes ser AFK mientras estás en un
equipo !", player.id);
return false;
}
}
else if (players.length == 1 && !getAFK(player)) {
room.setPlayerTeam(player.id, Team.SPECTATORS);
}
setAFK(player, !getAFK(player));
room.sendChat(player.name + (getAFK(player) ? " is now AFK !" : " is
not AFK anymore !"));
getAFK(player) ? updateRoleOnPlayerOut() : updateRoleOnPlayerIn();
}
else if (["!afks", "!afklist"].includes(message[0].toLowerCase())) {
var cstm = "[PV] Lista de AFK : ";
for (var i = 0; i < extendedP.length; i++) {
if (room.getPlayer(extendedP[i][eP.ID]) != null &&
getAFK(room.getPlayer(extendedP[i][eP.ID]))) {
if (140 - cstm.length < (room.getPlayer(extendedP[i]
[eP.ID]).name + ", ").length) {
room.sendChat(cstm, player.id);
cstm = "... ";
}
cstm += room.getPlayer(extendedP[i][eP.ID]).name + ", ";
}
}
if (cstm == "[PV] Lista de AFK : ") {
room.sendChat("[PV] No hay nadie en la lista de AFK !",
player.id);
return false;
}
cstm = cstm.substring(0, cstm.length - 2);
cstm += ".";
room.sendChat(cstm, player.id);
}
//---------------------------------------------------------------------------------
----------
else if (["!me"].includes(message[0].toLowerCase())) {
var stats;
localStorage.getItem(getAuth(player)) ? stats =
JSON.parse(localStorage.getItem(getAuth(player))) : stats = [0, 0, 0, 0, "0.00", 0,
0, 0, 0, "0.00"];
room.sendAnnouncement("------------------------------------------------",
player.id, statscolors, "bold" );
room.sendAnnouncement("👤 Stats de " + player.name,
player.id, 0x00FFCD, "bold" );
room.sendAnnouncement(" |➡️| Partidos jugados: " +
stats[Ss.GA], player.id, statscolors, "bold" );
room.sendAnnouncement(" |🏆| Victorias: " + stats[Ss.WI],
player.id, statscolors, "bold" );
room.sendAnnouncement(" |🏆🚫| Derrotas: " + stats[Ss.LS],
player.id, statscolors, "bold" );
room.sendAnnouncement(" |⚽| Goles: " + stats[Ss.GL],
player.id, statscolors, "bold" );
room.sendAnnouncement(" |🧤| GK: " + stats[Ss.GK],
player.id, statscolors, "bold" );
room.sendAnnouncement(" |🥅🚫| Porterias en cero: " +
stats[Ss.CS], player.id, statscolors, "bold" );
room.sendAnnouncement(" |👟| Asistencias: " + stats[Ss.AS],
player.id, statscolors, "bold" );
room.sendAnnouncement("------------------------------------------------",
player.id, statscolors, "bold" );
return false; // Indicamos que el comando fue manejado
}
//---------------------------------------------------------------------------------
----------
else if (["!tula"].includes(message[0].toLowerCase())) {
const random_number = Math.floor(Math.random() * 32) + 1;
room.sendAnnouncement(" La tula de " + player.name + " mide " +
random_number + " cm", null, comandoscolors, 'bold');
return false; // Indicamos que el comando fue manejado
}
//---------------------------------------------------------------------------------
----------
else if (["!goles"].includes(message[0].toLowerCase())) {
var tableau = [];
Object.keys(localStorage).forEach(function (key) {
if (!["player_name", "view_mode", "geo", "avatar",
"player_auth_key"].includes(key)) {
try {
var parsedData = JSON.parse(localStorage.getItem(key));
tableau.push([parsedData[Ss.NK], parsedData[Ss.GL]]);
} catch (error) {
console.error("Error parsing JSON for key:", key, error);
}
}
});
if (tableau.length < 5) {
room.sendAnnouncement("[PV] Aún no se han jugado partidos suficientes.",
player.id, errorcolors, "bold");
return false;
}
tableau.sort(function (a, b) {
return b[1] - a[1];
});
//---------------------------------------------------------------------------------
----------
else if (["!asistencias"].includes(message[0].toLowerCase())) {
var tableau = [];
Object.keys(localStorage).forEach(function (key) {
if (!["player_name", "view_mode", "geo", "avatar",
"player_auth_key"].includes(key)) {
try {
var parsedData = JSON.parse(localStorage.getItem(key));
tableau.push([parsedData[Ss.NK], parsedData[Ss.AS]]);
} catch (error) {
console.error("Error parsing JSON for key:", key, error);
}
}
});
if (tableau.length < 5) {
room.sendAnnouncement("[PV] Aún no se han jugado partidos suficientes.",
player.id, errorcolors, "bold");
return false;
}
tableau.sort(function (a, b) {
return b[1] - a[1];
});
//---------------------------------------------------------------------------------
----------
else if (["!jugados"].includes(message[0].toLowerCase())) {
var tableau = [];
Object.keys(localStorage).forEach(function (key) {
if (!["player_name", "view_mode", "geo", "avatar",
"player_auth_key"].includes(key)) {
try {
var parsedData = JSON.parse(localStorage.getItem(key));
tableau.push([parsedData[Ss.NK], parsedData[Ss.GA]]);
} catch (error) {
console.error("Error parsing JSON for key:", key, error);
}
}
});
if (tableau.length < 5) {
room.sendAnnouncement("[PV] Aún no se han jugado partidos suficientes.",
player.id, errorcolors, "bold");
return false;
}
tableau.sort(function (a, b) {
return b[1] - a[1];
});
else if (["!victorias"].includes(message[0].toLowerCase())) {
var tableau = [];
Object.keys(localStorage).forEach(function (key) {
if (!["player_name", "view_mode", "geo", "avatar",
"player_auth_key"].includes(key)) {
try {
var parsedData = JSON.parse(localStorage.getItem(key));
tableau.push([parsedData[Ss.NK], parsedData[Ss.WI]]);
} catch (error) {
console.error("Error parsing JSON for key:", key, error);
}
}
});
if (tableau.length < 5) {
room.sendAnnouncement("[PV] Aún no se han jugado partidos suficientes.",
player.id, errorcolors, "bold");
return false;
}
tableau.sort(function (a, b) {
return b[1] - a[1];
});
//---------------------------------------------------------------------------------
----------
else if (["!cs"].includes(message[0].toLowerCase())) {
var tableau = [];
Object.keys(localStorage).forEach(function (key) {
if (!["player_name", "view_mode", "geo", "avatar",
"player_auth_key"].includes(key)) {
try {
var parsedData = JSON.parse(localStorage.getItem(key));
tableau.push([parsedData[Ss.NK], parsedData[Ss.CS]]);
} catch (error) {
console.error("Error parsing JSON for key:", key, error);
}
}
});
if (tableau.length < 5) {
room.sendAnnouncement("[PV] Aún no se han jugado partidos suficientes.",
player.id, errorcolors, "bold");
return false;
}
tableau.sort(function (a, b) {
return b[1] - a[1];
});
//---------------------------------------------------------------------------------
----------
else if (["!claim"].includes(message[0].toLowerCase())) {
if (message[1] == adminPassword) {
room.setPlayerAdmin(player.id, true);
var stats;
localStorage.getItem(getAuth(player)) ? stats =
JSON.parse(localStorage.getItem(getAuth(player))) : stats = [0, 0, 0, 0, "0.00", 0,
0, 0, 0, "0.00", "player", player.name];
if (stats[Ss.RL] != "master") {
stats[Ss.RL] = "master";
room.sendChat(player.name + " is now a room master !");
localStorage.setItem(getAuth(player),
JSON.stringify(stats));
}
}
}
else if (["!setadmin", "!admin"].includes(message[0].toLowerCase())) {
if (localStorage.getItem(getAuth(player)) &&
JSON.parse(localStorage.getItem(getAuth(player)))[Ss.RL] == "master") {
if (message.length >= 2 && message[1][0] == "#") {
message[1] = message[1].substring(1, message[1].length);
if (!Number.isNaN(Number.parseInt(message[1])) &&
room.getPlayer(Number.parseInt(message[1])) != null) {
var stats;
localStorage.getItem(getAuth(room.getPlayer(Number.parseInt(message[1])))) ?
stats =
JSON.parse(localStorage.getItem(getAuth(room.getPlayer(Number.parseInt(message[1]))
))) : stats = [0, 0, 0, 0, "0.00", 0, 0, 0, 0, "0.00", "player",
room.getPlayer(Number.parseInt(message[1])).name];
if (stats[Ss.RL] == "player") {
stats[Ss.RL] = "admin";
localStorage.setItem(getAuth(room.getPlayer(Number.parseInt(message[1]))),
JSON.stringify(stats));
room.setPlayerAdmin(room.getPlayer(Number.parseInt(message[1])).id, true);
localStorage.getItem(getAuth(room.getPlayer(Number.parseInt(message[1])))) ?
stats =
JSON.parse(localStorage.getItem(getAuth(room.getPlayer(Number.parseInt(message[1]))
))) : stats = [0, 0, 0, 0, "0.00", 0, 0, 0, 0, "0.00", "player",
room.getPlayer(Number.parseInt(message[1])).name];
if (stats[Ss.RL] == "admin") {
room.sendChat(room.getPlayer(Number.parseInt(message[1])).name + " Ya no es
administrador del host !");
stats[Ss.RL] = "player";
localStorage.setItem(getAuth(room.getPlayer(Number.parseInt(message[1]))),
JSON.stringify(stats));
room.setPlayerAdmin(room.getPlayer(Number.parseInt(message[1])).id, false);
}
}
}
}
}
else if (["!mutes", "!mutelist"].includes(message[0].toLowerCase())) {
var cstm = "[PV] Lista de muteados : ";
for (var i = 0; i < extendedP.length; i++) {
if (room.getPlayer(extendedP[i][eP.ID]) != null &&
getMute(room.getPlayer(extendedP[i][eP.ID]))) {
if (140 - cstm.length < (room.getPlayer(extendedP[i]
[eP.ID]).name + "[" + (extendedP[i][eP.ID]) + "], ").length) {
room.sendChat(cstm, player.id);
cstm = "... ";
}
cstm += room.getPlayer(extendedP[i][eP.ID]).name + "[" +
(extendedP[i][eP.ID]) + "], ";
}
}
if (cstm == "[PV] Lista de Muteados : ") {
room.sendChat("[PV] No hay nadie en la lista de muteados !",
player.id);
return false;
}
cstm = cstm.substring(0, cstm.length - 2);
cstm += ".";
room.sendChat(cstm, player.id);
}
else if (["!mute"].includes(message[0].toLowerCase())) {
if (player.admin) {
updateTeams();
var timeOut;
if (!Number.isNaN(Number.parseInt(message[1])) && message.length
> 1) {
if (Number.parseInt(message[1]) > 0) {
timeOut = Number.parseInt(message[1]) * 60 * 1000;
}
else {
timeOut = 3 * 60 * 1000;
}
if (message[2].length > 1 && message[2][0] == "#") {
message[2] = message[2].substring(1,
message[2].length);
if (!Number.isNaN(Number.parseInt(message[2])) &&
room.getPlayer(Number.parseInt(message[2])) != null) {
if
(room.getPlayer(Number.parseInt(message[2])).admin ||
getMute(room.getPlayer(Number.parseInt(message[2])))) {
return false;
}
setTimeout(function (player) { setMute(player,
false); }, timeOut, room.getPlayer(Number.parseInt(message[2])));
setMute(room.getPlayer(Number.parseInt(message[2])), true);
setMute(room.getPlayer(Number.parseInt(message[1])), true);
setMute(room.getPlayer(Number.parseInt(message[1])), false);
room.setPlayerTeam(teamS[getRandomInt(teamS.length)].id, Team.BLUE);
blueCaptainChoice = "random";
clearTimeout(timeOutCap);
room.sendChat(player.name + " seleccionó Random !");
return false;
}
else if (["bottom",
"bot"].includes(message[0].toLowerCase())) {
room.setPlayerTeam(teamS[teamS.length - 1].id,
Team.BLUE);
blueCaptainChoice = "bottom";
clearTimeout(timeOutCap);
room.sendChat(player.name + " seleccionó Bottom !");
return false;
}
else if (!Number.isNaN(Number.parseInt(message[0]))) {
if (Number.parseInt(message[0]) > teamS.length ||
Number.parseInt(message[0]) < 1) {
room.sendChat("[PV] El número que elegiste es
inválido !", player.id);
return false;
}
else {
room.onPlayerActivity = function(player) {
setActivity(player, 0);
}
room.onPlayerBallKick = function(player) {
if (lastPlayersTouched[0] == null || player.id != lastPlayersTouched[0].id) {
!activePlay ? activePlay = true : null;
lastTeamTouched = player.team;
lastPlayersTouched[1] = lastPlayersTouched[0];
lastPlayersTouched[0] = player;
}
}
/* GAME MANAGEMENT */
room.onGameStart = function(byPlayer) {
game = new Game(Date.now(), room.getScores(), []);
countAFK = true;
activePlay = false;
goldenGoal = false;
endGameVariable = false;
lastPlayersTouched = [null, null];
Rposs = 0;
Bposs = 0;
GKList = [];
allReds = [];
allBlues = [];
if (teamR.length == maxTeamSize && teamB.length == maxTeamSize) {
for (var i = 0; i < maxTeamSize; i++) {
allReds.push(teamR[i]);
allBlues.push(teamB[i]);
}
}
for (var i = 0; i < extendedP.length; i++) {
extendedP[i][eP.GK] = 0;
extendedP[i][eP.ACT] = 0;
room.getPlayer(extendedP[i][eP.ID]) == null ? extendedP.splice(i, 1) :
null;
}
deactivateChooseMode();
}
room.onGameStop = function(byPlayer) {
if (byPlayer.id == 0 && endGameVariable) {
updateTeams();
if (inChooseMode) {
if (players.length == 2 * maxTeamSize) {
inChooseMode = false;
resetBtn();
for (var i = 0; i < maxTeamSize; i++) {
setTimeout(() => { randomBtn(); }, 400*i);
}
setTimeout(() => { room.startGame(); }, 2000);
}
else {
if (lastWinner == Team.RED) {
blueToSpecBtn();
}
else if (lastWinner == Team.BLUE) {
redToSpecBtn();
blueToRedBtn();
}
else {
resetBtn();
}
setTimeout(() => { topBtn(); }, 500);
}
}
else {
if (players.length == 2) {
if (lastWinner == Team.BLUE) {
room.setPlayerTeam(teamB[0].id, Team.RED);
room.setPlayerTeam(teamR[0].id, Team.BLUE);
}
setTimeout(() => { room.startGame(); }, 2000);
}
else if (players.length == 3 || players.length >= 2 * maxTeamSize
+ 1) {
if (lastWinner == Team.RED) {
blueToSpecBtn();
}
else {
redToSpecBtn();
blueToRedBtn();
}
setTimeout(() => { topBtn(); }, 200);
setTimeout(() => { room.startGame(); }, 2000);
}
else if (players.length == 4) {
resetBtn();
setTimeout(() => { randomBtn(); setTimeout(() =>
{ randomBtn(); }, 500); }, 500);
setTimeout(() => { room.startGame(); }, 2000);
}
else if (players.length == 5 || players.length >= 2 * maxTeamSize
+ 1) {
if (lastWinner == Team.RED) {
blueToSpecBtn();
}
else {
redToSpecBtn();
blueToRedBtn();
}
setTimeout(() => { topBtn(); }, 200);
activateChooseMode();
}
else if (players.length == 6) {
resetBtn();
setTimeout(() => { randomBtn(); setTimeout(() =>
{ randomBtn(); setTimeout(() => { randomBtn(); }, 500); }, 500); }, 500);
setTimeout(() => { room.startGame(); }, 2000);
}
}
}
}
room.onGamePause = function(byPlayer) {
}
room.onTeamGoal = function(team) {
activePlay = false;
countAFK = false;
const scores = room.getScores();
game.scores = scores;
if (lastPlayersTouched[0] != null && lastPlayersTouched[0].team == team) {
if (lastPlayersTouched[1] != null && lastPlayersTouched[1].team ==
team) {
room.sendAnnouncement("⚽ " + getTime(scores) + " Gol de " +
lastPlayersTouched[0].name + " ! Asistencia de " + lastPlayersTouched[1].name + ".
Velocidad de tiro : " + ballSpeed.toPrecision(4).toString() + "km/h " + (team ==
Team.RED ? "🔴" : "🔵"), null, golescolor, "bold");
game.goals.push(new Goal(scores.time, team,
lastPlayersTouched[0], lastPlayersTouched[1]));
}
else {
room.sendAnnouncement("⚽ " + getTime(scores) + " Gol de " +
lastPlayersTouched[0].name + " ! Velocidad de tiro : " +
ballSpeed.toPrecision(4).toString() + "km/h " + (team == Team.RED ? "🔴" : "🔵"),
null, golescolor, "bold");
game.goals.push(new Goal(scores.time, team,
lastPlayersTouched[0], null));
}
}
else {
room.sendAnnouncement("😂 " + getTime(scores) + " Gol en contra de " +
lastPlayersTouched[0].name + " ! Velocidad de tiro : " +
ballSpeed.toPrecision(4).toString() + "km/h " + (team == Team.RED ? "🔴" : "🔵"),
null, golescolor, "bold");
game.goals.push(new Goal(scores.time, team, null, null));
}
if (scores.scoreLimit != 0 && (scores.red == scores.scoreLimit || scores.blue
== scores.scoreLimit && scores.blue > 0 || goldenGoal == true)) {
endGame(team);
goldenGoal = false;
setTimeout(() => { room.stopGame(); }, 1000);
}
}
room.onPositionsReset = function() {
countAFK = true;
lastPlayersTouched = [null, null];
}
/* MISCELLANEOUS */
room.onRoomLink = function(url) {
}
room.onGameTick = function() {
checkTime();
getLastTouchOfTheBall();
getStats();
handleInactivity();
}