guessed the correct answer. Congratulations!
" +
@@ -128,7 +130,7 @@ var QuestionGiveAway = (function () {
};
QuestionGiveAway.sanitizeAnswers = function (target) {
- var ret = {};
+ let ret = {};
target.split("/").forEach(function (ans) {
ans = ans.replace(/[^a-z0-9 ]+/ig, "").trim();
if (!toId(ans)) return;
@@ -140,7 +142,7 @@ var QuestionGiveAway = (function () {
return QuestionGiveAway;
})();
-var LotteryGiveAway = (function () {
+let LotteryGiveAway = (function () {
function LotteryGiveAway(host, giver, room, options) {
this.host = host;
this.giver = giver;
@@ -171,7 +173,7 @@ var LotteryGiveAway = (function () {
if (this.phase !== 'joining') return output.sendReply("The join phase of the lottery giveaway has ended.");
if (!user.named) return output.sendReply("You need to choose a name before joining a lottery giveaway.");
- var joinError = checkAllAlts(user, this.joined);
+ let joinError = checkAllAlts(user, this.joined);
if (joinError) return output.sendReply("You have already joined the giveaway under the " + joinError + ". Use that alt/account to continue.");
joinError = checkAllAlts(user, this.excluded) || (user.userid in this.excluded);
if (joinError) return output.sendReply("You are the host/giver of the giveaway, and cannot join.");
@@ -190,13 +192,13 @@ var LotteryGiveAway = (function () {
this.phase = 'drawing';
clearTimeout(this.drawTimer);
- var userlist = Object.keys(this.joined);
+ let userlist = Object.keys(this.joined);
this.totalusers = userlist.length;
if (this.totalusers < this.maxwinners) return this.onEnd(true);
this.winners = {};
while (this.maxwinners) {
- var index = Math.floor(Math.random() * this.totalusers);
+ let index = Math.floor(Math.random() * this.totalusers);
if (!(userlist[index] in this.winners)) {
this.winners[userlist[index]] = Users.get(userlist[index]);
this.maxwinners--;
@@ -211,19 +213,19 @@ var LotteryGiveAway = (function () {
this.room.addRaw("
").update();
} else {
this.phase = 'ended';
- var finallist = [];
- for (var id in this.winners) {
+ let finallist = [];
+ for (let id in this.winners) {
finallist.push(this.winners[id].name);
}
- var multiWin = finallist.length > 1;
+ let multiWin = finallist.length > 1;
finallist = finallist.join(', ');
this.room.addRaw(
"
Lottery Draw: " + this.totalusers + " users have joined the lottery.
" +
"Our lucky winner" + (multiWin ? "s" : "") + ":
" + Tools.escapeHTML(finallist) + "! Congratulations!"
).update();
- for (var id in this.winners) {
- var targetUser = this.winners[id];
+ for (let id in this.winners) {
+ let targetUser = this.winners[id];
if (targetUser.connected) targetUser.popup("You have won the lottery giveaway! PM **" + this.giver.name + "** to claim your prize!");
}
if (this.giver.connected) this.giver.popup("The following users have won your lottery giveaway:\n" + finallist);
@@ -241,7 +243,7 @@ function spawnGiveaway(type, host, giver, room, options) {
}
}
-var commands = {
+let commands = {
// question giveaway.
quiz: 'question',
qg: 'question',
@@ -250,12 +252,12 @@ var commands = {
if (giveaways[room.id]) return this.sendReply("There is already a giveaway going on!");
target = this.splitTarget(target);
- var targetUser = this.targetUser;
+ let targetUser = this.targetUser;
if (!targetUser || !targetUser.connected) return this.sendReply("User '" + this.targetUsername + "' is not online.");
target = target.split(',').map(function (val) { return val.trim(); });
if (target.length !== 3) return this.sendReply("Invalid arguments specified - /question giver, prize, question, answer(s)");
- var options = {
+ let options = {
prize: target[0],
question: target[1],
answers: QuestionGiveAway.sanitizeAnswers(target[2])
@@ -278,16 +280,16 @@ var commands = {
showanswer: 'viewanswer',
viewanswer: function (target, room, user) {
if (room.id !== 'wifi') return false;
- var giveaway = giveaways[room.id];
+ let giveaway = giveaways[room.id];
if (!giveaway) return this.sendReply("There is no giveaway going on at the moment.");
if (giveaway.type !== 'question') return this.sendReply("This is not a question giveaway.");
if (user.userid !== giveaway.host.userid && user.userid !== giveaway.giver.userid) return;
- var answers = [];
- for (var i in giveaway.answers) {
+ let answers = [];
+ for (let i in giveaway.answers) {
answers.push(giveaway.answers[i]);
}
- var anstext = (answers.length === 1) ? 'answer is ' : 'answers are ';
+ let anstext = (answers.length === 1) ? 'answer is ' : 'answers are ';
this.sendReply("The giveaway question is " + giveaway.question + ".\n" +
"The " + anstext + answers.join('/') + ".");
},
@@ -307,12 +309,12 @@ var commands = {
if (giveaways[room.id]) return this.sendReply("There is already a giveaway going on!");
target = this.splitTarget(target);
- var targetUser = this.targetUser;
+ let targetUser = this.targetUser;
if (!targetUser || !targetUser.connected) return this.sendReply("User '" + this.targetUsername + "' is not online.");
target = target.split(',').map(function (val) { return val.trim(); });
if (target.length !== 2) return this.sendReply("Invalid arguments specified - /lottery giver, prize, max winners");
- var options = {
+ let options = {
prize: target[0],
maxwinners: parseInt(target[1])
};
@@ -328,7 +330,7 @@ var commands = {
joinlottery: 'join',
join: function (target, room, user, conn, cmd) {
if (room.id !== 'wifi') return this.sendReply("This command can only be used in the Wi-Fi room.");
- var giveaway = giveaways[room.id];
+ let giveaway = giveaways[room.id];
if (!giveaway) return this.sendReply("There is no giveaway going on at the moment.");
if (giveaway.type !== 'lottery') return this.sendReply("This is not a lottery giveaway.");
@@ -357,7 +359,7 @@ var commands = {
rm: 'remind',
remind: function (target, room, user) {
if (room.id !== 'wifi') return this.sendReply("This command can only be used in the Wi-Fi room.");
- var giveaway = giveaways[room.id];
+ let giveaway = giveaways[room.id];
if (!giveaway) return this.sendReply("There is no giveaway going on at the moment.");
if (!this.canBroadcast()) return;
if (giveaway.type === 'question') {
@@ -373,7 +375,7 @@ var commands = {
help: function (target, room, user) {
if (room.id !== 'wifi') return this.sendReply("This command can only be used in the Wi-Fi room.");
- var reply = '';
+ let reply = '';
switch (target) {
case 'staff':
if (!this.can('warn', null, room)) return;
diff --git a/cidr.js b/cidr.js
index 6b801e5e39..f0200772c2 100644
--- a/cidr.js
+++ b/cidr.js
@@ -8,23 +8,25 @@
* @license MIT license
*/
-var ipToLong = exports.ipToLong = function (ip) {
- var numIp = 0;
- var parts = ip.split('.');
- for (var i = 0, len = parts.length; i < len; i++) {
+'use strict';
+
+let ipToLong = exports.ipToLong = function (ip) {
+ let numIp = 0;
+ let parts = ip.split('.');
+ for (let i = 0, len = parts.length; i < len; i++) {
numIp *= 256;
numIp += Number(parts[i]);
}
return numIp;
};
-var getPattern = exports.getPattern = function (cidr) {
+let getPattern = exports.getPattern = function (cidr) {
if (!cidr) return null;
- var index = cidr.indexOf('/');
+ let index = cidr.indexOf('/');
if (index > 0) {
- var subnet = ipToLong(cidr.substr(0, index));
- var bits = parseInt(cidr.substr(index + 1), 10);
- var mask = -1 << (32 - bits);
+ let subnet = ipToLong(cidr.substr(0, index));
+ let bits = parseInt(cidr.substr(index + 1), 10);
+ let mask = -1 << (32 - bits);
return [subnet & mask, mask];
}
return [ipToLong(cidr), -1];
@@ -35,14 +37,14 @@ var getPattern = exports.getPattern = function (cidr) {
* ranges. The checker function returns boolean whether or not its
* passed IP is in the range.
*/
-var checker = exports.checker = function (cidr) {
+let checker = exports.checker = function (cidr) {
if (!cidr || !cidr.length) {
return function () {
return false;
};
}
- var patterns;
+ let patterns;
if (Array.isArray(cidr)) {
patterns = cidr.map(getPattern).filter(function (x) {
return x;
@@ -52,9 +54,9 @@ var checker = exports.checker = function (cidr) {
}
return function (ip) {
- var longip = ipToLong(ip);
- for (var i = 0; i < patterns.length; ++i) {
- var pattern = patterns[i];
+ let longip = ipToLong(ip);
+ for (let i = 0; i < patterns.length; ++i) {
+ let pattern = patterns[i];
if ((longip & pattern[1]) === pattern[0]) {
return true;
}
@@ -63,6 +65,6 @@ var checker = exports.checker = function (cidr) {
};
};
-var check = exports.check = function (cidr, ip) {
+let check = exports.check = function (cidr, ip) {
return checker(cidr)(ip);
};
diff --git a/command-parser.js b/command-parser.js
index 93af015b61..d606fb30ea 100644
--- a/command-parser.js
+++ b/command-parser.js
@@ -22,6 +22,8 @@ To reload chat commands:
*/
+'use strict';
+
const MAX_MESSAGE_LENGTH = 300;
const BROADCAST_COOLDOWN = 20 * 1000;
@@ -34,15 +36,15 @@ const VALID_COMMAND_TOKENS = '/!';
const BROADCAST_TOKEN = '!';
-var fs = require('fs');
-var path = require('path');
+const fs = require('fs');
+const path = require('path');
/*********************************************************
* Load command files
*********************************************************/
-var baseCommands = exports.baseCommands = require('./commands.js').commands;
-var commands = exports.commands = Object.clone(baseCommands);
+let baseCommands = exports.baseCommands = require('./commands.js').commands;
+let commands = exports.commands = Object.clone(baseCommands);
// Install plug-in commands
@@ -58,12 +60,12 @@ fs.readdirSync(path.resolve(__dirname, 'chat-plugins')).forEach(function (file)
* Modlog
*********************************************************/
-var modlog = exports.modlog = {
+let modlog = exports.modlog = {
lobby: fs.createWriteStream(path.resolve(__dirname, 'logs/modlog/modlog_lobby.txt'), {flags:'a+'}),
battle: fs.createWriteStream(path.resolve(__dirname, 'logs/modlog/modlog_battle.txt'), {flags:'a+'})
};
-var writeModlog = exports.writeModlog = function (roomid, text) {
+let writeModlog = exports.writeModlog = function (roomid, text) {
if (!modlog[roomid]) {
modlog[roomid] = fs.createWriteStream(path.resolve(__dirname, 'logs/modlog/modlog_' + roomid + '.txt'), {flags:'a+'});
}
@@ -92,7 +94,7 @@ function canTalk(user, room, connection, message, targetUser) {
return false;
}
if (room && room.modchat) {
- var userGroup = user.group;
+ let userGroup = user.group;
if (room.auth) {
if (room.auth[user.userid]) {
userGroup = room.auth[user.userid];
@@ -106,7 +108,7 @@ function canTalk(user, room, connection, message, targetUser) {
return false;
}
} else if (Config.groupsranking.indexOf(userGroup) < Config.groupsranking.indexOf(room.modchat) && !user.can('bypassall')) {
- var groupName = Config.groups[room.modchat].name || room.modchat;
+ let groupName = Config.groups[room.modchat].name || room.modchat;
connection.sendTo(room, "Because moderated chat is set, you must be of rank " + groupName + " or higher to speak in this room.");
return false;
}
@@ -130,7 +132,7 @@ function canTalk(user, room, connection, message, targetUser) {
message = message.replace(/[\u0300-\u036f\u0483-\u0489\u064b-\u065f\u0670\u0E31\u0E34-\u0E3A\u0E47-\u0E4E]{3,}/g, '');
if (room && room.id === 'lobby') {
- var normalized = message.trim();
+ let normalized = message.trim();
if ((normalized === user.lastMessage) &&
((Date.now() - user.lastMessageTime) < MESSAGE_COOLDOWN)) {
connection.popup("You can't send the same message again so soon.");
@@ -141,6 +143,7 @@ function canTalk(user, room, connection, message, targetUser) {
}
if (Config.chatfilter) {
+ /*jshint validthis:true */
return Config.chatfilter.call(this, message, user, room, connection, targetUser);
}
return message;
@@ -149,7 +152,7 @@ function canTalk(user, room, connection, message, targetUser) {
return true;
}
-var Context = exports.Context = (function () {
+let Context = exports.Context = (function () {
function Context(options) {
this.cmd = options.cmd || '';
this.cmdToken = options.cmdToken || '';
@@ -200,11 +203,11 @@ var Context = exports.Context = (function () {
this.logModCommand(data);
};
Context.prototype.sendModCommand = function (data) {
- var users = this.room.users;
- var auth = this.room.auth;
+ let users = this.room.users;
+ let auth = this.room.auth;
- for (var i in users) {
- var user = users[i];
+ for (let i in users) {
+ let user = users[i];
// hardcoded for performance reasons (this is an inner loop)
if (user.isStaff || (auth && (auth[user.userid] || '+') !== '+')) {
user.sendTo(this.room, data);
@@ -219,16 +222,16 @@ var Context = exports.Context = (function () {
this.logModCommand(text + (logOnlyText || ""));
};
Context.prototype.logModCommand = function (text) {
- var roomid = (this.room.battle ? 'battle' : this.room.id);
+ let roomid = (this.room.battle ? 'battle' : this.room.id);
if (this.room.isPersonal) roomid = 'groupchat';
writeModlog(roomid, '(' + this.room.id + ') ' + text);
};
Context.prototype.globalModlog = function (action, user, text) {
- var buf = "(" + this.room.id + ") " + action + ": ";
+ let buf = "(" + this.room.id + ") " + action + ": ";
if (typeof user === 'string') {
buf += "[" + toId(user) + "]";
} else {
- var userid = this.getLastIdOf(user);
+ let userid = this.getLastIdOf(user);
buf += "[" + userid + "]";
if (user.autoconfirmed && user.autoconfirmed !== userid) buf += " ac:[" + user.autoconfirmed + "]";
}
@@ -244,7 +247,7 @@ var Context = exports.Context = (function () {
};
Context.prototype.canBroadcast = function (suppressMessage) {
if (!this.broadcasting && this.cmdToken === BROADCAST_TOKEN) {
- var message = this.canTalk(this.message);
+ let message = this.canTalk(this.message);
if (!message) return false;
if (!this.user.can('broadcast', null, this.room)) {
this.errorReply("You need to be voiced to broadcast this command's information.");
@@ -253,7 +256,7 @@ var Context = exports.Context = (function () {
}
// broadcast cooldown
- var normalized = message.toLowerCase().replace(/[^a-z0-9\s!,]/g, '');
+ let normalized = message.toLowerCase().replace(/[^a-z0-9\s!,]/g, '');
if (this.room.lastBroadcast === normalized &&
this.room.lastBroadcastTime >= Date.now() - BROADCAST_COOLDOWN) {
this.errorReply("You can't broadcast this because it was just broadcast.");
@@ -274,12 +277,12 @@ var Context = exports.Context = (function () {
return CommandParser.parse(message, room || this.room, this.user, this.connection, this.levelsDeep + 1);
};
Context.prototype.run = function (targetCmd, inNamespace) {
- var commandHandler;
+ let commandHandler;
if (typeof targetCmd === 'function') {
commandHandler = targetCmd;
} else if (inNamespace) {
commandHandler = commands;
- for (var i = 0; i < this.namespaces.length; i++) {
+ for (let i = 0; i < this.namespaces.length; i++) {
commandHandler = commandHandler[this.namespaces[i]];
}
commandHandler = commandHandler[targetCmd];
@@ -287,19 +290,19 @@ var Context = exports.Context = (function () {
commandHandler = commands[targetCmd];
}
- var result;
+ let result;
try {
result = commandHandler.call(this, this.target, this.room, this.user, this.connection, this.cmd, this.message);
} catch (err) {
- var stack = err.stack + '\n\n' +
+ let stack = err.stack + '\n\n' +
'Additional information:\n' +
'user = ' + this.user.name + '\n' +
'room = ' + this.room.id + '\n' +
'message = ' + this.message;
- var fakeErr = {stack: stack};
+ let fakeErr = {stack: stack};
if (!require('./crashlogger.js')(fakeErr, 'A chat command')) {
- var ministack = ("" + err.stack).escapeHTML().split("\n").slice(0, 2).join("
");
+ let ministack = ("" + err.stack).escapeHTML().split("\n").slice(0, 2).join("
");
if (Rooms.lobby) Rooms.lobby.send('|html|
POKEMON SHOWDOWN HAS CRASHED: ' + ministack + '
');
} else {
this.sendReply('|html|
Pokemon Showdown crashed!
Don\'t worry, we\'re working on fixing it.
');
@@ -310,18 +313,18 @@ var Context = exports.Context = (function () {
return result;
};
Context.prototype.canTalk = function (message, relevantRoom, targetUser) {
- var innerRoom = (relevantRoom !== undefined) ? relevantRoom : this.room;
+ let innerRoom = (relevantRoom !== undefined) ? relevantRoom : this.room;
return canTalk.call(this, this.user, innerRoom, this.connection, message, targetUser);
};
Context.prototype.canHTML = function (html) {
html = '' + (html || '');
- var images = html.match(/
![]()
]*/ig);
+ let images = html.match(/
![]()
]*/ig);
if (images) {
if (this.room.isPersonal && !this.user.can('announce')) {
this.errorReply("Images are not allowed in personal rooms.");
return false;
}
- for (var i = 0; i < images.length; i++) {
+ for (let i = 0; i < images.length; i++) {
if (!/width=([0-9]+|"[0-9]+")/i.test(images[i]) || !/height=([0-9]+|"[0-9]+")/i.test(images[i])) {
// Width and height are required because most browsers insert the
//
![]()
element before width and height are known, and when the
@@ -342,11 +345,11 @@ var Context = exports.Context = (function () {
}
// check for mismatched tags
- var tags = html.toLowerCase().match(/<\/?(div|a|button|b|i|u|center|font)\b/g);
+ let tags = html.toLowerCase().match(/<\/?(div|a|button|b|i|u|center|font)\b/g);
if (tags) {
- var stack = [];
- for (var i = 0; i < tags.length; i++) {
- var tag = tags[i];
+ let stack = [];
+ for (let i = 0; i < tags.length; i++) {
+ let tag = tags[i];
if (tag.charAt(1) === '/') {
if (!stack.length) {
this.errorReply("Extraneous " + tag.substr(2) + "> without an opening tag.");
@@ -381,16 +384,16 @@ var Context = exports.Context = (function () {
return (user.named ? user.userid : (Object.keys(user.prevNames).last() || user.userid));
};
Context.prototype.splitTarget = function (target, exactName) {
- var commaIndex = target.indexOf(',');
+ let commaIndex = target.indexOf(',');
if (commaIndex < 0) {
- var targetUser = Users.get(target, exactName);
+ let targetUser = Users.get(target, exactName);
this.targetUser = targetUser;
this.inputUsername = target.trim();
this.targetUsername = targetUser ? targetUser.name : target;
return '';
}
this.inputUsername = target.substr(0, commaIndex);
- var targetUser = Users.get(this.inputUsername, exactName);
+ let targetUser = Users.get(this.inputUsername, exactName);
if (targetUser) {
this.targetUser = targetUser;
this.targetUsername = this.inputUsername = targetUser.name;
@@ -427,8 +430,8 @@ var Context = exports.Context = (function () {
* if he's muted, will warn him that he's muted, and
* return false.
*/
-var parse = exports.parse = function (message, room, user, connection, levelsDeep) {
- var cmd = '', target = '', cmdToken = '';
+let parse = exports.parse = function (message, room, user, connection, levelsDeep) {
+ let cmd = '', target = '', cmdToken = '';
if (!message || !message.trim().length) return;
if (!levelsDeep) {
levelsDeep = 0;
@@ -448,7 +451,7 @@ var parse = exports.parse = function (message, room, user, connection, levelsDee
if (VALID_COMMAND_TOKENS.includes(message.charAt(0)) && message.charAt(1) !== message.charAt(0)) {
cmdToken = message.charAt(0);
- var spaceIndex = message.indexOf(' ');
+ let spaceIndex = message.indexOf(' ');
if (spaceIndex > 0) {
cmd = message.substr(1, spaceIndex - 1).toLowerCase();
target = message.substr(spaceIndex + 1);
@@ -458,9 +461,9 @@ var parse = exports.parse = function (message, room, user, connection, levelsDee
}
}
- var namespaces = [];
- var currentCommands = commands;
- var commandHandler;
+ let namespaces = [];
+ let currentCommands = commands;
+ let commandHandler;
do {
commandHandler = currentCommands[cmd];
@@ -471,7 +474,7 @@ var parse = exports.parse = function (message, room, user, connection, levelsDee
if (commandHandler && typeof commandHandler === 'object') {
namespaces.push(cmd);
- var spaceIndex = target.indexOf(' ');
+ let spaceIndex = target.indexOf(' ');
if (spaceIndex > 0) {
cmd = target.substr(0, spaceIndex).toLowerCase();
target = target.substr(spaceIndex + 1);
@@ -489,9 +492,9 @@ var parse = exports.parse = function (message, room, user, connection, levelsDee
commandHandler = currentCommands[commandHandler];
}
}
- var fullCmd = namespaces.concat(cmd).join(' ');
+ let fullCmd = namespaces.concat(cmd).join(' ');
- var context = new Context({
+ let context = new Context({
target: target, room: room, user: user, connection: connection, cmd: cmd, message: message,
namespaces: namespaces, cmdToken: cmdToken, levelsDeep: levelsDeep
});
@@ -500,8 +503,8 @@ var parse = exports.parse = function (message, room, user, connection, levelsDee
return context.run(commandHandler);
} else {
// Check for mod/demod/admin/deadmin/etc depending on the group ids
- for (var g in Config.groups) {
- var groupid = Config.groups[g].id;
+ for (let g in Config.groups) {
+ let groupid = Config.groups[g].id;
if (cmd === groupid || cmd === 'global' + groupid) {
return parse('/promote ' + toId(target) + ', ' + g, room, user, connection, levelsDeep + 1);
} else if (cmd === 'de' + groupid || cmd === 'un' + groupid || cmd === 'globalde' + groupid || cmd === 'deglobal' + groupid) {
@@ -542,10 +545,10 @@ fs.readFile(path.resolve(__dirname, 'package.json'), function (err, data) {
});
exports.uncacheTree = function (root) {
- var uncache = [require.resolve(root)];
+ let uncache = [require.resolve(root)];
do {
- var newuncache = [];
- for (var i = 0; i < uncache.length; ++i) {
+ let newuncache = [];
+ for (let i = 0; i < uncache.length; ++i) {
if (require.cache[uncache[i]]) {
newuncache.push.apply(newuncache,
require.cache[uncache[i]].children.map('id')
diff --git a/commands.js b/commands.js
index a723d1fb92..c1613ababb 100644
--- a/commands.js
+++ b/commands.js
@@ -13,14 +13,16 @@
* @license MIT license
*/
-var crypto = require('crypto');
-var fs = require('fs');
+'use strict';
+
+const crypto = require('crypto');
+const fs = require('fs');
const MAX_REASON_LENGTH = 300;
const MUTE_LENGTH = 7 * 60 * 1000;
const HOURMUTE_LENGTH = 60 * 60 * 1000;
-var commands = exports.commands = {
+let commands = exports.commands = {
version: function (target, room, user) {
if (!this.canBroadcast()) return;
@@ -32,20 +34,20 @@ var commands = exports.commands = {
globalauth: 'authority',
authlist: 'authority',
authority: function (target, room, user, connection) {
- var rankLists = {};
- var ranks = Object.keys(Config.groups);
- for (var u in Users.usergroups) {
- var rank = Users.usergroups[u].charAt(0);
+ let rankLists = {};
+ let ranks = Object.keys(Config.groups);
+ for (let u in Users.usergroups) {
+ let rank = Users.usergroups[u].charAt(0);
if (rank === ' ' || rank === '+') continue;
// In case the usergroups.csv file is not proper, we check for the server ranks.
if (ranks.indexOf(rank) >= 0) {
- var name = Users.usergroups[u].substr(1);
+ let name = Users.usergroups[u].substr(1);
if (!rankLists[rank]) rankLists[rank] = [];
if (name) rankLists[rank].push(name);
}
}
- var buffer = [];
+ let buffer = [];
Object.keys(rankLists).sort(function (a, b) {
return (Config.groups[b] || {rank: 0}).rank - (Config.groups[a] || {rank: 0}).rank;
}).forEach(function (r) {
@@ -74,8 +76,8 @@ var commands = exports.commands = {
avatar: function (target, room, user) {
if (!target) return this.parse('/avatars');
- var parts = target.split(',');
- var avatar = parseInt(parts[0]);
+ let parts = target.split(',');
+ let avatar = parseInt(parts[0]);
if (parts[0] === '#bw2elesa') {
avatar = parts[0];
}
@@ -124,7 +126,7 @@ var commands = exports.commands = {
msg: function (target, room, user, connection) {
if (!target) return this.parse('/help msg');
target = this.splitTarget(target);
- var targetUser = this.targetUser;
+ let targetUser = this.targetUser;
if (!target) {
this.errorReply("You forgot the comma.");
return this.parse('/help msg');
@@ -142,9 +144,9 @@ var commands = exports.commands = {
}
if (Config.pmmodchat) {
- var userGroup = user.group;
+ let userGroup = user.group;
if (Config.groupsranking.indexOf(userGroup) < Config.groupsranking.indexOf(Config.pmmodchat)) {
- var groupName = Config.groups[Config.pmmodchat].name || Config.pmmodchat;
+ let groupName = Config.groups[Config.pmmodchat].name || Config.pmmodchat;
this.errorReply("Because moderated chat is set, you must be of rank " + groupName + " or higher to PM users.");
return false;
}
@@ -172,17 +174,17 @@ var commands = exports.commands = {
if (target.charAt(0) === '/' && target.charAt(1) !== '/') {
// PM command
- var innerCmdIndex = target.indexOf(' ');
- var innerCmd = (innerCmdIndex >= 0 ? target.slice(1, innerCmdIndex) : target.slice(1));
- var innerTarget = (innerCmdIndex >= 0 ? target.slice(innerCmdIndex + 1) : '');
+ let innerCmdIndex = target.indexOf(' ');
+ let innerCmd = (innerCmdIndex >= 0 ? target.slice(1, innerCmdIndex) : target.slice(1));
+ let innerTarget = (innerCmdIndex >= 0 ? target.slice(innerCmdIndex + 1) : '');
switch (innerCmd) {
case 'me':
case 'mee':
case 'announce':
break;
case 'invite':
- case 'inv':
- var targetRoom = Rooms.search(innerTarget);
+ case 'inv': {
+ let targetRoom = Rooms.search(innerTarget);
if (!targetRoom || targetRoom === Rooms.global) return this.errorReply('The room "' + innerTarget + '" does not exist.');
if (targetRoom.staffRoom && !targetUser.isStaff) return this.errorReply('User "' + this.targetUsername + '" requires global auth to join room "' + targetRoom.id + '".');
if (targetRoom.modjoin) {
@@ -204,12 +206,13 @@ var commands = exports.commands = {
target = '/invite ' + targetRoom.id;
break;
+ }
default:
return this.errorReply("The command '/" + innerCmd + "' was unrecognized or unavailable in private messages. To send a message starting with '/" + innerCmd + "', type '//" + innerCmd + "'.");
}
}
- var message = '|pm|' + user.getIdentity() + '|' + targetUser.getIdentity() + '|' + target;
+ let message = '|pm|' + user.getIdentity() + '|' + targetUser.getIdentity() + '|' + target;
user.send(message);
if (targetUser !== user) targetUser.send(message);
targetUser.lastPM = user.userid;
@@ -269,26 +272,26 @@ var commands = exports.commands = {
return this.errorReply("Room titles can't contain any of: ,|[-");
}
- var id = toId(target);
+ let id = toId(target);
if (!id) return this.parse('/help makechatroom');
// Check if the name already exists as a room or alias
if (Rooms.search(id)) return this.errorReply("The room '" + target + "' already exists.");
if (Rooms.global.addChatRoom(target)) {
if (cmd === 'makeprivatechatroom') {
- var targetRoom = Rooms.search(target);
+ let targetRoom = Rooms.search(target);
targetRoom.isPrivate = true;
targetRoom.chatRoomData.isPrivate = true;
Rooms.global.writeChatRoomData();
- if (Rooms('upperstaff')) {
- Rooms('upperstaff').add('|raw|
Private chat room created: ' + Tools.escapeHTML(target) + '
').update();
+ if (Rooms.get('upperstaff')) {
+ Rooms.get('upperstaff').add('|raw|
Private chat room created: ' + Tools.escapeHTML(target) + '
').update();
}
return this.sendReply("The private chat room '" + target + "' was created.");
} else {
- if (Rooms('staff')) {
- Rooms('staff').add('|raw|
Public chat room created: ' + Tools.escapeHTML(target) + '
').update();
+ if (Rooms.get('staff')) {
+ Rooms.get('staff').add('|raw|
Public chat room created: ' + Tools.escapeHTML(target) + '
').update();
}
- if (Rooms('upperstaff')) {
- Rooms('upperstaff').add('|raw|
Public chat room created: ' + Tools.escapeHTML(target) + '
').update();
+ if (Rooms.get('upperstaff')) {
+ Rooms.get('upperstaff').add('|raw|
Public chat room created: ' + Tools.escapeHTML(target) + '
').update();
}
return this.sendReply("The chat room '" + target + "' was created.");
}
@@ -303,16 +306,16 @@ var commands = exports.commands = {
}
if (!this.can('makegroupchat')) return false;
if (target.length > 64) return this.errorReply("Title must be under 32 characters long.");
- var targets = target.split(',', 2);
+ let targets = target.split(',', 2);
// Title defaults to a random 8-digit number.
- var title = targets[0].trim();
+ let title = targets[0].trim();
if (title.length >= 32) {
return this.errorReply("Title must be under 32 characters long.");
} else if (!title) {
title = ('' + Math.floor(Math.random() * 100000000));
} else if (Config.chatfilter) {
- var filterResult = Config.chatfilter.call(this, title, user, null, connection);
+ let filterResult = Config.chatfilter.call(this, title, user, null, connection);
if (!filterResult) return;
if (title !== filterResult) {
return this.errorReply("Invalid title.");
@@ -327,14 +330,14 @@ var commands = exports.commands = {
// Even though they're different namespaces, to cut down on confusion, you
// can't share names with registered chatrooms.
- var existingRoom = Rooms.search(toId(title));
+ let existingRoom = Rooms.search(toId(title));
if (existingRoom && !existingRoom.modjoin) return this.errorReply("The room '" + title + "' already exists.");
// Room IDs for groupchats are groupchat-TITLEID
- var titleid = toId(title);
+ let titleid = toId(title);
if (!titleid) {
titleid = '' + Math.floor(Math.random() * 100000000);
}
- var roomid = 'groupchat-' + user.userid + '-' + titleid;
+ let roomid = 'groupchat-' + user.userid + '-' + titleid;
// Titles must be unique.
if (Rooms.search(roomid)) return this.errorReply("A group chat named '" + title + "' already exists.");
// Tab title is prefixed with '[G]' to distinguish groupchats from
@@ -347,23 +350,23 @@ var commands = exports.commands = {
}
// Privacy settings, default to hidden.
- var privacy = toId(targets[1]) || 'hidden';
- var privacySettings = {private: true, hidden: 'hidden', public: false};
+ let privacy = toId(targets[1]) || 'hidden';
+ let privacySettings = {private: true, hidden: 'hidden', public: false};
if (!(privacy in privacySettings)) privacy = 'hidden';
- var groupChatLink = '
<<' + roomid + '>>';
- var groupChatURL = '';
+ let groupChatLink = '
<<' + roomid + '>>';
+ let groupChatURL = '';
if (Config.serverid) {
groupChatURL = 'http://' + (Config.serverid === 'showdown' ? 'psim.us' : Config.serverid + '.psim.us') + '/' + roomid;
groupChatLink = '
' + groupChatLink + '';
}
- var titleHTML = '';
+ let titleHTML = '';
if (/^[0-9]+$/.test(title)) {
titleHTML = groupChatLink;
} else {
titleHTML = Tools.escapeHTML(title) + '
' + groupChatLink + '';
}
- var targetRoom = Rooms.createChatRoom(roomid, '[G] ' + title, {
+ let targetRoom = Rooms.createChatRoom(roomid, '[G] ' + title, {
isPersonal: true,
isPrivate: privacySettings[privacy],
auth: {},
@@ -382,9 +385,9 @@ var commands = exports.commands = {
deregisterchatroom: function (target, room, user) {
if (!this.can('makeroom')) return;
- var id = toId(target);
+ let id = toId(target);
if (!id) return this.parse('/help deregisterchatroom');
- var targetRoom = Rooms.search(id);
+ let targetRoom = Rooms.search(id);
if (!targetRoom) return this.errorReply("The room '" + target + "' doesn't exist.");
target = targetRoom.title || targetRoom.id;
if (Rooms.global.deregisterChatRoom(id)) {
@@ -408,7 +411,7 @@ var commands = exports.commands = {
// higher permissions to modify privacy settings
if (!this.can('makeroom')) return;
}
- var setting;
+ let setting;
switch (cmd) {
case 'privateroom':
return this.parse('/help privateroom');
@@ -515,7 +518,7 @@ var commands = exports.commands = {
}
if (!this.can('declare')) return false;
if (target.length > 80) return this.errorReply("Error: Room description is too long (must be at most 80 characters).");
- var normalizedTarget = ' ' + target.toLowerCase().replace('[^a-zA-Z0-9]+', ' ').trim() + ' ';
+ let normalizedTarget = ' ' + target.toLowerCase().replace('[^a-zA-Z0-9]+', ' ').trim() + ' ';
if (normalizedTarget.includes(' welcome ')) {
return this.errorReply("Error: Room description must not contain the word 'welcome'.");
@@ -555,7 +558,7 @@ var commands = exports.commands = {
if (!this.canHTML(target)) return;
if (!/$1');
}
if (target.substr(0, 11) === '/roomintro ') target = target.substr(11);
@@ -589,7 +592,7 @@ var commands = exports.commands = {
if (!this.canHTML(target)) return;
if (!/$1');
}
if (target.substr(0, 12) === '/staffintro ') target = target.substr(12);
@@ -613,7 +616,7 @@ var commands = exports.commands = {
return this.sendReplyBox("This room has the following aliases: " + room.aliases.join(", ") + "");
}
if (!this.can('makeroom')) return false;
- var alias = toId(target);
+ let alias = toId(target);
if (!alias.length) return this.errorReply("Only alphanumeric characters are valid in an alias.");
if (Rooms.get(alias) || Rooms.aliases[alias]) return this.errorReply("You cannot set an alias to an existing room or alias.");
if (room.isPersonal) return this.errorReply("Personal rooms can't have aliases.");
@@ -632,13 +635,13 @@ var commands = exports.commands = {
removeroomalias: function (target, room, user) {
if (!room.aliases) return this.sendReply("This room does not have any aliases.");
if (!this.can('makeroom')) return false;
- var alias = toId(target);
+ let alias = toId(target);
if (!alias.length || !Rooms.aliases[alias]) return this.errorReply("Please specify an existing alias.");
if (Rooms.aliases[alias] !== room.id) return this.errorReply("You may only remove an alias from the current room.");
this.privateModCommand("(" + user.name + " removed the room alias '" + target + "'.)");
- var aliasIndex = room.aliases.indexOf(alias);
+ let aliasIndex = room.aliases.indexOf(alias);
if (aliasIndex >= 0) {
room.aliases.splice(aliasIndex, 1);
delete Rooms.aliases[alias];
@@ -652,7 +655,7 @@ var commands = exports.commands = {
}
if (!target) return this.parse('/help roomowner');
target = this.splitTarget(target, true);
- var targetUser = this.targetUser;
+ let targetUser = this.targetUser;
if (!targetUser) return this.errorReply("User '" + this.targetUsername + "' is not online.");
@@ -660,7 +663,7 @@ var commands = exports.commands = {
if (!room.auth) room.auth = room.chatRoomData.auth = {};
- var name = targetUser.name;
+ let name = targetUser.name;
room.auth[targetUser.userid] = '#';
this.addModCommand("" + name + " was appointed Room Owner by " + user.name + ".");
@@ -676,9 +679,9 @@ var commands = exports.commands = {
}
if (!target) return this.parse('/help roomdeowner');
target = this.splitTarget(target, true);
- var targetUser = this.targetUser;
- var name = this.targetUsername;
- var userid = toId(name);
+ let targetUser = this.targetUser;
+ let name = this.targetUsername;
+ let userid = toId(name);
if (!userid || userid === '') return this.errorReply("User '" + name + "' does not exist.");
if (room.auth[userid] !== '#') return this.errorReply("User '" + name + "' is not a room owner.");
@@ -702,9 +705,9 @@ var commands = exports.commands = {
if (!target) return this.parse('/help roompromote');
target = this.splitTarget(target, true);
- var targetUser = this.targetUser;
- var userid = toId(this.targetUsername);
- var name = targetUser ? targetUser.name : this.targetUsername;
+ let targetUser = this.targetUser;
+ let userid = toId(this.targetUsername);
+ let name = targetUser ? targetUser.name : this.targetUsername;
if (!userid) return this.parse('/help roompromote');
if (!room.auth || !room.auth[userid]) {
@@ -716,8 +719,8 @@ var commands = exports.commands = {
}
}
- var currentGroup = ((room.auth && room.auth[userid]) || (room.isPrivate !== true && targetUser.group) || ' ');
- var nextGroup = target;
+ let currentGroup = ((room.auth && room.auth[userid]) || (room.isPrivate !== true && targetUser.group) || ' ');
+ let nextGroup = target;
if (target === 'deauth') nextGroup = Config.groupsranking[0];
if (!nextGroup) {
return this.errorReply("Please specify a group such as /roomvoice or /roomdeauth");
@@ -730,7 +733,7 @@ var commands = exports.commands = {
return this.errorReply("Group 'room" + Config.groups[nextGroup].id + "' does not exist as a room rank.");
}
- var groupName = Config.groups[nextGroup].name || "regular user";
+ let groupName = Config.groups[nextGroup].name || "regular user";
if ((room.auth[userid] || Config.groupsranking[0]) === nextGroup) {
return this.errorReply("User '" + name + "' is already a " + groupName + " in this room.");
}
@@ -767,19 +770,19 @@ var commands = exports.commands = {
roomstaff: 'roomauth',
roomauth: function (target, room, user, connection) {
- var targetRoom = room;
+ let targetRoom = room;
if (target) targetRoom = Rooms.search(target);
- var unavailableRoom = targetRoom && (targetRoom !== room && (targetRoom.modjoin || targetRoom.staffRoom) && !user.can('makeroom'));
+ let unavailableRoom = targetRoom && (targetRoom !== room && (targetRoom.modjoin || targetRoom.staffRoom) && !user.can('makeroom'));
if (!targetRoom || unavailableRoom) return this.errorReply("The room '" + target + "' does not exist.");
if (!targetRoom.auth) return this.sendReply("/roomauth - The room '" + (targetRoom.title ? targetRoom.title : target) + "' isn't designed for per-room moderation and therefore has no auth list.");
- var rankLists = {};
- for (var u in targetRoom.auth) {
+ let rankLists = {};
+ for (let u in targetRoom.auth) {
if (!rankLists[targetRoom.auth[u]]) rankLists[targetRoom.auth[u]] = [];
rankLists[targetRoom.auth[u]].push(u);
}
- var buffer = [];
+ let buffer = [];
Object.keys(rankLists).sort(function (a, b) {
return (Config.groups[b] || {rank:0}).rank - (Config.groups[a] || {rank:0}).rank;
}).forEach(function (r) {
@@ -795,18 +798,18 @@ var commands = exports.commands = {
},
userauth: function (target, room, user, connection) {
- var targetId = toId(target) || user.userid;
- var targetUser = Users.getExact(targetId);
- var targetUsername = (targetUser ? targetUser.name : target);
+ let targetId = toId(target) || user.userid;
+ let targetUser = Users.getExact(targetId);
+ let targetUsername = (targetUser ? targetUser.name : target);
- var buffer = [];
- var innerBuffer = [];
- var group = Users.usergroups[targetId];
+ let buffer = [];
+ let innerBuffer = [];
+ let group = Users.usergroups[targetId];
if (group) {
buffer.push('Global auth: ' + group.charAt(0));
}
- for (var i = 0; i < Rooms.global.chatRooms.length; i++) {
- var curRoom = Rooms.global.chatRooms[i];
+ for (let i = 0; i < Rooms.global.chatRooms.length; i++) {
+ let curRoom = Rooms.global.chatRooms[i];
if (!curRoom.auth || curRoom.isPrivate) continue;
group = curRoom.auth[targetId];
if (!group) continue;
@@ -817,11 +820,11 @@ var commands = exports.commands = {
}
if (targetId === user.userid || user.can('lock')) {
innerBuffer = [];
- for (var i = 0; i < Rooms.global.chatRooms.length; i++) {
- var curRoom = Rooms.global.chatRooms[i];
+ for (let i = 0; i < Rooms.global.chatRooms.length; i++) {
+ let curRoom = Rooms.global.chatRooms[i];
if (!curRoom.auth || !curRoom.isPrivate) continue;
if (curRoom.isPrivate === true) continue;
- var auth = curRoom.auth[targetId];
+ let auth = curRoom.auth[targetId];
if (!auth) continue;
innerBuffer.push(auth + curRoom.id);
}
@@ -831,11 +834,11 @@ var commands = exports.commands = {
}
if (targetId === user.userid || user.can('makeroom')) {
innerBuffer = [];
- for (var i = 0; i < Rooms.global.chatRooms.length; i++) {
- var curRoom = Rooms.global.chatRooms[i];
+ for (let i = 0; i < Rooms.global.chatRooms.length; i++) {
+ let curRoom = Rooms.global.chatRooms[i];
if (!curRoom.auth || !curRoom.isPrivate) continue;
if (curRoom.isPrivate !== true) continue;
- var auth = curRoom.auth[targetId];
+ let auth = curRoom.auth[targetId];
if (!auth) continue;
innerBuffer.push(auth + curRoom.id);
}
@@ -857,9 +860,9 @@ var commands = exports.commands = {
if (room.isMuted(user) && !user.can('bypassall')) return this.errorReply("You cannot do this while unable to talk.");
target = this.splitTarget(target);
- var targetUser = this.targetUser;
- var name = this.targetUsername;
- var userid = toId(name);
+ let targetUser = this.targetUser;
+ let name = this.targetUsername;
+ let userid = toId(name);
if (!userid || !targetUser) return this.errorReply("User '" + name + "' does not exist.");
if (target.length > MAX_REASON_LENGTH) {
@@ -877,12 +880,12 @@ var commands = exports.commands = {
);
}
this.addModCommand("" + targetUser.name + " was banned from room " + room.id + " by " + user.name + "." + (target ? " (" + target + ")" : ""));
- var acAccount = (targetUser.autoconfirmed !== targetUser.userid && targetUser.autoconfirmed);
- var alts = room.roomBan(targetUser);
+ let acAccount = (targetUser.autoconfirmed !== targetUser.userid && targetUser.autoconfirmed);
+ let alts = room.roomBan(targetUser);
if (!(room.isPersonal || room.isPrivate === true) || user.can('alts', targetUser)) {
if (alts.length) {
this.privateModCommand("(" + targetUser.name + "'s " + (acAccount ? " ac account: " + acAccount + ", " : "") + "roombanned alts: " + alts.join(", ") + ")");
- for (var i = 0; i < alts.length; ++i) {
+ for (let i = 0; i < alts.length; ++i) {
this.add('|unlink|' + toId(alts[i]));
}
} else if (acAccount) {
@@ -902,12 +905,12 @@ var commands = exports.commands = {
if (room.isMuted(user) && !user.can('bypassall')) return this.errorReply("You cannot do this while unable to talk.");
this.splitTarget(target, true);
- var targetUser = this.targetUser;
- var userid = room.isRoomBanned(targetUser) || toId(target);
+ let targetUser = this.targetUser;
+ let userid = room.isRoomBanned(targetUser) || toId(target);
if (!userid) return this.errorReply("User '" + target + "' is an invalid username.");
if (targetUser && !this.can('ban', targetUser, room)) return false;
- var unbannedUserid = room.unRoomBan(userid);
+ let unbannedUserid = room.unRoomBan(userid);
if (!unbannedUserid) return this.errorReply("User " + userid + " is not banned from room " + room.id + ".");
this.addModCommand("" + unbannedUserid + " was unbanned from room " + room.id + " by " + user.name + ".");
@@ -916,10 +919,10 @@ var commands = exports.commands = {
autojoin: function (target, room, user, connection) {
Rooms.global.autojoinRooms(user, connection);
- var targets = target.split(',');
- var autojoins = [];
+ let targets = target.split(',');
+ let autojoins = [];
if (targets.length > 9 || Object.keys(connection.rooms).length > 1) return;
- for (var i = 0; i < targets.length; i++) {
+ for (let i = 0; i < targets.length; i++) {
if (user.tryJoinRoom(targets[i], connection) === null) {
autojoins.push(targets[i]);
}
@@ -939,7 +942,7 @@ var commands = exports.commands = {
leave: 'part',
part: function (target, room, user, connection) {
if (room.id === 'global') return false;
- var targetRoom = Rooms.search(target);
+ let targetRoom = Rooms.search(target);
if (target && !targetRoom) {
return this.errorReply("The room '" + target + "' does not exist.");
}
@@ -958,7 +961,7 @@ var commands = exports.commands = {
if (room.isPersonal && !user.can('warn')) return this.errorReply("Warning is unavailable in group chats.");
target = this.splitTarget(target);
- var targetUser = this.targetUser;
+ let targetUser = this.targetUser;
if (!targetUser || !targetUser.connected) return this.errorReply("User '" + this.targetUsername + "' does not exist.");
if (!(targetUser in room.users)) {
return this.errorReply("User " + this.targetUsername + " is not in the room " + room.id + ".");
@@ -980,8 +983,8 @@ var commands = exports.commands = {
if (room.isPrivate || room.isPersonal) return this.errorReply("Users cannot be redirected from private or personal rooms.");
target = this.splitTarget(target);
- var targetUser = this.targetUser;
- var targetRoom = Rooms.search(target);
+ let targetUser = this.targetUser;
+ let targetRoom = Rooms.search(target);
if (!targetRoom || targetRoom.modjoin) {
return this.errorReply("The room '" + target + "' does not exist.");
}
@@ -1011,17 +1014,17 @@ var commands = exports.commands = {
if (room.isMuted(user) && !user.can('bypassall')) return this.errorReply("You cannot do this while unable to talk.");
target = this.splitTarget(target);
- var targetUser = this.targetUser;
+ let targetUser = this.targetUser;
if (!targetUser) return this.errorReply("User '" + this.targetUsername + "' does not exist.");
if (target.length > MAX_REASON_LENGTH) {
return this.errorReply("The reason is too long. It cannot exceed " + MAX_REASON_LENGTH + " characters.");
}
- var muteDuration = ((cmd === 'hm' || cmd === 'hourmute') ? HOURMUTE_LENGTH : MUTE_LENGTH);
+ let muteDuration = ((cmd === 'hm' || cmd === 'hourmute') ? HOURMUTE_LENGTH : MUTE_LENGTH);
if (!this.can('mute', targetUser, room)) return false;
- var canBeMutedFurther = ((room.getMuteTime(targetUser) || 0) <= (muteDuration * 5 / 6));
+ let canBeMutedFurther = ((room.getMuteTime(targetUser) || 0) <= (muteDuration * 5 / 6));
if ((room.isMuted(targetUser) && !canBeMutedFurther) || targetUser.locked || !targetUser.connected) {
- var problem = " but was already " + (!targetUser.connected ? "offline" : targetUser.locked ? "locked" : "muted");
+ let problem = " but was already " + (!targetUser.connected ? "offline" : targetUser.locked ? "locked" : "muted");
if (!target) {
return this.privateModCommand("(" + targetUser.name + " would be muted by " + user.name + problem + ".)");
}
@@ -1051,8 +1054,8 @@ var commands = exports.commands = {
if (room.isMuted(user) && !user.can('bypassall')) return this.errorReply("You cannot do this while unable to talk.");
if (!this.can('mute', null, room)) return false;
- var targetUser = this.targetUser;
- var successfullyUnmuted = room.unmute(targetUser ? targetUser.userid : this.targetUsername, "Your mute in '" + room.title + "' has been lifted.");
+ let targetUser = this.targetUser;
+ let successfullyUnmuted = room.unmute(targetUser ? targetUser.userid : this.targetUsername, "Your mute in '" + room.title + "' has been lifted.");
if (successfullyUnmuted) {
this.addModCommand("" + (targetUser ? targetUser.name : successfullyUnmuted) + " was unmuted by " + user.name + ".");
@@ -1069,7 +1072,7 @@ var commands = exports.commands = {
if (!target) return this.parse('/help lock');
target = this.splitTarget(target);
- var targetUser = this.targetUser;
+ let targetUser = this.targetUser;
if (!targetUser) return this.errorReply("User '" + this.targetUsername + "' does not exist.");
if (target.length > MAX_REASON_LENGTH) {
return this.errorReply("The reason is too long. It cannot exceed " + MAX_REASON_LENGTH + " characters.");
@@ -1077,13 +1080,13 @@ var commands = exports.commands = {
if (!this.can('lock', targetUser)) return false;
if ((targetUser.locked || Users.checkBanned(targetUser.latestIp)) && !target) {
- var problem = " but was already " + (targetUser.locked ? "locked" : "banned");
+ let problem = " but was already " + (targetUser.locked ? "locked" : "banned");
return this.privateModCommand("(" + targetUser.name + " would be locked by " + user.name + problem + ".)");
}
if (targetUser.confirmed) {
if (cmd === 'forcelock') {
- var from = targetUser.deconfirm();
+ let from = targetUser.deconfirm();
Monitor.log("[CrisisMonitor] " + targetUser.name + " was locked by " + user.name + " and demoted from " + from.join(", ") + ".");
} else {
return this.sendReply("" + targetUser.name + " is a confirmed user. If you are sure you would like to lock them use /forcelock.");
@@ -1093,9 +1096,9 @@ var commands = exports.commands = {
}
// Destroy personal rooms of the locked user.
- for (var i in targetUser.roomCount) {
+ for (let i in targetUser.roomCount) {
if (i === 'global') continue;
- var targetRoom = Rooms.get(i);
+ let targetRoom = Rooms.get(i);
if (targetRoom.isPersonal && targetRoom.auth[targetUser.userid] && targetRoom.auth[targetUser.userid] === '#') {
targetRoom.destroy();
}
@@ -1104,14 +1107,14 @@ var commands = exports.commands = {
targetUser.popup("|modal|" + user.name + " has locked you from talking in chats, battles, and PMing regular users." + (target ? "\n\nReason: " + target : "") + "\n\nIf you feel that your lock was unjustified, you can still PM staff members (%, @, &, and ~) to discuss it" + (Config.appealurl ? " or you can appeal:\n" + Config.appealurl : ".") + "\n\nYour lock will expire in a few days.");
this.addModCommand("" + targetUser.name + " was locked from talking by " + user.name + "." + (target ? " (" + target + ")" : ""));
- var alts = targetUser.getAlts();
- var acAccount = (targetUser.autoconfirmed !== targetUser.userid && targetUser.autoconfirmed);
+ let alts = targetUser.getAlts();
+ let acAccount = (targetUser.autoconfirmed !== targetUser.userid && targetUser.autoconfirmed);
if (alts.length) {
this.privateModCommand("(" + targetUser.name + "'s " + (acAccount ? " ac account: " + acAccount + ", " : "") + "locked alts: " + alts.join(", ") + ")");
} else if (acAccount) {
this.privateModCommand("(" + targetUser.name + "'s ac account: " + acAccount + ")");
}
- var userid = this.getLastIdOf(targetUser);
+ let userid = this.getLastIdOf(targetUser);
this.add('|unlink|hide|' + userid);
if (userid !== toId(this.inputUsername)) this.add('|unlink|hide|' + toId(this.inputUsername));
@@ -1125,16 +1128,16 @@ var commands = exports.commands = {
if (!target) return this.parse('/help unlock');
if (!this.can('lock')) return false;
- var targetUser = Users.get(target);
- var reason = '';
+ let targetUser = Users.get(target);
+ let reason = '';
if (targetUser && targetUser.locked && targetUser.locked.charAt(0) === '#') {
reason = ' (' + targetUser.locked + ')';
}
- var unlocked = Users.unlock(target);
+ let unlocked = Users.unlock(target);
if (unlocked) {
- var names = Object.keys(unlocked);
+ let names = Object.keys(unlocked);
this.addModCommand(names.join(", ") + " " + ((names.length > 1) ? "were" : "was") +
" unlocked by " + user.name + "." + reason);
if (!reason) this.globalModlog("UNLOCK", target, " by " + user.name);
@@ -1151,7 +1154,7 @@ var commands = exports.commands = {
if (!target) return this.parse('/help ban');
target = this.splitTarget(target);
- var targetUser = this.targetUser;
+ let targetUser = this.targetUser;
if (!targetUser) return this.errorReply("User '" + this.targetUsername + "' does not exist.");
if (target.length > MAX_REASON_LENGTH) {
return this.errorReply("The reason is too long. It cannot exceed " + MAX_REASON_LENGTH + " characters.");
@@ -1159,13 +1162,13 @@ var commands = exports.commands = {
if (!this.can('ban', targetUser)) return false;
if (Users.checkBanned(targetUser.latestIp) && !target && !targetUser.connected) {
- var problem = " but was already banned";
+ let problem = " but was already banned";
return this.privateModCommand("(" + targetUser.name + " would be banned by " + user.name + problem + ".)");
}
if (targetUser.confirmed) {
if (cmd === 'forceban') {
- var from = targetUser.deconfirm();
+ let from = targetUser.deconfirm();
Monitor.log("[CrisisMonitor] " + targetUser.name + " was banned by " + user.name + " and demoted from " + from.join(", ") + ".");
} else {
return this.sendReply("" + targetUser.name + " is a confirmed user. If you are sure you would like to ban them use /forceban.");
@@ -1175,9 +1178,9 @@ var commands = exports.commands = {
}
// Destroy personal rooms of the banned user.
- for (var i in targetUser.roomCount) {
+ for (let i in targetUser.roomCount) {
if (i === 'global') continue;
- var targetRoom = Rooms.get(i);
+ let targetRoom = Rooms.get(i);
if (targetRoom.isPersonal && targetRoom.auth[targetUser.userid] && targetRoom.auth[targetUser.userid] === '#') {
targetRoom.destroy();
}
@@ -1186,24 +1189,24 @@ var commands = exports.commands = {
targetUser.popup("|modal|" + user.name + " has banned you." + (target ? "\n\nReason: " + target : "") + (Config.appealurl ? "\n\nIf you feel that your ban was unjustified, you can appeal:\n" + Config.appealurl : "") + "\n\nYour ban will expire in a few days.");
this.addModCommand("" + targetUser.name + " was banned by " + user.name + "." + (target ? " (" + target + ")" : ""), " (" + targetUser.latestIp + ")");
- var alts = targetUser.getAlts();
- var acAccount = (targetUser.autoconfirmed !== targetUser.userid && targetUser.autoconfirmed);
+ let alts = targetUser.getAlts();
+ let acAccount = (targetUser.autoconfirmed !== targetUser.userid && targetUser.autoconfirmed);
if (alts.length) {
- var guests = 0;
+ let guests = 0;
alts = alts.filter(function (alt) {
if (alt.substr(0, 6) !== 'Guest ') return true;
guests++;
return false;
});
this.privateModCommand("(" + targetUser.name + "'s " + (acAccount ? " ac account: " + acAccount + ", " : "") + "banned alts: " + alts.join(", ") + (guests ? " [" + guests + " guests]" : "") + ")");
- for (var i = 0; i < alts.length; ++i) {
+ for (let i = 0; i < alts.length; ++i) {
this.add('|unlink|' + toId(alts[i]));
}
} else if (acAccount) {
this.privateModCommand("(" + targetUser.name + "'s ac account: " + acAccount + ")");
}
- var userid = this.getLastIdOf(targetUser);
+ let userid = this.getLastIdOf(targetUser);
this.add('|unlink|hide|' + userid);
if (userid !== toId(this.inputUsername)) this.add('|unlink|hide|' + toId(this.inputUsername));
targetUser.ban(false, userid);
@@ -1216,7 +1219,7 @@ var commands = exports.commands = {
if (!target) return this.parse('/help unban');
if (!this.can('ban')) return false;
- var name = Users.unban(target);
+ let name = Users.unban(target);
if (name) {
this.addModCommand("" + name + " was unbanned by " + user.name + ".");
@@ -1239,10 +1242,10 @@ var commands = exports.commands = {
return this.parse('/help unbanall');
}
// we have to do this the hard way since it's no longer a global
- var punishKeys = ['bannedIps', 'bannedUsers', 'lockedIps', 'lockedUsers', 'lockedRanges', 'rangeLockedUsers'];
- for (var i = 0; i < punishKeys.length; i++) {
- var dict = Users[punishKeys[i]];
- for (var entry in dict) delete dict[entry];
+ let punishKeys = ['bannedIps', 'bannedUsers', 'lockedIps', 'lockedUsers', 'lockedRanges', 'rangeLockedUsers'];
+ for (let i = 0; i < punishKeys.length; i++) {
+ let dict = Users[punishKeys[i]];
+ for (let entry in dict) delete dict[entry];
}
this.addModCommand("All bans and locks have been lifted by " + user.name + ".");
},
@@ -1260,8 +1263,8 @@ var commands = exports.commands = {
if (user.lastCommand !== '/deroomvoiceall' || target !== 'confirm') {
return this.parse('/help deroomvoiceall');
}
- var count = 0;
- for (var userid in room.auth) {
+ let count = 0;
+ for (let userid in room.auth) {
if (room.auth[userid] === '+') {
delete room.auth[userid];
count++;
@@ -1308,8 +1311,8 @@ var commands = exports.commands = {
if (!target) return this.errorReply("Please specify a range to lock.");
if (!this.can('rangeban')) return false;
- var isIp = (target.slice(-1) === '*' ? true : false);
- var range = (isIp ? target : Users.shortenHost(target));
+ let isIp = (target.slice(-1) === '*' ? true : false);
+ let range = (isIp ? target : Users.shortenHost(target));
if (Users.lockedRanges[range]) return this.errorReply("The range " + range + " has already been temporarily locked.");
Users.lockRange(range, isIp);
@@ -1321,7 +1324,7 @@ var commands = exports.commands = {
if (!target) return this.errorReply("Please specify a range to unlock.");
if (!this.can('rangeban')) return false;
- var range = (target.slice(-1) === '*' ? target : Users.shortenHost(target));
+ let range = (target.slice(-1) === '*' ? target : Users.shortenHost(target));
if (!Users.lockedRanges[range]) return this.errorReply("The range " + range + " is not locked.");
Users.unlockRange(range);
@@ -1350,14 +1353,14 @@ var commands = exports.commands = {
if (!target) return this.parse('/help promote');
target = this.splitTarget(target, true);
- var targetUser = this.targetUser;
- var userid = toId(this.targetUsername);
- var name = targetUser ? targetUser.name : this.targetUsername;
+ let targetUser = this.targetUser;
+ let userid = toId(this.targetUsername);
+ let name = targetUser ? targetUser.name : this.targetUsername;
if (!userid) return this.parse('/help promote');
- var currentGroup = ((targetUser && targetUser.group) || Users.usergroups[userid] || ' ')[0];
- var nextGroup = target;
+ let currentGroup = ((targetUser && targetUser.group) || Users.usergroups[userid] || ' ')[0];
+ let nextGroup = target;
if (target === 'deauth') nextGroup = Config.groupsranking[0];
if (!nextGroup) {
return this.errorReply("Please specify a group such as /globalvoice or /globaldeauth");
@@ -1369,7 +1372,7 @@ var commands = exports.commands = {
return this.errorReply("Group '" + nextGroup + "' does not exist as a global rank.");
}
- var groupName = Config.groups[nextGroup].name || "regular user";
+ let groupName = Config.groups[nextGroup].name || "regular user";
if (currentGroup === nextGroup) {
return this.errorReply("User '" + name + "' is already a " + groupName);
}
@@ -1402,8 +1405,8 @@ var commands = exports.commands = {
// warning: never document this command in /help
if (!this.can('forcepromote')) return false;
target = this.splitTarget(target, true);
- var name = this.targetUsername;
- var nextGroup = target;
+ let name = this.targetUsername;
+ let nextGroup = target;
if (!Config.groups[nextGroup]) return this.errorReply("Group '" + nextGroup + "' does not exist.");
if (!Users.setOfflineGroup(name, nextGroup, true)) {
@@ -1435,7 +1438,7 @@ var commands = exports.commands = {
}
target = target.toLowerCase();
- var currentModchat = room.modchat;
+ let currentModchat = room.modchat;
switch (target) {
case 'off':
case 'false':
@@ -1467,7 +1470,7 @@ var commands = exports.commands = {
if (!room.modchat) {
this.add("|raw|
Moderated chat was disabled!
Anyone may talk now.
");
} else {
- var modchat = Tools.escapeHTML(room.modchat);
+ let modchat = Tools.escapeHTML(room.modchat);
this.add("|raw|
Moderated chat was set to " + modchat + "!
Only users of rank " + modchat + " and higher can talk.
");
}
this.logModCommand(user.name + " set modchat to " + room.modchat);
@@ -1506,7 +1509,7 @@ var commands = exports.commands = {
if (!target) return this.parse('/help globaldeclare');
if (!this.can('gdeclare')) return false;
- for (var id in Rooms.rooms) {
+ for (let id in Rooms.rooms) {
if (id !== 'global') Rooms.rooms[id].addRaw('
' + target + '
');
}
this.logModCommand(user.name + " globally declared " + target);
@@ -1518,7 +1521,7 @@ var commands = exports.commands = {
if (!target) return this.parse('/help chatdeclare');
if (!this.can('gdeclare')) return false;
- for (var id in Rooms.rooms) {
+ for (let id in Rooms.rooms) {
if (id !== 'global') if (Rooms.rooms[id].type !== 'battle') Rooms.rooms[id].addRaw('
' + target + '
');
}
this.logModCommand(user.name + " globally declared (chat level) " + target);
@@ -1542,8 +1545,8 @@ var commands = exports.commands = {
forcerename: function (target, room, user) {
if (!target) return this.parse('/help forcerename');
- var reason = this.splitTarget(target, true);
- var targetUser = this.targetUser;
+ let reason = this.splitTarget(target, true);
+ let targetUser = this.targetUser;
if (!targetUser) {
this.splitTarget(target);
if (this.targetUser) {
@@ -1553,7 +1556,7 @@ var commands = exports.commands = {
}
if (!this.can('forcerename', targetUser)) return false;
- var entry = targetUser.name + " was forced to choose a new name by " + user.name + (reason ? ": " + reason : "");
+ let entry = targetUser.name + " was forced to choose a new name by " + user.name + (reason ? ": " + reason : "");
this.privateModCommand("(" + entry + ")");
Rooms.global.cancelSearch(targetUser);
targetUser.resetName();
@@ -1565,12 +1568,12 @@ var commands = exports.commands = {
hidetext: function (target, room, user) {
if (!target) return this.parse('/help hidetext');
- var reason = this.splitTarget(target);
- var targetUser = this.targetUser;
- var name = this.targetUsername;
+ let reason = this.splitTarget(target);
+ let targetUser = this.targetUser;
+ let name = this.targetUsername;
if (!targetUser) return this.errorReply("User '" + name + "' does not exist.");
- var userid = this.getLastIdOf(targetUser);
- var hidetype = '';
+ let userid = this.getLastIdOf(targetUser);
+ let hidetype = '';
if (!user.can('lock', targetUser) && !user.can('ban', targetUser, room)) {
this.errorReply("/hidetext - Access denied.");
return false;
@@ -1591,17 +1594,17 @@ var commands = exports.commands = {
hidetexthelp: ["/hidetext [username] - Removes a locked or banned user's messages from chat (includes users banned from the room). Requires: % (global only), @ # & ~"],
modlog: function (target, room, user, connection) {
- var lines = 0;
+ let lines = 0;
// Specific case for modlog command. Room can be indicated with a comma, lines go after the comma.
// Otherwise, the text is defaulted to text search in current room's modlog.
- var roomId = (room.id === 'staff' ? 'global' : room.id);
- var hideIps = !user.can('lock');
- var path = require('path');
- var isWin = process.platform === 'win32';
- var logPath = 'logs/modlog/';
+ let roomId = (room.id === 'staff' ? 'global' : room.id);
+ let hideIps = !user.can('lock');
+ let path = require('path');
+ let isWin = process.platform === 'win32';
+ let logPath = 'logs/modlog/';
if (target.includes(',')) {
- var targets = target.split(',');
+ let targets = target.split(',');
target = targets[1].trim();
roomId = toId(targets[0]) || room.id;
}
@@ -1611,18 +1614,18 @@ var commands = exports.commands = {
lines = parseInt(target || 20, 10);
if (lines > 100) lines = 100;
}
- var wordSearch = (!lines || lines < 0);
+ let wordSearch = (!lines || lines < 0);
// Control if we really, really want to check all modlogs for a word.
- var roomNames = '';
- var filename = '';
- var command = '';
+ let roomNames = '';
+ let filename = '';
+ let command = '';
if (roomId === 'all' && wordSearch) {
if (!this.can('modlog')) return;
roomNames = "all rooms";
// Get a list of all the rooms
- var fileList = fs.readdirSync('logs/modlog');
- for (var i = 0; i < fileList.length; ++i) {
+ let fileList = fs.readdirSync('logs/modlog');
+ for (let i = 0; i < fileList.length; ++i) {
filename += path.normalize(__dirname + '/' + logPath + fileList[i]) + ' ';
}
} else if (roomId.startsWith('battle-') || roomId.startsWith('groupchat-')) {
@@ -1639,7 +1642,7 @@ var commands = exports.commands = {
} else {
command = 'tail -' + lines + ' ' + filename;
}
- var grepLimit = 100;
+ let grepLimit = 100;
if (wordSearch) { // searching for a word instead
if (target.match(/^["'].+["']$/)) target = target.substring(1, target.length - 1);
if (isWin) {
@@ -1660,15 +1663,15 @@ var commands = exports.commands = {
stdout = stdout.replace(/\([0-9]+\.[0-9]+\.[0-9]+\.[0-9]+\)/g, '');
}
stdout = stdout.split('\n').map(function (line) {
- var bracketIndex = line.indexOf(']');
- var parenIndex = line.indexOf(')');
+ let bracketIndex = line.indexOf(']');
+ let parenIndex = line.indexOf(')');
if (bracketIndex < 0) return Tools.escapeHTML(line);
- var time = line.slice(1, bracketIndex);
- var timestamp = new Date(time).format('{yyyy}-{MM}-{dd} {hh}:{mm}{tt}');
- var parenIndex = line.indexOf(')');
- var roomid = line.slice(bracketIndex + 3, parenIndex);
+ let time = line.slice(1, bracketIndex);
+ let timestamp = new Date(time).format('{yyyy}-{MM}-{dd} {hh}:{mm}{tt}');
+ parenIndex = line.indexOf(')');
+ let roomid = line.slice(bracketIndex + 3, parenIndex);
if (!hideIps && Config.modloglink) {
- var url = Config.modloglink(time, roomid);
+ let url = Config.modloglink(time, roomid);
if (url) timestamp = '
' + timestamp + '';
}
return '
[' + timestamp + '] (' + roomid + ')' + Tools.escapeHTML(line.slice(parenIndex + 1));
@@ -1709,7 +1712,7 @@ var commands = exports.commands = {
delete require.cache[require.resolve('./chat-plugins/info.js')];
global.CommandParser = require('./command-parser.js');
- var runningTournaments = Tournaments.tournaments;
+ let runningTournaments = Tournaments.tournaments;
CommandParser.uncacheTree('./tournaments');
global.Tournaments = require('./tournaments');
Tournaments.tournaments = runningTournaments;
@@ -1720,7 +1723,7 @@ var commands = exports.commands = {
}
} else if (target === 'tournaments') {
try {
- var runningTournaments = Tournaments.tournaments;
+ let runningTournaments = Tournaments.tournaments;
CommandParser.uncacheTree('./tournaments');
global.Tournaments = require('./tournaments');
Tournaments.tournaments = runningTournaments;
@@ -1733,7 +1736,7 @@ var commands = exports.commands = {
return this.sendReply("Battles have been hotpatched. Any battles started after now will use the new code; however, in-progress battles will continue to use the old code.");
} else if (target === 'formats') {
try {
- var toolsLoaded = !!Tools.isLoaded;
+ let toolsLoaded = !!Tools.isLoaded;
// uncache the tools.js dependency tree
CommandParser.uncacheTree('./tools.js');
// reload tools.js
@@ -1753,7 +1756,7 @@ var commands = exports.commands = {
}
} else if (target === 'learnsets') {
try {
- var toolsLoaded = !!Tools.isLoaded;
+ let toolsLoaded = !!Tools.isLoaded;
// uncache the tools.js dependency tree
CommandParser.uncacheTree('./tools.js');
// reload tools.js
@@ -1802,9 +1805,9 @@ var commands = exports.commands = {
if (!this.can('lockdown')) return false;
Rooms.global.lockdown = true;
- for (var id in Rooms.rooms) {
+ for (let id in Rooms.rooms) {
if (id === 'global') continue;
- var curRoom = Rooms.rooms[id];
+ let curRoom = Rooms.rooms[id];
curRoom.addRaw("
The server is restarting soon.
Please finish your battles quickly. No new battles can be started until the server resets in a few minutes.
");
if (curRoom.requestKickInactive && !curRoom.battle.ended) {
curRoom.requestKickInactive(user, true);
@@ -1830,9 +1833,9 @@ var commands = exports.commands = {
if (!this.can('lockdown')) return false;
Rooms.global.lockdown = true;
- for (var id in Rooms.rooms) {
+ for (let id in Rooms.rooms) {
if (id === 'global') continue;
- var curRoom = Rooms.rooms[id];
+ let curRoom = Rooms.rooms[id];
if (curRoom.battle) continue;
curRoom.addRaw("
The server is restarting soon.
Please finish your battles quickly. No new battles can be started until the server resets in a few minutes.
");
}
@@ -1847,7 +1850,7 @@ var commands = exports.commands = {
return this.errorReply("We're not under lockdown right now.");
}
if (Rooms.global.lockdown === true) {
- for (var id in Rooms.rooms) {
+ for (let id in Rooms.rooms) {
if (id !== 'global') Rooms.rooms[id].addRaw("
The server shutdown was canceled.
");
}
} else {
@@ -1865,7 +1868,7 @@ var commands = exports.commands = {
return this.errorReply("We're already in emergency mode.");
}
Config.emergency = true;
- for (var id in Rooms.rooms) {
+ for (let id in Rooms.rooms) {
if (id !== 'global') Rooms.rooms[id].addRaw("
The server has entered emergency mode. Some features might be disabled or limited.
");
}
@@ -1879,7 +1882,7 @@ var commands = exports.commands = {
return this.errorReply("We're not in emergency mode.");
}
Config.emergency = false;
- for (var id in Rooms.rooms) {
+ for (let id in Rooms.rooms) {
if (id !== 'global') Rooms.rooms[id].addRaw("
The server is no longer in emergency mode.
");
}
@@ -1897,7 +1900,7 @@ var commands = exports.commands = {
return this.errorReply("Wait for /updateserver to finish before using /kill.");
}
- for (var i in Sockets.workers) {
+ for (let i in Sockets.workers) {
Sockets.workers[i].kill();
}
@@ -1926,9 +1929,9 @@ var commands = exports.commands = {
fs.readFile('config/ipbans.txt', function (err, data) {
if (err) return;
data = ('' + data).split('\n');
- var rangebans = [];
- for (var i = 0; i < data.length; ++i) {
- var line = data[i].split('#')[0].trim();
+ let rangebans = [];
+ for (let i = 0; i < data.length; ++i) {
+ let line = data[i].split('#')[0].trim();
if (!line) continue;
if (line.includes('/')) {
rangebans.push(line);
@@ -1959,14 +1962,14 @@ var commands = exports.commands = {
CommandParser.updateServerLock = true;
- var logQueue = [];
+ let logQueue = [];
logQueue.push(user.name + " used /updateserver");
connection.sendTo(room, "updating...");
- var exec = require('child_process').exec;
+ let exec = require('child_process').exec;
exec('git diff-index --quiet HEAD --', function (error) {
- var cmd = 'git pull --rebase';
+ let cmd = 'git pull --rebase';
if (error) {
if (error.code === 1) {
// The working directory or index have local changes.
@@ -1983,7 +1986,7 @@ var commands = exports.commands = {
return;
}
}
- var entry = "Running `" + cmd + "`";
+ let entry = "Running `" + cmd + "`";
connection.sendTo(room, entry);
logQueue.push(entry);
exec(cmd, function (error, stdout, stderr) {
@@ -2017,11 +2020,11 @@ var commands = exports.commands = {
'memusage': 'memoryusage',
memoryusage: function (target) {
if (!this.can('hotpatch')) return false;
- var memUsage = process.memoryUsage();
- var results = [memUsage.rss, memUsage.heapUsed, memUsage.heapTotal];
- var units = ["B", "KiB", "MiB", "GiB", "TiB"];
- for (var i = 0; i < results.length; i++) {
- var unitIndex = Math.floor(Math.log2(results[i]) / 10); // 2^10 base log
+ let memUsage = process.memoryUsage();
+ let results = [memUsage.rss, memUsage.heapUsed, memUsage.heapTotal];
+ let units = ["B", "KiB", "MiB", "GiB", "TiB"];
+ for (let i = 0; i < results.length; i++) {
+ let unitIndex = Math.floor(Math.log2(results[i]) / 10); // 2^10 base log
results[i] = "" + (results[i] / Math.pow(2, 10 * unitIndex)).toFixed(2) + " " + units[unitIndex];
}
this.sendReply("Main process. RSS: " + results[0] + ". Heap: " + results[1] + " / " + results[2] + ".");
@@ -2032,7 +2035,7 @@ var commands = exports.commands = {
return this.errorReply("/bash - Access denied.");
}
- var exec = require('child_process').exec;
+ let exec = require('child_process').exec;
exec(target, function (error, stdout, stderr) {
connection.sendTo(room, ("" + stdout + stderr));
});
@@ -2046,12 +2049,12 @@ var commands = exports.commands = {
if (!this.broadcasting) this.sendReply('||>> ' + target);
try {
- var battle = room.battle;
- var me = user;
+ let battle = room.battle;
+ let me = user;
this.sendReply('||<< ' + eval(target));
} catch (e) {
this.sendReply('||<< error: ' + e.message);
- var stack = '||' + ('' + e.stack).replace(/\n/g, '\n||');
+ let stack = '||' + ('' + e.stack).replace(/\n/g, '\n||');
connection.sendTo(room, stack);
}
},
@@ -2076,8 +2079,8 @@ var commands = exports.commands = {
this.errorReply("/editbattle - This is not a battle room.");
return false;
}
- var cmd;
- var spaceIndex = target.indexOf(' ');
+ let cmd;
+ let spaceIndex = target.indexOf(' ');
if (spaceIndex > 0) {
cmd = target.substr(0, spaceIndex).toLowerCase();
target = target.substr(spaceIndex + 1);
@@ -2086,7 +2089,7 @@ var commands = exports.commands = {
target = '';
}
if (cmd.charAt(cmd.length - 1) === ',') cmd = cmd.slice(0, -1);
- var targets = target.split(',');
+ let targets = target.split(',');
function getPlayer(input) {
if (room.battle.playerids[0] === toId(input)) return 'p1';
if (room.battle.playerids[1] === toId(input)) return 'p2';
@@ -2103,26 +2106,26 @@ var commands = exports.commands = {
switch (cmd) {
case 'hp':
case 'h':
- room.battle.send('eval', "var p=" + getPlayer(targets[0]) + getPokemon(targets[1]) + ";p.sethp(" + parseInt(targets[2]) + ");if (p.isActive)battle.add('-damage',p,p.getHealth);");
+ room.battle.send('eval', "let p=" + getPlayer(targets[0]) + getPokemon(targets[1]) + ";p.sethp(" + parseInt(targets[2]) + ");if (p.isActive)battle.add('-damage',p,p.getHealth);");
break;
case 'status':
case 's':
- room.battle.send('eval', "var pl=" + getPlayer(targets[0]) + ";var p=pl" + getPokemon(targets[1]) + ";p.setStatus('" + toId(targets[2]) + "');if (!p.isActive){battle.add('','please ignore the above');battle.add('-status',pl.active[0],pl.active[0].status,'[silent]');}");
+ room.battle.send('eval', "let pl=" + getPlayer(targets[0]) + ";let p=pl" + getPokemon(targets[1]) + ";p.setStatus('" + toId(targets[2]) + "');if (!p.isActive){battle.add('','please ignore the above');battle.add('-status',pl.active[0],pl.active[0].status,'[silent]');}");
break;
case 'pp':
- room.battle.send('eval', "var pl=" + getPlayer(targets[0]) + ";var p=pl" + getPokemon(targets[1]) + ";p.moveset[p.moves.indexOf('" + toId(targets[2]) + "')].pp = " + parseInt(targets[3]));
+ room.battle.send('eval', "let pl=" + getPlayer(targets[0]) + ";let p=pl" + getPokemon(targets[1]) + ";p.moveset[p.moves.indexOf('" + toId(targets[2]) + "')].pp = " + parseInt(targets[3]));
break;
case 'boost':
case 'b':
- room.battle.send('eval', "var p=" + getPlayer(targets[0]) + getPokemon(targets[1]) + ";battle.boost({" + toId(targets[2]) + ":" + parseInt(targets[3]) + "},p)");
+ room.battle.send('eval', "let p=" + getPlayer(targets[0]) + getPokemon(targets[1]) + ";battle.boost({" + toId(targets[2]) + ":" + parseInt(targets[3]) + "},p)");
break;
case 'volatile':
case 'v':
- room.battle.send('eval', "var p=" + getPlayer(targets[0]) + getPokemon(targets[1]) + ";p.addVolatile('" + toId(targets[2]) + "')");
+ room.battle.send('eval', "let p=" + getPlayer(targets[0]) + getPokemon(targets[1]) + ";p.addVolatile('" + toId(targets[2]) + "')");
break;
case 'sidecondition':
case 'sc':
- room.battle.send('eval', "var p=" + getPlayer(targets[0]) + ".addSideCondition('" + toId(targets[1]) + "')");
+ room.battle.send('eval', "let p=" + getPlayer(targets[0]) + ".addSideCondition('" + toId(targets[1]) + "')");
break;
case 'fieldcondition': case 'pseudoweather':
case 'fc':
@@ -2168,15 +2171,15 @@ var commands = exports.commands = {
savereplay: function (target, room, user, connection) {
if (!room || !room.battle) return;
- var logidx = 0; // spectator log (no exact HP)
+ let logidx = 0; // spectator log (no exact HP)
if (room.battle.ended) {
// If the battle is finished when /savereplay is used, include
// exact HP in the replay log.
logidx = 3;
}
- var data = room.getLog(logidx).join("\n");
- var datahash = crypto.createHash('md5').update(data.replace(/[^(\x20-\x7F)]+/g, '')).digest('hex');
- var players = room.battle.lastPlayers.map(Users.getExact);
+ let data = room.getLog(logidx).join("\n");
+ let datahash = crypto.createHash('md5').update(data.replace(/[^(\x20-\x7F)]+/g, '')).digest('hex');
+ let players = room.battle.lastPlayers.map(Users.getExact);
LoginServer.request('prepreplay', {
id: room.id.substr(7),
loghash: datahash,
@@ -2234,9 +2237,9 @@ var commands = exports.commands = {
if (room.rated) return this.errorReply("You can only add a Player to unrated battles.");
target = this.splitTarget(target, true);
- var userid = toId(this.targetUsername);
- var targetUser = this.targetUser;
- var name = this.targetUsername;
+ let userid = toId(this.targetUsername);
+ let targetUser = this.targetUser;
+ let name = this.targetUsername;
if (!targetUser) return this.errorReply("User " + name + " not found.");
if (targetUser.can('joinbattle', null, room)) {
@@ -2267,7 +2270,7 @@ var commands = exports.commands = {
if (!room.leaveBattle) return this.errorReply("You can only do this in battle rooms.");
target = this.splitTarget(target);
- var targetUser = this.targetUser;
+ let targetUser = this.targetUser;
if (!targetUser || !targetUser.connected) {
return this.errorReply("User " + this.targetUsername + " not found.");
}
@@ -2293,7 +2296,7 @@ var commands = exports.commands = {
target = toId(target);
if (room.requestKickInactive) {
if (target === 'off' || target === 'false' || target === 'stop') {
- var canForceTimer = user.can('timer', null, room);
+ let canForceTimer = user.can('timer', null, room);
if (room.resetTimer) {
room.stopKickInactive(user, canForceTimer);
if (canForceTimer) room.send('|inactiveoff|Timer was turned off by staff. Please do not turn it back on until our staff say it\'s okay');
@@ -2337,7 +2340,7 @@ var commands = exports.commands = {
this.logModCommand(user.name + " forced a tie.");
return false;
}
- var targetUser = Users.getExact(target);
+ let targetUser = Users.getExact(target);
if (!targetUser) return this.errorReply("User '" + target + "' not found.");
target = targetUser ? targetUser.userid : '';
@@ -2358,9 +2361,9 @@ var commands = exports.commands = {
search: function (target, room, user) {
if (target) {
if (Config.pmmodchat) {
- var userGroup = user.group;
+ let userGroup = user.group;
if (Config.groupsranking.indexOf(userGroup) < Config.groupsranking.indexOf(Config.pmmodchat)) {
- var groupName = Config.groups[Config.pmmodchat].name || Config.pmmodchat;
+ let groupName = Config.groups[Config.pmmodchat].name || Config.pmmodchat;
this.popupReply("Because moderated chat is set, you must be of rank " + groupName + " or higher to search for a battle.");
return false;
}
@@ -2374,7 +2377,7 @@ var commands = exports.commands = {
chall: 'challenge',
challenge: function (target, room, user, connection) {
target = this.splitTarget(target);
- var targetUser = this.targetUser;
+ let targetUser = this.targetUser;
if (!targetUser || !targetUser.connected) {
return this.popupReply("The user '" + this.targetUsername + "' was not found.");
}
@@ -2382,9 +2385,9 @@ var commands = exports.commands = {
return this.popupReply("The user '" + this.targetUsername + "' is not accepting challenges right now.");
}
if (Config.pmmodchat) {
- var userGroup = user.group;
+ let userGroup = user.group;
if (Config.groupsranking.indexOf(userGroup) < Config.groupsranking.indexOf(Config.pmmodchat)) {
- var groupName = Config.groups[Config.pmmodchat].name || Config.pmmodchat;
+ let groupName = Config.groups[Config.pmmodchat].name || Config.pmmodchat;
this.popupReply("Because moderated chat is set, you must be of rank " + groupName + " or higher to challenge users.");
return false;
}
@@ -2421,8 +2424,8 @@ var commands = exports.commands = {
},
accept: function (target, room, user, connection) {
- var userid = toId(target);
- var format = '';
+ let userid = toId(target);
+ let format = '';
if (user.challengesFrom[userid]) format = user.challengesFrom[userid].format;
if (!format) {
this.popupReply(target + " cancelled their challenge before you could accept it.");
@@ -2448,7 +2451,7 @@ var commands = exports.commands = {
connection.popup("Due to high load, you are limited to 6 team validations every 3 minutes.");
return;
}
- var format = Tools.getFormat(target);
+ let format = Tools.getFormat(target);
if (format.effectType !== 'Format') format = Tools.getFormat('Anything Goes');
if (format.effectType !== 'Format') {
connection.popup("Please provide a valid format.");
@@ -2470,10 +2473,10 @@ var commands = exports.commands = {
cmd: 'query',
query: function (target, room, user, connection) {
// Avoid guest users to use the cmd errors to ease the app-layer attacks in emergency mode
- var trustable = (!Config.emergency || (user.named && user.registered));
+ let trustable = (!Config.emergency || (user.named && user.registered));
if (Config.emergency && Monitor.countCmd(connection.ip, user.name)) return false;
- var spaceIndex = target.indexOf(' ');
- var cmd = target;
+ let spaceIndex = target.indexOf(' ');
+ let cmd = target;
if (spaceIndex > 0) {
cmd = target.substr(0, spaceIndex);
target = target.substr(spaceIndex + 1);
@@ -2481,7 +2484,7 @@ var commands = exports.commands = {
target = '';
}
if (cmd === 'userdetails') {
- var targetUser = Users.get(target);
+ let targetUser = Users.get(target);
if (!trustable || !targetUser) {
connection.send('|queryresponse|userdetails|' + JSON.stringify({
userid: toId(target),
@@ -2489,22 +2492,22 @@ var commands = exports.commands = {
}));
return false;
}
- var roomList = {};
- for (var i in targetUser.roomCount) {
+ let roomList = {};
+ for (let i in targetUser.roomCount) {
if (i === 'global') continue;
- var targetRoom = Rooms.get(i);
+ let targetRoom = Rooms.get(i);
if (!targetRoom) continue; // shouldn't happen
if (targetRoom.isPrivate && (!targetRoom.battle || targetRoom.battle.lastPlayers.indexOf(user.userid) < 0)) continue;
- var roomData = {};
+ let roomData = {};
if (targetRoom.battle) {
- var battle = targetRoom.battle;
+ let battle = targetRoom.battle;
roomData.p1 = battle.p1 ? ' ' + battle.p1 : '';
roomData.p2 = battle.p2 ? ' ' + battle.p2 : '';
}
roomList[i] = roomData;
}
if (!targetUser.roomCount['global']) roomList = false;
- var userdetails = {
+ let userdetails = {
userid: targetUser.userid,
avatar: targetUser.avatar,
rooms: roomList
@@ -2522,7 +2525,7 @@ var commands = exports.commands = {
));
} else if (cmd === 'laddertop') {
if (!trustable) return false;
- Ladders(target).getTop().then(function (result) {
+ Ladders.get(target).getTop().then(function (result) {
connection.send('|queryresponse|laddertop|' + JSON.stringify(result));
});
} else {
@@ -2533,10 +2536,10 @@ var commands = exports.commands = {
},
trn: function (target, room, user, connection) {
- var commaIndex = target.indexOf(',');
- var targetName = target;
- var targetRegistered = false;
- var targetToken = '';
+ let commaIndex = target.indexOf(',');
+ let targetName = target;
+ let targetRegistered = false;
+ let targetToken = '';
if (commaIndex >= 0) {
targetName = target.substr(0, commaIndex);
target = target.substr(commaIndex + 1);
@@ -2580,10 +2583,10 @@ var commands = exports.commands = {
this.sendReply("For an overview of room commands, use /roomhelp");
this.sendReply("For details of a specific command, use something like: /help data");
} else {
- var altCommandHelp;
- var helpCmd;
- var targets = target.split(' ');
- var allCommands = CommandParser.commands;
+ let altCommandHelp;
+ let helpCmd;
+ let targets = target.split(' ');
+ let allCommands = CommandParser.commands;
if (typeof allCommands[target] === 'string') {
// If a function changes with command name, help for that command name will be searched first.
altCommandHelp = target + 'help';
@@ -2594,9 +2597,9 @@ var commands = exports.commands = {
}
} else if (targets.length > 1 && typeof allCommands[targets[0]] === 'object') {
// Handle internal namespace commands
- var helpCmd = targets[targets.length - 1] + 'help';
- var namespace = allCommands[targets[0]];
- for (var i = 1; i < targets.length - 1; i++) {
+ let helpCmd = targets[targets.length - 1] + 'help';
+ let namespace = allCommands[targets[0]];
+ for (let i = 1; i < targets.length - 1; i++) {
if (!namespace[targets[i]]) return this.errorReply("Help for the command '" + target + "' was not found. Try /help for general help");
namespace = namespace[targets[i]];
}
diff --git a/config/config-example.js b/config/config-example.js
index e21f4c3044..cdbec3ddb8 100644
--- a/config/config-example.js
+++ b/config/config-example.js
@@ -1,3 +1,5 @@
+'use strict';
+
// The server port - the port to run Pokemon Showdown under
exports.port = 8000;
@@ -180,7 +182,7 @@ exports.appealurl = '';
// replsocketprefix - the prefix for the repl sockets to be listening on
// replsocketmode - the file mode bits to use for the repl sockets
exports.replsocketprefix = './logs/repl/';
-exports.replsocketmode = 0600;
+exports.replsocketmode = '0600';
// permissions and groups:
// Each entry in `grouplist' is a seperate group. Some of the members are "special"
diff --git a/config/formats.js b/config/formats.js
index f015eaca78..37c9f5b48c 100644
--- a/config/formats.js
+++ b/config/formats.js
@@ -1,3 +1,5 @@
+'use strict';
+
// Note: This is the list of formats
// The rules that formats use are stored in data/rulesets.js
@@ -40,10 +42,10 @@ exports.Formats = [
ruleset: ['OU'],
onBegin: function () {
- for (var i = 0; i < this.p1.pokemon.length; i++) {
+ for (let i = 0; i < this.p1.pokemon.length; i++) {
this.p1.pokemon[i].canMegaEvo = false;
}
- for (var i = 0; i < this.p2.pokemon.length; i++) {
+ for (let i = 0; i < this.p2.pokemon.length; i++) {
this.p2.pokemon[i].canMegaEvo = false;
}
}
@@ -425,15 +427,15 @@ exports.Formats = [
noChangeForme: true,
noChangeAbility: true,
abilityMap: (function () {
- var Pokedex = require('./../tools.js').data.Pokedex;
+ let Pokedex = require('./../tools.js').data.Pokedex;
if (!Pokedex) return null; // Process is data-unaware
- var abilityMap = Object.create(null);
- for (var speciesid in Pokedex) {
- var pokemon = Pokedex[speciesid];
+ let abilityMap = Object.create(null);
+ for (let speciesid in Pokedex) {
+ let pokemon = Pokedex[speciesid];
if (pokemon.num < 1 || pokemon.num > 720) continue;
- for (var key in pokemon.abilities) {
- var abilityId = toId(pokemon.abilities[key]);
+ for (let key in pokemon.abilities) {
+ let abilityId = toId(pokemon.abilities[key]);
if (abilityMap[abilityId]) {
abilityMap[abilityId].push(speciesid);
} else {
@@ -444,7 +446,7 @@ exports.Formats = [
return abilityMap;
})(),
getEvoFamily: function (species) {
- var template = Tools.getTemplate(species);
+ let template = Tools.getTemplate(species);
while (template.prevo) {
template = Tools.getTemplate(template.prevo);
}
@@ -452,18 +454,18 @@ exports.Formats = [
},
onValidateTeam: function (team, format, teamHas) {
// Donor Clause
- var evoFamilyLists = [];
- for (var i = 0; i < team.length; i++) {
- var set = team[i];
+ let evoFamilyLists = [];
+ for (let i = 0; i < team.length; i++) {
+ let set = team[i];
if (!set.abilitySources) continue;
evoFamilyLists.push(set.abilitySources.map(format.getEvoFamily).unique());
}
// Checking actual full incompatibility would require expensive algebra.
// Instead, we only check the trivial case of multiple Pokémon only legal for exactly one family. FIXME?
- var requiredFamilies = Object.create(null);
- for (var i = 0; i < evoFamilyLists.length; i++) {
- var evoFamilies = evoFamilyLists[i];
+ let requiredFamilies = Object.create(null);
+ for (let i = 0; i < evoFamilyLists.length; i++) {
+ let evoFamilies = evoFamilyLists[i];
if (evoFamilies.length !== 1) continue;
if (requiredFamilies[evoFamilies[0]]) return ["You are limited to one inheritance from each family by the Donor Clause.", "(You inherit more than once from " + this.getTemplate(evoFamilies[0]).species + "'s.)"];
requiredFamilies[evoFamilies[0]] = 1;
@@ -473,13 +475,13 @@ exports.Formats = [
if (!this.format.abilityMap) return this.validateSet(set, teamHas); // shouldn't happen
this.format.noChangeForme = false;
- var problems = this.tools.getFormat('Pokemon').onChangeSet.call(this.tools, set, this.format) || [];
+ let problems = this.tools.getFormat('Pokemon').onChangeSet.call(this.tools, set, this.format) || [];
this.format.noChangeForme = true;
if (problems.length) return problems;
- var species = toId(set.species);
- var template = this.tools.getTemplate(species);
+ let species = toId(set.species);
+ let template = this.tools.getTemplate(species);
if (!template.exists) return ["" + set.species + " is not a real Pok\u00E9mon."];
if (template.isUnreleased) return ["" + set.species + " is unreleased."];
if (template.speciesid in this.format.customBans.receiver) {
@@ -490,26 +492,26 @@ exports.Formats = [
}
}
- var name = set.name;
+ let name = set.name;
- var abilityId = toId(set.ability);
+ let abilityId = toId(set.ability);
if (!abilityId) return ["" + (set.name || set.species) + " must have an ability."];
- var pokemonWithAbility = this.format.abilityMap[abilityId];
+ let pokemonWithAbility = this.format.abilityMap[abilityId];
if (!pokemonWithAbility) return ["" + set.ability + " is an invalid ability."];
- var isBaseAbility = Object.values(template.abilities).map(toId).indexOf(abilityId) >= 0;
+ let isBaseAbility = Object.values(template.abilities).map(toId).indexOf(abilityId) >= 0;
// Items must be fully validated here since we may pass a different item to the base set validator.
- var item = this.tools.getItem(set.item);
+ let item = this.tools.getItem(set.item);
if (item.id) {
if (!item.exists) return ["" + set.item + " is an invalid item."];
if (item.isUnreleased) return ["" + (set.name || set.species) + "'s item " + item.name + " is unreleased."];
if (item.id in this.format.customBans.items) return ["" + item.name + " is banned."];
}
- var validSources = set.abilitySources = []; // evolutionary families
- for (var i = 0; i < pokemonWithAbility.length; i++) {
- var donorTemplate = this.tools.getTemplate(pokemonWithAbility[i]);
- var evoFamily = this.format.getEvoFamily(donorTemplate);
+ let validSources = set.abilitySources = []; // evolutionary families
+ for (let i = 0; i < pokemonWithAbility.length; i++) {
+ let donorTemplate = this.tools.getTemplate(pokemonWithAbility[i]);
+ let evoFamily = this.format.getEvoFamily(donorTemplate);
if (validSources.indexOf(evoFamily) >= 0) {
// The existence of a legal set has already been established.
@@ -720,11 +722,11 @@ exports.Formats = [
'Blazikenite', 'Gengarite', 'Kangaskhanite', 'Lucarionite', 'Mawilite', 'Salamencite', 'Soul Dew', 'Chatter'
],
onValidateSet: function (set) {
- var bannedAbilities = {'Aerilate': 1, 'Arena Trap': 1, 'Contrary': 1, 'Fur Coat': 1, 'Huge Power': 1, 'Imposter': 1, 'Parental Bond': 1, 'Protean': 1, 'Pure Power': 1, 'Shadow Tag': 1, 'Simple':1, 'Speed Boost': 1, 'Wonder Guard': 1};
+ let bannedAbilities = {'Aerilate': 1, 'Arena Trap': 1, 'Contrary': 1, 'Fur Coat': 1, 'Huge Power': 1, 'Imposter': 1, 'Parental Bond': 1, 'Protean': 1, 'Pure Power': 1, 'Shadow Tag': 1, 'Simple':1, 'Speed Boost': 1, 'Wonder Guard': 1};
if (set.ability in bannedAbilities) {
- var template = this.getTemplate(set.species || set.name);
- var legalAbility = false;
- for (var i in template.abilities) {
+ let template = this.getTemplate(set.species || set.name);
+ let legalAbility = false;
+ for (let i in template.abilities) {
if (set.ability === template.abilities[i]) legalAbility = true;
}
if (!legalAbility) return ['The ability ' + set.ability + ' is banned on Pok\u00e9mon that do not naturally have it.'];
@@ -743,16 +745,16 @@ exports.Formats = [
ruleset: ['OU'],
banlist: ['Diggersby', 'Keldeo', 'Porygon-Z', 'Sylveon', 'Aerodactylite', 'Altarianite', "King's Rock", 'Lopunnite', 'Metagrossite', 'Razor Fang'],
validateSet: function (set, teamHas) {
- var statusProblems = this.validateSet(set, teamHas, {ignorestabmoves: {'Status':1}});
+ let statusProblems = this.validateSet(set, teamHas, {ignorestabmoves: {'Status':1}});
if (!statusProblems.length) return;
- var attackProblems = this.validateSet(set, teamHas, {ignorestabmoves: {'Physical':1, 'Special':1}});
+ let attackProblems = this.validateSet(set, teamHas, {ignorestabmoves: {'Physical':1, 'Special':1}});
if (!attackProblems.length) return;
- var problems = [];
- for (var i = 0; i < statusProblems.length; i++) {
+ let problems = [];
+ for (let i = 0; i < statusProblems.length; i++) {
problems.push('(Status) ' + statusProblems[i]);
}
- for (var i = 0; i < attackProblems.length; i++) {
+ for (let i = 0; i < attackProblems.length; i++) {
problems.push('(Attack) ' + attackProblems[i]);
}
return problems;
diff --git a/data/abilities.js b/data/abilities.js
index 67d63f42a2..4e305f5b95 100644
--- a/data/abilities.js
+++ b/data/abilities.js
@@ -1573,27 +1573,25 @@ exports.BattleAbilities = {
onResidualOrder: 26,
onResidualSubOrder: 1,
onResidual: function (pokemon) {
- var stats = [], i = '';
+ var stats = [];
var boost = {};
- for (var i in pokemon.boosts) {
- if (pokemon.boosts[i] < 6) {
- stats.push(i);
+ for (var statPlus in pokemon.boosts) {
+ if (pokemon.boosts[statPlus] < 6) {
+ stats.push(statPlus);
}
}
- if (stats.length) {
- i = stats[this.random(stats.length)];
- boost[i] = 2;
- }
+ var randomStat = stats.length ? stats[this.random(stats.length)] : "";
+ if (randomStat) boost[randomStat] = 2;
+
stats = [];
- for (var j in pokemon.boosts) {
- if (pokemon.boosts[j] > -6 && j !== i) {
- stats.push(j);
+ for (var statMinus in pokemon.boosts) {
+ if (pokemon.boosts[statMinus] > -6 && statMinus !== randomStat) {
+ stats.push(statMinus);
}
}
- if (stats.length) {
- i = stats[this.random(stats.length)];
- boost[i] = -1;
- }
+ randomStat = stats.length ? stats[this.random(stats.length)] : "";
+ if (randomStat) boost[randomStat] = -1;
+
this.boost(boost);
},
id: "moody",
@@ -1819,23 +1817,17 @@ exports.BattleAbilities = {
onResidual: function (pokemon) {
if (pokemon.item) return;
var pickupTargets = [];
- var target;
- for (var i = 0; i < pokemon.side.active.length; i++) {
- target = pokemon.side.active[i];
- if (target.lastItem && target.usedItemThisTurn && this.isAdjacent(pokemon, target)) {
- pickupTargets.push(target);
- }
- }
- for (var i = 0; i < pokemon.side.foe.active.length; i++) {
- target = pokemon.side.foe.active[i];
+ var allActives = pokemon.side.active.concat(pokemon.side.foe.active);
+ for (var i = 0; i < allActives.length; i++) {
+ var target = allActives[i];
if (target.lastItem && target.usedItemThisTurn && this.isAdjacent(pokemon, target)) {
pickupTargets.push(target);
}
}
if (!pickupTargets.length) return;
- target = pickupTargets[this.random(pickupTargets.length)];
- pokemon.setItem(target.lastItem);
- target.lastItem = '';
+ var randomTarget = pickupTargets[this.random(pickupTargets.length)];
+ pokemon.setItem(randomTarget.lastItem);
+ randomTarget.lastItem = '';
var item = pokemon.getItem();
this.add('-item', pokemon, item, '[from] Pickup');
if (item.isBerry) pokemon.update();
diff --git a/data/items.js b/data/items.js
index bf22354ac4..f7d040bdf5 100644
--- a/data/items.js
+++ b/data/items.js
@@ -2322,9 +2322,9 @@ exports.BattleItems = {
pokemon.removeVolatile('leppaberry');
} else {
var pp = 99;
- for (var i in pokemon.moveset) {
- if (pokemon.moveset[i].pp < pp) {
- move = pokemon.moveset[i];
+ for (var moveid in pokemon.moveset) {
+ if (pokemon.moveset[moveid].pp < pp) {
+ move = pokemon.moveset[moveid];
pp = move.pp;
}
}
@@ -4329,15 +4329,15 @@ exports.BattleItems = {
},
onEat: function (pokemon) {
var stats = [];
- for (var i in pokemon.boosts) {
- if (i !== 'accuracy' && i !== 'evasion' && pokemon.boosts[i] < 6) {
- stats.push(i);
+ for (var stat in pokemon.boosts) {
+ if (stat !== 'accuracy' && stat !== 'evasion' && pokemon.boosts[stat] < 6) {
+ stats.push(stat);
}
}
if (stats.length) {
- var i = stats[this.random(stats.length)];
+ var randomStat = stats[this.random(stats.length)];
var boost = {};
- boost[i] = 2;
+ boost[randomStat] = 2;
this.boost(boost);
}
},
diff --git a/data/moves.js b/data/moves.js
index da6806258d..0a88ffb24a 100644
--- a/data/moves.js
+++ b/data/moves.js
@@ -142,15 +142,15 @@ exports.BattleMovedex = {
flags: {},
onHit: function (target) {
var stats = [];
- for (var i in target.boosts) {
- if (target.boosts[i] < 6) {
- stats.push(i);
+ for (var stat in target.boosts) {
+ if (target.boosts[stat] < 6) {
+ stats.push(stat);
}
}
if (stats.length) {
- var i = stats[this.random(stats.length)];
+ var randomStat = stats[this.random(stats.length)];
var boost = {};
- boost[i] = 2;
+ boost[randomStat] = 2;
this.boost(boost);
} else {
return false;
@@ -502,12 +502,12 @@ exports.BattleMovedex = {
}
}
}
- var move = '';
- if (moves.length) move = moves[this.random(moves.length)];
- if (!move) {
+ var randomMove = '';
+ if (moves.length) randomMove = moves[this.random(moves.length)];
+ if (!randomMove) {
return false;
}
- this.useMove(move, target);
+ this.useMove(randomMove, target);
},
secondary: false,
target: "self",
@@ -1991,10 +1991,10 @@ exports.BattleMovedex = {
if (!possibleTypes.length) {
return false;
}
- var type = possibleTypes[this.random(possibleTypes.length)];
+ var randomType = possibleTypes[this.random(possibleTypes.length)];
- if (!source.setType(type)) return false;
- this.add('-start', source, 'typechange', type);
+ if (!source.setType(randomType)) return false;
+ this.add('-start', source, 'typechange', randomType);
},
secondary: false,
target: "normal",
@@ -2485,16 +2485,17 @@ exports.BattleMovedex = {
flags: {protect: 1, reflectable: 1, mirror: 1, authentic: 1},
onHit: function (target, source, move) {
if (!target.volatiles['substitute'] || move.infiltrates) this.boost({evasion:-1});
- var sideConditions = {reflect:1, lightscreen:1, safeguard:1, mist:1, spikes:1, toxicspikes:1, stealthrock:1, stickyweb:1};
- var sideEnd = {spikes:1, toxicspikes:1, stealthrock:1, stickyweb:1};
- for (var i in sideConditions) {
- if (target.side.removeSideCondition(i)) {
- if (sideEnd[i]) this.add('-sideend', target.side, this.getEffect(i).name, '[from] move: Defog', '[of] ' + target);
+ var removeTarget = {reflect:1, lightscreen:1, safeguard:1, mist:1, spikes:1, toxicspikes:1, stealthrock:1, stickyweb:1};
+ var removeAll = {spikes:1, toxicspikes:1, stealthrock:1, stickyweb:1};
+ for (var targetCondition in removeTarget) {
+ if (target.side.removeSideCondition(targetCondition)) {
+ if (!removeAll[targetCondition]) continue;
+ this.add('-sideend', target.side, this.getEffect(targetCondition).name, '[from] move: Defog', '[of] ' + target);
}
}
- for (var i in sideEnd) {
- if (source.side.removeSideCondition(i)) {
- this.add('-sideend', source.side, this.getEffect(i).name, '[from] move: Defog', '[of] ' + source);
+ for (var sideCondition in removeAll) {
+ if (source.side.removeSideCondition(sideCondition)) {
+ this.add('-sideend', source.side, this.getEffect(sideCondition).name, '[from] move: Defog', '[of] ' + source);
}
}
},
@@ -4464,16 +4465,19 @@ exports.BattleMovedex = {
flags: {distance: 1},
onHitField: function (target, source) {
var targets = [];
- for (var i = 0; i < this.sides.length; i++) {
- for (var j = 0; j < this.sides[i].active.length; j++) {
- if (this.sides[i].active[j] && this.sides[i].active[j].hasType('Grass')) {
+ for (var sideSlot = 0; sideSlot < this.sides.length; sideSlot++) {
+ var sideActive = this.sides[sideSlot].active;
+ for (var activeSlot = 0; activeSlot < sideActive.length; activeSlot++) {
+ if (sideActive[activeSlot] && sideActive[activeSlot].hasType('Grass')) {
// This move affects every Grass-type Pokemon in play.
- targets.push(this.sides[i].active[j]);
+ targets.push(sideActive[activeSlot]);
}
}
}
if (!targets.length) return false; // No targets; move fails
- for (var i = 0; i < targets.length; i++) this.boost({def: 1}, targets[i], source, this.getMove('Flower Shield'));
+ for (var i = 0; i < targets.length; i++) {
+ this.boost({def: 1}, targets[i], source, this.getMove('Flower Shield'));
+ }
},
secondary: false,
target: "all",
@@ -8451,15 +8455,15 @@ exports.BattleMovedex = {
moves.push(move);
}
}
- var move = '';
+ var randomMove = '';
if (moves.length) {
moves.sort(function (a, b) {return a.num - b.num;});
- move = moves[this.random(moves.length)].id;
+ randomMove = moves[this.random(moves.length)].id;
}
- if (!move) {
+ if (!randomMove) {
return false;
}
- this.useMove(move, target);
+ this.useMove(randomMove, target);
},
secondary: false,
target: "self",
@@ -11390,18 +11394,18 @@ exports.BattleMovedex = {
onHitField: function (target, source) {
var targets = [];
var anyAirborne = false;
- for (var i = 0; i < this.sides.length; i++) {
- for (var j = 0; j < this.sides[i].active.length; j++) {
- if (this.sides[i].active[j]) {
- if (!this.sides[i].active[j].runImmunity('Ground')) {
- this.add('-immune', this.sides[i].active[j], '[msg]');
- anyAirborne = true;
- continue;
- }
- if (this.sides[i].active[j].hasType('Grass')) {
- // This move affects every grounded Grass-type Pokemon in play.
- targets.push(this.sides[i].active[j]);
- }
+ for (var sideSlot = 0; sideSlot < this.sides.length; sideSlot++) {
+ var sideActive = this.sides[sideSlot].active;
+ for (var activeSlot = 0; activeSlot < sideActive.length; activeSlot++) {
+ if (!sideActive[activeSlot]) continue;
+ if (!sideActive[activeSlot].runImmunity('Ground')) {
+ this.add('-immune', sideActive[activeSlot], '[msg]');
+ anyAirborne = true;
+ continue;
+ }
+ if (sideActive[activeSlot].hasType('Grass')) {
+ // This move affects every grounded Grass-type Pokemon in play.
+ targets.push(sideActive[activeSlot]);
}
}
}
@@ -12483,12 +12487,12 @@ exports.BattleMovedex = {
moves.push(move);
}
}
- var move = '';
- if (moves.length) move = moves[this.random(moves.length)];
- if (!move) {
+ var randomMove = '';
+ if (moves.length) randomMove = moves[this.random(moves.length)];
+ if (!randomMove) {
return false;
}
- this.useMove(move, pokemon);
+ this.useMove(randomMove, pokemon);
},
secondary: false,
target: "self",
diff --git a/data/rulesets.js b/data/rulesets.js
index 4e09554294..9614c5ea9a 100644
--- a/data/rulesets.js
+++ b/data/rulesets.js
@@ -1,6 +1,8 @@
// Note: These are the rules that formats use
// The list of formats is stored in config/formats.js
+'use strict';
+
exports.BattleFormats = {
// Rulesets
@@ -65,12 +67,12 @@ exports.BattleFormats = {
pokemon: {
effectType: 'Banlist',
onValidateTeam: function (team, format) {
- var problems = [];
+ let problems = [];
// ----------- legality line ------------------------------------------
if (!format || !format.banlistTable || !format.banlistTable['illegal']) return problems;
// everything after this line only happens if we're doing legality enforcement
- var kyurems = 0;
- for (var i = 0; i < team.length; i++) {
+ let kyurems = 0;
+ for (let i = 0; i < team.length; i++) {
if (team[i].species === 'Kyurem-White' || team[i].species === 'Kyurem-Black') {
if (kyurems > 0) {
problems.push('You cannot have more than one Kyurem-Black/Kyurem-White.');
@@ -82,17 +84,17 @@ exports.BattleFormats = {
return problems;
},
onChangeSet: function (set, format) {
- var item = this.getItem(set.item);
- var template = this.getTemplate(set.species);
- var problems = [];
- var totalEV = 0;
- var allowCAP = !!(format && format.banlistTable && format.banlistTable['allowcap']);
+ let item = this.getItem(set.item);
+ let template = this.getTemplate(set.species);
+ let problems = [];
+ let totalEV = 0;
+ let allowCAP = !!(format && format.banlistTable && format.banlistTable['allowcap']);
if (set.species === set.name) delete set.name;
if (template.gen > this.gen) {
problems.push(set.species + ' does not exist in gen ' + this.gen + '.');
}
- var ability = {};
+ let ability = {};
if (set.ability) {
ability = this.getAbility(set.ability);
if (ability.gen > this.gen) {
@@ -100,8 +102,8 @@ exports.BattleFormats = {
}
}
if (set.moves) {
- for (var i = 0; i < set.moves.length; i++) {
- var move = this.getMove(set.moves[i]);
+ for (let i = 0; i < set.moves.length; i++) {
+ let move = this.getMove(set.moves[i]);
if (move.gen > this.gen) {
problems.push(move.name + ' does not exist in gen ' + this.gen + '.');
} else if (!allowCAP && move.isNonstandard) {
@@ -130,7 +132,7 @@ exports.BattleFormats = {
problems.push(item.name + ' is not a real item.');
}
}
- for (var k in set.evs) {
+ for (let k in set.evs) {
if (typeof set.evs[k] !== 'number' || set.evs[k] < 0) {
set.evs[k] = 0;
}
@@ -153,20 +155,20 @@ exports.BattleFormats = {
// "Undiscovered" egg group Pokemon caught in the wild in gen 6 must have at least 3 perfect IVs
if (set.ivs && this.gen >= 6 && ((template.species in {Xerneas:1, Yveltal:1, Zygarde:1}) ||
(format.requirePentagon && template.eggGroups.indexOf('Undiscovered') >= 0 && !template.evos.length))) {
- var perfectIVs = 0;
- for (var i in set.ivs) {
+ let perfectIVs = 0;
+ for (let i in set.ivs) {
if (set.ivs[i] >= 31) perfectIVs++;
}
if (perfectIVs < 3) problems.push((set.name || set.species) + " has less than three perfect IVs.");
}
// limit one of each move
- var moves = [];
+ let moves = [];
if (set.moves) {
- var hasMove = {};
- for (var i = 0; i < set.moves.length; i++) {
- var move = this.getMove(set.moves[i]);
- var moveid = move.id;
+ let hasMove = {};
+ for (let i = 0; i < set.moves.length; i++) {
+ let move = this.getMove(set.moves[i]);
+ let moveid = move.id;
if (hasMove[moveid]) continue;
hasMove[moveid] = true;
moves.push(set.moves[i]);
@@ -174,7 +176,7 @@ exports.BattleFormats = {
}
set.moves = moves;
- var battleForme = template.battleOnly && template.species;
+ let battleForme = template.battleOnly && template.species;
if (battleForme) {
if (template.requiredAbility && set.ability !== template.requiredAbility) {
problems.push("" + template.species + " transforms in-battle with " + template.requiredAbility + "."); // Darmanitan-Zen
@@ -210,8 +212,8 @@ exports.BattleFormats = {
if (!format.banlistTable['ignoreillegalabilities'] && !format.noChangeAbility) {
// Ensure that the ability is (still) legal.
- var legalAbility = false;
- for (var i in template.abilities) {
+ let legalAbility = false;
+ for (let i in template.abilities) {
if (template.abilities[i] !== set.ability) continue;
legalAbility = true;
break;
@@ -232,7 +234,7 @@ exports.BattleFormats = {
kalospokedex: {
effectType: 'Rule',
onValidateSet: function (set) {
- var validKalosDex = {
+ let validKalosDex = {
"Abomasnow":1, "Abomasnow-Mega":1, "Abra":1, "Absol":1, "Absol-Mega":1, "Accelgor":1, "Aegislash":1, "Aegislash-Blade":1, "Aerodactyl":1, "Aerodactyl-Mega":1, "Aggron":1, "Aggron-Mega":1, "Alakazam":1, "Alakazam-Mega":1, "Alomomola":1, "Altaria":1, "Amaura":1, "Amoonguss":1, "Ampharos":1, "Ampharos-Mega":1, "Arbok":1, "Ariados":1, "Aromatisse":1, "Aron":1, "Articuno":1, "Audino":1, "Aurorus":1, "Avalugg":1, "Axew":1, "Azumarill":1, "Azurill":1, "Bagon":1, "Banette":1, "Banette-Mega":1, "Barbaracle":1, "Barboach":1, "Basculin":1, "Basculin-Blue-Striped":1, "Beartic":1, "Beedrill":1, "Bellossom":1, "Bellsprout":1, "Bergmite":1, "Bibarel":1, "Bidoof":1, "Binacle":1, "Bisharp":1, "Blastoise":1, "Blastoise-Mega":1, "Boldore":1, "Bonsly":1, "Braixen":1, "Budew":1, "Buizel":1, "Bulbasaur":1, "Bunnelby":1, "Burmy":1, "Butterfree":1, "Carbink":1, "Carnivine":1, "Carvanha":1, "Caterpie":1, "Chandelure":1, "Charizard":1, "Charizard-Mega-X":1, "Charizard-Mega-Y":1, "Charmander":1, "Charmeleon":1, "Chatot":1, "Chesnaught":1, "Chespin":1, "Chimecho":1, "Chinchou":1, "Chingling":1, "Clamperl":1, "Clauncher":1, "Clawitzer":1, "Cloyster":1, "Combee":1, "Conkeldurr":1, "Corphish":1, "Corsola":1, "Crawdaunt":1, "Croagunk":1, "Crobat":1, "Crustle":1, "Cryogonal":1, "Cubchoo":1, "Cubone":1, "Dedenne":1, "Deino":1, "Delcatty":1, "Delibird":1, "Delphox":1, "Diggersby":1, "Diglett":1, "Ditto":1, "Dodrio":1, "Doduo":1, "Doublade":1, "Dragalge":1, "Dragonair":1, "Dragonite":1, "Drapion":1, "Dratini":1, "Drifblim":1, "Drifloon":1, "Druddigon":1, "Ducklett":1, "Dugtrio":1, "Dunsparce":1, "Duosion":1, "Durant":1, "Dwebble":1, "Eevee":1, "Ekans":1, "Electrike":1, "Electrode":1, "Emolga":1, "Escavalier":1, "Espeon":1, "Espurr":1, "Exeggcute":1, "Exeggutor":1, "Exploud":1, "Farfetch'd":1, "Fearow":1, "Fennekin":1, "Ferroseed":1, "Ferrothorn":1, "Flaaffy":1, "Flabebe":1, "Flareon":1, "Fletchinder":1, "Fletchling":1, "Floatzel":1, "Floette":1, "Florges":1, "Flygon":1, "Foongus":1, "Fraxure":1, "Froakie":1, "Frogadier":1, "Furfrou":1, "Furret":1, "Gabite":1, "Gallade":1, "Garbodor":1, "Garchomp":1, "Garchomp-Mega":1, "Gardevoir":1, "Gardevoir-Mega":1, "Gastly":1, "Gengar":1, "Gengar-Mega":1, "Geodude":1, "Gible":1, "Gigalith":1, "Glaceon":1, "Gligar":1, "Gliscor":1, "Gloom":1, "Gogoat":1, "Golbat":1, "Goldeen":1, "Golduck":1, "Golem":1, "Golett":1, "Golurk":1, "Goodra":1, "Goomy":1, "Gorebyss":1, "Gothita":1, "Gothitelle":1, "Gothorita":1, "Gourgeist-Small":1, "Gourgeist":1, "Gourgeist-Large":1, "Gourgeist-Super":1, "Granbull":1, "Graveler":1, "Greninja":1, "Grumpig":1, "Gulpin":1, "Gurdurr":1, "Gyarados":1, "Gyarados-Mega":1, "Hariyama":1, "Haunter":1, "Hawlucha":1, "Haxorus":1, "Heatmor":1, "Heliolisk":1, "Helioptile":1, "Heracross":1, "Heracross-Mega":1, "Hippopotas":1, "Hippowdon":1, "Honchkrow":1, "Honedge":1, "Hoothoot":1, "Hoppip":1, "Horsea":1, "Houndoom":1, "Houndoom-Mega":1, "Houndour":1, "Huntail":1, "Hydreigon":1, "Igglybuff":1, "Illumise":1, "Inkay":1, "Ivysaur":1, "Jigglypuff":1, "Jolteon":1, "Jumpluff":1, "Jynx":1, "Kadabra":1, "Kakuna":1, "Kangaskhan":1, "Kangaskhan-Mega":1, "Karrablast":1, "Kecleon":1, "Kingdra":1, "Kirlia":1, "Klefki":1, "Krokorok":1, "Krookodile":1, "Lairon":1, "Lampent":1, "Lanturn":1, "Lapras":1, "Larvitar":1, "Leafeon":1, "Ledian":1, "Ledyba":1, "Lickilicky":1, "Lickitung":1, "Liepard":1, "Linoone":1, "Litleo":1, "Litwick":1, "Lombre":1, "Lotad":1, "Loudred":1, "Lucario":1, "Lucario-Mega":1, "Ludicolo":1, "Lunatone":1, "Luvdisc":1, "Machamp":1, "Machoke":1, "Machop":1, "Magcargo":1, "Magikarp":1, "Magnemite":1, "Magneton":1, "Magnezone":1, "Makuhita":1, "Malamar":1, "Mamoswine":1, "Manectric":1, "Manectric-Mega":1, "Mantine":1, "Mantyke":1, "Mareep":1, "Marill":1, "Marowak":1, "Masquerain":1, "Mawile":1, "Mawile-Mega":1, "Medicham":1, "Medicham-Mega":1, "Meditite":1, "Meowstic":1, "Meowstic-F":1, "Metapod":1, "Mewtwo":1, "Mewtwo-Mega-X":1, "Mewtwo-Mega-Y":1, "Mienfoo":1, "Mienshao":1, "Mightyena":1, "Miltank":1, "Mime Jr.":1, "Minun":1, "Moltres":1, "Mothim":1, "Mr. Mime":1, "Munchlax":1, "Murkrow":1, "Nidoking":1, "Nidoqueen":1, "Nidoran-M":1, "Nidoran-F":1, "Nidorina":1, "Nidorino":1, "Nincada":1, "Ninjask":1, "Noctowl":1, "Noibat":1, "Noivern":1, "Nosepass":1, "Octillery":1, "Oddish":1, "Onix":1, "Pachirisu":1, "Pancham":1, "Pangoro":1, "Panpour":1, "Pansage":1, "Pansear":1, "Patrat":1, "Pawniard":1, "Pelipper":1, "Phantump":1, "Pichu":1, "Pidgeot":1, "Pidgeotto":1, "Pidgey":1, "Pikachu":1, "Piloswine":1, "Pinsir":1, "Pinsir-Mega":1, "Plusle":1, "Politoed":1, "Poliwag":1, "Poliwhirl":1, "Poliwrath":1, "Poochyena":1, "Probopass":1, "Psyduck":1, "Pumpkaboo-Small":1, "Pumpkaboo":1, "Pumpkaboo-Large":1, "Pumpkaboo-Super":1, "Pupitar":1, "Purrloin":1, "Pyroar":1, "Quagsire":1, "Quilladin":1, "Qwilfish":1, "Raichu":1, "Ralts":1, "Relicanth":1, "Remoraid":1, "Reuniclus":1, "Rhydon":1, "Rhyhorn":1, "Rhyperior":1, "Riolu":1, "Roggenrola":1, "Roselia":1, "Roserade":1, "Rotom":1, "Rotom-Heat":1, "Rotom-Wash":1, "Rotom-Frost":1, "Rotom-Fan":1, "Rotom-Mow":1, "Sableye":1, "Salamence":1, "Sandile":1, "Sandshrew":1, "Sandslash":1, "Sawk":1, "Scatterbug":1, "Scizor":1, "Scizor-Mega":1, "Scolipede":1, "Scrafty":1, "Scraggy":1, "Scyther":1, "Seadra":1, "Seaking":1, "Sentret":1, "Seviper":1, "Sharpedo":1, "Shedinja":1, "Shelgon":1, "Shellder":1, "Shelmet":1, "Shuckle":1, "Shuppet":1, "Sigilyph":1, "Simipour":1, "Simisage":1, "Simisear":1, "Skarmory":1, "Skiddo":1, "Skiploom":1, "Skitty":1, "Skorupi":1, "Skrelp":1, "Skuntank":1, "Sliggoo":1, "Slowbro":1, "Slowking":1, "Slowpoke":1, "Slugma":1, "Slurpuff":1, "Smeargle":1, "Smoochum":1, "Sneasel":1, "Snorlax":1, "Snover":1, "Snubbull":1, "Solosis":1, "Solrock":1, "Spearow":1, "Spewpa":1, "Spinarak":1, "Spinda":1, "Spoink":1, "Spritzee":1, "Squirtle":1, "Staraptor":1, "Staravia":1, "Starly":1, "Starmie":1, "Staryu":1, "Steelix":1, "Stunfisk":1, "Stunky":1, "Sudowoodo":1, "Surskit":1, "Swablu":1, "Swalot":1, "Swanna":1, "Swellow":1, "Swinub":1, "Swirlix":1, "Swoobat":1, "Sylveon":1, "Taillow":1, "Talonflame":1, "Tauros":1, "Teddiursa":1, "Tentacool":1, "Tentacruel":1, "Throh":1, "Timburr":1, "Torkoal":1, "Toxicroak":1, "Trapinch":1, "Trevenant":1, "Trubbish":1, "Tyranitar":1, "Tyranitar-Mega":1, "Tyrantrum":1, "Tyrunt":1, "Umbreon":1, "Ursaring":1, "Vanillish":1, "Vanillite":1, "Vanilluxe":1, "Vaporeon":1, "Venipede":1, "Venusaur":1, "Venusaur-Mega":1, "Vespiquen":1, "Vibrava":1, "Victreebel":1, "Vileplume":1, "Vivillon":1, "Volbeat":1, "Voltorb":1, "Wailmer":1, "Wailord":1, "Wartortle":1, "Watchog":1, "Weavile":1, "Weedle":1, "Weepinbell":1, "Whirlipede":1, "Whiscash":1, "Whismur":1, "Wigglytuff":1, "Wingull":1, "Wobbuffet":1, "Woobat":1, "Wooper":1, "Wormadam":1, "Wormadam-Sandy":1, "Wormadam-Trash":1, "Wynaut":1, "Xerneas":1, "Yanma":1, "Yanmega":1, "Yveltal":1, "Zangoose":1, "Zapdos":1, "Zigzagoon":1, "Zoroark":1, "Zorua":1, "Zubat":1, "Zweilous":1, "Zygarde":1
};
if (!(set.species in validKalosDex)) {
@@ -243,7 +245,7 @@ exports.BattleFormats = {
hoennpokedex: {
effectType: 'Rule',
onValidateSet: function (set) {
- var hoennDex = {
+ let hoennDex = {
"Abra":1, "Absol":1, "Aggron":1, "Alakazam":1, "Altaria":1, "Anorith":1, "Armaldo":1, "Aron":1, "Azumarill":1, "Azurill":1, "Bagon":1, "Baltoy":1, "Banette":1, "Barboach":1, "Beautifly":1, "Beldum":1, "Bellossom":1, "Blaziken":1, "Breloom":1, "Budew":1, "Cacnea":1, "Cacturne":1, "Camerupt":1, "Carvanha":1, "Cascoon":1, "Castform":1, "Chimecho":1, "Chinchou":1, "Chingling":1, "Clamperl":1, "Claydol":1, "Combusken":1, "Corphish":1, "Corsola":1, "Cradily":1, "Crawdaunt":1, "Crobat":1, "Delcatty":1, "Dodrio":1, "Doduo":1, "Donphan":1, "Dusclops":1, "Dusknoir":1, "Duskull":1, "Dustox":1, "Electrike":1, "Electrode":1, "Exploud":1, "Feebas":1, "Flygon":1, "Froslass":1, "Gallade":1, "Gardevoir":1, "Geodude":1, "Girafarig":1, "Glalie":1, "Gloom":1, "Golbat":1, "Goldeen":1, "Golduck":1, "Golem":1, "Gorebyss":1, "Graveler":1, "Grimer":1, "Grovyle":1, "Grumpig":1, "Gulpin":1, "Gyarados":1, "Hariyama":1, "Heracross":1, "Horsea":1, "Huntail":1, "Igglybuff":1, "Illumise":1, "Jigglypuff":1, "Kadabra":1, "Kecleon":1, "Kingdra":1, "Kirlia":1, "Koffing":1, "Lairon":1, "Lanturn":1, "Latias":1, "Latios":1, "Lileep":1, "Linoone":1, "Lombre":1, "Lotad":1, "Loudred":1, "Ludicolo":1, "Lunatone":1, "Luvdisc":1, "Machamp":1, "Machoke":1, "Machop":1, "Magcargo":1, "Magikarp":1, "Magnemite":1, "Magneton":1, "Magnezone":1, "Makuhita":1, "Manectric":1, "Marill":1, "Marshtomp":1, "Masquerain":1, "Mawile":1, "Medicham":1, "Meditite":1, "Metagross":1, "Metang":1, "Mightyena":1, "Milotic":1, "Minun":1, "Mudkip":1, "Muk":1, "Natu":1, "Ninetales":1, "Ninjask":1, "Nosepass":1, "Numel":1, "Nuzleaf":1, "Oddish":1, "Pelipper":1, "Phanpy":1, "Pichu":1, "Pikachu":1, "Pikachu-Belle":1, "Pikachu-Cosplay":1, "Pikachu-Libre":1, "Pikachu-PhD":1, "Pikachu-Pop-Star":1, "Pikachu-Rock-Star":1, "Pinsir":1, "Plusle":1, "Poochyena":1, "Probopass":1, "Psyduck":1, "Raichu":1, "Ralts":1, "Regice":1, "Regirock":1, "Registeel":1, "Relicanth":1, "Rhydon":1, "Rhyhorn":1, "Rhyperior":1, "Roselia":1, "Roserade":1, "Sableye":1, "Salamence":1, "Sandshrew":1, "Sandslash":1, "Sceptile":1, "Seadra":1, "Seaking":1, "Sealeo":1, "Seedot":1, "Seviper":1, "Sharpedo":1, "Shedinja":1, "Shelgon":1, "Shiftry":1, "Shroomish":1, "Shuppet":1, "Silcoon":1, "Skarmory":1, "Skitty":1, "Slaking":1, "Slakoth":1, "Slugma":1, "Snorunt":1, "Solrock":1, "Spheal":1, "Spinda":1, "Spoink":1, "Starmie":1, "Staryu":1, "Surskit":1, "Swablu":1, "Swalot":1, "Swampert":1, "Swellow":1, "Taillow":1, "Tentacool":1, "Tentacruel":1, "Torchic":1, "Torkoal":1, "Trapinch":1, "Treecko":1, "Tropius":1, "Vibrava":1, "Vigoroth":1, "Vileplume":1, "Volbeat":1, "Voltorb":1, "Vulpix":1, "Wailmer":1, "Wailord":1, "Walrein":1, "Weezing":1, "Whiscash":1, "Whismur":1, "Wigglytuff":1, "Wingull":1, "Wobbuffet":1, "Wurmple":1, "Wynaut":1, "Xatu":1, "Zangoose":1, "Zigzagoon":1, "Zubat":1
};
if (!(set.species in hoennDex)) {
@@ -264,22 +266,22 @@ exports.BattleFormats = {
onStartPriority: -10,
onStart: function () {
this.add('clearpoke');
- for (var i = 0; i < this.sides[0].pokemon.length; i++) {
+ for (let i = 0; i < this.sides[0].pokemon.length; i++) {
this.add('poke', this.sides[0].pokemon[i].side.id, this.sides[0].pokemon[i].details.replace(/(Arceus|Gourgeist|Genesect|Pumpkaboo)(-[a-zA-Z?]+)?/g, '$1-*'));
}
- for (var i = 0; i < this.sides[1].pokemon.length; i++) {
+ for (let i = 0; i < this.sides[1].pokemon.length; i++) {
this.add('poke', this.sides[1].pokemon[i].side.id, this.sides[1].pokemon[i].details.replace(/(Arceus|Gourgeist|Genesect|Pumpkaboo)(-[a-zA-Z?]+)?/g, '$1-*'));
}
},
onTeamPreview: function () {
- var lengthData = this.getFormat().teamLength;
+ let lengthData = this.getFormat().teamLength;
this.makeRequest('teampreview', lengthData && lengthData.battle || '');
}
},
littlecup: {
effectType: 'Rule',
onValidateSet: function (set) {
- var template = this.getTemplate(set.species || set.name);
+ let template = this.getTemplate(set.species || set.name);
if (template.prevo) {
return [set.species + " isn't the first in its evolution family."];
}
@@ -294,9 +296,9 @@ exports.BattleFormats = {
this.add('rule', 'Species Clause: Limit one of each Pokémon');
},
onValidateTeam: function (team, format) {
- var speciesTable = {};
- for (var i = 0; i < team.length; i++) {
- var template = this.getTemplate(team[i].species);
+ let speciesTable = {};
+ for (let i = 0; i < team.length; i++) {
+ let template = this.getTemplate(team[i].species);
if (speciesTable[template.num]) {
return ["You are limited to one of each Pokémon by Species Clause.", "(You have more than one " + template.baseSpecies + ")"];
}
@@ -307,9 +309,9 @@ exports.BattleFormats = {
nicknameclause: {
effectType: 'Rule',
onValidateTeam: function (team, format) {
- var nameTable = {};
- for (var i = 0; i < team.length; i++) {
- var name = team[i].name;
+ let nameTable = {};
+ for (let i = 0; i < team.length; i++) {
+ let name = team[i].name;
if (name) {
if (name === team[i].species) continue;
if (nameTable[name]) {
@@ -328,9 +330,9 @@ exports.BattleFormats = {
this.add('rule', 'Item Clause: Limit one of each item');
},
onValidateTeam: function (team, format) {
- var itemTable = {};
- for (var i = 0; i < team.length; i++) {
- var item = toId(team[i].item);
+ let itemTable = {};
+ for (let i = 0; i < team.length; i++) {
+ let item = toId(team[i].item);
if (!item) continue;
if (itemTable[item]) {
return ["You are limited to one of each item by Item Clause.", "(You have more than one " + this.getItem(item).name + ")"];
@@ -345,9 +347,9 @@ exports.BattleFormats = {
this.add('rule', 'Ability Clause: Limit two of each ability');
},
onValidateTeam: function (team, format) {
- var abilityTable = {};
- for (var i = 0; i < team.length; i++) {
- var ability = toId(team[i].ability);
+ let abilityTable = {};
+ for (let i = 0; i < team.length; i++) {
+ let ability = toId(team[i].ability);
if (!ability) continue;
if (ability in abilityTable) {
if (abilityTable[ability] >= 2) {
@@ -366,9 +368,9 @@ exports.BattleFormats = {
this.add('rule', '-ate Clause: Limit one of Aerilate/Refrigerate/Pixilate');
},
onValidateTeam: function (team, format) {
- var ateAbility = false;
- for (var i = 0; i < team.length; i++) {
- var ability = toId(team[i].ability);
+ let ateAbility = false;
+ for (let i = 0; i < team.length; i++) {
+ let ability = toId(team[i].ability);
if (ability === 'refrigerate' || ability === 'pixilate' || ability === 'aerilate') {
if (ateAbility) return [team[i].name + " has more than one of Aerilate/Refrigerate/Pixilate, which is banned by -ate Clause."];
ateAbility = true;
@@ -382,10 +384,10 @@ exports.BattleFormats = {
this.add('rule', 'OHKO Clause: OHKO moves are banned');
},
onValidateSet: function (set) {
- var problems = [];
+ let problems = [];
if (set.moves) {
- for (var i in set.moves) {
- var move = this.getMove(set.moves[i]);
+ for (let i in set.moves) {
+ let move = this.getMove(set.moves[i]);
if (move.ohko) problems.push(move.name + ' is banned by OHKO Clause.');
}
}
@@ -462,8 +464,8 @@ exports.BattleFormats = {
this.add('rule', 'Baton Pass Clause: Limit one Baton Passer, can\'t pass Spe and other stats simultaneously');
},
onValidateTeam: function (team, format) {
- var BPcount = 0;
- for (var i = 0; i < team.length; i++) {
+ let BPcount = 0;
+ for (let i = 0; i < team.length; i++) {
if (team[i].moves.indexOf('Baton Pass') >= 0) {
BPcount++;
}
@@ -476,17 +478,17 @@ exports.BattleFormats = {
if (!('batonpass' in setHas)) return;
// check if Speed is boosted
- var speedBoosted = false;
- for (var i = 0; i < set.moves.length; i++) {
- var move = this.getMove(set.moves[i]);
+ let speedBoosted = false;
+ for (let i = 0; i < set.moves.length; i++) {
+ let move = this.getMove(set.moves[i]);
if (move.boosts && move.boosts.spe > 0) {
speedBoosted = true;
break;
}
}
- var boostSpeed = ['flamecharge', 'geomancy', 'motordrive', 'rattled', 'speedboost', 'steadfast', 'weakarmor', 'salacberry'];
+ let boostSpeed = ['flamecharge', 'geomancy', 'motordrive', 'rattled', 'speedboost', 'steadfast', 'weakarmor', 'salacberry'];
if (!speedBoosted) {
- for (var i = 0; i < boostSpeed.length; i++) {
+ for (let i = 0; i < boostSpeed.length; i++) {
if (boostSpeed[i] in setHas) {
speedBoosted = true;
break;
@@ -496,17 +498,17 @@ exports.BattleFormats = {
if (!speedBoosted) return;
// check if non-Speed boosted
- var nonSpeedBoosted = false;
- for (var i = 0; i < set.moves.length; i++) {
- var move = this.getMove(set.moves[i]);
+ let nonSpeedBoosted = false;
+ for (let i = 0; i < set.moves.length; i++) {
+ let move = this.getMove(set.moves[i]);
if (move.boosts && (move.boosts.atk > 0 || move.boosts.def > 0 || move.boosts.spa > 0 || move.boosts.spd > 0)) {
nonSpeedBoosted = true;
break;
}
}
- var boostNonSpeed = ['acupressure', 'starfberry', 'curse', 'metalclaw', 'meteormash', 'poweruppunch', 'rage', 'rototiller', 'fellstinger', 'bellydrum', 'download', 'justified', 'moxie', 'sapsipper', 'defiant', 'angerpoint', 'cellbattery', 'liechiberry', 'snowball', 'weaknesspolicy', 'diamondstorm', 'flowershield', 'skullbash', 'steelwing', 'stockpile', 'cottonguard', 'ganlonberry', 'keeberry', 'chargebeam', 'fierydance', 'geomancy', 'lightningrod', 'stormdrain', 'competitive', 'absorbbulb', 'petayaberry', 'charge', 'apicotberry', 'luminousmoss', 'marangaberry'];
+ let boostNonSpeed = ['acupressure', 'starfberry', 'curse', 'metalclaw', 'meteormash', 'poweruppunch', 'rage', 'rototiller', 'fellstinger', 'bellydrum', 'download', 'justified', 'moxie', 'sapsipper', 'defiant', 'angerpoint', 'cellbattery', 'liechiberry', 'snowball', 'weaknesspolicy', 'diamondstorm', 'flowershield', 'skullbash', 'steelwing', 'stockpile', 'cottonguard', 'ganlonberry', 'keeberry', 'chargebeam', 'fierydance', 'geomancy', 'lightningrod', 'stormdrain', 'competitive', 'absorbbulb', 'petayaberry', 'charge', 'apicotberry', 'luminousmoss', 'marangaberry'];
if (!nonSpeedBoosted) {
- for (var i = 0; i < boostNonSpeed.length; i++) {
+ for (let i = 0; i < boostNonSpeed.length; i++) {
if (boostNonSpeed[i] in setHas) {
nonSpeedBoosted = true;
break;
@@ -550,8 +552,8 @@ exports.BattleFormats = {
return;
}
if (status.id === 'slp') {
- for (var i = 0; i < target.side.pokemon.length; i++) {
- var pokemon = target.side.pokemon[i];
+ for (let i = 0; i < target.side.pokemon.length; i++) {
+ let pokemon = target.side.pokemon[i];
if (pokemon.hp && pokemon.status === 'slp') {
if (!pokemon.statusData.source || pokemon.statusData.source.side !== pokemon.side) {
this.add('-message', 'Sleep Clause Mod activated.');
@@ -572,8 +574,8 @@ exports.BattleFormats = {
return;
}
if (status.id === 'frz') {
- for (var i = 0; i < target.side.pokemon.length; i++) {
- var pokemon = target.side.pokemon[i];
+ for (let i = 0; i < target.side.pokemon.length; i++) {
+ let pokemon = target.side.pokemon[i];
if (pokemon.status === 'frz') {
this.add('-message', 'Freeze Clause activated.');
return false;
@@ -589,10 +591,10 @@ exports.BattleFormats = {
},
onValidateTeam: function (team, format, teamHas) {
if (!team[0]) return;
- var template = this.getTemplate(team[0].species);
- var typeTable = template.types;
+ let template = this.getTemplate(team[0].species);
+ let typeTable = template.types;
if (!typeTable) return ["Your team must share a type."];
- for (var i = 1; i < team.length; i++) {
+ for (let i = 1; i < team.length; i++) {
template = this.getTemplate(team[i].species);
if (!template.types) return ["Your team must share a type."];
@@ -614,10 +616,10 @@ exports.BattleFormats = {
effectType: 'Rule',
onStart: function () {
this.add('rule', 'Mega Rayquaza Clause: You cannot mega evolve Rayquaza');
- for (var i = 0; i < this.sides[0].pokemon.length; i++) {
+ for (let i = 0; i < this.sides[0].pokemon.length; i++) {
if (this.sides[0].pokemon[i].speciesid === 'rayquaza') this.sides[0].pokemon[i].canMegaEvo = false;
}
- for (var i = 0; i < this.sides[1].pokemon.length; i++) {
+ for (let i = 0; i < this.sides[1].pokemon.length; i++) {
if (this.sides[1].pokemon[i].speciesid === 'rayquaza') this.sides[1].pokemon[i].canMegaEvo = false;
}
}
diff --git a/data/scripts.js b/data/scripts.js
index 7fc4aa27e4..c6919874f0 100644
--- a/data/scripts.js
+++ b/data/scripts.js
@@ -1,8 +1,10 @@
+'use strict';
+
exports.BattleScripts = {
gen: 6,
runMove: function (move, pokemon, target, sourceEffect) {
if (!sourceEffect && toId(move) !== 'struggle') {
- var changedMove = this.runEvent('OverrideDecision', pokemon, target, move);
+ let changedMove = this.runEvent('OverrideDecision', pokemon, target, move);
if (changedMove && changedMove !== true) {
move = changedMove;
target = null;
@@ -36,7 +38,7 @@ exports.BattleScripts = {
}
}
pokemon.lastDamage = 0;
- var lockedMove = this.runEvent('LockMove', pokemon);
+ let lockedMove = this.runEvent('LockMove', pokemon);
if (lockedMove === true) lockedMove = false;
if (!lockedMove) {
if (!pokemon.deductPP(move, null, target) && (move.id !== 'struggle')) {
@@ -55,13 +57,13 @@ exports.BattleScripts = {
if (!sourceEffect && this.effect.id) sourceEffect = this.effect;
move = this.getMoveCopy(move);
if (this.activeMove) move.priority = this.activeMove.priority;
- var baseTarget = move.target;
+ let baseTarget = move.target;
if (!target && target !== false) target = this.resolveTarget(pokemon, move);
if (move.target === 'self' || move.target === 'allies') {
target = pokemon;
}
if (sourceEffect) move.sourceEffect = sourceEffect.id;
- var moveResult = false;
+ let moveResult = false;
this.setActiveMove(move, pokemon, target);
@@ -79,8 +81,8 @@ exports.BattleScripts = {
}
if (!move) return false;
- var attrs = '';
- var missed = false;
+ let attrs = '';
+ let missed = false;
if (pokemon.fainted) {
return false;
}
@@ -89,7 +91,7 @@ exports.BattleScripts = {
attrs = '|[still]'; // suppress the default move animation
}
- var movename = move.name;
+ let movename = move.name;
if (move.id === 'hiddenpower') movename = 'Hidden Power';
if (sourceEffect) attrs += '|[from]' + this.getEffect(sourceEffect);
this.addMove('move', pokemon, movename, target + attrs);
@@ -101,10 +103,10 @@ exports.BattleScripts = {
return true;
}
- var targets = pokemon.getMoveTargets(move, target);
- var extraPP = 0;
- for (var i = 0; i < targets.length; i++) {
- var ppDrop = this.singleEvent('DeductPP', targets[i].getAbility(), targets[i].abilityData, targets[i], pokemon, move);
+ let targets = pokemon.getMoveTargets(move, target);
+ let extraPP = 0;
+ for (let i = 0; i < targets.length; i++) {
+ let ppDrop = this.singleEvent('DeductPP', targets[i].getAbility(), targets[i].abilityData, targets[i], pokemon, move);
if (ppDrop !== true) {
extraPP += ppDrop || 0;
}
@@ -123,7 +125,7 @@ exports.BattleScripts = {
move.ignoreImmunity = (move.category === 'Status');
}
- var damage = false;
+ let damage = false;
if (move.target === 'all' || move.target === 'foeSide' || move.target === 'allySide' || move.target === 'allyTeam') {
damage = this.tryMoveHit(target, pokemon, move);
if (damage || damage === 0 || damage === undefined) moveResult = true;
@@ -138,15 +140,15 @@ exports.BattleScripts = {
}
if (targets.length > 1) move.spreadHit = true;
damage = 0;
- for (var i = 0; i < targets.length; i++) {
- var hitResult = this.tryMoveHit(targets[i], pokemon, move, true);
+ for (let i = 0; i < targets.length; i++) {
+ let hitResult = this.tryMoveHit(targets[i], pokemon, move, true);
if (hitResult || hitResult === 0 || hitResult === undefined) moveResult = true;
damage += hitResult || 0;
}
if (!pokemon.hp) pokemon.faint();
} else {
target = targets[0];
- var lacksTarget = target.fainted;
+ let lacksTarget = target.fainted;
if (!lacksTarget) {
if (move.target === 'adjacentFoe' || move.target === 'adjacentAlly' || move.target === 'normal' || move.target === 'randomNormal') {
lacksTarget = !this.isAdjacent(target, pokemon);
@@ -184,7 +186,7 @@ exports.BattleScripts = {
if (move.selfdestruct && spreadHit) pokemon.hp = 0;
this.setActiveMove(move, pokemon, target);
- var hitResult = true;
+ let hitResult = true;
hitResult = this.singleEvent('PrepareHit', move, {}, target, pokemon, move);
if (!hitResult) {
@@ -224,11 +226,11 @@ exports.BattleScripts = {
return false;
}
- var boostTable = [1, 4 / 3, 5 / 3, 2, 7 / 3, 8 / 3, 3];
+ let boostTable = [1, 4 / 3, 5 / 3, 2, 7 / 3, 8 / 3, 3];
// calculate true accuracy
- var accuracy = move.accuracy;
- var boosts, boost;
+ let accuracy = move.accuracy;
+ let boosts, boost;
if (accuracy !== true) {
if (!move.ignoreAccuracy) {
boosts = this.runEvent('ModifyBoost', pokemon, null, null, Object.clone(pokemon.boosts));
@@ -274,12 +276,12 @@ exports.BattleScripts = {
}
if (move.breaksProtect) {
- var broke = false;
- for (var i in {kingsshield:1, protect:1, spikyshield:1}) {
+ let broke = false;
+ for (let i in {kingsshield:1, protect:1, spikyshield:1}) {
if (target.removeVolatile(i)) broke = true;
}
if (this.gen >= 6 || target.side !== pokemon.side) {
- for (var i in {craftyshield:1, matblock:1, quickguard:1, wideguard:1}) {
+ for (let i in {craftyshield:1, matblock:1, quickguard:1, wideguard:1}) {
if (target.side.removeSideCondition(i)) broke = true;
}
}
@@ -292,11 +294,11 @@ exports.BattleScripts = {
}
}
- var totalDamage = 0;
- var damage = 0;
+ let totalDamage = 0;
+ let damage = 0;
pokemon.lastDamage = 0;
if (move.multihit) {
- var hits = move.multihit;
+ let hits = move.multihit;
if (hits.length) {
// yes, it's hardcoded... meh
if (hits[0] === 2 && hits[1] === 5) {
@@ -310,11 +312,11 @@ exports.BattleScripts = {
}
}
hits = Math.floor(hits);
- var nullDamage = true;
- var moveDamage;
+ let nullDamage = true;
+ let moveDamage;
// There is no need to recursively check the ´sleepUsable´ flag as Sleep Talk can only be used while asleep.
- var isSleepUsable = move.sleepUsable || this.getMove(move.sourceEffect).sleepUsable;
- var i;
+ let isSleepUsable = move.sleepUsable || this.getMove(move.sourceEffect).sleepUsable;
+ let i;
for (i = 0; i < hits && target.hp && pokemon.hp; i++) {
if (pokemon.status === 'slp' && !isSleepUsable) break;
@@ -354,12 +356,12 @@ exports.BattleScripts = {
return damage;
},
moveHit: function (target, pokemon, move, moveData, isSecondary, isSelf) {
- var damage;
+ let damage;
move = this.getMoveCopy(move);
if (!moveData) moveData = move;
if (!moveData.flags) moveData.flags = {};
- var hitResult = true;
+ let hitResult = true;
// TryHit events:
// STEP 1: we see if the move will succeed at all:
@@ -421,7 +423,7 @@ exports.BattleScripts = {
}
if (target) {
- var didSomething = false;
+ let didSomething = false;
damage = this.getDamage(pokemon, target, moveData);
@@ -465,7 +467,7 @@ exports.BattleScripts = {
didSomething = didSomething || hitResult;
}
if (moveData.heal && !target.fainted) {
- var d = target.heal((this.gen < 5 ? Math.floor : Math.round)(target.maxhp * moveData.heal[0] / moveData.heal[1]));
+ let d = target.heal((this.gen < 5 ? Math.floor : Math.round)(target.maxhp * moveData.heal[0] / moveData.heal[1]));
if (!d && d !== 0) {
this.add('-fail', target);
this.debug('heal interrupted');
@@ -546,7 +548,7 @@ exports.BattleScripts = {
}
}
if (moveData.self) {
- var selfRoll;
+ let selfRoll;
if (!isSecondary && moveData.self.boosts) selfRoll = this.random(100);
// This is done solely to mimic in-game RNG behaviour. All self drops have a 100% chance of happening but still grab a random number.
if (typeof moveData.self.chance === 'undefined' || selfRoll < moveData.self.chance) {
@@ -554,9 +556,9 @@ exports.BattleScripts = {
}
}
if (moveData.secondaries) {
- var secondaryRoll;
- var secondaries = this.runEvent('ModifySecondaries', target, pokemon, moveData, moveData.secondaries.slice());
- for (var i = 0; i < secondaries.length; i++) {
+ let secondaryRoll;
+ let secondaries = this.runEvent('ModifySecondaries', target, pokemon, moveData, moveData.secondaries.slice());
+ for (let i = 0; i < secondaries.length; i++) {
secondaryRoll = this.random(100);
if (typeof secondaries[i].chance === 'undefined' || secondaryRoll < secondaries[i].chance) {
this.moveHit(target, pokemon, move, secondaries[i], true, isSelf);
@@ -578,20 +580,20 @@ exports.BattleScripts = {
},
canMegaEvo: function (pokemon) {
- var altForme = pokemon.baseTemplate.otherFormes && this.getTemplate(pokemon.baseTemplate.otherFormes[0]);
+ let altForme = pokemon.baseTemplate.otherFormes && this.getTemplate(pokemon.baseTemplate.otherFormes[0]);
if (altForme && altForme.isMega && altForme.requiredMove && pokemon.moves.indexOf(toId(altForme.requiredMove)) >= 0) return altForme.species;
- var item = pokemon.getItem();
+ let item = pokemon.getItem();
if (item.megaEvolves !== pokemon.baseTemplate.baseSpecies || item.megaStone === pokemon.species) return false;
return item.megaStone;
},
runMegaEvo: function (pokemon) {
- var template = this.getTemplate(pokemon.canMegaEvo);
- var side = pokemon.side;
+ let template = this.getTemplate(pokemon.canMegaEvo);
+ let side = pokemon.side;
// Pokémon affected by Sky Drop cannot mega evolve. Enforce it here for now.
- var foeActive = side.foe.active;
- for (var i = 0; i < foeActive.length; i++) {
+ let foeActive = side.foe.active;
+ for (let i = 0; i < foeActive.length; i++) {
if (foeActive[i].volatiles['skydrop'] && foeActive[i].volatiles['skydrop'].source === pokemon) {
return false;
}
@@ -606,7 +608,7 @@ exports.BattleScripts = {
pokemon.baseAbility = pokemon.ability;
// Limit one mega evolution
- for (var i = 0; i < side.pokemon.length; i++) {
+ for (let i = 0; i < side.pokemon.length; i++) {
side.pokemon[i].canMegaEvo = false;
}
return true;
@@ -619,10 +621,10 @@ exports.BattleScripts = {
},
checkAbilities: function (selectedAbilities, defaultAbilities) {
if (!selectedAbilities.length) return true;
- var selectedAbility = selectedAbilities.pop();
- var isValid = false;
- for (var i = 0; i < defaultAbilities.length; i++) {
- var defaultAbility = defaultAbilities[i];
+ let selectedAbility = selectedAbilities.pop();
+ let isValid = false;
+ for (let i = 0; i < defaultAbilities.length; i++) {
+ let defaultAbility = defaultAbilities[i];
if (!defaultAbility) break;
if (defaultAbility.indexOf(selectedAbility) >= 0) {
defaultAbilities.splice(i, 1);
@@ -635,10 +637,10 @@ exports.BattleScripts = {
return isValid;
},
sampleNoReplace: function (list) {
- var length = list.length;
- var index = this.random(length);
- var element = list[index];
- for (var nextIndex = index + 1; nextIndex < length; index += 1, nextIndex += 1) {
+ let length = list.length;
+ let index = this.random(length);
+ let element = list[index];
+ for (let nextIndex = index + 1; nextIndex < length; index += 1, nextIndex += 1) {
list[index] = list[nextIndex];
}
list.pop();
@@ -646,9 +648,9 @@ exports.BattleScripts = {
},
hasMegaEvo: function (template) {
if (template.otherFormes) {
- var forme = this.getTemplate(template.otherFormes[0]);
+ let forme = this.getTemplate(template.otherFormes[0]);
if (forme.requiredItem) {
- var item = this.getItem(forme.requiredItem);
+ let item = this.getItem(forme.requiredItem);
if (item.megaStone) return true;
} else if (forme.requiredMove && forme.isMega) {
return true;
@@ -657,7 +659,7 @@ exports.BattleScripts = {
return false;
},
getTeam: function (side, team) {
- var format = side.battle.getFormat();
+ let format = side.battle.getFormat();
if (typeof format.team === 'string' && format.team.substr(0, 6) === 'random') {
return this[format.team + 'Team'](side);
} else if (team) {
@@ -667,40 +669,40 @@ exports.BattleScripts = {
}
},
randomCCTeam: function (side) {
- var team = [];
+ let team = [];
- var natures = Object.keys(this.data.Natures);
- var items = Object.keys(this.data.Items);
+ let natures = Object.keys(this.data.Natures);
+ let items = Object.keys(this.data.Items);
- var hasDexNumber = {};
- var formes = [[], [], [], [], [], []];
+ let hasDexNumber = {};
+ let formes = [[], [], [], [], [], []];
// Pick six random pokemon--no repeats, even among formes
// Also need to either normalize for formes or select formes at random
// Unreleased are okay but no CAP
- var num;
- for (var i = 0; i < 6; i++) {
+ let num;
+ for (let i = 0; i < 6; i++) {
do {
num = this.random(721) + 1;
} while (num in hasDexNumber);
hasDexNumber[num] = i;
}
- for (var id in this.data.Pokedex) {
+ for (let id in this.data.Pokedex) {
if (!(this.data.Pokedex[id].num in hasDexNumber)) continue;
- var template = this.getTemplate(id);
+ let template = this.getTemplate(id);
if (template.species !== 'Pichu-Spiky-eared') {
formes[hasDexNumber[template.num]].push(template.species);
}
}
- for (var i = 0; i < 6; i++) {
- var poke = formes[i][this.random(formes[i].length)];
- var template = this.getTemplate(poke);
+ for (let i = 0; i < 6; i++) {
+ let poke = formes[i][this.random(formes[i].length)];
+ let template = this.getTemplate(poke);
// Random item
- var item = items[this.random(items.length)];
+ let item = items[this.random(items.length)];
// Make sure forme is legal
if ((template.requiredItem && item !== template.requiredItem) || template.num === 351 ||
@@ -718,18 +720,18 @@ exports.BattleScripts = {
}
// Random ability
- var abilities = [template.abilities['0']];
+ let abilities = [template.abilities['0']];
if (template.abilities['1']) {
abilities.push(template.abilities['1']);
}
if (template.abilities['H']) {
abilities.push(template.abilities['H']);
}
- var ability = abilities[this.random(abilities.length)];
+ let ability = abilities[this.random(abilities.length)];
// Four random unique moves from the movepool
- var moves;
- var pool = ['struggle'];
+ let moves;
+ let pool = ['struggle'];
if (poke === 'Smeargle') {
pool = Object.keys(this.data.Movedex).exclude('chatter', 'struggle', 'magikarpsrevenge');
} else if (template.learnset) {
@@ -744,36 +746,36 @@ exports.BattleScripts = {
}
// Random EVs
- var evs = {hp: 0, atk: 0, def: 0, spa: 0, spd: 0, spe: 0};
- var s = ["hp", "atk", "def", "spa", "spd", "spe"];
- var evpool = 510;
+ let evs = {hp: 0, atk: 0, def: 0, spa: 0, spd: 0, spe: 0};
+ let s = ["hp", "atk", "def", "spa", "spd", "spe"];
+ let evpool = 510;
do {
- var x = s[this.random(s.length)];
- var y = this.random(Math.min(256 - evs[x], evpool + 1));
+ let x = s[this.random(s.length)];
+ let y = this.random(Math.min(256 - evs[x], evpool + 1));
evs[x] += y;
evpool -= y;
} while (evpool > 0);
// Random IVs
- var ivs = {hp: this.random(32), atk: this.random(32), def: this.random(32), spa: this.random(32), spd: this.random(32), spe: this.random(32)};
+ let ivs = {hp: this.random(32), atk: this.random(32), def: this.random(32), spa: this.random(32), spd: this.random(32), spe: this.random(32)};
// Random nature
- var nature = natures[this.random(natures.length)];
+ let nature = natures[this.random(natures.length)];
// Level balance--calculate directly from stats rather than using some silly lookup table
- var mbstmin = 1307; // Sunkern has the lowest modified base stat total, and that total is 807
+ let mbstmin = 1307; // Sunkern has the lowest modified base stat total, and that total is 807
- var stats = template.baseStats;
+ let stats = template.baseStats;
// Modified base stat total assumes 31 IVs, 85 EVs in every stat
- var mbst = (stats["hp"] * 2 + 31 + 21 + 100) + 10;
+ let mbst = (stats["hp"] * 2 + 31 + 21 + 100) + 10;
mbst += (stats["atk"] * 2 + 31 + 21 + 100) + 5;
mbst += (stats["def"] * 2 + 31 + 21 + 100) + 5;
mbst += (stats["spa"] * 2 + 31 + 21 + 100) + 5;
mbst += (stats["spd"] * 2 + 31 + 21 + 100) + 5;
mbst += (stats["spe"] * 2 + 31 + 21 + 100) + 5;
- var level = Math.floor(100 * mbstmin / mbst); // Initial level guess will underestimate
+ let level = Math.floor(100 * mbstmin / mbst); // Initial level guess will underestimate
while (level < 100) {
mbst = Math.floor((stats["hp"] * 2 + 31 + 21 + 100) * level / 100 + 10);
@@ -790,10 +792,10 @@ exports.BattleScripts = {
// Random gender--already handled by PS
// Random happiness
- var happiness = this.random(256);
+ let happiness = this.random(256);
// Random shininess
- var shiny = !this.random(1024);
+ let shiny = !this.random(1024);
team.push({
name: poke,
@@ -812,43 +814,43 @@ exports.BattleScripts = {
return team;
},
randomHCTeam: function (side) {
- var team = [];
+ let team = [];
- var itemPool = Object.keys(this.data.Items);
- var abilityPool = Object.keys(this.data.Abilities);
- var movePool = Object.keys(this.data.Movedex);
- var naturePool = Object.keys(this.data.Natures);
+ let itemPool = Object.keys(this.data.Items);
+ let abilityPool = Object.keys(this.data.Abilities);
+ let movePool = Object.keys(this.data.Movedex);
+ let naturePool = Object.keys(this.data.Natures);
- var hasDexNumber = {};
- var formes = [[], [], [], [], [], []];
+ let hasDexNumber = {};
+ let formes = [[], [], [], [], [], []];
// Pick six random pokemon--no repeats, even among formes
// Also need to either normalize for formes or select formes at random
// Unreleased are okay but no CAP
- var num;
- for (var i = 0; i < 6; i++) {
+ let num;
+ for (let i = 0; i < 6; i++) {
do {
num = this.random(721) + 1;
} while (num in hasDexNumber);
hasDexNumber[num] = i;
}
- for (var id in this.data.Pokedex) {
+ for (let id in this.data.Pokedex) {
if (!(this.data.Pokedex[id].num in hasDexNumber)) continue;
- var template = this.getTemplate(id);
+ let template = this.getTemplate(id);
if (template.learnset && template.species !== 'Pichu-Spiky-eared') {
formes[hasDexNumber[template.num]].push(template.species);
}
}
- for (var i = 0; i < 6; i++) {
+ for (let i = 0; i < 6; i++) {
// Choose forme
- var pokemon = formes[i][this.random(formes[i].length)];
- var template = this.getTemplate(pokemon);
+ let pokemon = formes[i][this.random(formes[i].length)];
+ let template = this.getTemplate(pokemon);
// Random unique item
- var item = '';
+ let item = '';
do {
item = this.sampleNoReplace(itemPool);
} while (this.data.Items[item].isNonstandard);
@@ -857,47 +859,47 @@ exports.BattleScripts = {
if (template.species.substr(0, 9) === 'Genesect-' && item !== toId(template.requiredItem)) pokemon = 'Genesect';
// Random unique ability
- var ability = '';
+ let ability = '';
do {
ability = this.sampleNoReplace(abilityPool);
} while (this.data.Abilities[ability].isNonstandard);
// Random unique moves
- var m = [];
+ let m = [];
while (true) {
- var moveid = this.sampleNoReplace(movePool);
+ let moveid = this.sampleNoReplace(movePool);
if (!this.data.Movedex[moveid].isNonstandard && (moveid === 'hiddenpower' || moveid.substr(0, 11) !== 'hiddenpower')) {
if (m.push(moveid) >= 4) break;
}
}
// Random EVs
- var evs = {hp: 0, atk: 0, def: 0, spa: 0, spd: 0, spe: 0};
- var s = ['hp', 'atk', 'def', 'spa', 'spd', 'spe'];
- var evpool = 510;
+ let evs = {hp: 0, atk: 0, def: 0, spa: 0, spd: 0, spe: 0};
+ let s = ['hp', 'atk', 'def', 'spa', 'spd', 'spe'];
+ let evpool = 510;
do {
- var x = s[this.random(s.length)];
- var y = this.random(Math.min(256 - evs[x], evpool + 1));
+ let x = s[this.random(s.length)];
+ let y = this.random(Math.min(256 - evs[x], evpool + 1));
evs[x] += y;
evpool -= y;
} while (evpool > 0);
// Random IVs
- var ivs = {hp: this.random(32), atk: this.random(32), def: this.random(32), spa: this.random(32), spd: this.random(32), spe: this.random(32)};
+ let ivs = {hp: this.random(32), atk: this.random(32), def: this.random(32), spa: this.random(32), spd: this.random(32), spe: this.random(32)};
// Random nature
- var nature = naturePool[this.random(naturePool.length)];
+ let nature = naturePool[this.random(naturePool.length)];
// Level balance
- var mbstmin = 1307;
- var stats = template.baseStats;
- var mbst = (stats['hp'] * 2 + 31 + 21 + 100) + 10;
+ let mbstmin = 1307;
+ let stats = template.baseStats;
+ let mbst = (stats['hp'] * 2 + 31 + 21 + 100) + 10;
mbst += (stats['atk'] * 2 + 31 + 21 + 100) + 5;
mbst += (stats['def'] * 2 + 31 + 21 + 100) + 5;
mbst += (stats['spa'] * 2 + 31 + 21 + 100) + 5;
mbst += (stats['spd'] * 2 + 31 + 21 + 100) + 5;
mbst += (stats['spe'] * 2 + 31 + 21 + 100) + 5;
- var level = Math.floor(100 * mbstmin / mbst);
+ let level = Math.floor(100 * mbstmin / mbst);
while (level < 100) {
mbst = Math.floor((stats['hp'] * 2 + 31 + 21 + 100) * level / 100 + 10);
mbst += Math.floor(((stats['atk'] * 2 + 31 + 21 + 100) * level / 100 + 5) * level / 100);
@@ -910,10 +912,10 @@ exports.BattleScripts = {
}
// Random happiness
- var happiness = this.random(256);
+ let happiness = this.random(256);
// Random shininess
- var shiny = !this.random(1024);
+ let shiny = !this.random(1024);
team.push({
name: pokemon,
@@ -933,7 +935,7 @@ exports.BattleScripts = {
},
queryMoves: function (moves, hasType, hasAbility) {
// This is primarily a helper function for random setbuilder functions.
- var counter = {
+ let counter = {
Physical: 0, Special: 0, Status: 0, damage: 0, recovery: 0, stab: 0,
blaze: 0, overgrow: 0, swarm: 0, torrent: 0,
adaptability: 0, ate: 0, bite: 0, contrary: 0, hustle: 0,
@@ -950,38 +952,38 @@ exports.BattleScripts = {
if (!hasAbility) hasAbility = {};
// Moves that heal a fixed amount:
- var RecoveryMove = {
+ let RecoveryMove = {
milkdrink: 1, recover: 1, roost: 1, slackoff: 1, softboiled: 1
};
// Moves which drop stats:
- var ContraryMove = {
+ let ContraryMove = {
leafstorm: 1, overheat: 1, closecombat: 1, superpower: 1, vcreate: 1
};
// Moves that boost Attack:
- var PhysicalSetup = {
+ let PhysicalSetup = {
bellydrum:1, bulkup:1, coil:1, curse:1, dragondance:1, honeclaws:1, howl:1, poweruppunch:1, shiftgear:1, swordsdance:1
};
// Moves which boost Special Attack:
- var SpecialSetup = {
+ let SpecialSetup = {
calmmind:1, chargebeam:1, geomancy:1, nastyplot:1, quiverdance:1, tailglow:1
};
// Moves which boost Attack AND Special Attack:
- var MixedSetup = {
+ let MixedSetup = {
growth:1, workup:1, shellsmash:1
};
// Moves which boost Speed:
- var SpeedSetup = {
+ let SpeedSetup = {
autotomize:1, agility:1, rockpolish:1
};
// Moves that shouldn't be the only STAB moves:
- var NoStab = {
+ let NoStab = {
aquajet:1, bounce:1, chargebeam:1, clearsmog:1, eruption:1, fakeout:1, flamecharge:1, pursuit:1, quickattack:1, skyattack:1, waterspout:1
};
// Iterate through all moves we've chosen so far and keep track of what they do:
- for (var k = 0; k < moves.length; k++) {
- var move = this.getMove(moves[k]);
- var moveid = move.id;
+ for (let k = 0; k < moves.length; k++) {
+ let move = this.getMove(moves[k]);
+ let moveid = move.id;
if (move.damage || move.damageCallback) {
// Moves that do a set amount of damage:
counter['damage']++;
@@ -1056,15 +1058,15 @@ exports.BattleScripts = {
},
randomSet: function (template, slot, teamDetails) {
if (slot === undefined) slot = 1;
- var baseTemplate = (template = this.getTemplate(template));
- var name = template.name;
+ let baseTemplate = (template = this.getTemplate(template));
+ let name = template.name;
if (!template.exists || (!template.randomBattleMoves && !template.learnset)) {
// GET IT? UNOWN? BECAUSE WE CAN'T TELL WHAT THE POKEMON IS
template = this.getTemplate('unown');
- var stack = 'Template incompatible with random battles: ' + name;
- var fakeErr = {stack: stack};
+ let stack = 'Template incompatible with random battles: ' + name;
+ let fakeErr = {stack: stack};
require('../crashlogger.js')(fakeErr, 'The randbat set generator');
}
@@ -1092,11 +1094,11 @@ exports.BattleScripts = {
template = this.getTemplate(template.otherFormes[0]);
}
- var movePool = (template.randomBattleMoves ? template.randomBattleMoves.slice() : Object.keys(template.learnset));
- var moves = [];
- var ability = '';
- var item = '';
- var evs = {
+ let movePool = (template.randomBattleMoves ? template.randomBattleMoves.slice() : Object.keys(template.learnset));
+ let moves = [];
+ let ability = '';
+ let item = '';
+ let evs = {
hp: 85,
atk: 85,
def: 85,
@@ -1104,7 +1106,7 @@ exports.BattleScripts = {
spd: 85,
spe: 85
};
- var ivs = {
+ let ivs = {
hp: 31,
atk: 31,
def: 31,
@@ -1112,12 +1114,12 @@ exports.BattleScripts = {
spd: 31,
spe: 31
};
- var hasType = {};
+ let hasType = {};
hasType[template.types[0]] = true;
if (template.types[1]) {
hasType[template.types[1]] = true;
}
- var hasAbility = {};
+ let hasAbility = {};
hasAbility[template.abilities[0]] = true;
if (template.abilities[1]) {
hasAbility[template.abilities[1]] = true;
@@ -1125,30 +1127,30 @@ exports.BattleScripts = {
if (template.abilities['H']) {
hasAbility[template.abilities['H']] = true;
}
- var availableHP = 0;
- for (var i = 0, len = movePool.length; i < len; i++) {
+ let availableHP = 0;
+ for (let i = 0, len = movePool.length; i < len; i++) {
if (movePool[i].substr(0, 11) === 'hiddenpower') availableHP++;
}
// These moves can be used even if we aren't setting up to use them:
- var SetupException = {
+ let SetupException = {
extremespeed:1, suckerpunch:1, superpower:1,
dracometeor:1, leafstorm:1, overheat:1, technoblast:1
};
- var counterAbilities = {
+ let counterAbilities = {
'Adaptability':1, 'Blaze':1, 'Contrary':1, 'Hustle':1, 'Iron Fist':1,
'Overgrow':1, 'Sheer Force':1, 'Skill Link':1, 'Swarm':1, 'Torrent':1
};
- var ateAbilities = {
+ let ateAbilities = {
'Aerilate':1, 'Pixilate':1, 'Refrigerate':1
};
- var hasMove, counter;
+ let hasMove, counter;
do {
// Keep track of all moves we have:
hasMove = {};
- for (var k = 0; k < moves.length; k++) {
+ for (let k = 0; k < moves.length; k++) {
if (moves[k].substr(0, 11) === 'hiddenpower') {
hasMove['hiddenpower'] = true;
} else {
@@ -1158,7 +1160,7 @@ exports.BattleScripts = {
// Choose next 4 moves from learnset/viable moves and add them to moves list:
while (moves.length < 4 && movePool.length) {
- var moveid = this.sampleNoReplace(movePool);
+ let moveid = this.sampleNoReplace(movePool);
if (moveid.substr(0, 11) === 'hiddenpower') {
availableHP--;
if (hasMove['hiddenpower']) continue;
@@ -1172,11 +1174,11 @@ exports.BattleScripts = {
counter = this.queryMoves(moves, hasType, hasAbility);
// Iterate through the moves again, this time to cull them:
- for (var k = 0; k < moves.length; k++) {
- var moveid = moves[k];
- var move = this.getMove(moveid);
- var rejected = false;
- var isSetup = false;
+ for (let k = 0; k < moves.length; k++) {
+ let moveid = moves[k];
+ let move = this.getMove(moveid);
+ let rejected = false;
+ let isSetup = false;
switch (moveid) {
@@ -1190,13 +1192,14 @@ exports.BattleScripts = {
case 'perishsong':
if (!hasMove['protect']) rejected = true;
break;
- case 'rest':
- var sleepTalk = movePool.indexOf('sleeptalk');
+ case 'rest': {
+ let sleepTalk = movePool.indexOf('sleeptalk');
if (sleepTalk >= 0) {
movePool.splice(sleepTalk, 1);
rejected = true;
}
break;
+ }
case 'sleeptalk':
if (!hasMove['rest']) rejected = true;
break;
@@ -1512,8 +1515,8 @@ exports.BattleScripts = {
// Handle Hidden Power IVs
if (move.id === 'hiddenpower') {
- var HPivs = this.getType(move.type).HPivs;
- for (var iv in HPivs) {
+ let HPivs = this.getType(move.type).HPivs;
+ for (let iv in HPivs) {
ivs[iv] = HPivs[iv];
}
}
@@ -1522,9 +1525,9 @@ exports.BattleScripts = {
// Move post-processing:
if (template.baseStats.hp >= 165 && movePool.indexOf('wish') >= 0 && !counter.recovery) {
// Certain Pokemon should always have a recovery move
- var rejectableMoves = [];
- for (var l = 0; l < moves.length; l++) {
- var move = this.getMove(moves[l]);
+ let rejectableMoves = [];
+ for (let l = 0; l < moves.length; l++) {
+ let move = this.getMove(moves[l]);
if (move.category === 'Status' || (!hasType[move.type] && !move.damage)) {
rejectableMoves.push(l);
}
@@ -1536,15 +1539,15 @@ exports.BattleScripts = {
// A set shouldn't have no attacking moves
moves.splice(this.random(moves.length), 1);
} else if (counter.damagingMoves.length === 1) {
- var damagingid = counter.damagingMoves[0].id;
+ let damagingid = counter.damagingMoves[0].id;
if (movePool.length - availableHP || availableHP && (damagingid === 'hiddenpower' || !hasMove['hiddenpower'])) {
- var replace = false;
+ let replace = false;
if (damagingid in {focuspunch:1, suckerpunch:1} || (damagingid === 'hiddenpower' && !counter.stab)) {
// Unacceptable as the only attacking move
replace = true;
} else if (!counter.damagingMoves[0].damage) {
if (!counter.stab) {
- var damagingType = counter.damagingMoves[0].type;
+ let damagingType = counter.damagingMoves[0].type;
if (damagingType === 'Fairy') {
// Mono-Fairy is acceptable for Psychic types
if (!hasType['Psychic']) replace = true;
@@ -1564,11 +1567,11 @@ exports.BattleScripts = {
}
} else if (counter.damagingMoves.length === 2 && !counter.stab) {
// If you have two attacks, neither is STAB, and the combo isn't Electric/Ice or Fighting/Ghost, reject one of them at random.
- var type1 = counter.damagingMoves[0].type, type2 = counter.damagingMoves[1].type;
- var typeCombo = [type1, type2].sort().join('/');
+ let type1 = counter.damagingMoves[0].type, type2 = counter.damagingMoves[1].type;
+ let typeCombo = [type1, type2].sort().join('/');
if ((typeCombo !== 'Electric/Ice' || !hasType['Normal'] || counter.Physical >= 2) && typeCombo !== 'Fighting/Ghost' && !counter.damagingMoves[0].damage && !counter.damagingMoves[1].damage) {
- var rejectableMoves = [];
- var baseDiff = movePool.length - availableHP;
+ let rejectableMoves = [];
+ let baseDiff = movePool.length - availableHP;
if (baseDiff || availableHP && (!hasMove['hiddenpower'] || counter.damagingMoves[0].id === 'hiddenpower')) {
rejectableMoves.push(counter.damagingMoveIndex[counter.damagingMoves[0].id]);
}
@@ -1582,9 +1585,9 @@ exports.BattleScripts = {
} else if (!counter.stab || ((hasAbility['Aerilate'] || hasAbility['Pixilate'] || hasAbility['Refrigerate']) && !counter['ate'])) {
// If you have three or more attacks, and none of them are STAB, reject one of them at random.
// Alternatively, if you have an -ate ability and no Normal moves, reject an attack move at random.
- var rejectableMoves = [];
- var baseDiff = movePool.length - availableHP;
- for (var l = 0; l < counter.damagingMoves.length; l++) {
+ let rejectableMoves = [];
+ let baseDiff = movePool.length - availableHP;
+ for (let l = 0; l < counter.damagingMoves.length; l++) {
if (baseDiff || availableHP && (!hasMove['hiddenpower'] || counter.damagingMoves[l].id === 'hiddenpower')) {
rejectableMoves.push(counter.damagingMoveIndex[counter.damagingMoves[l].id]);
}
@@ -1598,7 +1601,7 @@ exports.BattleScripts = {
// Any moveset modification goes here:
// moves[0] = 'safeguard';
- var changedMove = false;
+ let changedMove = false;
if (template.requiredItem && template.requiredItem.slice(-5) === 'Drive' && !hasMove['technoblast']) {
delete hasMove[this.getMove(moves[3]).id];
moves[3] = 'technoblast';
@@ -1627,13 +1630,13 @@ exports.BattleScripts = {
// Re-query in case a moveset modification occurred
if (changedMove) counter = this.queryMoves(moves, hasType, hasAbility);
- var abilities = Object.values(baseTemplate.abilities).sort(function (a, b) {
+ let abilities = Object.values(baseTemplate.abilities).sort(function (a, b) {
return this.getAbility(b).rating - this.getAbility(a).rating;
}.bind(this));
- var ability0 = this.getAbility(abilities[0]);
- var ability1 = this.getAbility(abilities[1]);
- var ability2 = this.getAbility(abilities[2]);
- var ability = ability0.name;
+ let ability0 = this.getAbility(abilities[0]);
+ let ability1 = this.getAbility(abilities[1]);
+ let ability2 = this.getAbility(abilities[2]);
+ ability = ability0.name;
if (abilities[1]) {
if (abilities[2] && ability2.rating === ability1.rating) {
if (this.random(2)) ability1 = ability2;
@@ -1644,7 +1647,7 @@ exports.BattleScripts = {
if (!this.random(3)) ability = ability1.name;
}
- var rejectAbility = false;
+ let rejectAbility = false;
if (ability in counterAbilities) {
// Adaptability, Blaze, Contrary, Hustle, Iron Fist, Overgrow, Skill Link, Swarm, Technician, Torrent
rejectAbility = !counter[toId(ability)];
@@ -1717,7 +1720,7 @@ exports.BattleScripts = {
// Might as well give it Pickup just in case
ability = 'Pickup';
} else if (template.id === 'aurorus' && ability === 'Snow Warning' && hasMove['hypervoice']) {
- for (var i = 0; i < moves.length; i++) {
+ for (let i = 0; i < moves.length; i++) {
if (moves[i] === 'hypervoice') {
moves[i] = 'blizzard';
counter['ate'] = 0;
@@ -1809,7 +1812,7 @@ exports.BattleScripts = {
} else if (ability === 'Magic Guard' && hasMove['psychoshift']) {
item = 'Flame Orb';
} else if (hasMove['switcheroo'] || hasMove['trick']) {
- var randomNum = this.random(2);
+ let randomNum = this.random(2);
if (counter.Physical >= 3 && (template.baseStats.spe >= 95 || randomNum)) {
item = 'Choice Band';
} else if (counter.Special >= 3 && (template.baseStats.spe >= 95 || randomNum)) {
@@ -1854,8 +1857,8 @@ exports.BattleScripts = {
item = 'Sitrus Berry';
} else {
item = 'Red Card';
- for (var m in moves) {
- var move = this.getMove(moves[m]);
+ for (let m in moves) {
+ let move = this.getMove(moves[m]);
if (hasType[move.type] && move.basePower >= 90) {
item = move.type + ' Gem';
break;
@@ -1925,7 +1928,7 @@ exports.BattleScripts = {
item = 'Black Sludge';
}
- var levelScale = {
+ let levelScale = {
LC: 87,
'LC Uber': 86,
NFE: 84,
@@ -1943,7 +1946,7 @@ exports.BattleScripts = {
Uber: 73,
AG: 71
};
- var customScale = {
+ let customScale = {
// Between OU and Uber
Aegislash: 74, Blaziken: 74, 'Blaziken-Mega': 74, Genesect: 74, 'Genesect-Burn': 74, 'Genesect-Chill': 74, 'Genesect-Douse': 74, 'Genesect-Shock': 74, Greninja: 74, 'Kangaskhan-Mega': 74, 'Lucario-Mega': 74, 'Mawile-Mega': 74,
@@ -1959,18 +1962,18 @@ exports.BattleScripts = {
// Holistic judgement
Unown: 85
};
- var tier = template.tier;
+ let tier = template.tier;
if (tier.charAt(0) === '(') {
tier = tier.slice(1, -1);
}
- var level = levelScale[tier] || 90;
+ let level = levelScale[tier] || 90;
if (customScale[template.name]) level = customScale[template.name];
if (template.name === 'Xerneas' && hasMove['geomancy']) level = 71;
// Prepare HP for Belly Drum.
if (hasMove['bellydrum'] && item === 'Sitrus Berry') {
- var hp = Math.floor(Math.floor(2 * template.baseStats.hp + ivs.hp + Math.floor(evs.hp / 4) + 100) * level / 100 + 10);
+ let hp = Math.floor(Math.floor(2 * template.baseStats.hp + ivs.hp + Math.floor(evs.hp / 4) + 100) * level / 100 + 10);
if (hp % 2 > 0) {
evs.hp -= 4;
evs.atk += 4;
@@ -1979,7 +1982,7 @@ exports.BattleScripts = {
// Prepare HP for double Stealth Rock weaknesses. Those are mutually exclusive with Belly Drum HP check.
// First, 25% damage.
if (this.getEffectiveness('Rock', template) === 1) {
- var hp = Math.floor(Math.floor(2 * template.baseStats.hp + ivs.hp + Math.floor(evs.hp / 4) + 100) * level / 100 + 10);
+ let hp = Math.floor(Math.floor(2 * template.baseStats.hp + ivs.hp + Math.floor(evs.hp / 4) + 100) * level / 100 + 10);
if (hp % 4 === 0) {
evs.hp -= 4;
if (counter.Physical > counter.Special) {
@@ -1992,7 +1995,7 @@ exports.BattleScripts = {
// Then, prepare it for 50% damage.
if (this.getEffectiveness('Rock', template) === 2) {
- var hp = Math.floor(Math.floor(2 * template.baseStats.hp + ivs.hp + Math.floor(evs.hp / 4) + 100) * level / 100 + 10);
+ let hp = Math.floor(Math.floor(2 * template.baseStats.hp + ivs.hp + Math.floor(evs.hp / 4) + 100) * level / 100 + 10);
if (hp % 2 === 0) {
evs.hp -= 4;
if (counter.Physical > counter.Special) {
@@ -2016,35 +2019,35 @@ exports.BattleScripts = {
};
},
randomTeam: function (side) {
- var pokemonLeft = 0;
- var pokemon = [];
+ let pokemonLeft = 0;
+ let pokemon = [];
- var excludedTiers = {'LC':1, 'LC Uber':1, 'NFE':1};
- var allowedNFE = {'Chansey':1, 'Doublade':1, 'Gligar':1, 'Porygon2':1, 'Scyther':1};
+ let excludedTiers = {'LC':1, 'LC Uber':1, 'NFE':1};
+ let allowedNFE = {'Chansey':1, 'Doublade':1, 'Gligar':1, 'Porygon2':1, 'Scyther':1};
- var pokemonPool = [];
- for (var id in this.data.FormatsData) {
- var template = this.getTemplate(id);
+ let pokemonPool = [];
+ for (let id in this.data.FormatsData) {
+ let template = this.getTemplate(id);
if (!excludedTiers[template.tier] && !template.isMega && !template.isPrimal && !template.isNonstandard && template.randomBattleMoves) {
pokemonPool.push(id);
}
}
// PotD stuff
- var potd;
+ let potd;
if (Config.potd && 'Rule:potd' in this.getBanlistTable(this.getFormat())) {
potd = this.getTemplate(Config.potd);
}
- var typeCount = {};
- var typeComboCount = {};
- var baseFormes = {};
- var uberCount = 0;
- var puCount = 0;
- var teamDetails = {megaCount: 0, stealthRock: 0, hazardClear: 0};
+ let typeCount = {};
+ let typeComboCount = {};
+ let baseFormes = {};
+ let uberCount = 0;
+ let puCount = 0;
+ let teamDetails = {megaCount: 0, stealthRock: 0, hazardClear: 0};
while (pokemonPool.length && pokemonLeft < 6) {
- var template = this.getTemplate(this.sampleNoReplace(pokemonPool));
+ let template = this.getTemplate(this.sampleNoReplace(pokemonPool));
if (!template.exists) continue;
// Limit to one of each species (Species Clause)
@@ -2059,7 +2062,7 @@ exports.BattleScripts = {
// Only certain NFE Pokemon are allowed
if (template.evos.length && !allowedNFE[template.species]) continue;
- var tier = template.tier;
+ let tier = template.tier;
switch (tier) {
case 'PU':
// PUs are limited to 2 but have a 20% chance of being added anyway.
@@ -2110,9 +2113,9 @@ exports.BattleScripts = {
}
// Limit 2 of any type
- var types = template.types;
- var skip = false;
- for (var t = 0; t < types.length; t++) {
+ let types = template.types;
+ let skip = false;
+ for (let t = 0; t < types.length; t++) {
if (typeCount[types[t]] > 1 && this.random(5) >= 1) {
skip = true;
break;
@@ -2134,13 +2137,13 @@ exports.BattleScripts = {
}
}
- var set = this.randomSet(template, pokemon.length, teamDetails);
+ let set = this.randomSet(template, pokemon.length, teamDetails);
// Illusion shouldn't be on the last pokemon of the team
if (set.ability === 'Illusion' && pokemonLeft > 4) continue;
// Limit 1 of any type combination
- var typeCombo = types.join();
+ let typeCombo = types.join();
if (set.ability === 'Drought' || set.ability === 'Drizzle') {
// Drought and Drizzle don't count towards the type combo limit
typeCombo = set.ability;
@@ -2148,8 +2151,8 @@ exports.BattleScripts = {
if (typeCombo in typeComboCount) continue;
// Limit the number of Megas to one
- var forme = template.otherFormes && this.getTemplate(template.otherFormes[0]);
- var isMegaSet = this.getItem(set.item).megaStone || (forme && forme.isMega && forme.requiredMove && set.moves.indexOf(toId(forme.requiredMove)) >= 0);
+ let forme = template.otherFormes && this.getTemplate(template.otherFormes[0]);
+ let isMegaSet = this.getItem(set.item).megaStone || (forme && forme.isMega && forme.requiredMove && set.moves.indexOf(toId(forme.requiredMove)) >= 0);
if (isMegaSet && teamDetails.megaCount > 0) continue;
// Okay, the set passes, add it to our team
@@ -2159,7 +2162,7 @@ exports.BattleScripts = {
pokemonLeft++;
// Increment type counters
- for (var t = 0; t < types.length; t++) {
+ for (let t = 0; t < types.length; t++) {
if (types[t] in typeCount) {
typeCount[types[t]]++;
} else {
@@ -2186,35 +2189,35 @@ exports.BattleScripts = {
return pokemon;
},
randomDoublesTeam: function (side) {
- var pokemonLeft = 0;
- var pokemon = [];
+ let pokemonLeft = 0;
+ let pokemon = [];
- var excludedTiers = {'LC':1, 'LC Uber':1, 'NFE':1};
- var allowedNFE = {'Chansey':1, 'Doublade':1, 'Porygon2':1, 'Scyther':1};
+ let excludedTiers = {'LC':1, 'LC Uber':1, 'NFE':1};
+ let allowedNFE = {'Chansey':1, 'Doublade':1, 'Porygon2':1, 'Scyther':1};
- var pokemonPool = [];
- for (var id in this.data.FormatsData) {
- var template = this.getTemplate(id);
+ let pokemonPool = [];
+ for (let id in this.data.FormatsData) {
+ let template = this.getTemplate(id);
if (!excludedTiers[template.tier] && !template.isMega && !template.isPrimal && !template.isNonstandard && template.randomBattleMoves) {
pokemonPool.push(id);
}
}
// PotD stuff
- var potd;
+ let potd;
if (Config.potd && 'Rule:potd' in this.getBanlistTable(this.getFormat())) {
potd = this.getTemplate(Config.potd);
}
- var typeCount = {};
- var typeComboCount = {};
- var baseFormes = {};
- var uberCount = 0;
- var puCount = 0;
- var megaCount = 0;
+ let typeCount = {};
+ let typeComboCount = {};
+ let baseFormes = {};
+ let uberCount = 0;
+ let puCount = 0;
+ let megaCount = 0;
while (pokemonPool.length && pokemonLeft < 6) {
- var template = this.getTemplate(this.sampleNoReplace(pokemonPool));
+ let template = this.getTemplate(this.sampleNoReplace(pokemonPool));
if (!template.exists) continue;
// Limit to one of each species (Species Clause)
@@ -2226,7 +2229,7 @@ exports.BattleScripts = {
// Only certain NFE Pokemon are allowed
if (template.evos.length && !allowedNFE[template.species]) continue;
- var tier = template.tier;
+ let tier = template.tier;
switch (tier) {
case 'CAP':
// CAPs have 20% the normal rate
@@ -2269,9 +2272,9 @@ exports.BattleScripts = {
}
// Limit 2 of any type
- var types = template.types;
- var skip = false;
- for (var t = 0; t < types.length; t++) {
+ let types = template.types;
+ let skip = false;
+ for (let t = 0; t < types.length; t++) {
if (typeCount[types[t]] > 1 && this.random(5) >= 1) {
skip = true;
break;
@@ -2288,13 +2291,13 @@ exports.BattleScripts = {
}
}
- var set = this.randomDoublesSet(template, pokemon.length, megaCount);
+ let set = this.randomDoublesSet(template, pokemon.length, megaCount);
// Illusion shouldn't be on the last pokemon of the team
if (set.ability === 'Illusion' && pokemonLeft > 4) continue;
// Limit 1 of any type combination
- var typeCombo = types.join();
+ let typeCombo = types.join();
if (set.ability === 'Drought' || set.ability === 'Drizzle') {
// Drought and Drizzle don't count towards the type combo limit
typeCombo = set.ability;
@@ -2302,8 +2305,8 @@ exports.BattleScripts = {
if (typeCombo in typeComboCount) continue;
// Limit the number of Megas to one
- var forme = template.otherFormes && this.getTemplate(template.otherFormes[0]);
- var isMegaSet = this.getItem(set.item).megaStone || (forme && forme.isMega && forme.requiredMove && set.moves.indexOf(toId(forme.requiredMove)) >= 0);
+ let forme = template.otherFormes && this.getTemplate(template.otherFormes[0]);
+ let isMegaSet = this.getItem(set.item).megaStone || (forme && forme.isMega && forme.requiredMove && set.moves.indexOf(toId(forme.requiredMove)) >= 0);
if (isMegaSet && megaCount > 0) continue;
// Okay, the set passes, add it to our team
@@ -2313,7 +2316,7 @@ exports.BattleScripts = {
pokemonLeft++;
// Increment type counters
- for (var t = 0; t < types.length; t++) {
+ for (let t = 0; t < types.length; t++) {
if (types[t] in typeCount) {
typeCount[types[t]]++;
} else {
@@ -2336,14 +2339,14 @@ exports.BattleScripts = {
return pokemon;
},
randomDoublesSet: function (template, slot, noMega) {
- var baseTemplate = (template = this.getTemplate(template));
- var name = template.name;
+ let baseTemplate = (template = this.getTemplate(template));
+ let name = template.name;
if (!template.exists || (!template.randomDoubleBattleMoves && !template.randomBattleMoves && !template.learnset)) {
template = this.getTemplate('unown');
- var stack = 'Template incompatible with random battles: ' + name;
- var fakeErr = {stack: stack};
+ let stack = 'Template incompatible with random battles: ' + name;
+ let fakeErr = {stack: stack};
require('../crashlogger.js')(fakeErr, 'The doubles randbat set generator');
}
@@ -2369,13 +2372,13 @@ exports.BattleScripts = {
template = this.getTemplate(template.otherFormes[0]);
}
- var movePool = (template.randomDoubleBattleMoves || template.randomBattleMoves);
+ let movePool = (template.randomDoubleBattleMoves || template.randomBattleMoves);
movePool = movePool ? movePool.slice() : Object.keys(template.learnset);
- var moves = [];
- var ability = '';
- var item = '';
- var evs = {
+ let moves = [];
+ let ability = '';
+ let item = '';
+ let evs = {
hp: 0,
atk: 0,
def: 0,
@@ -2383,7 +2386,7 @@ exports.BattleScripts = {
spd: 0,
spe: 0
};
- var ivs = {
+ let ivs = {
hp: 31,
atk: 31,
def: 31,
@@ -2391,12 +2394,12 @@ exports.BattleScripts = {
spd: 31,
spe: 31
};
- var hasType = {};
+ let hasType = {};
hasType[template.types[0]] = true;
if (template.types[1]) {
hasType[template.types[1]] = true;
}
- var hasAbility = {};
+ let hasAbility = {};
hasAbility[template.abilities[0]] = true;
if (template.abilities[1]) {
hasAbility[template.abilities[1]] = true;
@@ -2404,31 +2407,31 @@ exports.BattleScripts = {
if (template.abilities['H']) {
hasAbility[template.abilities['H']] = true;
}
- var availableHP = 0;
- for (var i = 0, len = movePool.length; i < len; i++) {
+ let availableHP = 0;
+ for (let i = 0, len = movePool.length; i < len; i++) {
if (movePool[i].substr(0, 11) === 'hiddenpower') availableHP++;
}
// These moves can be used even if we aren't setting up to use them:
- var SetupException = {
+ let SetupException = {
dracometeor:1, leafstorm:1, overheat:1,
extremespeed:1, suckerpunch:1, superpower:1
};
- var counterAbilities = {
+ let counterAbilities = {
'Adaptability':1, 'Blaze':1, 'Contrary':1, 'Hustle':1, 'Iron Fist':1, 'Overgrow':1,
'Skill Link':1, 'Swarm':1, 'Torrent':1
};
// -ate Abilities
- var ateAbilities = {
+ let ateAbilities = {
'Aerilate':1, 'Pixilate':1, 'Refrigerate':1
};
- var hasMove, counter;
+ let hasMove, counter;
do {
// Keep track of all moves we have:
hasMove = {};
- for (var k = 0; k < moves.length; k++) {
+ for (let k = 0; k < moves.length; k++) {
if (moves[k].substr(0, 11) === 'hiddenpower') {
hasMove['hiddenpower'] = true;
} else {
@@ -2438,7 +2441,7 @@ exports.BattleScripts = {
// Choose next 4 moves from learnset/viable moves and add them to moves list:
while (moves.length < 4 && movePool.length) {
- var moveid = toId(this.sampleNoReplace(movePool));
+ let moveid = toId(this.sampleNoReplace(movePool));
if (moveid.substr(0, 11) === 'hiddenpower') {
availableHP--;
if (hasMove['hiddenpower']) continue;
@@ -2452,11 +2455,11 @@ exports.BattleScripts = {
counter = this.queryMoves(moves, hasType, hasAbility);
// Iterate through the moves again, this time to cull them:
- for (var k = 0; k < moves.length; k++) {
- var moveid = moves[k];
- var move = this.getMove(moveid);
- var rejected = false;
- var isSetup = false;
+ for (let k = 0; k < moves.length; k++) {
+ let moveid = moves[k];
+ let move = this.getMove(moveid);
+ let rejected = false;
+ let isSetup = false;
switch (moveid) {
// not very useful without their supporting moves
@@ -2731,8 +2734,8 @@ exports.BattleScripts = {
// Handle HP IVs
if (move.id === 'hiddenpower') {
- var HPivs = this.getType(move.type).HPivs;
- for (var iv in HPivs) {
+ let HPivs = this.getType(move.type).HPivs;
+ for (let iv in HPivs) {
ivs[iv] = HPivs[iv];
}
}
@@ -2743,16 +2746,16 @@ exports.BattleScripts = {
// A set shouldn't have no attacking moves
moves.splice(this.random(moves.length), 1);
} else if (counter.damagingMoves.length === 1) {
- var damagingid = counter.damagingMoves[0].id;
+ let damagingid = counter.damagingMoves[0].id;
// Night Shade, Seismic Toss, etc. don't count:
if (!counter.damagingMoves[0].damage && (movePool.length - availableHP || availableHP && (damagingid === 'hiddenpower' || !hasMove['hiddenpower']))) {
- var replace = false;
+ let replace = false;
if (damagingid in {counter:1, focuspunch:1, mirrorcoat:1, suckerpunch:1} || (damagingid === 'hiddenpower' && !counter.stab)) {
// Unacceptable as the only attacking move
replace = true;
} else {
if (!counter.stab) {
- var damagingType = counter.damagingMoves[0].type;
+ let damagingType = counter.damagingMoves[0].type;
if (damagingType === 'Fairy') {
// Mono-Fairy is acceptable for Psychic types
if (!hasType['Psychic']) replace = true;
@@ -2772,11 +2775,11 @@ exports.BattleScripts = {
}
} else if (counter.damagingMoves.length === 2 && !counter.stab) {
// If you have two attacks, neither is STAB, and the combo isn't Ice/Electric or Ghost/Fighting, reject one of them at random.
- var type1 = counter.damagingMoves[0].type, type2 = counter.damagingMoves[1].type;
- var typeCombo = [type1, type2].sort().join('/');
+ let type1 = counter.damagingMoves[0].type, type2 = counter.damagingMoves[1].type;
+ let typeCombo = [type1, type2].sort().join('/');
if (typeCombo !== 'Electric/Ice' && typeCombo !== 'Fighting/Ghost') {
- var rejectableMoves = [];
- var baseDiff = movePool.length - availableHP;
+ let rejectableMoves = [];
+ let baseDiff = movePool.length - availableHP;
if (baseDiff || availableHP && (!hasMove['hiddenpower'] || counter.damagingMoves[0].id === 'hiddenpower')) {
rejectableMoves.push(counter.damagingMoveIndex[counter.damagingMoves[0].id]);
}
@@ -2790,9 +2793,9 @@ exports.BattleScripts = {
} else if (!counter.stab || ((hasAbility['Aerilate'] || hasAbility['Pixilate'] || hasAbility['Refrigerate']) && !counter['ate'])) {
// If you have three or more attacks, and none of them are STAB, reject one of them at random.
// Alternatively, if you have an -ate ability and no Normal moves, reject an attack move at random.
- var rejectableMoves = [];
- var baseDiff = movePool.length - availableHP;
- for (var l = 0; l < counter.damagingMoves.length; l++) {
+ let rejectableMoves = [];
+ let baseDiff = movePool.length - availableHP;
+ for (let l = 0; l < counter.damagingMoves.length; l++) {
if (baseDiff || availableHP && (!hasMove['hiddenpower'] || counter.damagingMoves[l].id === 'hiddenpower')) {
rejectableMoves.push(counter.damagingMoveIndex[counter.damagingMoves[l].id]);
}
@@ -2806,7 +2809,7 @@ exports.BattleScripts = {
// any moveset modification goes here
//moves[0] = 'safeguard';
- var changedMove = false;
+ let changedMove = false;
if (template.requiredItem && template.requiredItem.slice(-5) === 'Drive' && !hasMove['technoblast']) {
delete hasMove[this.getMove(moves[3]).id];
moves[3] = 'technoblast';
@@ -2841,13 +2844,13 @@ exports.BattleScripts = {
};
}
- var abilities = Object.values(baseTemplate.abilities).sort(function (a, b) {
+ let abilities = Object.values(baseTemplate.abilities).sort(function (a, b) {
return this.getAbility(b).rating - this.getAbility(a).rating;
}.bind(this));
- var ability0 = this.getAbility(abilities[0]);
- var ability1 = this.getAbility(abilities[1]);
- var ability2 = this.getAbility(abilities[2]);
- var ability = ability0.name;
+ let ability0 = this.getAbility(abilities[0]);
+ let ability1 = this.getAbility(abilities[1]);
+ let ability2 = this.getAbility(abilities[2]);
+ ability = ability0.name;
if (abilities[1]) {
if (abilities[2] && ability2.rating === ability1.rating) {
if (this.random(2)) ability1 = ability2;
@@ -2858,7 +2861,7 @@ exports.BattleScripts = {
if (!this.random(3)) ability = ability1.name;
}
- var rejectAbility = false;
+ let rejectAbility = false;
if (ability in counterAbilities) {
rejectAbility = !counter[toId(ability)];
} else if (ability in ateAbilities) {
@@ -2928,7 +2931,7 @@ exports.BattleScripts = {
// Might as well give it Pickup just in case
ability = 'Pickup';
} else if (template.id === 'aurorus' && ability === 'Snow Warning' && hasMove['hypervoice']) {
- for (var i = 0; i < moves.length; i++) {
+ for (let i = 0; i < moves.length; i++) {
if (moves[i] === 'hypervoice') {
moves[i] = 'blizzard';
counter['ate'] = 0;
@@ -2997,7 +3000,7 @@ exports.BattleScripts = {
} else if (template.species === 'Unown') {
item = 'Choice Specs';
} else if (hasMove['trick'] || hasMove['switcheroo']) {
- var randomNum = this.random(2);
+ let randomNum = this.random(2);
if (counter.Physical >= 3 && (template.baseStats.spe >= 95 || randomNum)) {
item = 'Choice Band';
} else if (counter.Special >= 3 && (template.baseStats.spe >= 95 || randomNum)) {
@@ -3066,8 +3069,8 @@ exports.BattleScripts = {
item = 'Sitrus Berry';
} else {
item = 'Red Card';
- for (var m in moves) {
- var move = this.getMove(moves[m]);
+ for (let m in moves) {
+ let move = this.getMove(moves[m]);
if (hasType[move.type] && move.basePower >= 90) {
item = move.type + ' Gem';
break;
@@ -3080,7 +3083,7 @@ exports.BattleScripts = {
item = hasMove['drainpunch'] ? 'Flame Orb' : 'Toxic Orb';
if ((hasMove['return'] || hasMove['hyperfang']) && !hasMove['facade']) {
// lol no
- for (var j = 0; j < moves.length; j++) {
+ for (let j = 0; j < moves.length; j++) {
if (moves[j] === 'Return' || moves[j] === 'Hyper Fang') {
moves[j] = 'Facade';
break;
@@ -3149,10 +3152,10 @@ exports.BattleScripts = {
// We choose level based on BST. Min level is 70, max level is 99. 600+ BST is 70, less than 300 is 99. Calculate with those values.
// Every 10.34 BST adds a level from 70 up to 99. Results are floored. Uses the Mega's stats if holding a Mega Stone
- var bst = template.baseStats.hp + template.baseStats.atk + template.baseStats.def + template.baseStats.spa + template.baseStats.spd + template.baseStats.spe;
+ let bst = template.baseStats.hp + template.baseStats.atk + template.baseStats.def + template.baseStats.spa + template.baseStats.spd + template.baseStats.spe;
// Adjust levels of mons based on abilities (Pure Power, Sheer Force, etc.) and also Eviolite
// For the stat boosted, treat the Pokemon's base stat as if it were multiplied by the boost. (Actual effective base stats are higher.)
- var templateAbility = (baseTemplate === template ? ability : template.abilities[0]);
+ let templateAbility = (baseTemplate === template ? ability : template.abilities[0]);
if (templateAbility === 'Huge Power' || templateAbility === 'Pure Power') {
bst += template.baseStats.atk;
} else if (templateAbility === 'Parental Bond') {
@@ -3166,7 +3169,7 @@ exports.BattleScripts = {
if (item === 'Eviolite') {
bst += 0.5 * (template.baseStats.def + template.baseStats.spd);
}
- var level = 70 + Math.floor(((600 - this.clampIntRange(bst, 300, 600)) / 10.34));
+ let level = 70 + Math.floor(((600 - this.clampIntRange(bst, 300, 600)) / 10.34));
return {
name: name,
@@ -3180,7 +3183,7 @@ exports.BattleScripts = {
};
},
randomSeasonalHeroTeam: function () {
- var teams = [
+ let teams = [
['Wolverine', 'Professor X', 'Cyclops', 'Nightcrawler', 'Phoenix', 'Emma Frost', 'Storm', 'Iceman'],
['Magneto', 'Mystique', 'Quicksilver', 'Scarlet Witch', 'Blob', 'Pyro', 'Sabretooth', 'Juggernaut', 'Toad'],
['Captain America', 'Hulk', 'Iron Man', 'Hawkeye', 'Black Widow', 'Thor', 'Nick Fury', 'Vision'],
@@ -3192,7 +3195,7 @@ exports.BattleScripts = {
['Joker', 'Deadshot', 'Harley Quinn', 'Boomerang', 'Killer Croc', 'Enchantress'],
['Poison Ivy', 'Bane', 'Scarecrow', 'Two-Face', 'Penguin', 'Mr. Freeze', 'Catwoman']
];
- var mons = {
+ let mons = {
'Wolverine': {species: 'excadrill', ability: 'Regenerator', item: 'lifeorb', gender: 'M'},
'Professor X': {species: 'beheeyem', moves: ['psystrike', 'thunderbolt', 'calmmind', 'aurasphere', 'signalbeam'], gender: 'M'},
'Cyclops': {species: 'sigilyph', moves: ['icebeam', 'psybeam', 'signalbeam', 'chargebeam'], item: 'lifeorb',
@@ -3233,24 +3236,24 @@ exports.BattleScripts = {
if (!this.seasonal) this.seasonal = {};
- var teamDetails = {megaCount: 1, stealthRock: 0, hazardClear: 0};
- var sides = Object.keys(teams);
- var side;
+ let teamDetails = {megaCount: 1, stealthRock: 0, hazardClear: 0};
+ let sides = Object.keys(teams);
+ let side;
while (side === undefined || this.seasonal.side === side) {
// You can't have both players have the same squad
side = this.sampleNoReplace(sides);
}
if (this.seasonal.side === undefined) this.seasonal.side = side;
- var heroes = teams[side];
- var pokemonTeam = [];
- var hero, heroTemplate, template, pokemon;
+ let heroes = teams[side];
+ let pokemonTeam = [];
+ let hero, heroTemplate, template, pokemon;
- for (var i = 0; i < 6; i++) {
+ for (let i = 0; i < 6; i++) {
hero = this.sampleNoReplace(heroes);
heroTemplate = mons[hero];
- var template = {};
+ let template = {};
if (heroTemplate.moves) template.randomBattleMoves = heroTemplate.moves;
if (heroTemplate.required) template.requiredMove = heroTemplate.required;
Object.merge(template, this.getTemplate(heroTemplate.species), false);
@@ -3276,42 +3279,42 @@ exports.BattleScripts = {
},
randomFactorySets: require('./factory-sets.json'),
randomFactorySet: function (template, slot, teamData, tier) {
- var speciesId = toId(template.species);
- var flags = this.randomFactorySets[tier][speciesId].flags;
- var setList = this.randomFactorySets[tier][speciesId].sets;
- var effectivePool, priorityPool;
+ let speciesId = toId(template.species);
+ let flags = this.randomFactorySets[tier][speciesId].flags;
+ let setList = this.randomFactorySets[tier][speciesId].sets;
+ let effectivePool, priorityPool;
- var itemsMax = {'choicespecs':1, 'choiceband':1, 'choicescarf':1};
- var movesMax = {'rapidspin':1, 'batonpass':1, 'stealthrock':1, 'defog':1, 'spikes':1, 'toxicspikes':1};
- var requiredMoves = {'stealthrock': 'hazardSet', 'rapidspin': 'hazardClear', 'defog': 'hazardClear'};
- var weatherAbilitiesRequire = {
+ let itemsMax = {'choicespecs':1, 'choiceband':1, 'choicescarf':1};
+ let movesMax = {'rapidspin':1, 'batonpass':1, 'stealthrock':1, 'defog':1, 'spikes':1, 'toxicspikes':1};
+ let requiredMoves = {'stealthrock': 'hazardSet', 'rapidspin': 'hazardClear', 'defog': 'hazardClear'};
+ let weatherAbilitiesRequire = {
'hydration': 'raindance', 'swiftswim': 'raindance',
'leafguard': 'sunnyday', 'solarpower': 'sunnyday', 'chlorophyll': 'sunnyday',
'sandforce': 'sandstorm', 'sandrush': 'sandstorm', 'sandveil': 'sandstorm',
'snowcloak': 'hail'
};
- var weatherAbilitiesSet = {'drizzle':1, 'drought':1, 'snowwarning':1, 'sandstream':1};
+ let weatherAbilitiesSet = {'drizzle':1, 'drought':1, 'snowwarning':1, 'sandstream':1};
// Build a pool of eligible sets, given the team partners
// Also keep track of sets with moves the team requires
effectivePool = [];
priorityPool = [];
- for (var i = 0, l = setList.length; i < l; i++) {
- var curSet = setList[i];
- var itemData = this.getItem(curSet.item);
+ for (let i = 0, l = setList.length; i < l; i++) {
+ let curSet = setList[i];
+ let itemData = this.getItem(curSet.item);
if (teamData.megaCount > 0 && itemData.megaStone) continue; // reject 2+ mega stones
if (itemsMax[itemData.id] && teamData.has[itemData.id] >= itemsMax[itemData.id]) continue;
- var abilityData = this.getAbility(curSet.ability);
+ let abilityData = this.getAbility(curSet.ability);
if (weatherAbilitiesRequire[abilityData.id] && teamData.weather !== weatherAbilitiesRequire[abilityData.id]) continue;
if (teamData.weather && weatherAbilitiesSet[abilityData.id]) continue; // reject 2+ weather setters
- var reject = false;
- var hasRequiredMove = false;
- var curSetVariants = [];
- for (var j = 0, m = curSet.moves.length; j < m; j++) {
- var variantIndex = this.random(curSet.moves[j].length);
- var moveId = toId(curSet.moves[j][variantIndex]);
+ let reject = false;
+ let hasRequiredMove = false;
+ let curSetVariants = [];
+ for (let j = 0, m = curSet.moves.length; j < m; j++) {
+ let variantIndex = this.random(curSet.moves[j].length);
+ let moveId = toId(curSet.moves[j][variantIndex]);
if (movesMax[moveId] && teamData.has[moveId] >= movesMax[moveId]) {
reject = true;
break;
@@ -3329,15 +3332,15 @@ exports.BattleScripts = {
if (!effectivePool.length) {
if (!teamData.forceResult) return false;
- for (var i = 0; i < setList.length; i++) {
+ for (let i = 0; i < setList.length; i++) {
effectivePool.push({set: setList[i]});
}
}
- var setData = effectivePool[this.random(effectivePool.length)];
- var moves = [];
- for (var i = 0; i < setData.set.moves.length; i++) {
- var moveSlot = setData.set.moves[i];
+ let setData = effectivePool[this.random(effectivePool.length)];
+ let moves = [];
+ for (let i = 0; i < setData.set.moves.length; i++) {
+ let moveSlot = setData.set.moves[i];
moves.push(setData.moveVariants ? moveSlot[setData.moveVariants[i]] : moveSlot[this.random(moveSlot.length)]);
}
@@ -3358,26 +3361,26 @@ exports.BattleScripts = {
},
randomFactoryTeam: function (side, depth) {
if (!depth) depth = 0;
- var forceResult = (depth >= 4);
+ let forceResult = (depth >= 4);
- var availableTiers = ['Uber', 'OU', 'UU', 'RU', 'NU', 'PU'];
- var chosenTier;
+ let availableTiers = ['Uber', 'OU', 'UU', 'RU', 'NU', 'PU'];
+ let chosenTier;
- var currentSeed = this.seed.slice();
+ let currentSeed = this.seed.slice();
this.seed = this.startingSeed.slice();
chosenTier = availableTiers[this.random(availableTiers.length)];
this.seed = currentSeed;
- var pokemonLeft = 0;
- var pokemon = [];
+ let pokemonLeft = 0;
+ let pokemon = [];
- var pokemonPool = Object.keys(this.randomFactorySets[chosenTier]);
+ let pokemonPool = Object.keys(this.randomFactorySets[chosenTier]);
- var teamData = {typeCount: {}, typeComboCount: {}, baseFormes: {}, megaCount: 0, has: {}, forceResult: forceResult, weaknesses: {}, resistances: {}};
- var requiredMoveFamilies = {'hazardSet': 1, 'hazardClear':1};
- var requiredMoves = {'stealthrock': 'hazardSet', 'rapidspin': 'hazardClear', 'defog': 'hazardClear'};
- var weatherAbilitiesSet = {'drizzle': 'raindance', 'drought': 'sunnyday', 'snowwarning': 'hail', 'sandstream': 'sandstorm'};
- var resistanceAbilities = {
+ let teamData = {typeCount: {}, typeComboCount: {}, baseFormes: {}, megaCount: 0, has: {}, forceResult: forceResult, weaknesses: {}, resistances: {}};
+ let requiredMoveFamilies = {'hazardSet': 1, 'hazardClear':1};
+ let requiredMoves = {'stealthrock': 'hazardSet', 'rapidspin': 'hazardClear', 'defog': 'hazardClear'};
+ let weatherAbilitiesSet = {'drizzle': 'raindance', 'drought': 'sunnyday', 'snowwarning': 'hail', 'sandstream': 'sandstorm'};
+ let resistanceAbilities = {
'dryskin': ['Water'], 'waterabsorb': ['Water'], 'stormdrain': ['Water'],
'flashfire': ['Fire'], 'heatproof': ['Fire'],
'lightningrod': ['Electric'], 'motordrive': ['Electric'], 'voltabsorb': ['Electric'],
@@ -3387,10 +3390,10 @@ exports.BattleScripts = {
};
while (pokemonPool.length && pokemonLeft < 6) {
- var template = this.getTemplate(this.sampleNoReplace(pokemonPool));
+ let template = this.getTemplate(this.sampleNoReplace(pokemonPool));
if (!template.exists) continue;
- var speciesFlags = this.randomFactorySets[chosenTier][template.speciesid].flags;
+ let speciesFlags = this.randomFactorySets[chosenTier][template.speciesid].flags;
// Limit to one of each species (Species Clause)
if (teamData.baseFormes[template.baseSpecies]) continue;
@@ -3399,9 +3402,9 @@ exports.BattleScripts = {
if (teamData.megaCount >= 1 && speciesFlags.megaOnly) continue;
// Limit 2 of any type
- var types = template.types;
- var skip = false;
- for (var t = 0; t < types.length; t++) {
+ let types = template.types;
+ let skip = false;
+ for (let t = 0; t < types.length; t++) {
if (teamData.typeCount[types[t]] > 1 && this.random(5)) {
skip = true;
break;
@@ -3409,11 +3412,11 @@ exports.BattleScripts = {
}
if (skip) continue;
- var set = this.randomFactorySet(template, pokemon.length, teamData, chosenTier);
+ let set = this.randomFactorySet(template, pokemon.length, teamData, chosenTier);
if (!set) continue;
// Limit 1 of any type combination
- var typeCombo = types.slice().sort().join();
+ let typeCombo = types.slice().sort().join();
if (set.ability === 'Drought' || set.ability === 'Drizzle') {
// Drought and Drizzle don't count towards the type combo limit
typeCombo = set.ability;
@@ -3425,7 +3428,7 @@ exports.BattleScripts = {
pokemonLeft++;
// Now that our Pokemon has passed all checks, we can update team data:
- for (var t = 0; t < types.length; t++) {
+ for (let t = 0; t < types.length; t++) {
if (types[t] in teamData.typeCount) {
teamData.typeCount[types[t]]++;
} else {
@@ -3436,7 +3439,7 @@ exports.BattleScripts = {
teamData.baseFormes[template.baseSpecies] = 1;
- var itemData = this.getItem(set.item);
+ let itemData = this.getItem(set.item);
if (itemData.megaStone) teamData.megaCount++;
if (itemData.id in teamData.has) {
teamData.has[itemData.id]++;
@@ -3444,13 +3447,13 @@ exports.BattleScripts = {
teamData.has[itemData.id] = 1;
}
- var abilityData = this.getAbility(set.ability);
+ let abilityData = this.getAbility(set.ability);
if (abilityData.id in weatherAbilitiesSet) {
teamData.weather = weatherAbilitiesSet[abilityData.id];
}
- for (var m = 0; m < set.moves.length; m++) {
- var moveId = toId(set.moves[m]);
+ for (let m = 0; m < set.moves.length; m++) {
+ let moveId = toId(set.moves[m]);
if (moveId in teamData.has) {
teamData.has[moveId]++;
} else {
@@ -3461,7 +3464,7 @@ exports.BattleScripts = {
}
}
- for (var typeName in this.data.TypeChart) {
+ for (let typeName in this.data.TypeChart) {
// Cover any major weakness (3+) with at least one resistance
if (teamData.resistances[typeName] >= 1) continue;
if (resistanceAbilities[abilityData.id] && resistanceAbilities[abilityData.id].indexOf(typeName) >= 0 || !this.getImmunity(typeName, types)) {
@@ -3470,7 +3473,7 @@ exports.BattleScripts = {
if (teamData.resistances[typeName] >= 1) teamData.weaknesses[typeName] = 0;
continue;
}
- var typeMod = this.getEffectiveness(typeName, types);
+ let typeMod = this.getEffectiveness(typeName, types);
if (typeMod < 0) {
teamData.resistances[typeName] = (teamData.resistances[typeName] || 0) + 1;
if (teamData.resistances[typeName] >= 1) teamData.weaknesses[typeName] = 0;
@@ -3483,10 +3486,10 @@ exports.BattleScripts = {
// Quality control
if (!teamData.forceResult) {
- for (var requiredFamily in requiredMoveFamilies) {
+ for (let requiredFamily in requiredMoveFamilies) {
if (!teamData.has[requiredFamily]) return this.randomFactoryTeam(side, ++depth);
}
- for (var type in teamData.weaknesses) {
+ for (let type in teamData.weaknesses) {
if (teamData.weaknesses[type] >= 3) return this.randomFactoryTeam(side, ++depth);
}
}
@@ -3494,17 +3497,17 @@ exports.BattleScripts = {
return pokemon;
},
randomMonotypeTeam: function (side) {
- var pokemonLeft = 0;
- var pokemon = [];
- var excludedTiers = {'LC':1, 'LC Uber':1, 'NFE':1};
- var allowedNFE = {'Chansey':1, 'Doublade':1, 'Pikachu':1, 'Porygon2':1, 'Scyther':1};
- var typePool = Object.keys(this.data.TypeChart);
- var type = typePool[this.random(typePool.length)];
+ let pokemonLeft = 0;
+ let pokemon = [];
+ let excludedTiers = {'LC':1, 'LC Uber':1, 'NFE':1};
+ let allowedNFE = {'Chansey':1, 'Doublade':1, 'Pikachu':1, 'Porygon2':1, 'Scyther':1};
+ let typePool = Object.keys(this.data.TypeChart);
+ let type = typePool[this.random(typePool.length)];
- var pokemonPool = [];
- for (var id in this.data.FormatsData) {
- var template = this.getTemplate(id);
- var types = template.types;
+ let pokemonPool = [];
+ for (let id in this.data.FormatsData) {
+ let template = this.getTemplate(id);
+ let types = template.types;
if (template.baseSpecies === 'Castform') types = ['Normal'];
if (template.speciesid === 'meloettapirouette') types = ['Normal', 'Psychic'];
if (!excludedTiers[template.tier] && types.indexOf(type) >= 0 && !template.isMega && !template.isPrimal && !template.isNonstandard && template.randomBattleMoves) {
@@ -3512,13 +3515,13 @@ exports.BattleScripts = {
}
}
- var baseFormes = {};
- var uberCount = 0;
- var puCount = 0;
- var megaCount = 0;
+ let baseFormes = {};
+ let uberCount = 0;
+ let puCount = 0;
+ let megaCount = 0;
while (pokemonPool.length && pokemonLeft < 6) {
- var template = this.getTemplate(this.sampleNoReplace(pokemonPool));
+ let template = this.getTemplate(this.sampleNoReplace(pokemonPool));
if (!template.exists) continue;
// Limit to one of each species (Species Clause)
@@ -3530,7 +3533,7 @@ exports.BattleScripts = {
// Only certain NFE Pokemon are allowed
if (template.evos.length && !allowedNFE[template.species]) continue;
- var tier = template.tier;
+ let tier = template.tier;
switch (tier) {
case 'PU':
// PUs are limited to 2 but have a 20% chance of being added anyway.
@@ -3571,14 +3574,14 @@ exports.BattleScripts = {
if (template.species !== 'Pikachu' && this.random(30) >= 1) continue;
}
- var set = this.randomSet(template, pokemon.length, megaCount);
+ let set = this.randomSet(template, pokemon.length, megaCount);
// Illusion shouldn't be on the last pokemon of the team
if (set.ability === 'Illusion' && pokemonLeft > 4) continue;
// Limit the number of Megas to one
- var forme = template.otherFormes && this.getTemplate(template.otherFormes[0]);
- var isMegaSet = this.getItem(set.item).megaStone || (forme && forme.isMega && forme.requiredMove && set.moves.indexOf(toId(forme.requiredMove)) >= 0);
+ let forme = template.otherFormes && this.getTemplate(template.otherFormes[0]);
+ let isMegaSet = this.getItem(set.item).megaStone || (forme && forme.isMega && forme.requiredMove && set.moves.indexOf(toId(forme.requiredMove)) >= 0);
if (isMegaSet && megaCount > 0) continue;
// Okay, the set passes, add it to our team
diff --git a/data/statuses.js b/data/statuses.js
index a9f96249b8..ec3d472f2c 100644
--- a/data/statuses.js
+++ b/data/statuses.js
@@ -1,3 +1,5 @@
+'use strict';
+
exports.BattleStatuses = {
brn: {
effectType: 'Status',
@@ -62,7 +64,7 @@ exports.BattleStatuses = {
onStart: function (target) {
this.add('-status', target, 'frz');
if (target.template.species === 'Shaymin-Sky' && target.baseTemplate.baseSpecies === 'Shaymin') {
- var template = this.getTemplate('Shaymin');
+ let template = this.getTemplate('Shaymin');
target.formeChange(template);
target.baseTemplate = template;
target.setAbility(template.abilities['0']);
@@ -128,7 +130,7 @@ exports.BattleStatuses = {
confusion: {
// this is a volatile status
onStart: function (target, source, sourceEffect) {
- var result = this.runEvent('TryConfusion', target, source, sourceEffect);
+ let result = this.runEvent('TryConfusion', target, source, sourceEffect);
if (!result) return result;
if (sourceEffect && sourceEffect.id === 'lockedmove') {
this.add('-start', target, 'confusion', '[fatigue]');
@@ -270,8 +272,8 @@ exports.BattleStatuses = {
if (pokemon.ignoringItem()) {
return;
}
- var moves = pokemon.moveset;
- for (var i = 0; i < moves.length; i++) {
+ let moves = pokemon.moveset;
+ for (let i = 0; i < moves.length; i++) {
if (moves[i].id !== this.effectData.move) {
pokemon.disableMove(moves[i].id, false, this.effectData.sourceEffect);
}
@@ -295,15 +297,15 @@ exports.BattleStatuses = {
// this is a side condition
onStart: function (side) {
this.effectData.positions = [];
- for (var i = 0; i < side.active.length; i++) {
+ for (let i = 0; i < side.active.length; i++) {
this.effectData.positions[i] = null;
}
},
onResidualOrder: 3,
onResidual: function (side) {
- var finished = true;
- for (var i = 0; i < side.active.length; i++) {
- var posData = this.effectData.positions[i];
+ let finished = true;
+ for (let i = 0; i < side.active.length; i++) {
+ let posData = this.effectData.positions[i];
if (!posData) continue;
posData.duration--;
@@ -314,8 +316,8 @@ exports.BattleStatuses = {
}
// time's up; time to hit! :D
- var target = side.foe.active[posData.targetPosition];
- var move = this.getMove(posData.move);
+ let target = side.foe.active[posData.targetPosition];
+ let move = this.getMove(posData.move);
if (target.fainted) {
this.add('-hint', '' + move.name + ' did not hit because the target is fainted.');
this.effectData.positions[i] = null;
@@ -367,7 +369,7 @@ exports.BattleStatuses = {
onStallMove: function () {
// this.effectData.counter should never be undefined here.
// However, just in case, use 1 if it is undefined.
- var counter = this.effectData.counter || 1;
+ let counter = this.effectData.counter || 1;
this.debug("Success chance: " + Math.round(100 / counter) + "%");
return (this.random(counter) === 0);
},
@@ -390,7 +392,7 @@ exports.BattleStatuses = {
duration: 1,
onBasePowerPriority: 8,
onBasePower: function (basePower, user, target, move) {
- var modifier = 0x1547;
+ let modifier = 0x1547;
this.debug('Aura Boost');
if (user.volatiles['aurabreak']) {
modifier = 0x0C00;
@@ -633,7 +635,7 @@ exports.BattleStatuses = {
// Hackmons.
onSwitchInPriority: 101,
onSwitchIn: function (pokemon) {
- var type = 'Normal';
+ let type = 'Normal';
if (pokemon.ability === 'multitype') {
type = pokemon.getItem().onPlate;
if (!type || type === true) {
diff --git a/dev-tools/jscs-custom-rules/validate-case-indentation.js b/dev-tools/jscs-custom-rules/validate-case-indentation.js
index 9edab6ee24..9e3fa4a5b1 100644
--- a/dev-tools/jscs-custom-rules/validate-case-indentation.js
+++ b/dev-tools/jscs-custom-rules/validate-case-indentation.js
@@ -44,7 +44,9 @@
* ```
*/
-var assert = require('assert');
+'use strict';
+
+const assert = require('assert');
module.exports = function () {};
@@ -63,10 +65,10 @@ module.exports.prototype = {
check: function (file, errors) {
file.iterateNodesByType('SwitchStatement', function (node) {
- var column = node.loc.start.column;
- var currentLine = 0;
- for (var i = 0; i < node.cases.length; i++) {
- var currentCase = node.cases[i];
+ let column = node.loc.start.column;
+ let currentLine = 0;
+ for (let i = 0; i < node.cases.length; i++) {
+ let currentCase = node.cases[i];
if (currentCase.loc.line === currentLine) continue;
currentLine = currentCase.loc.line;
if (currentCase.loc.start.column === column) continue;
diff --git a/dev-tools/jscs-custom-rules/validate-conditionals.js b/dev-tools/jscs-custom-rules/validate-conditionals.js
index 75e6164319..a5d208c12e 100644
--- a/dev-tools/jscs-custom-rules/validate-conditionals.js
+++ b/dev-tools/jscs-custom-rules/validate-conditionals.js
@@ -76,7 +76,9 @@
* ```
*/
-var assert = require('assert');
+'use strict';
+
+const assert = require('assert');
module.exports = function () {};
@@ -95,11 +97,11 @@ module.exports.prototype = {
check: function (file, errors) {
file.iterateNodesByType('IfStatement', function (node) {
- var consequent = node.consequent;
- var statementType = consequent.type;
+ let consequent = node.consequent;
+ let statementType = consequent.type;
// Either all `BlockStatement` or none.
- var subNode = node;
+ let subNode = node;
while (subNode.alternate) {
subNode = subNode.alternate;
if (subNode.type === 'IfStatement') {
@@ -121,13 +123,13 @@ module.exports.prototype = {
}
// Curly braces iff multiline
- var nodesCheck = [consequent];
+ let nodesCheck = [consequent];
if (node.alternate) nodesCheck.push(node.alternate);
- for (var i = 0; i < nodesCheck.length; i++) {
- var subNode = nodesCheck[i];
+ for (let i = 0; i < nodesCheck.length; i++) {
+ let subNode = nodesCheck[i];
if (subNode.type === 'BlockStatement') {
- var openingBrace = file.getFirstNodeToken(subNode);
- var closingBrace = file.getLastNodeToken(subNode);
+ let openingBrace = file.getFirstNodeToken(subNode);
+ let closingBrace = file.getLastNodeToken(subNode);
if (!subNode.body.length) {
// Empty block
errors.assert.differentLine({
@@ -136,8 +138,8 @@ module.exports.prototype = {
});
continue;
}
- var nextToken = file.getFirstNodeToken(subNode.body[0]);
- var prevToken = file.getPrevToken(closingBrace);
+ let nextToken = file.getFirstNodeToken(subNode.body[0]);
+ let prevToken = file.getPrevToken(closingBrace);
errors.assert.differentLine({
token: openingBrace,
@@ -151,7 +153,7 @@ module.exports.prototype = {
});
} else if (subNode.type !== 'IfStatement') {
if (subNode === consequent) {
- var token = file.getFirstNodeToken(subNode);
+ let token = file.getFirstNodeToken(subNode);
errors.assert.sameLine({
token: node.test,
nextToken: token,
diff --git a/dev-tools/users-utils.js b/dev-tools/users-utils.js
index db280c7632..94a4446744 100644
--- a/dev-tools/users-utils.js
+++ b/dev-tools/users-utils.js
@@ -1,7 +1,9 @@
-var EventEmitter = require('events').EventEmitter;
+'use strict';
+
+let EventEmitter = require('events').EventEmitter;
function createWorker() {
- var fakeWorker = new EventEmitter();
+ let fakeWorker = new EventEmitter();
fakeWorker.send = function () {};
Sockets.workers[fakeWorker.id] = fakeWorker;
return fakeWorker;
@@ -16,14 +18,14 @@ function createConnection(ip, workerid, socketid) {
socketid++;
}
}
- var connectionid = workerid + '-' + socketid;
- var connection = Users.connections[connectionid] = new Users.Connection(connectionid, Sockets.workers[workerid], socketid, null, ip || '127.0.0.1');
+ let connectionid = workerid + '-' + socketid;
+ let connection = Users.connections[connectionid] = new Users.Connection(connectionid, Sockets.workers[workerid], socketid, null, ip || '127.0.0.1');
return connection;
}
function createUser(connection) {
if (!connection) connection = createConnection();
- var user = new Users.User(connection);
+ let user = new Users.User(connection);
connection.user = user;
user.joinRoom('global', connection);
return user;
diff --git a/dnsbl.js b/dnsbl.js
index 788aade85c..16753da6e4 100644
--- a/dnsbl.js
+++ b/dnsbl.js
@@ -14,12 +14,12 @@
const BLOCKLISTS = ['sbl.spamhaus.org', 'rbl.efnetrbl.org'];
-var dns = require('dns');
+let dns = require('dns');
/* global Dnsbl: true */
-var Dnsbl = module.exports;
+let Dnsbl = module.exports;
-var dnsblCache = exports.cache = {
+let dnsblCache = exports.cache = {
'127.0.0.1': false
};
@@ -29,7 +29,7 @@ function queryDnsblLoop(ip, callback, reversedIpDot, index) {
callback(dnsblCache[ip] = false);
return;
}
- var blocklist = BLOCKLISTS[index];
+ let blocklist = BLOCKLISTS[index];
dns.resolve4(reversedIpDot + blocklist, function (err, addresses) {
if (!err) {
// blocked
@@ -53,23 +53,23 @@ exports.query = function queryDnsbl(ip, callback) {
callback(dnsblCache[ip]);
return;
}
- var reversedIpDot = ip.split('.').reverse().join('.') + '.';
+ let reversedIpDot = ip.split('.').reverse().join('.') + '.';
queryDnsblLoop(ip, callback, reversedIpDot, 0);
};
// require cidr and dns separately for ease of hotpatching
-var cidr = require('./cidr.js');
-var rangeLeaseweb = cidr.checker('207.244.64.0/18');
-var rangeLeaseweb2 = cidr.checker('209.58.128.0/18');
-var rangeLeaseweb3 = cidr.checker('103.254.152.0/22');
-var rangeVoxility = cidr.checker('5.254.64.0/20');
-var rangeCenet = cidr.checker('27.111.64.0/21');
-var rangeQlded = cidr.checker('203.104.0.0/20');
-var rangeCathednet = cidr.checker('180.95.40.0/21');
-var rangeTelefonica = cidr.checker('181.64.0.0/14');
-var rangeTelstra = cidr.checker('101.160.0.0/11');
-var rangeStarhub = cidr.checker(['27.125.128.0/18', '101.127.0.0/17', '116.88.0.0/17', '122.11.192.0/18', '182.19.128.0/17', '182.55.0.0/16', '183.90.0.0/17', '203.116.122.0/23']);
-var rangeUltrasurf = cidr.checker('65.49.0.0/17');
+let cidr = require('./cidr.js');
+let rangeLeaseweb = cidr.checker('207.244.64.0/18');
+let rangeLeaseweb2 = cidr.checker('209.58.128.0/18');
+let rangeLeaseweb3 = cidr.checker('103.254.152.0/22');
+let rangeVoxility = cidr.checker('5.254.64.0/20');
+let rangeCenet = cidr.checker('27.111.64.0/21');
+let rangeQlded = cidr.checker('203.104.0.0/20');
+let rangeCathednet = cidr.checker('180.95.40.0/21');
+let rangeTelefonica = cidr.checker('181.64.0.0/14');
+let rangeTelstra = cidr.checker('101.160.0.0/11');
+let rangeStarhub = cidr.checker(['27.125.128.0/18', '101.127.0.0/17', '116.88.0.0/17', '122.11.192.0/18', '182.19.128.0/17', '182.55.0.0/16', '183.90.0.0/17', '203.116.122.0/23']);
+let rangeUltrasurf = cidr.checker('65.49.0.0/17');
Dnsbl.reverse = function reverseDns(ip, callback) {
if (ip) {
diff --git a/gulpfile.js b/gulpfile.js
index c3d99d4bc6..bc1d90f48f 100644
--- a/gulpfile.js
+++ b/gulpfile.js
@@ -1,35 +1,28 @@
-var path = require('path');
-var util = require('util');
+'use strict';
-var gulp = require('gulp');
-var lazypipe = require('lazypipe');
-var merge = require('merge-stream');
-var cache = require('gulp-cache');
-var jscs = require('gulp-jscs');
-var jshint = require('gulp-jshint');
-var replace = require('gulp-replace');
-var CacheSwap = require('cache-swap');
-var jshintStylish = require('jshint-stylish');
+const path = require('path');
+const util = require('util');
-var fileCache = new CacheSwap({tmpDir: '', cacheDirName: 'gulp-cache'});
+const gulp = require('gulp');
+const lazypipe = require('lazypipe');
+const merge = require('merge-stream');
+const cache = require('gulp-cache');
+const jscs = require('gulp-jscs');
+const jshint = require('gulp-jshint');
+const replace = require('gulp-replace');
+const CacheSwap = require('cache-swap');
+const jshintStylish = require('jshint-stylish');
-var globals = {};
-var globalList = [
+const fileCache = new CacheSwap({tmpDir: '', cacheDirName: 'gulp-cache'});
+
+let globals = {};
+let globalList = [
'Config', 'Monitor', 'toId', 'Tools', 'LoginServer', 'Users', 'Rooms', 'Verifier',
'CommandParser', 'Simulator', 'Tournaments', 'Dnsbl', 'Cidr', 'Sockets', 'TeamValidator',
'Ladders'
];
globalList.forEach(function (identifier) {globals[identifier] = false;});
-function transformLet() {
- // Replacing `var` with `let` is sort of a hack that stops jsHint from
- // complaining that I'm using `var` like `let` should be used, but
- // without having to deal with iffy `let` support.
-
- return lazypipe()
- .pipe(replace.bind(null, /\bvar\b/g, 'let'))();
-}
-
function lint(jsHintOptions, jscsOptions) {
function cachedJsHint() {
return cache(jshint(jsHintOptions), {
@@ -47,7 +40,7 @@ function lint(jsHintOptions, jscsOptions) {
.pipe(jscs.bind(jscs, jscsOptions))();
}
-var jsHintOptions = {};
+let jsHintOptions = {};
jsHintOptions.base = {
"nonbsp": true,
"nonew": true,
@@ -76,7 +69,7 @@ jsHintOptions.test = util._extend(util._extend({}, jsHintOptions.base), {
"mocha": true
});
-var jscsOptions = {};
+let jscsOptions = {};
jscsOptions.base = {
"preset": "yandex",
@@ -160,7 +153,7 @@ jscsOptions.dataCompactAllIndented = util._extend(util._extend({}, jscsOptions.d
"validateIndentation": '\t'
});
-var lintData = [
+let lintData = [
{
dirs: ['./*.js', './tournaments/*.js', './chat-plugins/*.js', './config/!(config).js', './data/rulesets.js', './data/statuses.js'],
jsHint: jsHintOptions.base,
@@ -200,13 +193,12 @@ lintData.extra = {
}
};
-var linter = function () {
+let linter = function () {
return (
merge.apply(
null,
lintData.map(function (source) {
return gulp.src(source.dirs)
- .pipe(transformLet())
.pipe(lint(source.jsHint, source.jscs));
})
).pipe(jshint.reporter(jshintStylish))
@@ -214,11 +206,10 @@ var linter = function () {
);
};
-for (var taskName in lintData.extra) {
+for (let taskName in lintData.extra) {
gulp.task(taskName, (function (task) {
return function () {
return gulp.src(task.dirs)
- .pipe(transformLet())
.pipe(lint(task.jsHint, task.jscs))
.pipe(jshint.reporter(jshintStylish))
.pipe(jshint.reporter('fail'));
diff --git a/ladders-remote.js b/ladders-remote.js
index f8a66b5647..eca190ea7b 100644
--- a/ladders-remote.js
+++ b/ladders-remote.js
@@ -8,7 +8,7 @@
*/
/* global Ladders: true */
-var Ladders = module.exports = getLadder;
+let Ladders = Ladders.get = module.exports = getLadder;
function getLadder(formatid) {
return new Ladder(formatid);
@@ -23,8 +23,8 @@ Ladder.prototype.getTop = function () {
};
Ladder.prototype.getRating = function (userid) {
- var formatid = this.formatid;
- var user = Users.getExact(userid);
+ let formatid = this.formatid;
+ let user = Users.getExact(userid);
if (user && user.mmrCache[formatid]) {
return Promise.resolve(user.mmrCache[formatid]);
}
@@ -38,7 +38,7 @@ Ladder.prototype.getRating = function (userid) {
return resolve(1000);
}
- var mmr = parseInt(data, 10);
+ let mmr = parseInt(data, 10);
if (isNaN(mmr)) return resolve(1000);
if (user.userid !== userid) return reject(new Error("Expired rating"));
@@ -49,8 +49,8 @@ Ladder.prototype.getRating = function (userid) {
};
Ladder.prototype.updateRating = function (p1name, p2name, p1score, room) {
- var formatid = this.formatid;
- var p1rating, p2rating;
+ let formatid = this.formatid;
+ let p1rating, p2rating;
room.update();
room.send('||Ladder updating...');
LoginServer.request('ladderupdate', {
@@ -80,9 +80,9 @@ Ladder.prototype.updateRating = function (p1name, p2name, p1score, room) {
p1rating = data.p1rating;
p2rating = data.p2rating;
- var oldacre = Math.round(p1rating.oldacre);
- var acre = Math.round(p1rating.acre);
- var reasons = '' + (acre - oldacre) + ' for ' + (p1score > 0.9 ? 'winning' : (p1score < 0.1 ? 'losing' : 'tying'));
+ let oldacre = Math.round(p1rating.oldacre);
+ let acre = Math.round(p1rating.acre);
+ let reasons = '' + (acre - oldacre) + ' for ' + (p1score > 0.9 ? 'winning' : (p1score < 0.1 ? 'losing' : 'tying'));
if (reasons.charAt(0) !== '-') reasons = '+' + reasons;
room.addRaw(Tools.escapeHTML(p1name) + '\'s rating: ' + oldacre + ' →
' + acre + '(' + reasons + ')');
@@ -92,9 +92,9 @@ Ladder.prototype.updateRating = function (p1name, p2name, p1score, room) {
if (reasons.charAt(0) !== '-') reasons = '+' + reasons;
room.addRaw(Tools.escapeHTML(p2name) + '\'s rating: ' + oldacre + ' →
' + acre + '(' + reasons + ')');
- var p1 = Users.getExact(p1name);
+ let p1 = Users.getExact(p1name);
if (p1) p1.mmrCache[formatid] = +p1rating.acre;
- var p2 = Users.getExact(p2name);
+ let p2 = Users.getExact(p2name);
if (p2) p2.mmrCache[formatid] = +p2rating.acre;
room.update();
} catch (e) {
diff --git a/ladders.js b/ladders.js
index a94c186c5c..598a561077 100644
--- a/ladders.js
+++ b/ladders.js
@@ -8,10 +8,13 @@
*/
/* global Ladders: true */
-var Ladders = module.exports = getLadder;
-var fs = require('fs');
-var readline = require('readline');
+'use strict';
+
+let Ladders = module.exports = getLadder;
+
+const fs = require('fs');
+const readline = require('readline');
function getLadder(formatid) {
return new Ladder(formatid);
@@ -25,7 +28,7 @@ Ladders.formatsListPrefix = '|,LL';
// ladder is basically a 2D array representing the corresponding ladder.tsv
// with userid in front
// ladder = [[userid, elo, username, w, l, t]]
-var ladderCaches = Ladders.ladderCaches = Object.create(null);
+let ladderCaches = Ladders.ladderCaches = Object.create(null);
function Ladder(formatid) {
this.formatid = toId(formatid);
@@ -36,9 +39,9 @@ function Ladder(formatid) {
Ladder.prototype.load = function () {
// ladderCaches[formatid]
if (this.formatid in ladderCaches) {
- var cachedLadder = ladderCaches[this.formatid];
+ let cachedLadder = ladderCaches[this.formatid];
if (cachedLadder.then) {
- var self = this;
+ let self = this;
return cachedLadder.then(function (ladder) {
self.loadedLadder = ladder;
return ladder;
@@ -47,7 +50,7 @@ Ladder.prototype.load = function () {
return Promise.resolve(this.loadedLadder = cachedLadder);
}
}
- var self = this;
+ let self = this;
return (ladderCaches[this.formatid] = new Promise(function (resolve, reject) {
fs.readFile('config/ladders/' + self.formatid + '.tsv', function (err, data) {
if (err) {
@@ -56,12 +59,12 @@ Ladder.prototype.load = function () {
resolve(self.loadedLadder);
return;
}
- var ladder = [];
- var dataLines = ('' + data).split('\n');
- for (var i = 1; i < dataLines.length; i++) {
- var line = dataLines[i].trim();
+ let ladder = [];
+ let dataLines = ('' + data).split('\n');
+ for (let i = 1; i < dataLines.length; i++) {
+ let line = dataLines[i].trim();
if (!line) continue;
- var row = line.split('\t');
+ let row = line.split('\t');
ladder.push([toId(row[1]), Number(row[0]), row[1], Number(row[2]), Number(row[3]), Number(row[4]), row[5]]);
}
self.loadedLadder = ladderCaches[self.formatid] = ladder;
@@ -75,7 +78,7 @@ Ladder.prototype.save = function () {
if (this.saving) return;
this.saving = true;
if (!this.loadedLadder) {
- var self = this;
+ let self = this;
this.ladder.then(function () {
self.save();
});
@@ -85,10 +88,10 @@ Ladder.prototype.save = function () {
this.saving = false;
return;
}
- var stream = fs.createWriteStream('config/ladders/' + this.formatid + '.tsv');
+ let stream = fs.createWriteStream('config/ladders/' + this.formatid + '.tsv');
stream.write('Elo\tUsername\tW\tL\tT\tLast update\r\n');
- for (var i = 0; i < this.loadedLadder.length; i++) {
- var row = this.loadedLadder[i];
+ for (let i = 0; i < this.loadedLadder.length; i++) {
+ let row = this.loadedLadder[i];
stream.write(row.slice(1).join('\t') + '\r\n');
}
stream.end();
@@ -96,12 +99,12 @@ Ladder.prototype.save = function () {
};
Ladder.prototype.indexOfUser = function (username, createIfNeeded) {
- var userid = toId(username);
- for (var i = 0; i < this.loadedLadder.length; i++) {
+ let userid = toId(username);
+ for (let i = 0; i < this.loadedLadder.length; i++) {
if (this.loadedLadder[i][0] === userid) return i;
}
if (createIfNeeded) {
- var index = this.loadedLadder.length;
+ let index = this.loadedLadder.length;
this.loadedLadder.push([userid, 1000, username, 0, 0, 0]);
return index;
}
@@ -109,14 +112,14 @@ Ladder.prototype.indexOfUser = function (username, createIfNeeded) {
};
Ladder.prototype.getTop = function () {
- var formatid = this.formatid;
- var name = Tools.getFormat(formatid).name;
+ let formatid = this.formatid;
+ let name = Tools.getFormat(formatid).name;
return this.ladder.then(function (ladder) {
- var buf = '
' + name + ' Top 100
';
+ let buf = '
' + name + ' Top 100
';
buf += '
';
buf += '| ' + ['', 'Username', 'Elo', 'W', 'L', 'T'].join(' | ') + ' |
';
- for (var i = 0; i < ladder.length; i++) {
- var row = ladder[i];
+ for (let i = 0; i < ladder.length; i++) {
+ let row = ladder[i];
buf += '| ' + [
i + 1, row[2], '' + Math.round(row[1]) + '', row[3], row[4], row[5]
].join(' | ') + ' |
';
@@ -126,28 +129,28 @@ Ladder.prototype.getTop = function () {
};
Ladder.prototype.getRating = function (userid) {
- var formatid = this.formatid;
- var user = Users.getExact(userid);
+ let formatid = this.formatid;
+ let user = Users.getExact(userid);
if (user && user.mmrCache[formatid]) {
return Promise.resolve(user.mmrCache[formatid]);
}
- var self = this;
+ let self = this;
return this.ladder.then(function () {
if (user.userid !== userid) return;
- var index = self.indexOfUser(userid);
+ let index = self.indexOfUser(userid);
if (index < 0) return (user.mmrCache[formatid] = 1000);
return (user.mmrCache[formatid] = self.loadedLadder[index][1]);
});
};
Ladder.prototype.updateRow = function (row, score, foeElo) {
- var elo = row[1];
+ let elo = row[1];
// The K factor determines how much your Elo changes when you win or
// lose games. Larger K means more change.
// In the "original" Elo, K is constant, but it's common for K to
// get smaller as your rating goes up
- var K = 50;
+ let K = 50;
// dynamic K-scaling (optional)
if (elo < 1200) {
@@ -163,7 +166,7 @@ Ladder.prototype.updateRow = function (row, score, foeElo) {
}
// main Elo formula
- var E = 1 / (1 + Math.pow(10, (foeElo - elo) / 400));
+ let E = 1 / (1 + Math.pow(10, (foeElo - elo) / 400));
elo += K * (score - E);
if (elo < 1000) elo = 1000;
@@ -180,22 +183,22 @@ Ladder.prototype.updateRow = function (row, score, foeElo) {
};
Ladder.prototype.updateRating = function (p1name, p2name, p1score, room) {
- var formatid = this.formatid;
- var self = this;
+ let formatid = this.formatid;
+ let self = this;
this.ladder.then(function () {
if (!room.battle) {
console.log('room expired before ladder update was received');
return;
}
- var p1newElo, p2newElo;
+ let p1newElo, p2newElo;
try {
- var p1id = toId(p1name);
- var p1index = self.indexOfUser(p1name, true);
- var p1elo = self.loadedLadder[p1index][1];
+ let p1id = toId(p1name);
+ let p1index = self.indexOfUser(p1name, true);
+ let p1elo = self.loadedLadder[p1index][1];
- var p2id = toId(p2name);
- var p2index = self.indexOfUser(p2name, true);
- var p2elo = self.loadedLadder[p2index][1];
+ let p2id = toId(p2name);
+ let p2index = self.indexOfUser(p2name, true);
+ let p2elo = self.loadedLadder[p2index][1];
self.updateRow(self.loadedLadder[p1index], p1score, p2elo);
self.updateRow(self.loadedLadder[p2index], 1 - p1score, p1elo);
@@ -206,12 +209,12 @@ Ladder.prototype.updateRating = function (p1name, p2name, p1score, room) {
// console.log('L: ' + self.loadedLadder.map(r => ''+Math.round(r[1])+' '+r[2]).join('\n'));
// move p1 to its new location
- var newIndex = p1index;
+ let newIndex = p1index;
while (newIndex > 0 && self.loadedLadder[newIndex - 1][1] <= p1newElo) newIndex--;
while (newIndex === p1index || (self.loadedLadder[newIndex] && self.loadedLadder[newIndex][1] > p1newElo)) newIndex++;
// console.log('ni='+newIndex+', p1i='+p1index);
if (newIndex !== p1index && newIndex !== p1index + 1) {
- var row = self.loadedLadder.splice(p1index, 1)[0];
+ let row = self.loadedLadder.splice(p1index, 1)[0];
// adjust for removed row
if (newIndex > p1index) newIndex--;
if (p2index > p1index) p2index--;
@@ -227,14 +230,14 @@ Ladder.prototype.updateRating = function (p1name, p2name, p1score, room) {
while (newIndex === p2index || (self.loadedLadder[newIndex] && self.loadedLadder[newIndex][1] > p2newElo)) newIndex++;
// console.log('ni='+newIndex+', p2i='+p2index);
if (newIndex !== p2index && newIndex !== p2index + 1) {
- var row = self.loadedLadder.splice(p2index, 1)[0];
+ let row = self.loadedLadder.splice(p2index, 1)[0];
// adjust for removed row
if (newIndex > p2index) newIndex--;
self.loadedLadder.splice(newIndex, 0, row);
}
- var reasons = '' + (Math.round(p1newElo) - Math.round(p1elo)) + ' for ' + (p1score > 0.9 ? 'winning' : (p1score < 0.1 ? 'losing' : 'tying'));
+ let reasons = '' + (Math.round(p1newElo) - Math.round(p1elo)) + ' for ' + (p1score > 0.9 ? 'winning' : (p1score < 0.1 ? 'losing' : 'tying'));
if (reasons.charAt(0) !== '-') reasons = '+' + reasons;
room.addRaw(Tools.escapeHTML(p1name) + '\'s rating: ' + Math.round(p1elo) + ' → ' + Math.round(p1newElo) + '
(' + reasons + ')');
@@ -242,9 +245,9 @@ Ladder.prototype.updateRating = function (p1name, p2name, p1score, room) {
if (reasons.charAt(0) !== '-') reasons = '+' + reasons;
room.addRaw(Tools.escapeHTML(p2name) + '\'s rating: ' + Math.round(p2elo) + ' → ' + Math.round(p2newElo) + '
(' + reasons + ')');
- var p1 = Users.getExact(p1name);
+ let p1 = Users.getExact(p1name);
if (p1) p1.mmrCache[formatid] = +p1newElo;
- var p2 = Users.getExact(p2name);
+ let p2 = Users.getExact(p2name);
if (p2) p2.mmrCache[formatid] = +p2newElo;
self.save();
room.update();
diff --git a/loginserver.js b/loginserver.js
index 42cf5c4c1e..268e1362fc 100644
--- a/loginserver.js
+++ b/loginserver.js
@@ -7,14 +7,16 @@
* @license MIT license
*/
+'use strict';
+
const LOGIN_SERVER_TIMEOUT = 15000;
const LOGIN_SERVER_BATCH_TIME = 1000;
-var http = require("http");
-var url = require('url');
+const http = require("http");
+const url = require('url');
/* global LoginServer: true */
-var LoginServer = module.exports = (function () {
+let LoginServer = module.exports = (function () {
function LoginServer(uri) {
console.log('Creating LoginServer object for ' + uri + '...');
this.uri = uri;
@@ -34,8 +36,8 @@ var LoginServer = module.exports = (function () {
LoginServer.prototype.lastRequest = 0;
LoginServer.prototype.openRequests = 0;
- var getLoginServer = function (action) {
- var uri;
+ let getLoginServer = function (action) {
+ let uri;
if (Config.loginservers) {
uri = Config.loginservers[action] || Config.loginservers[null];
} else {
@@ -53,7 +55,7 @@ var LoginServer = module.exports = (function () {
LoginServer.request = function (action, data, callback) {
return getLoginServer(action).request(action, data, callback);
};
- var TimeoutError = LoginServer.TimeoutError = function (message) {
+ let TimeoutError = LoginServer.TimeoutError = function (message) {
Error.captureStackTrace(this, TimeoutError);
this.name = "TimeoutError";
this.message = message || "";
@@ -65,9 +67,9 @@ var LoginServer = module.exports = (function () {
return this.name + ": " + this.message;
};
- var parseJSON = function (json) {
+ let parseJSON = function (json) {
if (json[0] === ']') json = json.substr(1);
- var data = {error: null};
+ let data = {error: null};
try {
data.json = JSON.parse(json);
} catch (err) {
@@ -86,14 +88,14 @@ var LoginServer = module.exports = (function () {
return;
}
this.openRequests++;
- var dataString = '';
+ let dataString = '';
if (data) {
- for (var i in data) {
+ for (let i in data) {
dataString += '&' + i + '=' + encodeURIComponent('' + data[i]);
}
}
- var req = http.get(url.parse(this.uri + 'action.php?act=' + action + '&serverid=' + Config.serverid + '&servertoken=' + encodeURIComponent(Config.servertoken) + '&nocache=' + new Date().getTime() + dataString), function (res) {
- var buffer = '';
+ let req = http.get(url.parse(this.uri + 'action.php?act=' + action + '&serverid=' + Config.serverid + '&servertoken=' + encodeURIComponent(Config.servertoken) + '&nocache=' + new Date().getTime() + dataString), function (res) {
+ let buffer = '';
res.setEncoding('utf8');
res.on('data', function (chunk) {
@@ -101,7 +103,7 @@ var LoginServer = module.exports = (function () {
});
res.on('end', function () {
- var data = parseJSON(buffer).json;
+ let data = parseJSON(buffer).json;
setImmediate(callback, data, res.statusCode);
this.openRequests--;
});
@@ -141,36 +143,36 @@ var LoginServer = module.exports = (function () {
};
LoginServer.prototype.makeRequests = function () {
this.requestTimer = null;
- var self = this;
- var requests = this.requestQueue;
+ let self = this;
+ let requests = this.requestQueue;
this.requestQueue = [];
if (!requests.length) return;
- var requestCallbacks = [];
- for (var i = 0, len = requests.length; i < len; i++) {
- var request = requests[i];
+ let requestCallbacks = [];
+ for (let i = 0, len = requests.length; i < len; i++) {
+ let request = requests[i];
requestCallbacks[i] = request.callback;
delete request.callback;
}
this.requestStart(requests.length);
- var postData = 'serverid=' + Config.serverid + '&servertoken=' + encodeURIComponent(Config.servertoken) + '&nocache=' + new Date().getTime() + '&json=' + encodeURIComponent(JSON.stringify(requests)) + '\n';
- var requestOptions = url.parse(this.uri + 'action.php');
+ let postData = 'serverid=' + Config.serverid + '&servertoken=' + encodeURIComponent(Config.servertoken) + '&nocache=' + new Date().getTime() + '&json=' + encodeURIComponent(JSON.stringify(requests)) + '\n';
+ let requestOptions = url.parse(this.uri + 'action.php');
requestOptions.method = 'post';
requestOptions.headers = {
'Content-Type': 'application/x-www-form-urlencoded',
'Content-Length': postData.length
};
- var req = null;
- var onReqError = function onReqError(error) {
+ let req = null;
+ let onReqError = function onReqError(error) {
if (self.requestTimeoutTimer) {
clearTimeout(self.requestTimeoutTimer);
self.requestTimeoutTimer = null;
}
req.abort();
- for (var i = 0, len = requestCallbacks.length; i < len; i++) {
+ for (let i = 0, len = requestCallbacks.length; i < len; i++) {
setImmediate(requestCallbacks[i], null, null, error);
}
self.requestEnd();
@@ -181,21 +183,21 @@ var LoginServer = module.exports = (function () {
clearTimeout(self.requestTimeoutTimer);
self.requestTimeoutTimer = null;
}
- var buffer = '';
+ let buffer = '';
res.setEncoding('utf8');
res.on('data', function onData(chunk) {
buffer += chunk;
});
- var endReq = function endRequest() {
+ let endReq = function endRequest() {
if (self.requestTimeoutTimer) {
clearTimeout(self.requestTimeoutTimer);
self.requestTimeoutTimer = null;
}
//console.log('RESPONSE: ' + buffer);
- var data = parseJSON(buffer).json;
- for (var i = 0, len = requestCallbacks.length; i < len; i++) {
+ let data = parseJSON(buffer).json;
+ for (let i = 0, len = requestCallbacks.length; i < len; i++) {
if (data) {
setImmediate(requestCallbacks[i], data[i], res.statusCode);
} else {
diff --git a/mods/averagemons/scripts.js b/mods/averagemons/scripts.js
index 86c7b54c12..7ee70185f5 100644
--- a/mods/averagemons/scripts.js
+++ b/mods/averagemons/scripts.js
@@ -1,6 +1,8 @@
+'use strict';
+
exports.BattleScripts = {
init: function () {
- for (var i in this.data.Pokedex) {
+ for (let i in this.data.Pokedex) {
this.modData('Pokedex', i).baseStats = {hp:100, atk:100, def:100, spa:100, spd:100, spe:100};
}
}
diff --git a/mods/gen1/moves.js b/mods/gen1/moves.js
index b024eafecc..add3f60ee2 100644
--- a/mods/gen1/moves.js
+++ b/mods/gen1/moves.js
@@ -2,6 +2,9 @@
* A lot of Gen 1 moves have to be updated due to different mechanics.
* Some moves have had major changes, such as Bite's typing.
*/
+
+'use strict';
+
exports.BattleMovedex = {
acid: {
inherit: true,
@@ -42,7 +45,7 @@ exports.BattleMovedex = {
},
onHit: function (target, source, move) {
if (source && source !== target && move.category !== 'Physical' && move.category !== 'Special') {
- var damage = this.effectData.totalDamage;
+ let damage = this.effectData.totalDamage;
this.effectData.totalDamage += damage;
this.effectData.lastDamage = damage;
this.effectData.sourcePosition = source.position;
@@ -82,7 +85,7 @@ exports.BattleMovedex = {
return false;
}
this.add('-end', pokemon, 'Bide');
- var target = this.effectData.sourceSide.active[this.effectData.sourcePosition];
+ let target = this.effectData.sourceSide.active[this.effectData.sourcePosition];
this.moveHit(target, pokemon, 'bide', {damage: this.effectData.totalDamage * 2});
return false;
}
@@ -93,8 +96,8 @@ exports.BattleMovedex = {
if (!pokemon.hasMove('bide')) {
return;
}
- var moves = pokemon.moveset;
- for (var i = 0; i < moves.length; i++) {
+ let moves = pokemon.moveset;
+ for (let i = 0; i < moves.length; i++) {
if (moves[i].id !== 'bide') {
pokemon.disableMove(moves[i].id);
}
@@ -180,14 +183,14 @@ exports.BattleMovedex = {
noCopy: true,
onStart: function (target, source) {
this.effectData.typesData = [];
- for (var i = 0, l = target.typesData.length; i < l; i++) {
+ for (let i = 0, l = target.typesData.length; i < l; i++) {
this.effectData.typesData.push(Object.clone(target.typesData[i]));
}
this.add('-start', source, 'typechange', target.getTypes(true).join(', '), '[from] move: Conversion', '[of] ' + target);
},
onRestart: function (target, source) {
this.effectData.typesData = [];
- for (var i = 0, l = target.typesData.length; i < l; i++) {
+ for (let i = 0, l = target.typesData.length; i < l; i++) {
this.effectData.typesData.push(Object.clone(target.typesData[i]));
}
this.add('-start', source, 'typechange', target.getTypes(true).join(', '), '[from] move: Conversion', '[of] ' + target);
@@ -206,7 +209,7 @@ exports.BattleMovedex = {
// It will fail if the last move selected by the opponent has base power 0 or is not Normal or Fighting Type.
// If both are true, counter will deal twice the last damage dealt in battle, no matter what was the move.
// That means that, if opponent switches, counter will use last counter damage * 2.
- var lastUsedMove = this.getMove(target.side.lastMove);
+ let lastUsedMove = this.getMove(target.side.lastMove);
if (lastUsedMove && lastUsedMove.basePower > 0 && lastUsedMove.type in {'Normal': 1, 'Fighting': 1} && target.battle.lastDamage > 0) {
return 2 * target.battle.lastDamage;
}
@@ -245,15 +248,15 @@ exports.BattleMovedex = {
effect: {
duration: 4,
durationCallback: function (target, source, effect) {
- var duration = this.random(1, 7);
+ let duration = this.random(1, 7);
return duration;
},
onStart: function (pokemon) {
if (!this.willMove(pokemon)) {
this.effectData.duration++;
}
- var moves = pokemon.moves;
- var move = this.getMove(moves[this.random(moves.length)]);
+ let moves = pokemon.moves;
+ let move = this.getMove(moves[this.random(moves.length)]);
this.add('-start', pokemon, 'Disable', move.name);
this.effectData.move = move.id;
return;
@@ -269,8 +272,8 @@ exports.BattleMovedex = {
}
},
onDisableMove: function (pokemon) {
- var moves = pokemon.moveset;
- for (var i = 0; i < moves.length; i++) {
+ let moves = pokemon.moveset;
+ for (let i = 0; i < moves.length; i++) {
if (moves[i].id === this.effectData.move) {
pokemon.disableMove(moves[i].id);
}
@@ -392,9 +395,9 @@ exports.BattleMovedex = {
shortDesc: "Eliminates all stat changes and status.",
onHit: function (target, source) {
this.add('-clearallboost');
- for (var i = 0; i < this.sides.length; i++) {
- for (var j = 0; j < this.sides[i].active.length; j++) {
- var pokemon = this.sides[i].active[j];
+ for (let i = 0; i < this.sides.length; i++) {
+ for (let j = 0; j < this.sides[i].active.length; j++) {
+ let pokemon = this.sides[i].active[j];
pokemon.clearBoosts();
if (pokemon !== source) {
@@ -404,9 +407,9 @@ exports.BattleMovedex = {
if (pokemon.status === 'tox') {
pokemon.setStatus('psn');
}
- var volatiles = Object.keys(pokemon.volatiles);
- for (var n = 0; n < volatiles.length; n++) {
- var id = volatiles[n];
+ let volatiles = Object.keys(pokemon.volatiles);
+ for (let n = 0; n < volatiles.length; n++) {
+ let id = volatiles[n];
if (id === 'residualdmg') {
pokemon.volatiles[id].counter = 0;
} else {
@@ -456,19 +459,19 @@ exports.BattleMovedex = {
},
onAfterMoveSelfPriority: 1,
onAfterMoveSelf: function (pokemon) {
- var leecher = pokemon.side.foe.active[pokemon.volatiles['leechseed'].sourcePosition];
+ let leecher = pokemon.side.foe.active[pokemon.volatiles['leechseed'].sourcePosition];
if (!leecher || leecher.fainted || leecher.hp <= 0) {
this.debug('Nothing to leech into');
return;
}
// We check if leeched Pokémon has Toxic to increase leeched damage.
- var toxicCounter = 1;
+ let toxicCounter = 1;
if (pokemon.volatiles['residualdmg']) {
pokemon.volatiles['residualdmg'].counter++;
toxicCounter = pokemon.volatiles['residualdmg'].counter;
}
- var toLeech = this.clampIntRange(Math.floor(pokemon.maxhp / 16), 1) * toxicCounter;
- var damage = this.damage(toLeech, pokemon, leecher);
+ let toLeech = this.clampIntRange(Math.floor(pokemon.maxhp / 16), 1) * toxicCounter;
+ let damage = this.damage(toLeech, pokemon, leecher);
if (damage) this.heal(damage, leecher, pokemon);
}
}
@@ -503,19 +506,19 @@ exports.BattleMovedex = {
metronome: {
inherit: true,
onHit: function (target) {
- var moves = [];
- for (var i in exports.BattleMovedex) {
- var move = exports.BattleMovedex[i];
+ let moves = [];
+ for (let i in exports.BattleMovedex) {
+ let move = exports.BattleMovedex[i];
if (i !== move.id) continue;
if (move.isNonstandard) continue;
- var noMetronome = {
+ let noMetronome = {
metronome:1, struggle:1
};
if (!noMetronome[move.id] && move.num <= 165) {
moves.push(move.id);
}
}
- var move = '';
+ let move = '';
if (moves.length) move = moves[this.random(moves.length)];
if (!move) return false;
this.useMove(move, target);
@@ -529,10 +532,10 @@ exports.BattleMovedex = {
desc: "This move is replaced by a random move on target's moveset. The copied move has the maximum PP for that move. Ignores a target's Substitute.",
shortDesc: "A random target's move replaces this one.",
onHit: function (target, source) {
- var moveslot = source.moves.indexOf('mimic');
+ let moveslot = source.moves.indexOf('mimic');
if (moveslot < 0) return false;
- var moves = target.moves;
- var move = moves[this.random(moves.length)];
+ let moves = target.moves;
+ let move = moves[this.random(moves.length)];
if (!move) return false;
move = this.getMove(move);
source.moveset[moveslot] = {
@@ -552,7 +555,7 @@ exports.BattleMovedex = {
mirrormove: {
inherit: true,
onHit: function (pokemon) {
- var foe = pokemon.side.foe.active[0];
+ let foe = pokemon.side.foe.active[0];
if (!foe || !foe.lastMove || foe.lastMove === 'mirrormove') {
return false;
}
@@ -788,7 +791,7 @@ exports.BattleMovedex = {
if (move.category === 'Status') {
// In gen 1 it only blocks:
// poison, confusion, secondary effect confusion, stat reducing moves and Leech Seed.
- var SubBlocked = {
+ let SubBlocked = {
lockon:1, meanlook:1, mindreader:1, nightmare:1
};
if (move.status === 'psn' || move.status === 'tox' || (move.boosts && target !== source) || move.volatileStatus === 'confusion' || SubBlocked[move.id]) {
@@ -797,7 +800,7 @@ exports.BattleMovedex = {
return;
}
if (move.volatileStatus && target === source) return;
- var damage = this.getDamage(source, target, move);
+ let damage = this.getDamage(source, target, move);
if (!damage) return null;
damage = this.runEvent('SubDamage', target, source, move, damage);
if (!damage) return damage;
diff --git a/mods/gen1/rulesets.js b/mods/gen1/rulesets.js
index c34284e5f8..c863f471e3 100644
--- a/mods/gen1/rulesets.js
+++ b/mods/gen1/rulesets.js
@@ -1,9 +1,11 @@
+'use strict';
+
exports.BattleFormats = {
pokemon: {
effectType: 'Banlist',
onValidateSet: function (set, format) {
- var template = this.getTemplate(set.species);
- var problems = [];
+ let template = this.getTemplate(set.species);
+ let problems = [];
if (set.species === set.name) delete set.name;
if (template.gen > this.gen) {
@@ -12,8 +14,8 @@ exports.BattleFormats = {
problems.push(set.species + ' is not a real Pokemon.');
}
if (set.moves) {
- for (var i = 0; i < set.moves.length; i++) {
- var move = this.getMove(set.moves[i]);
+ for (let i = 0; i < set.moves.length; i++) {
+ let move = this.getMove(set.moves[i]);
if (move.gen > this.gen) {
problems.push(move.name + ' does not exist in gen ' + this.gen + '.');
} else if (move.isNonstandard) {
@@ -92,12 +94,12 @@ exports.BattleFormats = {
],
onValidateSet: function (set) {
// limit one of each move in Standard
- var moves = [];
+ let moves = [];
if (set.moves) {
- var hasMove = {};
- for (var i = 0; i < set.moves.length; i++) {
- var move = this.getMove(set.moves[i]);
- var moveid = move.id;
+ let hasMove = {};
+ for (let i = 0; i < set.moves.length; i++) {
+ let move = this.getMove(set.moves[i]);
+ let moveid = move.id;
if (hasMove[moveid]) continue;
hasMove[moveid] = true;
moves.push(set.moves[i]);
diff --git a/mods/gen1/scripts.js b/mods/gen1/scripts.js
index cefa750779..9894d9ff78 100644
--- a/mods/gen1/scripts.js
+++ b/mods/gen1/scripts.js
@@ -1,3 +1,5 @@
+'use strict';
+
/**
* Gen 1 mechanics are fairly different to those we know on current gen.
* Therefor we need to make a lot of changes to the battle engine for this game simulation.
@@ -37,8 +39,8 @@ exports.BattleScripts = {
},
// In generation 1, boosting function increases the stored modified stat and checks for opponent's status.
boostBy: function (boost) {
- var changed = false;
- for (var i in boost) {
+ let changed = false;
+ for (let i in boost) {
this.boosts[i] += boost[i];
if (this.boosts[i] > 6) {
this.boosts[i] = 6;
@@ -50,7 +52,7 @@ exports.BattleScripts = {
changed = true;
// Recalculate the modified stat
if (this.stats[i]) {
- var stat = this.template.baseStats[i];
+ let stat = this.template.baseStats[i];
stat = Math.floor(Math.floor(2 * stat + this.set.ivs[i] + Math.floor(this.set.evs[i] / 4)) * this.level / 100 + 5);
this.modifiedStats[i] = this.stats[i] = Math.floor(stat);
if (this.boosts[i] >= 0) {
@@ -94,7 +96,7 @@ exports.BattleScripts = {
}
}
pokemon.lastDamage = 0;
- var lockedMove = this.runEvent('LockMove', pokemon);
+ let lockedMove = this.runEvent('LockMove', pokemon);
if (lockedMove === true) lockedMove = false;
if (!lockedMove && (!pokemon.volatiles['partialtrappinglock'] || pokemon.volatiles['partialtrappinglock'].locked !== target)) {
pokemon.deductPP(move, null, target);
@@ -129,14 +131,14 @@ exports.BattleScripts = {
} else {
if (pokemon.volatiles['partialtrappinglock'].locked !== target && target !== pokemon) {
// The target switched, therefor, we must re-roll the duration, damage, and accuracy.
- var duration = [2, 2, 2, 3, 3, 3, 4, 5][this.random(8)];
+ let duration = [2, 2, 2, 3, 3, 3, 4, 5][this.random(8)];
pokemon.volatiles['partialtrappinglock'].duration = duration;
pokemon.volatiles['partialtrappinglock'].locked = target;
// Duration reset thus partially trapped at 2 always.
target.volatiles['partiallytrapped'].duration = 2;
// We get the move position for the PP change.
- var usedMovePos = -1;
- for (var m in pokemon.moveset) {
+ let usedMovePos = -1;
+ for (let m in pokemon.moveset) {
if (pokemon.moveset[m].id === move.id) usedMovePos = m;
}
if (usedMovePos > -1 && pokemon.moveset[usedMovePos].pp === 0) {
@@ -156,7 +158,7 @@ exports.BattleScripts = {
useMove: function (move, pokemon, target, sourceEffect) {
if (!sourceEffect && this.effect.id) sourceEffect = this.effect;
move = this.getMove(move);
- var baseMove = move;
+ let baseMove = move;
move = this.getMoveCopy(move);
if (!target) target = this.resolveTarget(pokemon, move);
if (move.target === 'self') {
@@ -178,8 +180,8 @@ exports.BattleScripts = {
}
if (!move) return false;
- var attrs = '';
- var missed = false;
+ let attrs = '';
+ let missed = false;
if (pokemon.fainted) {
// Removing screens upon faint.
pokemon.side.removeSideCondition('reflect');
@@ -205,7 +207,7 @@ exports.BattleScripts = {
move.ignoreImmunity = (move.category === 'Status');
}
- var damage = false;
+ let damage = false;
if (target.fainted) {
this.attrLastMove('[notarget]');
this.add('-notarget');
@@ -236,9 +238,9 @@ exports.BattleScripts = {
// This function attempts a move hit and returns the attempt result before the actual hit happens.
// It deals with partial trapping weirdness and accuracy bugs as well.
tryMoveHit: function (target, pokemon, move, spreadHit) {
- var boostTable = [1, 4 / 3, 5 / 3, 2, 7 / 3, 8 / 3, 3];
- var doSelfDestruct = true;
- var damage = 0;
+ let boostTable = [1, 4 / 3, 5 / 3, 2, 7 / 3, 8 / 3, 3];
+ let doSelfDestruct = true;
+ let damage = 0;
// First, check if the Pokémon is immune to this move.
if (move.ignoreImmunity !== true && !move.ignoreImmunity[move.type] && !target.runImmunity(move.type, true)) {
@@ -249,7 +251,7 @@ exports.BattleScripts = {
}
// Now, let's calculate the accuracy.
- var accuracy = move.accuracy;
+ let accuracy = move.accuracy;
// Partial trapping moves: true accuracy while it lasts
if (move.volatileStatus === 'partiallytrapped' && pokemon.volatiles['partialtrappinglock'] && target === pokemon.volatiles['partialtrappinglock'].locked) {
@@ -303,7 +305,7 @@ exports.BattleScripts = {
if (damage !== false) {
pokemon.lastDamage = 0;
if (move.multihit) {
- var hits = move.multihit;
+ let hits = move.multihit;
if (hits.length) {
// Yes, it's hardcoded... meh
if (hits[0] === 2 && hits[1] === 5) {
@@ -314,9 +316,9 @@ exports.BattleScripts = {
}
hits = Math.floor(hits);
// In gen 1, all the hits have the same damage for multihits move
- var moveDamage = 0;
- var firstDamage;
- var i;
+ let moveDamage = 0;
+ let firstDamage;
+ let i;
for (i = 0; i < hits && target.hp && pokemon.hp; i++) {
if (i === 0) {
// First hit, we calculate
@@ -370,11 +372,11 @@ exports.BattleScripts = {
// It deals with the actual move hit, as the name indicates, dealing damage and/or effects.
// This function also deals with the Gen 1 Substitute behaviour on the hitting process.
moveHit: function (target, pokemon, move, moveData, isSecondary, isSelf) {
- var damage = 0;
+ let damage = 0;
move = this.getMoveCopy(move);
if (!isSecondary && !isSelf) this.setActiveMove(move, pokemon, target);
- var hitResult = true;
+ let hitResult = true;
if (!moveData) moveData = move;
if (move.ignoreImmunity === undefined) {
@@ -382,8 +384,8 @@ exports.BattleScripts = {
}
// We get the sub to the target to see if it existed
- var targetSub = (target) ? target.volatiles['substitute'] : false;
- var targetHadSub = (targetSub !== null && targetSub !== false && (typeof targetSub !== 'undefined'));
+ let targetSub = (target) ? target.volatiles['substitute'] : false;
+ let targetHadSub = (targetSub !== null && targetSub !== false && (typeof targetSub !== 'undefined'));
if (target) {
hitResult = this.singleEvent('TryHit', moveData, {}, target, pokemon, move);
@@ -424,7 +426,7 @@ exports.BattleScripts = {
}
if (target) {
- var didSomething = false;
+ let didSomething = false;
damage = this.getDamage(pokemon, target, moveData);
@@ -476,7 +478,7 @@ exports.BattleScripts = {
}
}
if (moveData.heal && !target.fainted) {
- var d = target.heal(Math.floor(target.maxhp * moveData.heal[0] / moveData.heal[1]));
+ let d = target.heal(Math.floor(target.maxhp * moveData.heal[0] / moveData.heal[1]));
if (!d) {
this.add('-fail', target);
return false;
@@ -534,16 +536,16 @@ exports.BattleScripts = {
return false;
}
}
- var targetHasSub = false;
+ let targetHasSub = false;
if (target) {
- var targetSub = target.getVolatile('substitute');
+ let targetSub = target.getVolatile('substitute');
if (targetSub !== null) {
targetHasSub = (targetSub.hp > 0);
}
}
// Here's where self effects are applied.
- var doSelf = (targetHadSub && targetHasSub) || !targetHadSub;
+ let doSelf = (targetHadSub && targetHasSub) || !targetHadSub;
if (moveData.self && (doSelf || moveData.self.volatileStatus === 'partialtrappinglock')) {
this.moveHit(pokemon, pokemon, move, moveData.self, isSecondary, true);
}
@@ -555,13 +557,13 @@ exports.BattleScripts = {
// Apply move secondaries.
if (moveData.secondaries) {
- for (var i = 0; i < moveData.secondaries.length; i++) {
+ for (let i = 0; i < moveData.secondaries.length; i++) {
// We check here whether to negate the probable secondary status if it's para, burn, or freeze.
// In the game, this is checked and if true, the random number generator is not called.
// That means that a move that does not share the type of the target can status it.
// If a move that was not fire-type would exist on Gen 1, it could burn a Pokémon.
if (!(moveData.secondaries[i].status && moveData.secondaries[i].status in {'par':1, 'brn':1, 'frz':1} && target && target.hasType(move.type))) {
- var effectChance = Math.floor(moveData.secondaries[i].chance * 255 / 100);
+ let effectChance = Math.floor(moveData.secondaries[i].chance * 255 / 100);
if (typeof moveData.secondaries[i].chance === 'undefined' || this.random(256) < effectChance) {
this.moveHit(target, pokemon, move, moveData.secondaries[i], true, isSelf);
}
@@ -585,11 +587,11 @@ exports.BattleScripts = {
if (!target || !target.hp) return 0;
effect = this.getEffect(effect);
boost = this.runEvent('Boost', target, source, effect, Object.clone(boost));
- for (var i in boost) {
- var currentBoost = {};
+ for (let i in boost) {
+ let currentBoost = {};
currentBoost[i] = boost[i];
if (boost[i] !== 0 && target.boostBy(currentBoost)) {
- var msg = '-boost';
+ let msg = '-boost';
if (boost[i] < 0) {
msg = '-unboost';
boost[i] = -boost[i];
@@ -644,7 +646,7 @@ exports.BattleScripts = {
if (!(effect.id in {'recoil':1, 'drain':1}) && effect.effectType !== 'Status') target.battle.lastDamage = damage;
damage = target.damage(damage, source, effect);
if (source) source.lastDamage = damage;
- var name = effect.fullname;
+ let name = effect.fullname;
if (name === 'tox') name = 'psn';
switch (effect.id) {
case 'partiallytrapped':
@@ -772,10 +774,10 @@ exports.BattleScripts = {
if (!move.defensiveCategory) move.defensiveCategory = move.category;
// '???' is typeless damage: used for Struggle and Confusion etc
if (!move.type) move.type = '???';
- var type = move.type;
+ let type = move.type;
// We get the base power and apply basePowerCallback if necessary.
- var basePower = move.basePower;
+ let basePower = move.basePower;
if (move.basePowerCallback) {
basePower = move.basePowerCallback.call(this, pokemon, target, move);
}
@@ -792,7 +794,7 @@ exports.BattleScripts = {
if (!move.crit) {
// In gen 1, the critical chance is based on speed.
// First, we get the base speed, divide it by 2 and floor it. This is our current crit chance.
- var critChance = Math.floor(pokemon.template.baseStats['spe'] / 2);
+ let critChance = Math.floor(pokemon.template.baseStats['spe'] / 2);
// Now we check for focus energy volatile.
if (pokemon.volatiles['focusenergy']) {
@@ -831,15 +833,15 @@ exports.BattleScripts = {
basePower = this.clampIntRange(basePower, 1);
// We now check attacker's and defender's stats.
- var level = pokemon.level;
- var attacker = pokemon;
- var defender = target;
+ let level = pokemon.level;
+ let attacker = pokemon;
+ let defender = target;
if (move.useTargetOffensive) attacker = target;
if (move.useSourceDefensive) defender = pokemon;
- var atkType = (move.category === 'Physical') ? 'atk' : 'spa';
- var defType = (move.defensiveCategory === 'Physical') ? 'def' : 'spd';
- var attack = attacker.getStat(atkType);
- var defense = defender.getStat(defType);
+ let atkType = (move.category === 'Physical') ? 'atk' : 'spa';
+ let defType = (move.defensiveCategory === 'Physical') ? 'def' : 'spd';
+ let attack = attacker.getStat(atkType);
+ let defense = defender.getStat(defType);
// In gen 1, screen effect is applied here.
if ((defType === 'def' && defender.volatiles['reflect']) || (defType === 'spd' && defender.volatiles['lightscreen'])) {
this.debug('Screen doubling (Sp)Def');
@@ -881,7 +883,7 @@ exports.BattleScripts = {
// Let's go with the calculation now that we have what we need.
// We do it step by step just like the game does.
- var damage = level * 2;
+ let damage = level * 2;
damage = Math.floor(damage / 5);
damage += 2;
damage *= basePower;
@@ -897,7 +899,7 @@ exports.BattleScripts = {
// Type effectiveness.
// The order here is not correct, must change to check the move versus each type.
- var totalTypeMod = this.getEffectiveness(type, target);
+ let totalTypeMod = this.getEffectiveness(type, target);
// Super effective attack
if (totalTypeMod > 0) {
if (!suppressMessages) this.add('-supereffective', target);
@@ -936,25 +938,25 @@ exports.BattleScripts = {
// This is random teams making for gen 1.
// Challenge Cup or CC teams are basically fully random teams.
randomCCTeam: function (side) {
- var teamdexno = [];
- var team = [];
+ let teamdexno = [];
+ let team = [];
- var hasDexNumber = {};
- var formes = [[], [], [], [], [], []];
+ let hasDexNumber = {};
+ let formes = [[], [], [], [], [], []];
// Pick six random Pokémon, no repeats.
- var num;
- for (var i = 0; i < 6; i++) {
+ let num;
+ for (let i = 0; i < 6; i++) {
do {
num = this.random(151) + 1;
} while (num in hasDexNumber);
hasDexNumber[num] = i;
}
- var formeCounter = 0;
- for (var id in this.data.Pokedex) {
+ let formeCounter = 0;
+ for (let id in this.data.Pokedex) {
if (!(this.data.Pokedex[id].num in hasDexNumber)) continue;
- var template = this.getTemplate(id);
+ let template = this.getTemplate(id);
if (!template.learnset || template.forme) continue;
formes[hasDexNumber[template.num]].push(template.species);
if (++formeCounter >= 6) {
@@ -963,24 +965,24 @@ exports.BattleScripts = {
}
}
- for (var i = 0; i < 6; i++) {
+ for (let i = 0; i < 6; i++) {
// Choose forme.
- var poke = formes[i][this.random(formes[i].length)];
- var template = this.getTemplate(poke);
+ let poke = formes[i][this.random(formes[i].length)];
+ let template = this.getTemplate(poke);
// Level balance: calculate directly from stats rather than using some silly lookup table.
- var mbstmin = 1307;
- var stats = template.baseStats;
+ let mbstmin = 1307;
+ let stats = template.baseStats;
// Modified base stat total assumes 15 DVs, 255 EVs in every stat
- var mbst = (stats["hp"] * 2 + 30 + 63 + 100) + 10;
+ let mbst = (stats["hp"] * 2 + 30 + 63 + 100) + 10;
mbst += (stats["atk"] * 2 + 30 + 63 + 100) + 5;
mbst += (stats["def"] * 2 + 30 + 63 + 100) + 5;
mbst += (stats["spa"] * 2 + 30 + 63 + 100) + 5;
mbst += (stats["spd"] * 2 + 30 + 63 + 100) + 5;
mbst += (stats["spe"] * 2 + 30 + 63 + 100) + 5;
- var level = Math.floor(100 * mbstmin / mbst); // Initial level guess will underestimate
+ let level = Math.floor(100 * mbstmin / mbst); // Initial level guess will underestimate
while (level < 100) {
mbst = Math.floor((stats["hp"] * 2 + 30 + 63 + 100) * level / 100 + 10);
@@ -995,7 +997,7 @@ exports.BattleScripts = {
}
// Random DVs.
- var ivs = {
+ let ivs = {
hp: this.random(30),
atk: this.random(30),
def: this.random(30),
@@ -1005,13 +1007,13 @@ exports.BattleScripts = {
};
// Maxed EVs.
- var evs = {hp: 255, atk: 255, def: 255, spa: 255, spd: 255, spe: 255};
+ let evs = {hp: 255, atk: 255, def: 255, spa: 255, spd: 255, spe: 255};
// Four random unique moves from movepool. don't worry about "attacking" or "viable".
// Since Gens 1 and 2 learnsets are shared, we need to weed out Gen 2 moves.
- var moves;
- var pool = [];
- for (var move in template.learnset) {
+ let moves;
+ let pool = [];
+ for (let move in template.learnset) {
if (this.getMove(move).gen === 1) pool.push(move);
}
if (pool.length <= 4) {
@@ -1039,35 +1041,35 @@ exports.BattleScripts = {
// Random team generation for Gen 1 Random Battles.
randomTeam: function (side) {
// Get what we need ready.
- var pokemonLeft = 0;
- var pokemon = [];
+ let pokemonLeft = 0;
+ let pokemon = [];
- var handicapMons = {'magikarp':1, 'weedle':1, 'kakuna':1, 'caterpie':1, 'metapod':1, 'ditto':1};
- var nuTiers = {'UU':1, 'BL':1, 'NFE':1, 'LC':1};
- var uuTiers = {'NFE':1, 'UU':1, 'BL':1};
+ let handicapMons = {'magikarp':1, 'weedle':1, 'kakuna':1, 'caterpie':1, 'metapod':1, 'ditto':1};
+ let nuTiers = {'UU':1, 'BL':1, 'NFE':1, 'LC':1};
+ let uuTiers = {'NFE':1, 'UU':1, 'BL':1};
- var n = 1;
- var pokemonPool = [];
- for (var id in this.data.FormatsData) {
+ let n = 1;
+ let pokemonPool = [];
+ for (let id in this.data.FormatsData) {
// FIXME: Not ES-compliant
if (n++ > 151 || !this.data.FormatsData[id].randomBattleMoves) continue;
pokemonPool.push(id);
}
// Now let's store what we are getting.
- var typeCount = {};
- var weaknessCount = {'Electric':0, 'Psychic':0, 'Water':0, 'Ice':0};
- var uberCount = 0;
- var nuCount = 0;
- var hasShitmon = false;
+ let typeCount = {};
+ let weaknessCount = {'Electric':0, 'Psychic':0, 'Water':0, 'Ice':0};
+ let uberCount = 0;
+ let nuCount = 0;
+ let hasShitmon = false;
while (pokemonPool.length && pokemonLeft < 6) {
- var template = this.getTemplate(this.sampleNoReplace(pokemonPool));
+ let template = this.getTemplate(this.sampleNoReplace(pokemonPool));
if (!template.exists) continue;
// Bias the tiers so you get less shitmons and only one of the two Ubers.
// If you have a shitmon, you're covered in OUs and Ubers if possible
- var tier = template.tier;
+ let tier = template.tier;
switch (tier) {
case 'LC':
if (nuCount > 1 || hasShitmon) continue;
@@ -1080,12 +1082,12 @@ exports.BattleScripts = {
if (uuTiers[tier] && (hasShitmon || (nuCount > 2 && this.random(2) >= 1))) continue;
}
- var skip = false;
+ let skip = false;
// Limit 2 of any type as well. Diversity and minor weakness count.
// The second of a same type has halved chance of being added.
- var types = template.types;
- for (var t = 0; t < types.length; t++) {
+ let types = template.types;
+ for (let t = 0; t < types.length; t++) {
if (typeCount[types[t]] > 1 || (typeCount[types[t]] === 1 && this.random(2))) {
skip = true;
break;
@@ -1095,9 +1097,9 @@ exports.BattleScripts = {
// We need a weakness count of spammable attacks to avoid being swept by those.
// Spammable attacks are: Thunderbolt, Psychic, Surf, Blizzard.
- var pokemonWeaknesses = [];
- for (var type in weaknessCount) {
- var increaseCount = Tools.getImmunity(type, template) && Tools.getEffectiveness(type, template) > 0;
+ let pokemonWeaknesses = [];
+ for (let type in weaknessCount) {
+ let increaseCount = Tools.getImmunity(type, template) && Tools.getEffectiveness(type, template) > 0;
if (!increaseCount) continue;
if (weaknessCount[type] >= 2) {
skip = true;
@@ -1109,14 +1111,14 @@ exports.BattleScripts = {
if (skip) continue;
// The set passes the limitations.
- var set = this.randomSet(template, pokemon.length);
+ let set = this.randomSet(template, pokemon.length);
pokemon.push(set);
// Now let's increase the counters. First, the Pokémon left.
pokemonLeft++;
// Type counter.
- for (var t = 0; t < types.length; t++) {
+ for (let t = 0; t < types.length; t++) {
if (typeCount[types[t]]) {
typeCount[types[t]]++;
} else {
@@ -1125,7 +1127,7 @@ exports.BattleScripts = {
}
// Weakness counter.
- for (var t = 0; t < pokemonWeaknesses.length; t++) {
+ for (let t = 0; t < pokemonWeaknesses.length; t++) {
weaknessCount[pokemonWeaknesses[t]]++;
}
@@ -1148,21 +1150,21 @@ exports.BattleScripts = {
template = this.getTemplate(template);
if (!template.exists) template = this.getTemplate('pikachu'); // Because Gen 1.
- var movePool = template.randomBattleMoves.slice();
- var moves = [];
- var hasType = {};
+ let movePool = template.randomBattleMoves.slice();
+ let moves = [];
+ let hasType = {};
hasType[template.types[0]] = true;
if (template.types[1]) hasType[template.types[1]] = true;
- var hasMove = {};
- var counter = {};
- var setupType = '';
+ let hasMove = {};
+ let counter = {};
+ let setupType = '';
// Moves that boost Attack:
- var PhysicalSetup = {
+ let PhysicalSetup = {
swordsdance:1, sharpen:1
};
// Moves which boost Special Attack:
- var SpecialSetup = {
+ let SpecialSetup = {
amnesia:1, growth:1
};
@@ -1173,7 +1175,7 @@ exports.BattleScripts = {
do {
// Choose next 4 moves from learnset/viable moves and add them to moves list:
while (moves.length < 4 && movePool.length) {
- var moveid = this.sampleNoReplace(movePool);
+ let moveid = this.sampleNoReplace(movePool);
moves.push(moveid);
}
@@ -1181,9 +1183,9 @@ exports.BattleScripts = {
if (movePool.length) {
hasMove = {};
counter = {Physical: 0, Special: 0, Status: 0, physicalsetup: 0, specialsetup: 0};
- for (var k = 0; k < moves.length; k++) {
- var move = this.getMove(moves[k]);
- var moveid = move.id;
+ for (let k = 0; k < moves.length; k++) {
+ let move = this.getMove(moves[k]);
+ let moveid = move.id;
hasMove[moveid] = true;
if (!move.damage && !move.damageCallback) {
counter[move.category]++;
@@ -1202,14 +1204,14 @@ exports.BattleScripts = {
setupType = 'Physical';
}
- for (var k = 0; k < moves.length; k++) {
- var moveid = moves[k];
+ for (let k = 0; k < moves.length; k++) {
+ let moveid = moves[k];
if (moveid === template.essentialMove) continue;
- var move = this.getMove(moveid);
- var rejected = false;
+ let move = this.getMove(moveid);
+ let rejected = false;
if (hasMove[moveid]) rejected = true;
if (!template.essentialMove || moveid !== template.essentialMove) {
- var isSetup = false;
+ let isSetup = false;
switch (moveid) {
// bad after setup
@@ -1326,7 +1328,7 @@ exports.BattleScripts = {
} // End of the check for more than 4 moves on moveset.
} while (moves.length < 4 && movePool.length);
- var levelScale = {
+ let levelScale = {
LC: 96,
NFE: 90,
NU: 90,
@@ -1335,12 +1337,12 @@ exports.BattleScripts = {
Uber: 74
};
// Really bad Pokemon and jokemons, MEWTWO, Pokémon with higher tier in Wrap metas.
- var customScale = {
+ let customScale = {
Caterpie: 99, Kakuna: 99, Magikarp: 99, Metapod: 99, Weedle: 99,
Clefairy: 95, "Farfetch'd": 99, Jigglypuff: 99, Ditto: 99, Mewtwo: 70,
Dragonite: 85, Cloyster: 83, Staryu: 90
};
- var level = levelScale[template.tier] || 90;
+ let level = levelScale[template.tier] || 90;
if (customScale[template.name]) level = customScale[template.name];
if (template.name === 'Mewtwo' && hasMove['amnesia']) level = 68;
diff --git a/mods/gen1/statuses.js b/mods/gen1/statuses.js
index 8675d622ac..ad58fe800b 100644
--- a/mods/gen1/statuses.js
+++ b/mods/gen1/statuses.js
@@ -7,6 +7,9 @@
* separated as volatile statuses that are applied on switch in, removed
* under certain conditions and re-applied under other conditions.
*/
+
+'use strict';
+
exports.BattleStatuses = {
brn: {
effectType: 'Status',
@@ -16,7 +19,7 @@ exports.BattleStatuses = {
},
onAfterMoveSelfPriority: 2,
onAfterMoveSelf: function (pokemon) {
- var toxicCounter = 1;
+ let toxicCounter = 1;
if (pokemon.volatiles['residualdmg']) {
pokemon.volatiles['residualdmg'].counter++;
toxicCounter = pokemon.volatiles['residualdmg'].counter;
@@ -99,7 +102,7 @@ exports.BattleStatuses = {
},
onAfterMoveSelfPriority: 2,
onAfterMoveSelf: function (pokemon) {
- var toxicCounter = 1;
+ let toxicCounter = 1;
if (pokemon.volatiles['residualdmg']) {
pokemon.volatiles['residualdmg'].counter++;
toxicCounter = pokemon.volatiles['residualdmg'].counter;
@@ -133,7 +136,7 @@ exports.BattleStatuses = {
confusion: {
// this is a volatile status
onStart: function (target, source, sourceEffect) {
- var result = this.runEvent('TryConfusion');
+ let result = this.runEvent('TryConfusion');
if (!result) return result;
if (sourceEffect && sourceEffect.id === 'lockedmove') {
this.add('-start', target, 'confusion', '[silent]');
@@ -154,7 +157,7 @@ exports.BattleStatuses = {
this.add('-activate', pokemon, 'confusion');
if (this.random(256) >= 128) {
// We check here to implement the substitute bug since otherwise we need to change directDamage to take target.
- var damage = Math.floor(Math.floor(((Math.floor(2 * pokemon.level / 5) + 2) * pokemon.getStat('atk') * 40) / pokemon.getStat('def', false, false, true)) / 50) + 2;
+ let damage = Math.floor(Math.floor(((Math.floor(2 * pokemon.level / 5) + 2) * pokemon.getStat('atk') * 40) / pokemon.getStat('def', false, false, true)) / 50) + 2;
if (pokemon.volatiles['substitute']) {
// If there is Substitute, we check for opposing substitute.
if (target.volatiles['substitute']) {
@@ -214,7 +217,7 @@ exports.BattleStatuses = {
},
partialtrappinglock: {
durationCallback: function () {
- var duration = [2, 2, 2, 3, 3, 3, 4, 5][this.random(8)];
+ let duration = [2, 2, 2, 3, 3, 3, 4, 5][this.random(8)];
return duration;
},
onResidual: function (target) {
@@ -229,8 +232,8 @@ exports.BattleStatuses = {
if (!pokemon.hasMove(this.effectData.move)) {
return;
}
- var moves = pokemon.moveset;
- for (var i = 0; i < moves.length; i++) {
+ let moves = pokemon.moveset;
+ for (let i = 0; i < moves.length; i++) {
if (moves[i].id !== this.effectData.move) {
moves[i].disabled = true;
}
@@ -248,15 +251,15 @@ exports.BattleStatuses = {
// this is a side condition
onStart: function (side) {
this.effectData.positions = [];
- for (var i = 0; i < side.active.length; i++) {
+ for (let i = 0; i < side.active.length; i++) {
this.effectData.positions[i] = null;
}
},
onResidualOrder: 3,
onResidual: function (side) {
- var finished = true;
- for (var i = 0; i < side.active.length; i++) {
- var posData = this.effectData.positions[i];
+ let finished = true;
+ for (let i = 0; i < side.active.length; i++) {
+ let posData = this.effectData.positions[i];
if (!posData) continue;
posData.duration--;
@@ -267,8 +270,8 @@ exports.BattleStatuses = {
}
// time's up; time to hit! :D
- var target = side.foe.active[posData.targetPosition];
- var move = this.getMove(posData.move);
+ let target = side.foe.active[posData.targetPosition];
+ let move = this.getMove(posData.move);
if (target.fainted) {
this.add('-hint', '' + move.name + ' did not hit because the target is fainted.');
this.effectData.positions[i] = null;
@@ -302,7 +305,7 @@ exports.BattleStatuses = {
onStallMove: function () {
// this.effectData.counter should never be undefined here.
// However, just in case, use 1 if it is undefined.
- var counter = this.effectData.counter || 1;
+ let counter = this.effectData.counter || 1;
if (counter >= 256) {
// 2^32 - special-cased because Battle.random(n) can't handle n > 2^16 - 1
return (this.random() * 4294967296 < 1);
diff --git a/mods/gen2/items.js b/mods/gen2/items.js
index 5113b98ac6..b6382ec1de 100644
--- a/mods/gen2/items.js
+++ b/mods/gen2/items.js
@@ -1,3 +1,5 @@
+'use strict';
+
exports.BattleItems = {
amuletcoin: {
id: "amuletcoin",
@@ -55,13 +57,13 @@ exports.BattleItems = {
leppaberry: {
inherit: true,
onEat: function (pokemon) {
- var move;
+ let move;
if (pokemon.volatiles['leppaberry']) {
move = pokemon.volatiles['leppaberry'].move;
pokemon.removeVolatile('leppaberry');
} else {
- var pp = 99;
- for (var i in pokemon.moveset) {
+ let pp = 99;
+ for (let i in pokemon.moveset) {
if (pokemon.moveset[i].pp < pp) {
move = pokemon.moveset[i];
pp = move.pp;
diff --git a/mods/gen2/moves.js b/mods/gen2/moves.js
index 0084399d1f..f6da5244be 100644
--- a/mods/gen2/moves.js
+++ b/mods/gen2/moves.js
@@ -1,6 +1,9 @@
/**
* Gen 2 moves
*/
+
+'use strict';
+
exports.BattleMovedex = {
aeroblast: {
inherit: true,
@@ -69,8 +72,8 @@ exports.BattleMovedex = {
return this.random(3, 7);
},
onStart: function (target) {
- var noEncore = {encore:1, metronome:1, mimic:1, mirrormove:1, sketch:1, sleeptalk:1, struggle:1, transform:1};
- var moveIndex = target.moves.indexOf(target.lastMove);
+ let noEncore = {encore:1, metronome:1, mimic:1, mirrormove:1, sketch:1, sleeptalk:1, struggle:1, transform:1};
+ let moveIndex = target.moves.indexOf(target.lastMove);
if (!target.lastMove || noEncore[target.lastMove] || (target.moveset[moveIndex] && target.moveset[moveIndex].pp <= 0)) {
// it failed
this.add('-fail', target);
@@ -101,7 +104,7 @@ exports.BattleMovedex = {
if (!this.effectData.move || !pokemon.hasMove(this.effectData.move)) {
return;
}
- for (var i = 0; i < pokemon.moveset.length; i++) {
+ for (let i = 0; i < pokemon.moveset.length; i++) {
if (pokemon.moveset[i].id !== this.effectData.move) {
pokemon.disableMove(pokemon.moveset[i].id);
}
@@ -148,7 +151,7 @@ exports.BattleMovedex = {
inherit: true,
onMoveFail: function (target, source, move) {
if (target.runImmunity('Fighting')) {
- var damage = this.getDamage(source, target, move, true);
+ let damage = this.getDamage(source, target, move, true);
this.damage(this.clampIntRange(damage / 8, 1), source, source, 'highjumpkick');
}
}
@@ -157,7 +160,7 @@ exports.BattleMovedex = {
inherit: true,
onMoveFail: function (target, source, move) {
if (target.runImmunity('Fighting')) {
- var damage = this.getDamage(source, target, move, true);
+ let damage = this.getDamage(source, target, move, true);
this.damage(this.clampIntRange(damage / 8, 1), source, source, 'jumpkick');
}
}
@@ -174,13 +177,13 @@ exports.BattleMovedex = {
this.add('-start', target, 'move: Leech Seed');
},
onAfterMoveSelf: function (pokemon) {
- var leecher = pokemon.side.foe.active[pokemon.volatiles['leechseed'].sourcePosition];
+ let leecher = pokemon.side.foe.active[pokemon.volatiles['leechseed'].sourcePosition];
if (!leecher || leecher.fainted || leecher.hp <= 0) {
this.debug('Nothing to leech into');
return;
}
- var toLeech = this.clampIntRange(pokemon.maxhp / 8, 1);
- var damage = this.damage(toLeech, pokemon, leecher);
+ let toLeech = this.clampIntRange(pokemon.maxhp / 8, 1);
+ let damage = this.damage(toLeech, pokemon, leecher);
if (damage) {
this.heal(damage, leecher, pokemon);
}
@@ -218,19 +221,19 @@ exports.BattleMovedex = {
metronome: {
inherit: true,
onHit: function (target) {
- var moves = [];
- for (var i in exports.BattleMovedex) {
- var move = exports.BattleMovedex[i];
+ let moves = [];
+ for (let i in exports.BattleMovedex) {
+ let move = exports.BattleMovedex[i];
if (i !== move.id) continue;
if (move.isNonstandard) continue;
- var noMetronome = {
+ let noMetronome = {
counter:1, destinybond:1, detect:1, endure:1, metronome:1, mimic:1, mirrorcoat:1, protect:1, sketch:1, sleeptalk:1, struggle:1, thief:1
};
if (!noMetronome[move.id] && move.num < 252) {
moves.push(move.id);
}
}
- var move = '';
+ let move = '';
if (moves.length) move = moves[this.random(moves.length)];
if (!move) return false;
this.useMove(move, target);
@@ -267,8 +270,8 @@ exports.BattleMovedex = {
mirrormove: {
inherit: true,
onHit: function (pokemon) {
- var noMirror = {metronome: 1, mimic: 1, mirrormove: 1, sketch: 1, sleeptalk: 1, transform: 1};
- var foe = pokemon.side.foe.active[0];
+ let noMirror = {metronome: 1, mimic: 1, mirrormove: 1, sketch: 1, sleeptalk: 1, transform: 1};
+ let foe = pokemon.side.foe.active[0];
if (!foe || !foe.lastMove || (!pokemon.activeTurns && !foe.moveThisTurn) || noMirror[foe.lastMove] || pokemon.moves.indexOf(foe.lastMove) >= 0) {
return false;
}
@@ -383,7 +386,7 @@ exports.BattleMovedex = {
roar: {
inherit: true,
onTryHit: function () {
- for (var i = 0; i < this.queue.length; i++) {
+ for (let i = 0; i < this.queue.length; i++) {
// Roar only works if it is the last action in a turn, including when it's called by Sleep Talk
if (this.queue[i].choice === 'move' || this.queue[i].choice === 'switch') return false;
}
@@ -414,10 +417,10 @@ exports.BattleMovedex = {
sleeptalk: {
inherit: true,
onHit: function (pokemon) {
- var moves = [];
- for (var i = 0; i < pokemon.moveset.length; i++) {
- var move = pokemon.moveset[i].id;
- var NoSleepTalk = {
+ let moves = [];
+ for (let i = 0; i < pokemon.moveset.length; i++) {
+ let move = pokemon.moveset[i].id;
+ let NoSleepTalk = {
bide:1, dig:1, fly:1, metronome:1, mirrormove:1,
skullbash:1, skyattack:1, sleeptalk:1, solarbeam:1, razorwind:1
};
@@ -425,7 +428,7 @@ exports.BattleMovedex = {
moves.push(move);
}
}
- var move = '';
+ let move = '';
if (moves.length) move = moves[this.random(moves.length)];
if (!move) return false;
move.isSleepTalk = true;
@@ -454,10 +457,10 @@ exports.BattleMovedex = {
}
},
onSwitchIn: function (pokemon) {
- var side = pokemon.side;
+ let side = pokemon.side;
if (!pokemon.runImmunity('Ground')) return;
- var damageAmounts = [0, 3];
- var damage = this.damage(damageAmounts[this.effectData.layers] * pokemon.maxhp / 24);
+ let damageAmounts = [0, 3];
+ let damage = this.damage(damageAmounts[this.effectData.layers] * pokemon.maxhp / 24);
}
}
},
@@ -485,7 +488,7 @@ exports.BattleMovedex = {
return null;
}
if (move.category === 'Status') {
- var SubBlocked = {
+ let SubBlocked = {
leechseed:1, lockon:1, mindreader:1, nightmare:1, painsplit:1, sketch:1
};
if (move.id === 'swagger') {
@@ -498,7 +501,7 @@ exports.BattleMovedex = {
}
return;
}
- var damage = this.getDamage(source, target, move);
+ let damage = this.getDamage(source, target, move);
if (!damage) {
return null;
}
@@ -567,7 +570,7 @@ exports.BattleMovedex = {
chance: 20,
onHit: function (target, source) {
if (!target.hasType('Normal')) {
- var result = this.random(3);
+ let result = this.random(3);
if (result === 0) {
target.trySetStatus('brn', source);
} else if (result === 1) {
@@ -582,7 +585,7 @@ exports.BattleMovedex = {
whirlwind: {
inherit: true,
onTryHit: function () {
- for (var i = 0; i < this.queue.length; i++) {
+ for (let i = 0; i < this.queue.length; i++) {
// Whirlwind only works if it is the last action in a turn, including when it's called by Sleep Talk
if (this.queue[i].choice === 'move' || this.queue[i].choice === 'switch') return false;
}
diff --git a/mods/gen2/rulesets.js b/mods/gen2/rulesets.js
index a7c25d221a..e384431285 100644
--- a/mods/gen2/rulesets.js
+++ b/mods/gen2/rulesets.js
@@ -1,9 +1,11 @@
+'use strict';
+
exports.BattleFormats = {
pokemon: {
effectType: 'Banlist',
onValidateSet: function (set, format) {
- var template = this.getTemplate(set.species);
- var problems = [];
+ let template = this.getTemplate(set.species);
+ let problems = [];
if (set.species === set.name) delete set.name;
if (template.gen > this.gen) {
@@ -11,10 +13,10 @@ exports.BattleFormats = {
} else if (template.isNonstandard) {
problems.push(set.species + ' is not a real Pokemon.');
}
- var hasHP = false;
- var hasSD = false;
+ let hasHP = false;
+ let hasSD = false;
if (set.item) {
- var item = this.getItem(set.item);
+ let item = this.getItem(set.item);
if (item.gen > this.gen) {
problems.push(item.name + ' does not exist in gen ' + this.gen + '.');
} else if (item.isNonstandard) {
@@ -22,8 +24,8 @@ exports.BattleFormats = {
}
}
if (set.moves) {
- for (var i = 0; i < set.moves.length; i++) {
- var move = this.getMove(set.moves[i]);
+ for (let i = 0; i < set.moves.length; i++) {
+ let move = this.getMove(set.moves[i]);
if (move.gen > this.gen) {
problems.push(move.name + ' does not exist in gen ' + this.gen + '.');
} else if (move.isNonstandard) {
@@ -54,7 +56,7 @@ exports.BattleFormats = {
if (!set.ivs) {
set.ivs = {hp: 30, atk: 30, def: 30, spa: 30, spd: 30, spe: 30};
} else {
- for (var iv in set.ivs) {
+ for (let iv in set.ivs) {
// Since Gen 2 has 0-15 DVs that increase 2 points, we only want pair numbers
if (set.ivs[iv] % 2 !== 0) set.ivs[iv]--;
// This shouldn't even be possible
@@ -66,7 +68,7 @@ exports.BattleFormats = {
// Calculate all the IV oddness on gen 2.
// If you use Marowak with Thick Club, we'll be gentle enough to deal with your Attack DVs.
// This is only done because the gen 6 Teambuilder is confusing, using IVs and all.
- var marowakClub = false;
+ let marowakClub = false;
if (toId(set.item) === 'thickclub' && set.species === 'Marowak' && hasSD) {
set.ivs.atk = 26;
marowakClub = true;
@@ -130,12 +132,12 @@ exports.BattleFormats = {
],
onValidateSet: function (set) {
// limit one of each move in Standard
- var moves = [];
+ let moves = [];
if (set.moves) {
- var hasMove = {};
- for (var i = 0; i < set.moves.length; i++) {
- var move = this.getMove(set.moves[i]);
- var moveid = move.id;
+ let hasMove = {};
+ for (let i = 0; i < set.moves.length; i++) {
+ let move = this.getMove(set.moves[i]);
+ let moveid = move.id;
if (hasMove[moveid]) continue;
hasMove[moveid] = true;
moves.push(set.moves[i]);
diff --git a/mods/gen2/scripts.js b/mods/gen2/scripts.js
index 6585f1473d..8f08a6be6e 100644
--- a/mods/gen2/scripts.js
+++ b/mods/gen2/scripts.js
@@ -1,3 +1,5 @@
+'use strict';
+
/**
* Gen 2 scripts.
*/
@@ -11,24 +13,24 @@ exports.BattleScripts = {
if (statName === 'hp') return this.maxhp;
// base stat
- var stat = this.stats[statName];
+ let stat = this.stats[statName];
// Stat boosts.
if (!unboosted) {
- var boost = this.boosts[statName];
+ let boost = this.boosts[statName];
if (boost > 6) boost = 6;
if (boost < -6) boost = -6;
if (boost >= 0) {
- var boostTable = [1, 1.5, 2, 2.5, 3, 3.5, 4];
+ let boostTable = [1, 1.5, 2, 2.5, 3, 3.5, 4];
stat = Math.floor(stat * boostTable[boost]);
} else {
- var numerators = [100, 66, 50, 40, 33, 28, 25];
+ let numerators = [100, 66, 50, 40, 33, 28, 25];
stat = Math.floor(stat * numerators[-boost] / 100);
}
// On Gen 2 we check modifications here from moves and items
- var statTable = {atk:'Atk', def:'Def', spa:'SpA', spd:'SpD', spe:'Spe'};
- var statMod = 1;
+ let statTable = {atk:'Atk', def:'Def', spa:'SpA', spd:'SpD', spe:'Spe'};
+ let statMod = 1;
statMod = this.battle.runEvent('Modify' + statTable[statName], this, null, null, statMod);
stat = this.battle.modify(stat, statMod);
}
@@ -57,7 +59,7 @@ exports.BattleScripts = {
// Battle scripts.
runMove: function (move, pokemon, target, sourceEffect) {
if (!sourceEffect && toId(move) !== 'struggle') {
- var changedMove = this.runEvent('OverrideDecision', pokemon, target, move);
+ let changedMove = this.runEvent('OverrideDecision', pokemon, target, move);
if (changedMove && changedMove !== true) {
move = changedMove;
target = null;
@@ -93,7 +95,7 @@ exports.BattleScripts = {
}
}
pokemon.lastDamage = 0;
- var lockedMove = this.runEvent('LockMove', pokemon);
+ let lockedMove = this.runEvent('LockMove', pokemon);
if (lockedMove === true) lockedMove = false;
if (!lockedMove) {
if (!pokemon.deductPP(move, null, target) && (move.id !== 'struggle')) {
@@ -108,11 +110,11 @@ exports.BattleScripts = {
if (!move.selfSwitch && target.hp > 0) this.runEvent('AfterMoveSelf', pokemon, target, move);
},
moveHit: function (target, pokemon, move, moveData, isSecondary, isSelf) {
- var damage;
+ let damage;
move = this.getMoveCopy(move);
if (!moveData) moveData = move;
- var hitResult = true;
+ let hitResult = true;
if (move.target === 'all' && !isSelf) {
hitResult = this.singleEvent('TryHitField', moveData, {}, target, pokemon, move);
@@ -142,7 +144,7 @@ exports.BattleScripts = {
}
if (target) {
- var didSomething = false;
+ let didSomething = false;
damage = this.getDamage(pokemon, target, moveData);
if ((damage || damage === 0) && !target.fainted) {
@@ -169,7 +171,7 @@ exports.BattleScripts = {
didSomething = didSomething || hitResult;
}
if (moveData.heal && !target.fainted) {
- var d = target.heal(Math.round(target.maxhp * moveData.heal[0] / moveData.heal[1]));
+ let d = target.heal(Math.round(target.maxhp * moveData.heal[0] / moveData.heal[1]));
if (!d && d !== 0) {
this.add('-fail', target);
this.debug('heal interrupted');
@@ -242,7 +244,7 @@ exports.BattleScripts = {
}
}
if (moveData.self) {
- var selfRoll;
+ let selfRoll;
if (!isSecondary && moveData.self.boosts) selfRoll = this.random(100);
// This is done solely to mimic in-game RNG behaviour. All self drops have a 100% chance of happening but still grab a random number.
if (typeof moveData.self.chance === 'undefined' || selfRoll < moveData.self.chance) {
@@ -250,14 +252,14 @@ exports.BattleScripts = {
}
}
if (moveData.secondaries && this.runEvent('TrySecondaryHit', target, pokemon, moveData)) {
- for (var i = 0; i < moveData.secondaries.length; i++) {
+ for (let i = 0; i < moveData.secondaries.length; i++) {
// We check here whether to negate the probable secondary status if it's burn or freeze.
// In the game, this is checked and if true, the random number generator is not called.
// That means that a move that does not share the type of the target can status it.
// This means tri-attack can burn fire-types and freeze ice-types.
// Unlike gen 1, though, paralysis works for all unless the target is immune to direct move (ie. ground-types and t-wave).
if (!(moveData.secondaries[i].status && moveData.secondaries[i].status in {'brn':1, 'frz':1} && target && target.hasType(move.type))) {
- var effectChance = Math.floor(moveData.secondaries[i].chance * 255 / 100);
+ let effectChance = Math.floor(moveData.secondaries[i].chance * 255 / 100);
if (typeof moveData.secondaries[i].chance === 'undefined' || this.random(256) <= effectChance) {
this.moveHit(target, pokemon, move, moveData.secondaries[i], true, isSelf);
}
@@ -319,10 +321,10 @@ exports.BattleScripts = {
if (!move.defensiveCategory) move.defensiveCategory = move.category;
// '???' is typeless damage: used for Struggle and Confusion etc
if (!move.type) move.type = '???';
- var type = move.type;
+ let type = move.type;
// We get the base power and apply basePowerCallback if necessary
- var basePower = move.basePower;
+ let basePower = move.basePower;
if (move.basePowerCallback) {
basePower = move.basePowerCallback.call(this, pokemon, target, move);
}
@@ -336,7 +338,7 @@ exports.BattleScripts = {
// Checking for the move's Critical Hit ratio
move.critRatio = this.clampIntRange(move.critRatio, 0, 5);
- var critMult = [0, 16, 8, 4, 3, 2];
+ let critMult = [0, 16, 8, 4, 3, 2];
move.crit = move.willCrit || false;
if (typeof move.willCrit === 'undefined') {
if (move.critRatio) {
@@ -359,15 +361,15 @@ exports.BattleScripts = {
basePower = this.clampIntRange(basePower, 1);
// We now check for attacker and defender
- var level = pokemon.level;
- var attacker = pokemon;
- var defender = target;
+ let level = pokemon.level;
+ let attacker = pokemon;
+ let defender = target;
if (move.useTargetOffensive) attacker = target;
if (move.useSourceDefensive) defender = pokemon;
- var atkType = (move.category === 'Physical') ? 'atk' : 'spa';
- var defType = (move.defensiveCategory === 'Physical') ? 'def' : 'spd';
- var unboosted = false;
- var noburndrop = false;
+ let atkType = (move.category === 'Physical') ? 'atk' : 'spa';
+ let defType = (move.defensiveCategory === 'Physical') ? 'def' : 'spd';
+ let unboosted = false;
+ let noburndrop = false;
// The move is a critical hit. Several things happen here.
if (move.crit) {
@@ -384,8 +386,8 @@ exports.BattleScripts = {
}
}
// Get stats now.
- var attack = attacker.getStat(atkType, unboosted, noburndrop);
- var defense = defender.getStat(defType, unboosted);
+ let attack = attacker.getStat(atkType, unboosted, noburndrop);
+ let defense = defender.getStat(defType, unboosted);
// Moves that ignore offense and defense respectively.
if (move.ignoreOffensive) {
@@ -412,7 +414,7 @@ exports.BattleScripts = {
// Let's go with the calculation now that we have what we need.
// We do it step by step just like the game does.
- var damage = level * 2;
+ let damage = level * 2;
damage = Math.floor(damage / 5);
damage += 2;
damage *= basePower;
@@ -427,7 +429,7 @@ exports.BattleScripts = {
}
// Type effectiveness
- var totalTypeMod = this.getEffectiveness(type, target);
+ let totalTypeMod = this.getEffectiveness(type, target);
// Super effective attack
if (totalTypeMod > 0) {
if (!suppressMessages) this.add('-supereffective', target);
@@ -489,7 +491,7 @@ exports.BattleScripts = {
if (damage !== 0) damage = this.clampIntRange(damage, 1);
damage = target.damage(damage, source, effect);
if (source) source.lastDamage = damage;
- var name = effect.fullname;
+ let name = effect.fullname;
if (name === 'tox') name = 'psn';
switch (effect.id) {
case 'partiallytrapped':
@@ -521,34 +523,34 @@ exports.BattleScripts = {
return damage;
},
randomTeam: function (side) {
- var pokemonLeft = 0;
- var pokemon = [];
+ let pokemonLeft = 0;
+ let pokemon = [];
- var handicapMons = {'magikarp':1, 'weedle':1, 'kakuna':1, 'caterpie':1, 'metapod':1, 'ditto':1};
- var nuTiers = {'UU':1, 'BL':1, 'NFE':1, 'LC':1};
- var uuTiers = {'NFE':1, 'UU':1, 'BL':1};
+ let handicapMons = {'magikarp':1, 'weedle':1, 'kakuna':1, 'caterpie':1, 'metapod':1, 'ditto':1};
+ let nuTiers = {'UU':1, 'BL':1, 'NFE':1, 'LC':1};
+ let uuTiers = {'NFE':1, 'UU':1, 'BL':1};
- var n = 1;
- var pokemonPool = [];
- for (var id in this.data.FormatsData) {
+ let n = 1;
+ let pokemonPool = [];
+ for (let id in this.data.FormatsData) {
// FIXME: Not ES-compliant
if (n++ > 251 || !this.data.FormatsData[id].randomBattleMoves) continue;
pokemonPool.push(id);
}
// Setup storage.
- var typeCount = {};
- var uberCount = 0;
- var nuCount = 0;
- var hasShitmon = false;
+ let typeCount = {};
+ let uberCount = 0;
+ let nuCount = 0;
+ let hasShitmon = false;
while (pokemonPool.length && pokemonLeft < 6) {
- var template = this.getTemplate(this.sampleNoReplace(pokemonPool));
+ let template = this.getTemplate(this.sampleNoReplace(pokemonPool));
if (!template.exists) continue;
// Bias the tiers so you get less shitmons and only one of the two Ubers.
// If you have a shitmon, you're covered in OUs and Ubers if possible
- var tier = template.tier;
+ let tier = template.tier;
switch (tier) {
case 'LC':
if (nuCount > 1 || hasShitmon) continue;
@@ -563,9 +565,9 @@ exports.BattleScripts = {
// Limit 2 of any type. Diversity and minor weakness count.
// The second of a same type has halved chance of being added.
- var types = template.types;
- var skip = false;
- for (var t = 0; t < types.length; t++) {
+ let types = template.types;
+ let skip = false;
+ for (let t = 0; t < types.length; t++) {
if (typeCount[types[t]] > 1 || (typeCount[types[t]] === 1 && this.random(2) >= 1)) {
skip = true;
break;
@@ -574,14 +576,14 @@ exports.BattleScripts = {
if (skip) continue;
// The set passes the limitations.
- var set = this.randomSet(template, pokemon.length);
+ let set = this.randomSet(template, pokemon.length);
pokemon.push(set);
// Now let's increase the counters. First, the Pokémon left.
pokemonLeft++;
// Type counter.
- for (var t = 0; t < types.length; t++) {
+ for (let t = 0; t < types.length; t++) {
if (typeCount[types[t]]) {
typeCount[types[t]]++;
} else {
@@ -608,30 +610,30 @@ exports.BattleScripts = {
template = this.getTemplate(template);
if (!template.exists) template = this.getTemplate('unown');
- var movePool = template.randomBattleMoves.slice();
- var moves = [];
- var hasType = {};
+ let movePool = template.randomBattleMoves.slice();
+ let moves = [];
+ let hasType = {};
hasType[template.types[0]] = true;
if (template.types[1]) hasType[template.types[1]] = true;
- var hasMove = {};
- var counter = {};
- var setupType = '';
- var item = 'leftovers';
- var ivs = {hp: 30, atk: 30, def: 30, spa: 30, spd: 30, spe: 30};
+ let hasMove = {};
+ let counter = {};
+ let setupType = '';
+ let item = 'leftovers';
+ let ivs = {hp: 30, atk: 30, def: 30, spa: 30, spd: 30, spe: 30};
// Moves that boost Attack:
- var PhysicalSetup = {
+ let PhysicalSetup = {
swordsdance:1, sharpen:1
};
// Moves which boost Special Attack:
- var SpecialSetup = {
+ let SpecialSetup = {
amnesia:1, growth:1
};
do {
// Keep track of all moves we have:
hasMove = {};
- for (var k = 0; k < moves.length; k++) {
+ for (let k = 0; k < moves.length; k++) {
if (moves[k].substr(0, 11) === 'hiddenpower') {
hasMove['hiddenpower'] = true;
} else {
@@ -641,7 +643,7 @@ exports.BattleScripts = {
// Choose next 4 moves from learnset/viable moves and add them to moves list:
while (moves.length < 4 && movePool.length) {
- var moveid = this.sampleNoReplace(movePool);
+ let moveid = this.sampleNoReplace(movePool);
if (moveid.substr(0, 11) === 'hiddenpower') {
if (hasMove['hiddenpower']) continue;
hasMove['hiddenpower'] = true;
@@ -652,9 +654,9 @@ exports.BattleScripts = {
}
counter = {Physical: 0, Special: 0, Status: 0, physicalsetup: 0, specialsetup: 0};
- for (var k = 0; k < moves.length; k++) {
- var move = this.getMove(moves[k]);
- var moveid = move.id;
+ for (let k = 0; k < moves.length; k++) {
+ let move = this.getMove(moves[k]);
+ let moveid = move.id;
if (!move.damage && !move.damageCallback) {
counter[move.category]++;
}
@@ -672,20 +674,20 @@ exports.BattleScripts = {
setupType = 'Physical';
}
- for (var k = 0; k < moves.length; k++) {
- var moveid = moves[k];
- var move = this.getMove(moveid);
- var rejected = false;
+ for (let k = 0; k < moves.length; k++) {
+ let moveid = moves[k];
+ let move = this.getMove(moveid);
+ let rejected = false;
if (moveid.substr(0, 11) === 'hiddenpower') {
// Check for hidden power DVs
- var HPivs = this.getType(move.type).HPivs;
- for (var iv in HPivs) {
+ let HPivs = this.getType(move.type).HPivs;
+ for (let iv in HPivs) {
ivs[iv] = HPivs[iv];
}
moveid = 'hiddenpower';
}
if (!template.essentialMove || moveid !== template.essentialMove) {
- var isSetup = false;
+ let isSetup = false;
switch (moveid) {
// bad after setup
@@ -810,7 +812,7 @@ exports.BattleScripts = {
break;
}
- var levelScale = {
+ let levelScale = {
LC: 96,
NFE: 90,
UU: 85,
@@ -819,12 +821,12 @@ exports.BattleScripts = {
Uber: 74
};
// Hollistic judgment.
- var customScale = {
+ let customScale = {
Caterpie: 99, Kakuna: 99, Magikarp: 99, Metapod: 99, Weedle: 99, Pichu: 99, Smoochum: 99,
Clefairy: 95, "Farfetch'd": 99, Igglybuff: 99, Jigglypuff: 99, Ditto: 99, Mewtwo: 70,
Dragonite: 85, Cloyster: 83, Staryu: 90
};
- var level = levelScale[template.tier] || 90;
+ let level = levelScale[template.tier] || 90;
if (customScale[template.name]) level = customScale[template.name];
return {
diff --git a/mods/gen2/statuses.js b/mods/gen2/statuses.js
index 20fbdab02b..2e69c0babd 100644
--- a/mods/gen2/statuses.js
+++ b/mods/gen2/statuses.js
@@ -1,3 +1,5 @@
+'use strict';
+
exports.BattleStatuses = {
brn: {
effectType: 'Status',
@@ -93,7 +95,7 @@ exports.BattleStatuses = {
confusion: {
inherit: true,
onStart: function (target, source, sourceEffect) {
- var result = this.runEvent('TryConfusion', target, source, sourceEffect);
+ let result = this.runEvent('TryConfusion', target, source, sourceEffect);
if (!result) return result;
if (sourceEffect && sourceEffect.id === 'lockedmove') {
this.add('-start', target, 'confusion', '[silent]');
@@ -149,7 +151,7 @@ exports.BattleStatuses = {
return this.effectData.move;
},
onBeforeTurn: function (pokemon) {
- var move = this.getMove(this.effectData.move);
+ let move = this.getMove(this.effectData.move);
if (move.id) {
this.debug('Forcing into ' + move.id);
this.changeDecision(pokemon, {move: move.id});
@@ -170,7 +172,7 @@ exports.BattleStatuses = {
},
onStallMove: function () {
// Gen 2 starts counting at x=255, x/256 and then halves x on every turn
- var counter = this.effectData.counter || 255;
+ let counter = this.effectData.counter || 255;
this.debug("Success chance: " + Math.round(counter / 256) + "% (" + counter + "/256)");
return (this.random(counter) === 0);
},
diff --git a/mods/gen3/abilities.js b/mods/gen3/abilities.js
index bc09e114f8..7d2fdb7075 100644
--- a/mods/gen3/abilities.js
+++ b/mods/gen3/abilities.js
@@ -1,3 +1,5 @@
+'use strict';
+
exports.BattleAbilities = {
"cutecharm": {
inherit: true,
@@ -13,7 +15,7 @@ exports.BattleAbilities = {
inherit: true,
onAfterDamage: function (damage, target, source, move) {
if (move && move.flags['contact'] && !source.status) {
- var r = this.random(300);
+ let r = this.random(300);
if (r < 10) {
source.setStatus('slp');
} else if (r < 20) {
@@ -119,7 +121,7 @@ exports.BattleAbilities = {
inherit: true,
onAfterSetStatus: function (status, target, source) {
if (!source || source === target) return;
- var id = status.id;
+ let id = status.id;
if (id === 'slp' || id === 'frz') return;
if (id === 'tox') id = 'psn';
source.trySetStatus(id);
@@ -128,10 +130,10 @@ exports.BattleAbilities = {
"trace": {
inherit: true,
onUpdate: function (pokemon) {
- var target = pokemon.side.foe.randomActive();
+ let target = pokemon.side.foe.randomActive();
if (!target || target.fainted) return;
- var ability = this.getAbility(target.ability);
- var bannedAbilities = {forecast:1, multitype:1, trace:1};
+ let ability = this.getAbility(target.ability);
+ let bannedAbilities = {forecast:1, multitype:1, trace:1};
if (bannedAbilities[target.ability]) {
return;
}
diff --git a/mods/gen3/moves.js b/mods/gen3/moves.js
index 42f0598a75..6ca3d74a60 100644
--- a/mods/gen3/moves.js
+++ b/mods/gen3/moves.js
@@ -1,6 +1,9 @@
/**
* Gen 3 moves
*/
+
+'use strict';
+
exports.BattleMovedex = {
absorb: {
inherit: true,
@@ -23,13 +26,13 @@ exports.BattleMovedex = {
inherit: true,
desc: "The user performs a random move from any of the Pokemon on its team. Assist cannot generate itself, Chatter, Copycat, Counter, Covet, Destiny Bond, Detect, Endure, Feint, Focus Punch, Follow Me, Helping Hand, Me First, Metronome, Mimic, Mirror Coat, Mirror Move, Protect, Sketch, Sleep Talk, Snatch, Struggle, Switcheroo, Thief or Trick.",
onHit: function (target) {
- var moves = [];
- for (var j = 0; j < target.side.pokemon.length; j++) {
- var pokemon = target.side.pokemon[j];
+ let moves = [];
+ for (let j = 0; j < target.side.pokemon.length; j++) {
+ let pokemon = target.side.pokemon[j];
if (pokemon === target) continue;
- for (var i = 0; i < pokemon.moves.length; i++) {
- var move = pokemon.moves[i];
- var noAssist = {
+ for (let i = 0; i < pokemon.moves.length; i++) {
+ let move = pokemon.moves[i];
+ let noAssist = {
assist:1, chatter:1, copycat:1, counter:1, covet:1, destinybond:1, detect:1, endure:1, feint:1, focuspunch:1, followme:1, helpinghand:1, mefirst:1, metronome:1, mimic:1, mirrorcoat:1, mirrormove:1, protect:1, sketch:1, sleeptalk:1, snatch:1, struggle:1, switcheroo:1, thief:1, trick:1
};
if (move && !noAssist[move]) {
@@ -37,7 +40,7 @@ exports.BattleMovedex = {
}
}
}
- var move = '';
+ let move = '';
if (moves.length) move = moves[this.random(moves.length)];
if (!move) {
return false;
@@ -154,8 +157,8 @@ exports.BattleMovedex = {
if (!pokemon.lastMove) {
return false;
}
- var moves = pokemon.moveset;
- for (var i = 0; i < moves.length; i++) {
+ let moves = pokemon.moveset;
+ for (let i = 0; i < moves.length; i++) {
if (moves[i].id === pokemon.lastMove) {
if (!moves[i].pp) {
return false;
@@ -178,8 +181,8 @@ exports.BattleMovedex = {
}
},
onDisableMove: function (pokemon) {
- var moves = pokemon.moveset;
- for (var i = 0; i < moves.length; i++) {
+ let moves = pokemon.moveset;
+ for (let i = 0; i < moves.length; i++) {
if (moves[i].id === this.effectData.move) {
pokemon.disableMove(moves[i].id);
}
@@ -215,8 +218,8 @@ exports.BattleMovedex = {
return this.random(3, 7);
},
onStart: function (target) {
- var noEncore = {encore:1, mimic:1, mirrormove:1, sketch:1, struggle:1, transform:1};
- var moveIndex = target.moves.indexOf(target.lastMove);
+ let noEncore = {encore:1, mimic:1, mirrormove:1, sketch:1, struggle:1, transform:1};
+ let moveIndex = target.moves.indexOf(target.lastMove);
if (!target.lastMove || noEncore[target.lastMove] || (target.moveset[moveIndex] && target.moveset[moveIndex].pp <= 0)) {
// it failed
this.add('-fail', target);
@@ -247,7 +250,7 @@ exports.BattleMovedex = {
if (!this.effectData.move || !pokemon.hasMove(this.effectData.move)) {
return;
}
- for (var i = 0; i < pokemon.moveset.length; i++) {
+ for (let i = 0; i < pokemon.moveset.length; i++) {
if (pokemon.moveset[i].id !== this.effectData.move) {
pokemon.disableMove(pokemon.moveset[i].id);
}
@@ -287,7 +290,7 @@ exports.BattleMovedex = {
flail: {
inherit: true,
basePowerCallback: function (pokemon, target) {
- var ratio = pokemon.hp * 48 / pokemon.maxhp;
+ let ratio = pokemon.hp * 48 / pokemon.maxhp;
if (ratio < 2) {
return 200;
}
@@ -368,7 +371,7 @@ exports.BattleMovedex = {
category: "Physical",
onModifyMove: function (move, pokemon) {
move.type = pokemon.hpType || 'Dark';
- var specialTypes = {Fire:1, Water:1, Grass:1, Ice:1, Electric:1, Dark:1, Psychic:1, Dragon:1};
+ let specialTypes = {Fire:1, Water:1, Grass:1, Ice:1, Electric:1, Dark:1, Psychic:1, Dragon:1};
move.category = specialTypes[move.type] ? 'Special' : 'Physical';
}
},
@@ -378,7 +381,7 @@ exports.BattleMovedex = {
pp: 20,
onMoveFail: function (target, source, move) {
if (target.runImmunity('Fighting')) {
- var damage = this.getDamage(source, target, move, true);
+ let damage = this.getDamage(source, target, move, true);
this.damage(this.clampIntRange(damage / 2, 1, Math.floor(target.maxhp / 2)), source, source, 'highjumpkick');
}
}
@@ -397,7 +400,7 @@ exports.BattleMovedex = {
pp: 25,
onMoveFail: function (target, source, move) {
if (target.runImmunity('Fighting')) {
- var damage = this.getDamage(source, target, move, true);
+ let damage = this.getDamage(source, target, move, true);
this.damage(this.clampIntRange(damage / 2, 1, Math.floor(target.maxhp / 2)), source, source, 'jumpkick');
}
}
@@ -413,19 +416,19 @@ exports.BattleMovedex = {
metronome: {
inherit: true,
onHit: function (target) {
- var moves = [];
- for (var i in exports.BattleMovedex) {
- var move = exports.BattleMovedex[i];
+ let moves = [];
+ for (let i in exports.BattleMovedex) {
+ let move = exports.BattleMovedex[i];
if (i !== move.id) continue;
if (move.isNonstandard) continue;
- var noMetronome = {
+ let noMetronome = {
assist:1, counter:1, covet:1, destinybond:1, detect:1, endure:1, focuspunch:1, followme:1, helpinghand:1, metronome:1, mimic:1, mirrorcoat:1, mirrormove:1, protect:1, sketch:1, sleeptalk:1, snatch:1, struggle:1, thief:1, trick:1
};
if (!noMetronome[move.id] && move.num < 355) {
moves.push(move.id);
}
}
- var move = '';
+ let move = '';
if (moves.length) move = moves[this.random(moves.length)];
if (!move) return false;
this.useMove(move, target);
@@ -441,7 +444,7 @@ exports.BattleMovedex = {
inherit: true,
onTryHit: function () { },
onHit: function (pokemon) {
- var noMirror = {assist:1, curse:1, doomdesire:1, focuspunch:1, futuresight:1, magiccoat:1, metronome:1, mimic:1, mirrormove:1, naturepower:1, psychup:1, roleplay:1, sketch:1, sleeptalk:1, spikes:1, spitup:1, taunt:1, teeterdance:1, transform:1};
+ let noMirror = {assist:1, curse:1, doomdesire:1, focuspunch:1, futuresight:1, magiccoat:1, metronome:1, mimic:1, mirrormove:1, naturepower:1, psychup:1, roleplay:1, sketch:1, sleeptalk:1, spikes:1, spitup:1, taunt:1, teeterdance:1, transform:1};
if (!pokemon.lastAttackedBy || !pokemon.lastAttackedBy.pokemon.lastMove || noMirror[pokemon.lastAttackedBy.move] || !pokemon.lastAttackedBy.pokemon.hasMove(pokemon.lastAttackedBy.move)) {
return false;
}
@@ -523,7 +526,7 @@ exports.BattleMovedex = {
reversal: {
inherit: true,
basePowerCallback: function (pokemon, target) {
- var ratio = pokemon.hp * 48 / pokemon.maxhp;
+ let ratio = pokemon.hp * 48 / pokemon.maxhp;
if (ratio < 2) {
return 200;
}
@@ -570,8 +573,8 @@ exports.BattleMovedex = {
skillswap: {
inherit: true,
onHit: function (target, source) {
- var targetAbility = this.getAbility(target.ability);
- var sourceAbility = this.getAbility(source.ability);
+ let targetAbility = this.getAbility(target.ability);
+ let sourceAbility = this.getAbility(source.ability);
if (targetAbility.id === sourceAbility.id) {
return false;
}
@@ -598,7 +601,7 @@ exports.BattleMovedex = {
inherit: true,
flags: {protect: 1, mirror: 1, authentic: 1},
onHit: function (target) {
- var roll = this.random(2, 6);
+ let roll = this.random(2, 6);
if (target.deductPP(target.lastMove, roll)) {
this.add("-activate", target, 'move: Spite', target.lastMove, roll);
return;
@@ -670,8 +673,8 @@ exports.BattleMovedex = {
this.add('-end', target, 'move: Taunt', '[silent]');
},
onDisableMove: function (pokemon) {
- var moves = pokemon.moveset;
- for (var i = 0; i < moves.length; i++) {
+ let moves = pokemon.moveset;
+ for (let i = 0; i < moves.length; i++) {
if (this.getMove(moves[i].move).category === 'Status') {
pokemon.disableMove(moves[i].id);
}
@@ -757,10 +760,10 @@ exports.BattleMovedex = {
duration: 2,
onResidualOrder: 0,
onEnd: function (side) {
- var target = side.active[this.effectData.sourcePosition];
+ let target = side.active[this.effectData.sourcePosition];
if (!target.fainted) {
- var source = this.effectData.source;
- var damage = this.heal(target.maxhp / 2, target, target);
+ let source = this.effectData.source;
+ let damage = this.heal(target.maxhp / 2, target, target);
if (damage) this.add('-heal', target, target.getHealth, '[from] move: Wish', '[wisher] ' + source.name);
}
}
diff --git a/mods/gen3/scripts.js b/mods/gen3/scripts.js
index f0505cb1d3..57ee6cb282 100644
--- a/mods/gen3/scripts.js
+++ b/mods/gen3/scripts.js
@@ -1,13 +1,15 @@
+'use strict';
+
exports.BattleScripts = {
inherit: 'gen5',
gen: 3,
init: function () {
- for (var i in this.data.Pokedex) {
+ for (let i in this.data.Pokedex) {
delete this.data.Pokedex[i].abilities['H'];
}
- var specialTypes = {Fire:1, Water:1, Grass:1, Ice:1, Electric:1, Dark:1, Psychic:1, Dragon:1};
- var newCategory = '';
- for (var i in this.data.Movedex) {
+ let specialTypes = {Fire:1, Water:1, Grass:1, Ice:1, Electric:1, Dark:1, Psychic:1, Dragon:1};
+ let newCategory = '';
+ for (let i in this.data.Movedex) {
if (this.data.Movedex[i].category === 'Status') continue;
newCategory = specialTypes[this.data.Movedex[i].type] ? 'Special' : 'Physical';
if (newCategory !== this.data.Movedex[i].category) {
diff --git a/mods/gen4/abilities.js b/mods/gen4/abilities.js
index 983d2c0871..47ee1573be 100644
--- a/mods/gen4/abilities.js
+++ b/mods/gen4/abilities.js
@@ -1,3 +1,5 @@
+'use strict';
+
exports.BattleAbilities = {
"angerpoint": {
inherit: true,
@@ -27,14 +29,14 @@ exports.BattleAbilities = {
"forewarn": {
inherit: true,
onStart: function (pokemon) {
- var targets = pokemon.side.foe.active;
- var warnMoves = [];
- var warnBp = 1;
- for (var i = 0; i < targets.length; i++) {
+ let targets = pokemon.side.foe.active;
+ let warnMoves = [];
+ let warnBp = 1;
+ for (let i = 0; i < targets.length; i++) {
if (targets[i].fainted) continue;
- for (var j = 0; j < targets[i].moveset.length; j++) {
- var move = this.getMove(targets[i].moveset[j].move);
- var bp = move.basePower;
+ for (let j = 0; j < targets[i].moveset.length; j++) {
+ let move = this.getMove(targets[i].moveset[j].move);
+ let bp = move.basePower;
if (move.ohko) bp = 160;
if (move.id === 'counter' || move.id === 'metalburst' || move.id === 'mirrorcoat') bp = 120;
if (!bp && move.category !== 'Status') bp = 80;
@@ -47,7 +49,7 @@ exports.BattleAbilities = {
}
}
if (!warnMoves.length) return;
- var warnMove = warnMoves[this.random(warnMoves.length)];
+ let warnMove = warnMoves[this.random(warnMoves.length)];
this.add('-activate', pokemon, 'ability: Forewarn', warnMove);
}
},
@@ -90,11 +92,11 @@ exports.BattleAbilities = {
desc: "This Pokemon's Special Attack receives a 50% boost in double battles if its partner has the Plus ability.",
shortDesc: "If an ally has the Plus Ability, this Pokemon's Sp. Atk is 1.5x.",
onModifySpA: function (spa, pokemon) {
- var allyActive = pokemon.side.active;
+ let allyActive = pokemon.side.active;
if (allyActive.length === 1) {
return;
}
- for (var i = 0; i < allyActive.length; i++) {
+ for (let i = 0; i < allyActive.length; i++) {
if (allyActive[i] && allyActive[i].position !== pokemon.position && !allyActive[i].fainted && allyActive[i].ability === 'plus') {
return spa * 1.5;
}
@@ -126,11 +128,11 @@ exports.BattleAbilities = {
desc: "This Pokemon's Special Attack receives a 50% boost in double battles if its partner has the Minus ability.",
shortDesc: "If an ally has the Minus Ability, this Pokemon's Sp. Atk is 1.5x.",
onModifySpA: function (spa, pokemon) {
- var allyActive = pokemon.side.active;
+ let allyActive = pokemon.side.active;
if (allyActive.length === 1) {
return;
}
- for (var i = 0; i < allyActive.length; i++) {
+ for (let i = 0; i < allyActive.length; i++) {
if (allyActive[i] && allyActive[i].position !== pokemon.position && !allyActive[i].fainted && allyActive[i].ability === 'minus') {
return spa * 1.5;
}
@@ -159,7 +161,7 @@ exports.BattleAbilities = {
"simple": {
shortDesc: "If this Pokemon's stat stages are raised or lowered, the effect is doubled instead.",
onModifyBoost: function (boosts) {
- for (var key in boosts) {
+ for (let key in boosts) {
boosts[key] *= 2;
}
},
@@ -192,7 +194,7 @@ exports.BattleAbilities = {
onAfterSetStatus: function (status, target, source, effect) {
if (!source || source === target) return;
if (effect && effect.id === 'toxicspikes') return;
- var id = status.id;
+ let id = status.id;
if (id === 'slp' || id === 'frz') return;
if (id === 'tox') id = 'psn';
source.trySetStatus(id);
@@ -201,10 +203,10 @@ exports.BattleAbilities = {
"trace": {
inherit: true,
onUpdate: function (pokemon) {
- var target = pokemon.side.foe.randomActive();
+ let target = pokemon.side.foe.randomActive();
if (!target || target.fainted) return;
- var ability = this.getAbility(target.ability);
- var bannedAbilities = {forecast:1, multitype:1, trace:1};
+ let ability = this.getAbility(target.ability);
+ let bannedAbilities = {forecast:1, multitype:1, trace:1};
if (bannedAbilities[target.ability]) {
return;
}
diff --git a/mods/gen4/items.js b/mods/gen4/items.js
index 1a3429c80b..814f2047f5 100644
--- a/mods/gen4/items.js
+++ b/mods/gen4/items.js
@@ -1,3 +1,5 @@
+'use strict';
+
exports.BattleItems = {
"adamantorb": {
inherit: true,
@@ -30,7 +32,7 @@ exports.BattleItems = {
},
onBeforeTurn: function (pokemon) {
if (pokemon.hp <= pokemon.maxhp / 4 || (pokemon.hp <= pokemon.maxhp / 2 && pokemon.ability === 'gluttony')) {
- var decision = this.willMove(pokemon);
+ let decision = this.willMove(pokemon);
if (!decision) return;
this.insertQueue({
choice: 'event',
@@ -43,14 +45,14 @@ exports.BattleItems = {
}
},
onCustap: function (pokemon) {
- var decision = this.willMove(pokemon);
+ let decision = this.willMove(pokemon);
this.debug('custap decision: ' + decision);
if (decision) {
pokemon.eatItem();
}
},
onEat: function (pokemon) {
- var decision = this.willMove(pokemon);
+ let decision = this.willMove(pokemon);
this.debug('custap eaten: ' + decision);
if (decision) {
this.cancelDecision(pokemon);
diff --git a/mods/gen4/moves.js b/mods/gen4/moves.js
index dfefb8cdb1..7ddd1f338e 100644
--- a/mods/gen4/moves.js
+++ b/mods/gen4/moves.js
@@ -1,3 +1,5 @@
+'use strict';
+
exports.BattleMovedex = {
acupressure: {
inherit: true,
@@ -7,15 +9,15 @@ exports.BattleMovedex = {
if (target.volatiles['substitute']) {
return false;
}
- var stats = [];
- for (var i in target.boosts) {
+ let stats = [];
+ for (let i in target.boosts) {
if (target.boosts[i] < 6) {
stats.push(i);
}
}
if (stats.length) {
- var i = stats[this.random(stats.length)];
- var boost = {};
+ let i = stats[this.random(stats.length)];
+ let boost = {};
boost[i] = 2;
this.boost(boost);
} else {
@@ -27,13 +29,13 @@ exports.BattleMovedex = {
inherit: true,
desc: "The user performs a random move from any of the Pokemon on its team. Assist cannot generate itself, Chatter, Copycat, Counter, Covet, Destiny Bond, Detect, Endure, Feint, Focus Punch, Follow Me, Helping Hand, Me First, Metronome, Mimic, Mirror Coat, Mirror Move, Protect, Sketch, Sleep Talk, Snatch, Struggle, Switcheroo, Thief or Trick.",
onHit: function (target) {
- var moves = [];
- for (var j = 0; j < target.side.pokemon.length; j++) {
- var pokemon = target.side.pokemon[j];
+ let moves = [];
+ for (let j = 0; j < target.side.pokemon.length; j++) {
+ let pokemon = target.side.pokemon[j];
if (pokemon === target) continue;
- for (var i = 0; i < pokemon.moves.length; i++) {
- var move = pokemon.moves[i];
- var noAssist = {
+ for (let i = 0; i < pokemon.moves.length; i++) {
+ let move = pokemon.moves[i];
+ let noAssist = {
assist:1, chatter:1, copycat:1, counter:1, covet:1, destinybond:1, detect:1, endure:1, feint:1, focuspunch:1, followme:1, helpinghand:1, mefirst:1, metronome:1, mimic:1, mirrorcoat:1, mirrormove:1, protect:1, sketch:1, sleeptalk:1, snatch:1, struggle:1, switcheroo:1, thief:1, trick:1
};
if (move && !noAssist[move]) {
@@ -41,7 +43,7 @@ exports.BattleMovedex = {
}
}
}
- var move = '';
+ let move = '';
if (moves.length) move = moves[this.random(moves.length)];
if (!move) {
return false;
@@ -117,7 +119,7 @@ exports.BattleMovedex = {
return false;
}
this.add('-end', pokemon, 'Bide');
- var target = this.effectData.sourceSide.active[this.effectData.sourcePosition];
+ let target = this.effectData.sourceSide.active[this.effectData.sourcePosition];
this.moveHit(target, pokemon, 'bide', {damage: this.effectData.totalDamage * 2});
return false;
}
@@ -167,7 +169,7 @@ exports.BattleMovedex = {
copycat: {
inherit: true,
onHit: function (pokemon) {
- var noCopycat = {assist:1, chatter:1, copycat:1, counter:1, covet:1, destinybond:1, detect:1, endure:1, feint:1, focuspunch:1, followme:1, helpinghand:1, mefirst:1, metronome:1, mimic:1, mirrorcoat:1, mirrormove:1, protect:1, sketch:1, sleeptalk:1, snatch:1, struggle:1, switcheroo:1, thief:1, trick:1};
+ let noCopycat = {assist:1, chatter:1, copycat:1, counter:1, covet:1, destinybond:1, detect:1, endure:1, feint:1, focuspunch:1, followme:1, helpinghand:1, mefirst:1, metronome:1, mimic:1, mirrorcoat:1, mirrormove:1, protect:1, sketch:1, sleeptalk:1, snatch:1, struggle:1, switcheroo:1, thief:1, trick:1};
if (!this.lastMove || noCopycat[this.lastMove]) {
return false;
}
@@ -224,7 +226,7 @@ exports.BattleMovedex = {
onTryHit: function (target, source, move) {
if (!move.flags['protect']) return;
this.add('-activate', target, 'Protect');
- var lockedmove = source.getVolatile('lockedmove');
+ let lockedmove = source.getVolatile('lockedmove');
if (lockedmove) {
// Outrage counter is NOT reset
if (source.volatiles['lockedmove'].trueDuration >= 2) {
@@ -253,8 +255,8 @@ exports.BattleMovedex = {
if (!pokemon.lastMove) {
return false;
}
- var moves = pokemon.moveset;
- for (var i = 0; i < moves.length; i++) {
+ let moves = pokemon.moveset;
+ for (let i = 0; i < moves.length; i++) {
if (moves[i].id === pokemon.lastMove) {
if (!moves[i].pp) {
return false;
@@ -278,8 +280,8 @@ exports.BattleMovedex = {
}
},
onDisableMove: function (pokemon) {
- var moves = pokemon.moveset;
- for (var i = 0; i < moves.length; i++) {
+ let moves = pokemon.moveset;
+ for (let i = 0; i < moves.length; i++) {
if (moves[i].id === this.effectData.move) {
pokemon.disableMove(moves[i].id);
}
@@ -325,8 +327,8 @@ exports.BattleMovedex = {
return this.random(4, 9);
},
onStart: function (target) {
- var noEncore = {encore:1, mimic:1, mirrormove:1, sketch:1, struggle:1, transform:1};
- var moveIndex = target.moves.indexOf(target.lastMove);
+ let noEncore = {encore:1, mimic:1, mirrormove:1, sketch:1, struggle:1, transform:1};
+ let moveIndex = target.moves.indexOf(target.lastMove);
if (!target.lastMove || noEncore[target.lastMove] || (target.moveset[moveIndex] && target.moveset[moveIndex].pp <= 0)) {
// it failed
this.add('-fail', target);
@@ -357,7 +359,7 @@ exports.BattleMovedex = {
if (!this.effectData.move || !pokemon.hasMove(this.effectData.move)) {
return;
}
- for (var i = 0; i < pokemon.moveset.length; i++) {
+ for (let i = 0; i < pokemon.moveset.length; i++) {
if (pokemon.moveset[i].id !== this.effectData.move) {
pokemon.moveset[i].disabled = true;
}
@@ -406,7 +408,7 @@ exports.BattleMovedex = {
flail: {
inherit: true,
basePowerCallback: function (pokemon, target) {
- var ratio = pokemon.hp * 64 / pokemon.maxhp;
+ let ratio = pokemon.hp * 64 / pokemon.maxhp;
if (ratio < 2) {
return 200;
}
@@ -485,9 +487,9 @@ exports.BattleMovedex = {
this.add('-start', pokemon, 'move: Heal Block');
},
onDisableMove: function (pokemon) {
- var disabledMoves = {healingwish:1, lunardance:1, rest:1, swallow:1, wish:1};
- var moves = pokemon.moveset;
- for (var i = 0; i < moves.length; i++) {
+ let disabledMoves = {healingwish:1, lunardance:1, rest:1, swallow:1, wish:1};
+ let moves = pokemon.moveset;
+ for (let i = 0; i < moves.length; i++) {
if (disabledMoves[moves[i].id] || this.getMove(moves[i].id).heal) {
pokemon.disableMove(moves[i].id);
}
@@ -495,7 +497,7 @@ exports.BattleMovedex = {
},
onBeforeMovePriority: 6,
onBeforeMove: function (pokemon, target, move) {
- var disabledMoves = {healingwish:1, lunardance:1, rest:1, swallow:1, wish:1};
+ let disabledMoves = {healingwish:1, lunardance:1, rest:1, swallow:1, wish:1};
if (disabledMoves[move.id] || move.heal) {
this.add('cant', pokemon, 'move: Heal Block', move);
return false;
@@ -529,8 +531,8 @@ exports.BattleMovedex = {
return;
}
if (target.hp > 0) {
- var source = this.effectData.source;
- var damage = target.heal(target.maxhp);
+ let source = this.effectData.source;
+ let damage = target.heal(target.maxhp);
target.setStatus('');
this.add('-heal', target, target.getHealth, '[from] move: Healing Wish');
target.side.removeSideCondition('healingwish');
@@ -620,7 +622,7 @@ exports.BattleMovedex = {
shortDesc: "User takes half damage it would have dealt if miss.",
pp: 20,
onMoveFail: function (target, source, move) {
- var damage = this.getDamage(source, target, move, true);
+ let damage = this.getDamage(source, target, move, true);
if (!damage) damage = target.maxhp;
this.damage(this.clampIntRange(damage / 2, 1, Math.floor(target.maxhp / 2)), source, source, 'highjumpkick');
}
@@ -633,10 +635,10 @@ exports.BattleMovedex = {
inherit: true,
flags: {authentic: 1},
onTryHit: function (pokemon) {
- var targets = pokemon.side.foe.active;
- for (var i = 0; i < targets.length; i++) {
+ let targets = pokemon.side.foe.active;
+ for (let i = 0; i < targets.length; i++) {
if (!targets[i] || targets[i].fainted) continue;
- for (var j = 0; j < pokemon.moves.length; j++) {
+ for (let j = 0; j < pokemon.moves.length; j++) {
if (targets[i].moves.indexOf(pokemon.moves[j]) >= 0) return;
}
}
@@ -650,7 +652,7 @@ exports.BattleMovedex = {
shortDesc: "User takes half damage it would have dealt if miss.",
pp: 25,
onMoveFail: function (target, source, move) {
- var damage = this.getDamage(source, target, move, true);
+ let damage = this.getDamage(source, target, move, true);
if (!damage) damage = target.maxhp;
this.damage(this.clampIntRange(damage / 2, 1, Math.floor(target.maxhp / 2)), source, source, 'jumpkick');
}
@@ -680,10 +682,10 @@ exports.BattleMovedex = {
return;
}
if (target.hp > 0) {
- var source = this.effectData.source;
- var damage = target.heal(target.maxhp);
+ let source = this.effectData.source;
+ let damage = target.heal(target.maxhp);
target.setStatus('');
- for (var m in target.moveset) {
+ for (let m in target.moveset) {
target.moveset[m].pp = target.moveset[m].maxpp;
}
this.add('-heal', target, target.getHealth, '[from] move: Lunar Dance');
@@ -704,7 +706,7 @@ exports.BattleMovedex = {
return;
}
target.removeVolatile('magiccoat');
- var newMove = this.getMoveCopy(move.id);
+ let newMove = this.getMoveCopy(move.id);
newMove.hasBounced = true;
this.useMove(newMove, target, source);
return null;
@@ -738,19 +740,19 @@ exports.BattleMovedex = {
metronome: {
inherit: true,
onHit: function (target) {
- var moves = [];
- for (var i in exports.BattleMovedex) {
- var move = exports.BattleMovedex[i];
+ let moves = [];
+ for (let i in exports.BattleMovedex) {
+ let move = exports.BattleMovedex[i];
if (i !== move.id) continue;
if (move.isNonstandard) continue;
- var noMetronome = {
+ let noMetronome = {
assist:1, chatter:1, copycat:1, counter:1, covet:1, destinybond:1, detect:1, endure:1, feint:1, focuspunch:1, followme:1, helpinghand:1, mefirst:1, metronome:1, mimic:1, mirrorcoat:1, mirrormove:1, protect:1, sketch:1, sleeptalk:1, snatch:1, struggle:1, switcheroo:1, thief:1, trick:1
};
if (!noMetronome[move.id] && move.num < 468) {
moves.push(move.id);
}
}
- var move = '';
+ let move = '';
if (moves.length) move = moves[this.random(moves.length)];
if (!move) return false;
this.useMove(move, target);
@@ -759,11 +761,11 @@ exports.BattleMovedex = {
mimic: {
inherit: true,
onHit: function (target, source) {
- var disallowedMoves = {chatter:1, metronome:1, mimic:1, sketch:1, struggle:1, transform:1};
+ let disallowedMoves = {chatter:1, metronome:1, mimic:1, sketch:1, struggle:1, transform:1};
if (source.transformed || !target.lastMove || disallowedMoves[target.lastMove] || source.moves.indexOf(target.lastMove) !== -1 || target.volatiles['substitute']) return false;
- var moveslot = source.moves.indexOf('mimic');
+ let moveslot = source.moves.indexOf('mimic');
if (moveslot < 0) return false;
- var move = Tools.getMove(target.lastMove);
+ let move = Tools.getMove(target.lastMove);
source.moveset[moveslot] = {
move: move.name,
id: move.id,
@@ -793,7 +795,7 @@ exports.BattleMovedex = {
inherit: true,
onTryHit: function () { },
onHit: function (pokemon) {
- var noMirror = {acupressure:1, aromatherapy:1, assist:1, chatter:1, copycat:1, counter:1, curse:1, doomdesire:1, feint:1, focuspunch:1, futuresight:1, gravity:1, hail:1, haze:1, healbell:1, helpinghand:1, lightscreen:1, luckychant:1, magiccoat:1, mefirst:1, metronome:1, mimic:1, mirrorcoat:1, mirrormove:1, mist:1, mudsport:1, naturepower:1, perishsong:1, psychup:1, raindance:1, reflect:1, roleplay:1, safeguard:1, sandstorm:1, sketch:1, sleeptalk:1, snatch:1, spikes:1, spitup:1, stealthrock:1, struggle:1, sunnyday:1, tailwind:1, toxicspikes:1, transform:1, watersport:1};
+ let noMirror = {acupressure:1, aromatherapy:1, assist:1, chatter:1, copycat:1, counter:1, curse:1, doomdesire:1, feint:1, focuspunch:1, futuresight:1, gravity:1, hail:1, haze:1, healbell:1, helpinghand:1, lightscreen:1, luckychant:1, magiccoat:1, mefirst:1, metronome:1, mimic:1, mirrorcoat:1, mirrormove:1, mist:1, mudsport:1, naturepower:1, perishsong:1, psychup:1, raindance:1, reflect:1, roleplay:1, safeguard:1, sandstorm:1, sketch:1, sleeptalk:1, snatch:1, spikes:1, spitup:1, stealthrock:1, struggle:1, sunnyday:1, tailwind:1, toxicspikes:1, transform:1, watersport:1};
if (!pokemon.lastAttackedBy || !pokemon.lastAttackedBy.pokemon.lastMove || noMirror[pokemon.lastAttackedBy.move] || !pokemon.lastAttackedBy.pokemon.hasMove(pokemon.lastAttackedBy.move)) {
return false;
}
@@ -870,7 +872,7 @@ exports.BattleMovedex = {
onTryHit: function (target, source, move) {
if (!move.flags['protect']) return;
this.add('-activate', target, 'Protect');
- var lockedmove = source.getVolatile('lockedmove');
+ let lockedmove = source.getVolatile('lockedmove');
if (lockedmove) {
// Outrage counter is NOT reset
if (source.volatiles['lockedmove'].trueDuration >= 2) {
@@ -892,7 +894,7 @@ exports.BattleMovedex = {
reversal: {
inherit: true,
basePowerCallback: function (pokemon, target) {
- var ratio = pokemon.hp * 64 / pokemon.maxhp;
+ let ratio = pokemon.hp * 64 / pokemon.maxhp;
if (ratio < 2) {
return 200;
}
@@ -935,12 +937,12 @@ exports.BattleMovedex = {
sketch: {
inherit: true,
onHit: function (target, source) {
- var disallowedMoves = {chatter:1, sketch:1, struggle:1};
+ let disallowedMoves = {chatter:1, sketch:1, struggle:1};
if (source.transformed || !target.lastMove || disallowedMoves[target.lastMove] || source.moves.indexOf(target.lastMove) >= 0 || target.volatiles['substitute']) return false;
- var moveslot = source.moves.indexOf('sketch');
+ let moveslot = source.moves.indexOf('sketch');
if (moveslot < 0) return false;
- var move = Tools.getMove(target.lastMove);
- var sketchedMove = {
+ let move = Tools.getMove(target.lastMove);
+ let sketchedMove = {
move: move.name,
id: move.id,
pp: move.pp,
@@ -957,8 +959,8 @@ exports.BattleMovedex = {
skillswap: {
inherit: true,
onHit: function (target, source) {
- var targetAbility = target.ability;
- var sourceAbility = source.ability;
+ let targetAbility = target.ability;
+ let sourceAbility = source.ability;
if (targetAbility === sourceAbility) {
return false;
}
@@ -998,7 +1000,7 @@ exports.BattleMovedex = {
suckerpunch: {
inherit: true,
onTry: function (source, target) {
- var decision = this.willMove(target);
+ let decision = this.willMove(target);
if (!decision || decision.choice !== 'move' || decision.move.category === 'Status' || target.volatiles.mustrecharge) {
this.add('-fail', source);
return null;
@@ -1070,8 +1072,8 @@ exports.BattleMovedex = {
this.add('-end', target, 'move: Taunt');
},
onDisableMove: function (pokemon) {
- var moves = pokemon.moveset;
- for (var i = 0; i < moves.length; i++) {
+ let moves = pokemon.moveset;
+ for (let i = 0; i < moves.length; i++) {
if (this.getMove(moves[i].move).category === 'Status') {
pokemon.disableMove(moves[i].id);
}
@@ -1157,10 +1159,10 @@ exports.BattleMovedex = {
duration: 2,
onResidualOrder: 0,
onEnd: function (side) {
- var target = side.active[this.effectData.sourcePosition];
+ let target = side.active[this.effectData.sourcePosition];
if (!target.fainted) {
- var source = this.effectData.source;
- var damage = this.heal(target.maxhp / 2, target, target);
+ let source = this.effectData.source;
+ let damage = this.heal(target.maxhp / 2, target, target);
if (damage) this.add('-heal', target, target.getHealth, '[from] move: Wish', '[wisher] ' + source.name);
}
}
@@ -1169,7 +1171,7 @@ exports.BattleMovedex = {
worryseed: {
inherit: true,
onTryHit: function (pokemon) {
- var bannedAbilities = {multitype:1, truant:1};
+ let bannedAbilities = {multitype:1, truant:1};
if (bannedAbilities[pokemon.ability]) {
return false;
}
diff --git a/mods/gen4/rulesets.js b/mods/gen4/rulesets.js
index c3c1ef039f..9d480d92f7 100644
--- a/mods/gen4/rulesets.js
+++ b/mods/gen4/rulesets.js
@@ -1,15 +1,17 @@
+'use strict';
+
exports.BattleFormats = {
pokemon: {
inherit: true,
effectType: 'Banlist',
onValidateSet: function (set) {
- var template = this.getTemplate(set.species);
- var item = this.getItem(set.item);
+ let template = this.getTemplate(set.species);
+ let item = this.getItem(set.item);
if (item && item.id === 'griseousorb' && template.num !== 487) {
return ['Griseous Orb can only be held by Giratina in Generation 4.'];
}
if (template.num === 493 && set.evs) {
- for (var stat in set.evs) {
+ for (let stat in set.evs) {
if (set.evs[stat] > 100) return ["Arceus may not have more than 100 of any EVs in Generation 4."];
}
}
diff --git a/mods/gen4/scripts.js b/mods/gen4/scripts.js
index 6227696796..edc9f5abba 100644
--- a/mods/gen4/scripts.js
+++ b/mods/gen4/scripts.js
@@ -1,8 +1,10 @@
+'use strict';
+
exports.BattleScripts = {
inherit: 'gen5',
gen: 4,
init: function () {
- for (var i in this.data.Pokedex) {
+ for (let i in this.data.Pokedex) {
delete this.data.Pokedex[i].abilities['H'];
}
}
diff --git a/mods/gen4/statuses.js b/mods/gen4/statuses.js
index 96840fb38a..43d7b36a8f 100644
--- a/mods/gen4/statuses.js
+++ b/mods/gen4/statuses.js
@@ -1,3 +1,5 @@
+'use strict';
+
exports.BattleStatuses = {
par: {
inherit: true,
diff --git a/mods/gen5/abilities.js b/mods/gen5/abilities.js
index 27a26ba04a..1b26253080 100644
--- a/mods/gen5/abilities.js
+++ b/mods/gen5/abilities.js
@@ -1,10 +1,12 @@
+'use strict';
+
exports.BattleAbilities = {
"frisk": {
inherit: true,
desc: "When this Pokemon enters the field, it identifies the opponent's held item; in double battles, the held item of an unrevealed, randomly selected opponent is identified.",
shortDesc: "On switch-in, this Pokemon identifies a random foe's held item.",
onStart: function (pokemon) {
- var target = pokemon.side.foe.randomActive();
+ let target = pokemon.side.foe.randomActive();
if (target && target.item) {
this.add('-item', target, target.getItem().name, '[from] ability: Frisk', '[of] ' + pokemon);
}
diff --git a/mods/gen5/moves.js b/mods/gen5/moves.js
index d31cd636ca..8b46ca8c2a 100644
--- a/mods/gen5/moves.js
+++ b/mods/gen5/moves.js
@@ -1,3 +1,5 @@
+'use strict';
+
exports.BattleMovedex = {
acidarmor: {
inherit: true,
@@ -14,8 +16,8 @@ exports.BattleMovedex = {
aromatherapy: {
inherit: true,
onHit: function (pokemon, source) {
- var side = pokemon.side;
- for (var i = 0; i < side.pokemon.length; i++) {
+ let side = pokemon.side;
+ for (let i = 0; i < side.pokemon.length; i++) {
side.pokemon[i].status = '';
}
this.add('-cureteam', source, '[from] move: Aromatherapy');
@@ -25,13 +27,13 @@ exports.BattleMovedex = {
inherit: true,
desc: "A random move among those known by the user's party members is selected for use. Does not select Assist, Bestow, Chatter, Circle Throw, Copycat, Counter, Covet, Destiny Bond, Detect, Dragon Tail, Endure, Feint, Focus Punch, Follow Me, Helping Hand, Me First, Metronome, Mimic, Mirror Coat, Mirror Move, Nature Power, Protect, Rage Powder, Sketch, Sleep Talk, Snatch, Struggle, Switcheroo, Thief, Transform, or Trick.",
onHit: function (target) {
- var moves = [];
- for (var j = 0; j < target.side.pokemon.length; j++) {
- var pokemon = target.side.pokemon[j];
+ let moves = [];
+ for (let j = 0; j < target.side.pokemon.length; j++) {
+ let pokemon = target.side.pokemon[j];
if (pokemon === target) continue;
- for (var i = 0; i < pokemon.moves.length; i++) {
- var move = pokemon.moves[i];
- var noAssist = {
+ for (let i = 0; i < pokemon.moves.length; i++) {
+ let move = pokemon.moves[i];
+ let noAssist = {
assist:1, bestow:1, chatter:1, circlethrow:1, copycat:1, counter:1, covet:1, destinybond:1, detect:1, dragontail:1, endure:1, feint:1, focuspunch:1, followme:1, helpinghand:1, mefirst:1, metronome:1, mimic:1, mirrorcoat:1, mirrormove:1, naturepower:1, protect:1, ragepowder:1, sketch:1, sleeptalk:1, snatch:1, struggle:1, switcheroo:1, thief:1, transform:1, trick:1
};
if (move && !noAssist[move]) {
@@ -39,7 +41,7 @@ exports.BattleMovedex = {
}
}
}
- var move = '';
+ let move = '';
if (moves.length) move = moves[this.random(moves.length)];
if (!move) {
return false;
@@ -126,8 +128,8 @@ exports.BattleMovedex = {
desc: "The user's type changes to match the original type of one of its four moves besides this move, at random, but not either of its current types. Fails if the user cannot change its type, or if this move would only be able to select one of the user's current types.",
shortDesc: "Changes user's type to match a known move.",
onHit: function (target) {
- var possibleTypes = target.moveset.map(function (val) {
- var move = this.getMove(val.id);
+ let possibleTypes = target.moveset.map(function (val) {
+ let move = this.getMove(val.id);
if (move.id !== 'conversion' && !target.hasType(move.type)) {
return move.type;
}
@@ -135,7 +137,7 @@ exports.BattleMovedex = {
if (!possibleTypes.length) {
return false;
}
- var type = possibleTypes[this.random(possibleTypes.length)];
+ let type = possibleTypes[this.random(possibleTypes.length)];
if (!target.setType(type)) return false;
this.add('-start', target, 'typechange', type);
@@ -146,7 +148,7 @@ exports.BattleMovedex = {
desc: "The user uses the last move used by any Pokemon, including itself. Fails if no move has been used, or if the last move used was Assist, Bestow, Chatter, Circle Throw, Copycat, Counter, Covet, Destiny Bond, Detect, Dragon Tail, Endure, Feint, Focus Punch, Follow Me, Helping Hand, Me First, Metronome, Mimic, Mirror Coat, Mirror Move, Nature Power, Protect, Rage Powder, Sketch, Sleep Talk, Snatch, Struggle, Switcheroo, Thief, Transform, or Trick.",
shortDesc: "Uses the last move used in the battle.",
onHit: function (pokemon) {
- var noCopycat = {assist:1, bestow:1, chatter:1, circlethrow:1, copycat:1, counter:1, covet:1, destinybond:1, detect:1, dragontail:1, endure:1, feint:1, focuspunch:1, followme:1, helpinghand:1, mefirst:1, metronome:1, mimic:1, mirrorcoat:1, mirrormove:1, naturepower:1, protect:1, ragepowder:1, sketch:1, sleeptalk:1, snatch:1, struggle:1, switcheroo:1, thief:1, transform:1, trick:1};
+ let noCopycat = {assist:1, bestow:1, chatter:1, circlethrow:1, copycat:1, counter:1, covet:1, destinybond:1, detect:1, dragontail:1, endure:1, feint:1, focuspunch:1, followme:1, helpinghand:1, mefirst:1, metronome:1, mimic:1, mirrorcoat:1, mirrormove:1, naturepower:1, protect:1, ragepowder:1, sketch:1, sleeptalk:1, snatch:1, struggle:1, switcheroo:1, thief:1, transform:1, trick:1};
if (!this.lastMove || noCopycat[this.lastMove]) {
return false;
}
@@ -172,8 +174,8 @@ exports.BattleMovedex = {
shortDesc: "Removes target's hazards, lowers evasion by 1.",
onHit: function (pokemon) {
if (!pokemon.volatiles['substitute']) this.boost({evasion:-1});
- var sideConditions = {reflect:1, lightscreen:1, safeguard:1, mist:1, spikes:1, toxicspikes:1, stealthrock:1};
- for (var i in sideConditions) {
+ let sideConditions = {reflect:1, lightscreen:1, safeguard:1, mist:1, spikes:1, toxicspikes:1, stealthrock:1};
+ for (let i in sideConditions) {
if (pokemon.side.removeSideCondition(i)) {
this.add('-sideend', pokemon.side, this.getEffect(i).name, '[from] move: Defog', '[of] ' + pokemon);
}
@@ -333,9 +335,9 @@ exports.BattleMovedex = {
this.add('-start', pokemon, 'move: Heal Block');
},
onDisableMove: function (pokemon) {
- var disabledMoves = {healingwish:1, lunardance:1, rest:1, swallow:1, wish:1};
- var moves = pokemon.moveset;
- for (var i = 0; i < moves.length; i++) {
+ let disabledMoves = {healingwish:1, lunardance:1, rest:1, swallow:1, wish:1};
+ let moves = pokemon.moveset;
+ for (let i = 0; i < moves.length; i++) {
if (disabledMoves[moves[i].id] || this.getMove(moves[i].id).heal) {
pokemon.disableMove(moves[i].id);
}
@@ -343,7 +345,7 @@ exports.BattleMovedex = {
},
onBeforeMovePriority: 6,
onBeforeMove: function (pokemon, target, move) {
- var disabledMoves = {healingwish:1, lunardance:1, rest:1, swallow:1, wish:1};
+ let disabledMoves = {healingwish:1, lunardance:1, rest:1, swallow:1, wish:1};
if (disabledMoves[move.id] || move.heal) {
this.add('cant', pokemon, 'move: Heal Block', move);
return false;
@@ -468,7 +470,7 @@ exports.BattleMovedex = {
desc: "Deals damage to all adjacent foes and destroys any Berry they may be holding.",
shortDesc: "Destroys the foe(s) Berry.",
onHit: function (pokemon, source) {
- var item = pokemon.getItem();
+ let item = pokemon.getItem();
if (item.isBerry && pokemon.takeItem(source)) {
this.add('-enditem', pokemon, item.name, '[from] move: Incinerate');
}
@@ -518,19 +520,19 @@ exports.BattleMovedex = {
metronome: {
inherit: true,
onHit: function (target) {
- var moves = [];
- for (var i in exports.BattleMovedex) {
- var move = exports.BattleMovedex[i];
+ let moves = [];
+ for (let i in exports.BattleMovedex) {
+ let move = exports.BattleMovedex[i];
if (i !== move.id) continue;
if (move.isNonstandard) continue;
- var noMetronome = {
+ let noMetronome = {
afteryou:1, assist:1, bestow:1, chatter:1, copycat:1, counter:1, covet:1, destinybond:1, detect:1, endure:1, feint:1, focuspunch:1, followme:1, freezeschok:1, helpinghand:1, iceburn:1, mefirst:1, metronome:1, mimic:1, mirrorcoat:1, mirrormove:1, naturepower:1, protect:1, quash:1, quickguard:1, ragepowder:1, relicsong:1, secretsword:1, sketch:1, sleeptalk:1, snarl:1, snatch:1, snore:1, struggle:1, switcheroo:1, technoblast:1, thief:1, transform:1, trick:1, vcreate:1, wideguard:1
};
if (!noMetronome[move.id] && move.num < 560) {
moves.push(move.id);
}
}
- var move = '';
+ let move = '';
if (moves.length) move = moves[this.random(moves.length)];
if (!move) return false;
this.useMove(move, target);
@@ -660,7 +662,7 @@ exports.BattleMovedex = {
return;
}
this.add('-activate', target, 'Quick Guard');
- var lockedmove = source.getVolatile('lockedmove');
+ let lockedmove = source.getVolatile('lockedmove');
if (lockedmove) {
// Outrage counter is reset
if (source.volatiles['lockedmove'].duration === 2) {
@@ -740,8 +742,8 @@ exports.BattleMovedex = {
skillswap: {
inherit: true,
onHit: function (target, source) {
- var targetAbility = target.ability;
- var sourceAbility = source.ability;
+ let targetAbility = target.ability;
+ let sourceAbility = source.ability;
if (targetAbility === sourceAbility) {
return false;
}
@@ -840,7 +842,7 @@ exports.BattleMovedex = {
if (target === source || move.flags['authentic']) {
return;
}
- var damage = this.getDamage(source, target, move);
+ let damage = this.getDamage(source, target, move);
if (!damage && damage !== 0) {
this.add('-fail', target);
return null;
diff --git a/mods/gen5/scripts.js b/mods/gen5/scripts.js
index 4e731f2b9f..e96474f32c 100644
--- a/mods/gen5/scripts.js
+++ b/mods/gen5/scripts.js
@@ -1,24 +1,26 @@
+'use strict';
+
exports.BattleScripts = {
gen: 5,
randomSet: function (template, slot) {
if (slot === undefined) slot = 1;
template = this.getTemplate(template);
- var name = template.name;
+ let name = template.name;
if (!template.exists || (!template.randomBattleMoves && !template.learnset)) {
// GET IT? UNOWN? BECAUSE WE CAN'T TELL WHAT THE POKEMON IS
template = this.getTemplate('unown');
- var stack = 'Template incompatible with random battles: ' + name;
- var fakeErr = {stack: stack};
+ let stack = 'Template incompatible with random battles: ' + name;
+ let fakeErr = {stack: stack};
require('./../../crashlogger.js')(fakeErr, 'The randbat set generator');
}
- var movePool = (template.randomBattleMoves ? template.randomBattleMoves.slice() : Object.keys(template.learnset));
- var moves = [];
- var ability = '';
- var item = '';
- var evs = {
+ let movePool = (template.randomBattleMoves ? template.randomBattleMoves.slice() : Object.keys(template.learnset));
+ let moves = [];
+ let ability = '';
+ let item = '';
+ let evs = {
hp: 85,
atk: 85,
def: 85,
@@ -26,7 +28,7 @@ exports.BattleScripts = {
spd: 85,
spe: 85
};
- var ivs = {
+ let ivs = {
hp: 31,
atk: 31,
def: 31,
@@ -34,25 +36,25 @@ exports.BattleScripts = {
spd: 31,
spe: 31
};
- var hasStab = {};
+ let hasStab = {};
hasStab[template.types[0]] = true;
- var hasType = {};
+ let hasType = {};
hasType[template.types[0]] = true;
if (template.types[1]) {
hasStab[template.types[1]] = true;
hasType[template.types[1]] = true;
}
- var damagingMoves = [];
- var damagingMoveIndex = {};
- var hasMove = {};
- var counter = {};
- var setupType = '';
+ let damagingMoves = [];
+ let damagingMoveIndex = {};
+ let hasMove = {};
+ let counter = {};
+ let setupType = '';
do {
// Choose next 4 moves from learnset/viable moves and add them to moves list:
while (moves.length < 4 && movePool.length) {
- var moveid = this.sampleNoReplace(movePool);
+ let moveid = this.sampleNoReplace(movePool);
if (moveid.substr(0, 11) === 'hiddenpower') {
if (!hasMove['hiddenpower']) {
hasMove['hiddenpower'] = true;
@@ -74,9 +76,9 @@ exports.BattleScripts = {
physicalsetup: 0, specialsetup: 0, mixedsetup: 0
};
// Iterate through all moves we've chosen so far and keep track of what they do:
- for (var k = 0; k < moves.length; k++) {
- var move = this.getMove(moves[k]);
- var moveid = move.id;
+ for (let k = 0; k < moves.length; k++) {
+ let move = this.getMove(moves[k]);
+ let moveid = move.id;
// Keep track of all moves we have:
hasMove[moveid] = true;
if (move.damage || move.damageCallback) {
@@ -137,22 +139,22 @@ exports.BattleScripts = {
counter['inaccurate']++;
}
// Moves which drop stats:
- var ContraryMove = {
+ let ContraryMove = {
leafstorm: 1, overheat: 1, closecombat: 1, superpower: 1, vcreate: 1
};
if (ContraryMove[moveid]) {
counter['contrary']++;
}
// Moves that boost Attack:
- var PhysicalSetup = {
+ let PhysicalSetup = {
swordsdance:1, dragondance:1, coil:1, bulkup:1, curse:1, bellydrum:1, shiftgear:1, honeclaws:1, howl:1
};
// Moves which boost Special Attack:
- var SpecialSetup = {
+ let SpecialSetup = {
nastyplot:1, tailglow:1, quiverdance:1, calmmind:1, chargebeam:1
};
// Moves which boost Attack AND Special Attack:
- var MixedSetup = {
+ let MixedSetup = {
growth:1, workup:1, shellsmash:1
};
@@ -177,11 +179,11 @@ exports.BattleScripts = {
}
// Iterate through the moves again, this time to cull them:
- for (var k = 0; k < moves.length; k++) {
- var moveid = moves[k];
- var move = this.getMove(moveid);
- var rejected = false;
- var isSetup = false;
+ for (let k = 0; k < moves.length; k++) {
+ let moveid = moves[k];
+ let move = this.getMove(moveid);
+ let rejected = false;
+ let isSetup = false;
switch (moveid) {
@@ -381,7 +383,7 @@ exports.BattleScripts = {
}
// These moves can be used even if we aren't setting up to use them:
- var SetupException = {
+ let SetupException = {
overheat:1, dracometeor:1, leafstorm:1,
voltswitch:1, uturn:1,
suckerpunch:1, extremespeed:1
@@ -409,8 +411,8 @@ exports.BattleScripts = {
// handle HP IVs
if (move.id === 'hiddenpower') {
- var HPivs = this.getType(move.type).HPivs;
- for (var iv in HPivs) {
+ let HPivs = this.getType(move.type).HPivs;
+ for (let iv in HPivs) {
ivs[iv] = HPivs[iv];
}
}
@@ -423,9 +425,9 @@ exports.BattleScripts = {
} else if (damagingMoves.length === 1) {
// Night Shade, Seismic Toss, etc. don't count:
if (!damagingMoves[0].damage) {
- var damagingid = damagingMoves[0].id;
- var damagingType = damagingMoves[0].type;
- var replace = false;
+ let damagingid = damagingMoves[0].id;
+ let damagingType = damagingMoves[0].type;
+ let replace = false;
if (damagingid === 'suckerpunch' || damagingid === 'counter' || damagingid === 'mirrorcoat') {
// A player shouldn't be forced to rely upon the opponent attacking them to do damage.
if (!hasMove['encore'] && this.random(2)) replace = true;
@@ -452,9 +454,9 @@ exports.BattleScripts = {
}
} else if (damagingMoves.length === 2) {
// If you have two attacks, neither is STAB, and the combo isn't Ice/Electric, Ghost/Fighting, or Dark/Fighting, reject one of them at random.
- var type1 = damagingMoves[0].type, type2 = damagingMoves[1].type;
- var typeCombo = [type1, type2].sort().join('/');
- var rejectCombo = true;
+ let type1 = damagingMoves[0].type, type2 = damagingMoves[1].type;
+ let typeCombo = [type1, type2].sort().join('/');
+ let rejectCombo = true;
if (!(type1 in hasStab) && !(type2 in hasStab)) {
if (typeCombo === 'Electric/Ice' || typeCombo === 'Fighting/Ghost' || typeCombo === 'Dark/Fighting') rejectCombo = false;
} else {
@@ -463,8 +465,8 @@ exports.BattleScripts = {
if (rejectCombo) this.sampleNoReplace(moves);
} else {
// If you have three or more attacks, and none of them are STAB, reject one of them at random.
- var isStab = false;
- for (var l = 0; l < damagingMoves.length; l++) {
+ let isStab = false;
+ for (let l = 0; l < damagingMoves.length; l++) {
if (hasStab[damagingMoves[l].type]) {
isStab = true;
break;
@@ -477,7 +479,7 @@ exports.BattleScripts = {
// any moveset modification goes here
//moves[0] = 'Safeguard';
- var abilities = [template.abilities['0']];
+ let abilities = [template.abilities['0']];
if (template.abilities['1']) {
abilities.push(template.abilities['1']);
}
@@ -487,9 +489,9 @@ exports.BattleScripts = {
abilities.sort(function (a, b) {
return this.getAbility(b).rating - this.getAbility(a).rating;
}.bind(this));
- var ability0 = this.getAbility(abilities[0]);
- var ability1 = this.getAbility(abilities[1]);
- var ability = ability0.name;
+ let ability0 = this.getAbility(abilities[0]);
+ let ability1 = this.getAbility(abilities[1]);
+ ability = ability0.name;
if (abilities[1]) {
if (ability0.rating <= ability1.rating) {
if (this.random(2)) {
@@ -501,7 +503,7 @@ exports.BattleScripts = {
}
}
- var rejectAbility = false;
+ let rejectAbility = false;
if (ability === 'Blaze' && !counter['blaze']) {
rejectAbility = true;
}
@@ -622,7 +624,7 @@ exports.BattleScripts = {
} else if (hasMove['trick'] && hasMove['gyroball']) {
item = 'Iron Ball';
} else if (hasMove['trick'] || hasMove['switcheroo']) {
- var randomNum = this.random(2);
+ let randomNum = this.random(2);
if (counter.Physical >= 3 && (template.baseStats.spe >= 95 || randomNum)) {
item = 'Choice Band';
} else if (counter.Special >= 3 && (template.baseStats.spe >= 95 || randomNum)) {
@@ -664,9 +666,9 @@ exports.BattleScripts = {
item = 'Life Orb';
} else if (ability === 'Unburden' && (counter['Physical'] || counter['Special'])) {
// Give Unburden mons a random Gem of the type of one of their damaging moves
- var eligibleTypes = [];
- for (var i = 0; i < moves.length; i++) {
- var move = this.getMove(moves[i]);
+ let eligibleTypes = [];
+ for (let i = 0; i < moves.length; i++) {
+ let move = this.getMove(moves[i]);
if (!move.basePower && !move.basePowerCallback) continue;
eligibleTypes.push(move.type);
}
@@ -679,7 +681,7 @@ exports.BattleScripts = {
}
if ((hasMove['return'] || hasMove['hyperfang']) && !hasMove['facade']) {
// lol no
- for (var j = 0; j < moves.length; j++) {
+ for (let j = 0; j < moves.length; j++) {
if (moves[j] === 'Return' || moves[j] === 'HyperFang') {
moves[j] = 'Facade';
break;
@@ -700,9 +702,9 @@ exports.BattleScripts = {
} else if ((hasMove['eruption'] || hasMove['waterspout']) && !counter['Status']) {
item = 'Choice Scarf';
} else if (hasMove['substitute'] && hasMove['reversal']) {
- var eligibleTypes = [];
- for (var i = 0; i < moves.length; i++) {
- var move = this.getMove(moves[i]);
+ let eligibleTypes = [];
+ for (let i = 0; i < moves.length; i++) {
+ let move = this.getMove(moves[i]);
if (!move.basePower && !move.basePowerCallback) continue;
eligibleTypes.push(move.type);
}
@@ -747,7 +749,7 @@ exports.BattleScripts = {
}
// 95-86-82-78-74-70
- var levelScale = {
+ let levelScale = {
LC: 95,
NFE: 90,
'LC Uber': 86,
@@ -762,7 +764,7 @@ exports.BattleScripts = {
Unreleased: 74,
Uber: 70
};
- var customScale = {
+ let customScale = {
// Really bad Pokemon and jokemons
Azurill: 99, Burmy: 99, Cascoon: 99, Caterpie: 99, Cleffa: 99, Combee: 99, Feebas: 99, Igglybuff: 99, Happiny: 99, Hoppip: 99,
Kakuna: 99, Kricketot: 99, Ledyba: 99, Magikarp: 99, Metapod: 99, Pichu: 99, Ralts: 99, Sentret: 99, Shedinja: 99,
@@ -781,7 +783,7 @@ exports.BattleScripts = {
// Holistic judgment
Carvanha: 90, Blaziken: 74, "Deoxys-Defense": 74, "Deoxys-Speed": 74, Garchomp: 74, Thundurus: 74
};
- var level = levelScale[template.tier] || 90;
+ let level = levelScale[template.tier] || 90;
if (customScale[template.name]) level = customScale[template.name];
if (template.name === 'Chandelure' && ability === 'Shadow Tag') level = 70;
@@ -801,35 +803,35 @@ exports.BattleScripts = {
};
},
randomTeam: function (side) {
- var pokemonLeft = 0;
- var pokemon = [];
+ let pokemonLeft = 0;
+ let pokemon = [];
- var pokemonPool = [];
- for (var id in this.data.FormatsData) {
- var template = this.getTemplate(id);
+ let pokemonPool = [];
+ for (let id in this.data.FormatsData) {
+ let template = this.getTemplate(id);
if (template.gen >= this.gen || !template.randomBattleMoves) continue;
pokemonPool.push(id);
}
// PotD stuff
- var potd;
+ let potd;
if (Config.potd && 'Rule:potd' in this.getBanlistTable(this.getFormat())) {
potd = this.getTemplate(Config.potd);
}
- var typeCount = {};
- var typeComboCount = {};
- var uberCount = 0;
- var nuCount = 0;
+ let typeCount = {};
+ let typeComboCount = {};
+ let uberCount = 0;
+ let nuCount = 0;
while (pokemonPool.length && pokemonLeft < 6) {
- var template = this.getTemplate(this.sampleNoReplace(pokemonPool));
+ let template = this.getTemplate(this.sampleNoReplace(pokemonPool));
if (!template.exists) continue;
// Not available on BW
if (template.species === 'Pichu-Spiky-eared') continue;
- var tier = template.tier;
+ let tier = template.tier;
// This tries to limit the amount of Ubers and NUs on one team to promote "fun":
// LC Pokemon have a hard limit in place at 2; NFEs/NUs/Ubers are also limited to 2 but have a 20% chance of being added anyway.
// LC/NFE/NU Pokemon all share a counter (so having one of each would make the counter 3), while Ubers have a counter of their own.
@@ -859,9 +861,9 @@ exports.BattleScripts = {
}
// Limit 2 of any type
- var types = template.types;
- var skip = false;
- for (var t = 0; t < types.length; t++) {
+ let types = template.types;
+ let skip = false;
+ for (let t = 0; t < types.length; t++) {
if (typeCount[types[t]] > 1 && this.random(5) >= 1) {
skip = true;
break;
@@ -883,10 +885,10 @@ exports.BattleScripts = {
}
}
- var set = this.randomSet(template, pokemon.length);
+ let set = this.randomSet(template, pokemon.length);
// Limit 1 of any type combination
- var typeCombo = types.join();
+ let typeCombo = types.join();
if (set.ability === 'Drought' || set.ability === 'Drizzle') {
// Drought and Drizzle don't count towards the type combo limit
typeCombo = set.ability;
@@ -900,7 +902,7 @@ exports.BattleScripts = {
pokemonLeft++;
// Increment type counters
- for (var t = 0; t < types.length; t++) {
+ for (let t = 0; t < types.length; t++) {
if (types[t] in typeCount) {
typeCount[types[t]]++;
} else {
diff --git a/mods/gen5/statuses.js b/mods/gen5/statuses.js
index afaea4df2a..c8c2a2fc86 100644
--- a/mods/gen5/statuses.js
+++ b/mods/gen5/statuses.js
@@ -1,3 +1,5 @@
+'use strict';
+
exports.BattleStatuses = {
slp: {
inherit: true,
@@ -29,7 +31,7 @@ exports.BattleStatuses = {
onStallMove: function () {
// this.effectData.counter should never be undefined here.
// However, just in case, use 1 if it is undefined.
- var counter = this.effectData.counter || 1;
+ let counter = this.effectData.counter || 1;
if (counter >= 256) {
// 2^32 - special-cased because Battle.random(n) can't handle n > 2^16 - 1
return (this.random() * 4294967296 < 1);
diff --git a/mods/gennext/abilities.js b/mods/gennext/abilities.js
index a640ce4182..3606ee769b 100644
--- a/mods/gennext/abilities.js
+++ b/mods/gennext/abilities.js
@@ -1,3 +1,5 @@
+'use strict';
+
exports.BattleAbilities = {
"swiftswim": {
inherit: true,
@@ -27,7 +29,7 @@ exports.BattleAbilities = {
inherit: true,
onModifyMove: function (move) {
if (move.weather) {
- var weather = move.weather;
+ let weather = move.weather;
move.weather = null;
move.onHit = function (target, source) {
this.setWeather(weather, source, this.getAbility('forecast'));
@@ -146,7 +148,7 @@ exports.BattleAbilities = {
inherit: true,
onModifyMove: function (move) {
if (move.id === 'sunnyday') {
- var weather = move.weather;
+ let weather = move.weather;
move.weather = null;
move.onHit = function (target, source) {
this.setWeather(weather, source, this.getAbility('flowergift'));
@@ -269,7 +271,7 @@ exports.BattleAbilities = {
"clearbody": {
inherit: true,
onBoost: function (boost, target, source) {
- for (var i in boost) {
+ for (let i in boost) {
if (boost[i] < 0) {
delete boost[i];
this.add("-message", target.name + "'s stats were not lowered! (placeholder)");
@@ -280,7 +282,7 @@ exports.BattleAbilities = {
"whitesmoke": {
inherit: true,
onBoost: function (boost, target, source) {
- for (var i in boost) {
+ for (let i in boost) {
if (boost[i] < 0) {
delete boost[i];
this.add("-message", target.name + "'s stats were not lowered! (placeholder)");
@@ -300,10 +302,10 @@ exports.BattleAbilities = {
if (pokemon.template.baseSpecies === 'Genesect') {
if (!pokemon.getItem().onDrive) return;
}
- var foeactive = pokemon.side.foe.active;
- var totaldef = 0;
- var totalspd = 0;
- for (var i = 0; i < foeactive.length; i++) {
+ let foeactive = pokemon.side.foe.active;
+ let totaldef = 0;
+ let totalspd = 0;
+ for (let i = 0; i < foeactive.length; i++) {
if (!foeactive[i] || foeactive[i].fainted) continue;
totaldef += foeactive[i].stats.def;
totalspd += foeactive[i].stats.spd;
@@ -407,7 +409,7 @@ exports.BattleAbilities = {
if (move.category !== "Status") {
this.debug('Adding Stench flinch');
if (!move.secondaries) move.secondaries = [];
- for (var i = 0; i < move.secondaries.length; i++) {
+ for (let i = 0; i < move.secondaries.length; i++) {
if (move.secondaries[i].volatileStatus === 'flinch') return;
}
move.secondaries.push({
@@ -508,8 +510,8 @@ exports.BattleAbilities = {
this.add('-start', target, 'move: Imprison');
},
onFoeDisableMove: function (pokemon) {
- var foeMoves = this.effectData.target.moveset;
- for (var f = 0; f < foeMoves.length; f++) {
+ let foeMoves = this.effectData.target.moveset;
+ for (let f = 0; f < foeMoves.length; f++) {
pokemon.disableMove(foeMoves[f].id, true);
}
pokemon.maybeDisabled = true;
diff --git a/mods/gennext/items.js b/mods/gennext/items.js
index b14b8caed6..7c1f57da5f 100644
--- a/mods/gennext/items.js
+++ b/mods/gennext/items.js
@@ -1,3 +1,5 @@
+'use strict';
+
exports.BattleItems = {
"burndrive": {
id: "burndrive",
@@ -99,7 +101,7 @@ exports.BattleItems = {
basePower: 10
},
onDamage: function (damage, target, source, effect) {
- var types = target.getTypes();
+ let types = target.getTypes();
if (types.length === 1 && types[0] === 'Fighting' &&
effect && effect.effectType === 'Move' &&
target.useItem()) {
@@ -119,7 +121,7 @@ exports.BattleItems = {
inherit: true,
onBasePower: function (basePower, user, target, move) {
if (move.category === 'Special') {
- var types = user.getTypes();
+ let types = user.getTypes();
if (types.length === 1 && types[0] === 'Psychic') {
return basePower * 1.2;
}
@@ -131,7 +133,7 @@ exports.BattleItems = {
inherit: true,
onBasePower: function (basePower, user, target, move) {
if (move.category === 'Physical') {
- var types = user.getTypes();
+ let types = user.getTypes();
if (types.length === 1 && types[0] === 'Fighting') {
return basePower * 1.2;
}
@@ -177,7 +179,7 @@ exports.BattleItems = {
}
},
onFoeBasePower: function (basePower, attacker, defender, move) {
- var GossamerWingUsers = {"Butterfree":1, "Masquerain":1, "Beautifly":1, "Mothim":1, "Vivillon":1};
+ let GossamerWingUsers = {"Butterfree":1, "Masquerain":1, "Beautifly":1, "Mothim":1, "Vivillon":1};
if (GossamerWingUsers[defender.template.species]) {
if (move.type === 'Rock' || move.type === 'Electric' || move.type === 'Ice') {
this.add('-message', "The attack was weakened by GoassamerWing!");
@@ -186,7 +188,7 @@ exports.BattleItems = {
}
},
onDamage: function (damage, defender, attacker, effect) {
- var GossamerWingUsers = {"Butterfree":1, "Masquerain":1, "Beautifly":1, "Mothim":1, "Vivillon":1};
+ let GossamerWingUsers = {"Butterfree":1, "Masquerain":1, "Beautifly":1, "Mothim":1, "Vivillon":1};
if (GossamerWingUsers[defender.template.species]) {
if (effect && effect.id === 'stealthrock') {
return damage / 2;
@@ -194,7 +196,7 @@ exports.BattleItems = {
}
},
onAfterMoveSecondarySelf: function (source, target, move) {
- var GossamerWingUsers = {"Butterfree":1, "Masquerain":1, "Beautifly":1, "Mothim":1, "Vivillon":1, "Venomoth":1, "Volcarona":1, "Dustox": 1, "Lilligant":1};
+ let GossamerWingUsers = {"Butterfree":1, "Masquerain":1, "Beautifly":1, "Mothim":1, "Vivillon":1, "Venomoth":1, "Volcarona":1, "Dustox": 1, "Lilligant":1};
if (move && move.effectType === 'Move' && move.category === 'Status' && GossamerWingUsers[source.template.species]) {
this.heal(source.maxhp / 16);
}
diff --git a/mods/gennext/moves.js b/mods/gennext/moves.js
index 2c3b475a2e..6e3fd7210c 100644
--- a/mods/gennext/moves.js
+++ b/mods/gennext/moves.js
@@ -1,3 +1,5 @@
+'use strict';
+
exports.BattleMovedex = {
/******************************************************************
Perfect accuracy moves:
@@ -147,7 +149,7 @@ exports.BattleMovedex = {
if (target === source || move.flags['authentic'] || move.infiltrates) {
return;
}
- var damage = this.getDamage(source, target, move);
+ let damage = this.getDamage(source, target, move);
if (!damage) {
return null;
}
@@ -190,7 +192,7 @@ exports.BattleMovedex = {
onTryHit: function (target, source, move) {
if (target.volatiles.substitute || !move.flags['protect']) return;
this.add('-activate', target, 'Protect');
- var lockedmove = source.getVolatile('lockedmove');
+ let lockedmove = source.getVolatile('lockedmove');
if (lockedmove) {
// Outrage counter is reset
if (source.volatiles['lockedmove'].duration === 2) {
@@ -212,7 +214,7 @@ exports.BattleMovedex = {
onTryHit: function (target, source, move) {
if (target.volatiles.substitute || !move.flags['protect'] || move.category === 'Status') return;
this.add('-activate', target, 'Protect');
- var lockedmove = source.getVolatile('lockedmove');
+ let lockedmove = source.getVolatile('lockedmove');
if (lockedmove) {
// Outrage counter is reset
if (source.volatiles['lockedmove'].duration === 2) {
@@ -629,7 +631,7 @@ exports.BattleMovedex = {
return false;
}
this.add('-end', pokemon, 'Bide');
- var target = this.effectData.sourceSide.active[this.effectData.sourcePosition];
+ let target = this.effectData.sourceSide.active[this.effectData.sourcePosition];
this.moveHit(target, pokemon, 'bide', {damage: this.effectData.totalDamage * 2});
return false;
}
@@ -716,7 +718,7 @@ exports.BattleMovedex = {
if (pokemon.baseTemplate.species !== 'Meloetta' || pokemon.transformed) {
return;
}
- var natureChange = {
+ let natureChange = {
'Modest': 'Adamant',
'Adamant': 'Modest',
'Timid': 'Jolly',
@@ -724,22 +726,22 @@ exports.BattleMovedex = {
};
if (pokemon.template.speciesid === 'meloettapirouette' && pokemon.formeChange('Meloetta')) {
this.add('-formechange', pokemon, 'Meloetta');
- var tmpAtkEVs = pokemon.set.evs.atk;
+ let tmpAtkEVs = pokemon.set.evs.atk;
pokemon.set.evs.atk = pokemon.set.evs.spa;
pokemon.set.evs.spa = tmpAtkEVs;
if (natureChange[pokemon.set.nature]) pokemon.set.nature = natureChange[pokemon.set.nature];
- var Atk2SpA = (pokemon.boosts.spa || 0) - (pokemon.boosts.atk || 0);
+ let Atk2SpA = (pokemon.boosts.spa || 0) - (pokemon.boosts.atk || 0);
this.boost({
atk: Atk2SpA,
spa: -Atk2SpA
}, pokemon);
} else if (pokemon.formeChange('Meloetta-Pirouette')) {
this.add('-formechange', pokemon, 'Meloetta-Pirouette');
- var tmpAtkEVs = pokemon.set.evs.atk;
+ let tmpAtkEVs = pokemon.set.evs.atk;
pokemon.set.evs.atk = pokemon.set.evs.spa;
pokemon.set.evs.spa = tmpAtkEVs;
if (natureChange[pokemon.set.nature]) pokemon.set.nature = natureChange[pokemon.set.nature];
- var Atk2SpA = (pokemon.boosts.spa || 0) - (pokemon.boosts.atk || 0);
+ let Atk2SpA = (pokemon.boosts.spa || 0) - (pokemon.boosts.atk || 0);
this.boost({
atk: Atk2SpA,
spa: -Atk2SpA
@@ -774,9 +776,9 @@ exports.BattleMovedex = {
this.add('-sidestart', side, 'move: Stealth Rock');
},
onSwitchIn: function (pokemon) {
- var factor = 2;
+ let factor = 2;
if (pokemon.hasType('Flying')) factor = 4;
- var damage = this.damage(pokemon.maxhp * factor / 16);
+ let damage = this.damage(pokemon.maxhp * factor / 16);
}
}
},
@@ -808,15 +810,15 @@ exports.BattleMovedex = {
chance: 100,
self: {
onHit: function (target, source) {
- var stats = [];
- for (var i in target.boosts) {
+ let stats = [];
+ for (let i in target.boosts) {
if (i !== 'accuracy' && i !== 'evasion' && i !== 'atk' && target.boosts[i] < 6) {
stats.push(i);
}
}
if (stats.length) {
- var i = stats[this.random(stats.length)];
- var boost = {};
+ let i = stats[this.random(stats.length)];
+ let boost = {};
boost[i] = 1;
this.boost(boost);
} else {
@@ -838,15 +840,15 @@ exports.BattleMovedex = {
chance: 100,
self: {
onHit: function (target, source) {
- var stats = [];
- for (var i in target.boosts) {
+ let stats = [];
+ for (let i in target.boosts) {
if (i !== 'accuracy' && i !== 'evasion' && i !== 'atk' && target.boosts[i] < 6) {
stats.push(i);
}
}
if (stats.length) {
- var i = stats[this.random(stats.length)];
- var boost = {};
+ let i = stats[this.random(stats.length)];
+ let boost = {};
boost[i] = 1;
this.boost(boost);
} else {
@@ -862,15 +864,15 @@ exports.BattleMovedex = {
chance: 100,
self: {
onHit: function (target, source) {
- var stats = [];
- for (var i in target.boosts) {
+ let stats = [];
+ for (let i in target.boosts) {
if (i !== 'accuracy' && i !== 'evasion' && i !== 'atk' && target.boosts[i] < 6) {
stats.push(i);
}
}
if (stats.length) {
- var i = stats[this.random(stats.length)];
- var boost = {};
+ let i = stats[this.random(stats.length)];
+ let boost = {};
boost[i] = 1;
this.boost(boost);
} else {
@@ -1029,7 +1031,7 @@ exports.BattleMovedex = {
inherit: true,
basePower: 80,
onBasePower: function (power, user) {
- var GossamerWingUsers = {"Butterfree":1, "Venomoth":1, "Masquerain":1, "Dustox":1, "Beautifly":1, "Mothim":1, "Lilligant":1, "Volcarona":1, "Vivillon":1};
+ let GossamerWingUsers = {"Butterfree":1, "Venomoth":1, "Masquerain":1, "Dustox":1, "Beautifly":1, "Mothim":1, "Lilligant":1, "Volcarona":1, "Vivillon":1};
if (user.hasItem('stick') && GossamerWingUsers[user.template.species]) {
return power * 1.5;
}
@@ -1218,13 +1220,13 @@ exports.BattleMovedex = {
inherit: true,
basePower: 30,
onBasePower: function (power, user) {
- var doubled = false;
+ let doubled = false;
if (user.removeVolatile('leechseed')) {
this.add('-end', user, 'Leech Seed', '[from] move: Rapid Spin', '[of] ' + user);
doubled = true;
}
- var sideConditions = {spikes:1, toxicspikes:1, stealthrock:1};
- for (var i in sideConditions) {
+ let sideConditions = {spikes:1, toxicspikes:1, stealthrock:1};
+ for (let i in sideConditions) {
if (user.side.removeSideCondition(i)) {
this.add('-sideend', user.side, this.getEffect(i).name, '[from] move: Rapid Spin', '[of] ' + user);
doubled = true;
@@ -1849,7 +1851,7 @@ exports.BattleMovedex = {
accuracy: 100,
onModifyMove: function (move, user) {
if (user.illusion) {
- var illusionMoves = user.illusion.moves.filter(function (move) {
+ let illusionMoves = user.illusion.moves.filter(function (move) {
return this.getMove(move).category !== 'Status';
}, this);
if (!illusionMoves.length) return;
@@ -1909,7 +1911,7 @@ exports.BattleMovedex = {
secondary: {
chance: 10,
onHit: function (target, source) {
- var result = this.random(3);
+ let result = this.random(3);
if (result === 0) {
target.trySetStatus('brn', source);
} else if (result === 1) {
diff --git a/mods/gennext/scripts.js b/mods/gennext/scripts.js
index 0932c084d0..6cbd2070e5 100644
--- a/mods/gennext/scripts.js
+++ b/mods/gennext/scripts.js
@@ -1,3 +1,5 @@
+'use strict';
+
exports.BattleScripts = {
init: function () {
this.modData('Pokedex', 'cherrimsunshine').types = ['Grass', 'Fire'];
@@ -118,7 +120,7 @@ exports.BattleScripts = {
this.modData('Pokedex', 'crawdaunt').abilities['H'] = 'Tough Claws';
// Every hidden ability becomes released
- for (var i in this.data.FormatsData) {
+ for (let i in this.data.FormatsData) {
this.modData('FormatsData', i).unreleasedHidden = false;
}
}
diff --git a/mods/gennext/statuses.js b/mods/gennext/statuses.js
index 33d0d2ba55..14acba5ada 100644
--- a/mods/gennext/statuses.js
+++ b/mods/gennext/statuses.js
@@ -1,3 +1,5 @@
+'use strict';
+
exports.BattleStatuses = {
frz: {
effectType: 'Status',
@@ -29,7 +31,7 @@ exports.BattleStatuses = {
return this.random(2, 4);
},
onResidual: function (target) {
- var move = this.getMove(target.lastMove);
+ let move = this.getMove(target.lastMove);
if (!move.self || move.self.volatileStatus !== 'lockedmove') {
// don't lock, and bypass confusion for calming
delete target.volatiles['lockedmove'];
@@ -48,7 +50,7 @@ exports.BattleStatuses = {
confusion: {
// this is a volatile status
onStart: function (target, source, sourceEffect) {
- var result = this.runEvent('TryConfusion', target, source, sourceEffect);
+ let result = this.runEvent('TryConfusion', target, source, sourceEffect);
if (!result) return result;
if (sourceEffect && sourceEffect.id === 'lockedmove') {
this.add('-start', target, 'confusion', '[fatigue]');
@@ -263,7 +265,7 @@ exports.BattleStatuses = {
// Cryogonal: infinite hail, Ice Body
onModifyMove: function (move) {
if (move.id === 'hail') {
- var weather = move.weather;
+ let weather = move.weather;
move.weather = null;
move.onHit = function (target, source) {
this.setWeather(weather, source, this.getAbility('snowwarning'));
@@ -286,7 +288,7 @@ exports.BattleStatuses = {
// Probopass: infinite sand
onModifyMove: function (move) {
if (move.id === 'sandstorm') {
- var weather = move.weather;
+ let weather = move.weather;
move.weather = null;
move.onHit = function (target, source) {
this.setWeather(weather, source, this.getAbility('sandstream'));
@@ -300,7 +302,7 @@ exports.BattleStatuses = {
// Phione: infinite rain
onModifyMove: function (move) {
if (move.id === 'raindance') {
- var weather = move.weather;
+ let weather = move.weather;
move.weather = null;
move.onHit = function (target, source) {
this.setWeather(weather, source, this.getAbility('drizzle'));
diff --git a/mods/hiddentype/moves.js b/mods/hiddentype/moves.js
index 0da6be8c06..83ff5a4936 100644
--- a/mods/hiddentype/moves.js
+++ b/mods/hiddentype/moves.js
@@ -1,3 +1,5 @@
+'use strict';
+
exports.BattleMovedex = {
reflecttype: {
inherit: true,
@@ -5,10 +7,10 @@ exports.BattleMovedex = {
if (source.template && source.template.num === 493) return false;
this.add('-start', source, 'typechange', '[from] move: Reflect Type', '[of] ' + target);
- var typeMap = {};
+ let typeMap = {};
source.typesData = [];
- for (var i = 0, l = target.typesData.length; i < l; i++) {
- var typeData = target.typesData[i];
+ for (let i = 0, l = target.typesData.length; i < l; i++) {
+ let typeData = target.typesData[i];
if (typeMap[typeData.type]) continue;
typeMap[typeData.type] = true;
diff --git a/mods/hiddentype/scripts.js b/mods/hiddentype/scripts.js
index 1ac0372793..dab11bc267 100644
--- a/mods/hiddentype/scripts.js
+++ b/mods/hiddentype/scripts.js
@@ -1,3 +1,5 @@
+'use strict';
+
exports.BattleScripts = {
pokemon: {
formeChange: function (template, dontRecalculateStats) {
@@ -8,7 +10,7 @@ exports.BattleScripts = {
this.template = template;
this.types = template.types;
this.typesData = [];
- for (var i = 0, l = this.types.length; i < l; i++) {
+ for (let i = 0, l = this.types.length; i < l; i++) {
this.typesData.push({
type: this.types[i],
suppressed: false,
@@ -25,12 +27,12 @@ exports.BattleScripts = {
}
if (!dontRecalculateStats) {
- for (var statName in this.stats) {
- var stat = this.template.baseStats[statName];
+ for (let statName in this.stats) {
+ let stat = this.template.baseStats[statName];
stat = Math.floor(Math.floor(2 * stat + this.set.ivs[statName] + Math.floor(this.set.evs[statName] / 4)) * this.level / 100 + 5);
// nature
- var nature = this.battle.getNature(this.set.nature);
+ let nature = this.battle.getNature(this.set.nature);
if (statName === nature.plus) stat *= 1.1;
if (statName === nature.minus) stat *= 0.9;
this.baseStats[statName] = this.stats[statName] = Math.floor(stat);
@@ -40,7 +42,7 @@ exports.BattleScripts = {
return true;
},
transformInto: function (pokemon, user) {
- var template = pokemon.template;
+ let template = pokemon.template;
if (pokemon.fainted || pokemon.illusion || (pokemon.volatiles['substitute'] && this.battle.gen >= 5)) {
return false;
}
@@ -51,10 +53,10 @@ exports.BattleScripts = {
return false;
}
this.transformed = true;
- var typeMap = {};
+ let typeMap = {};
this.typesData = [];
- for (var i = 0, l = pokemon.typesData.length; i < l; i++) {
- var typeData = pokemon.typesData[i];
+ for (let i = 0, l = pokemon.typesData.length; i < l; i++) {
+ let typeData = pokemon.typesData[i];
if (typeMap[typeData.type]) continue;
typeMap[typeData.type] = true;
@@ -73,7 +75,7 @@ exports.BattleScripts = {
});
}
}
- for (var statName in this.stats) {
+ for (let statName in this.stats) {
this.stats[statName] = pokemon.stats[statName];
}
this.moveset = [];
@@ -81,10 +83,10 @@ exports.BattleScripts = {
this.set.ivs = (this.battle.gen >= 5 ? this.set.ivs : pokemon.set.ivs);
this.hpType = (this.battle.gen >= 5 ? this.hpType : pokemon.hpType);
this.hpPower = (this.battle.gen >= 5 ? this.hpPower : pokemon.hpPower);
- for (var i = 0; i < pokemon.moveset.length; i++) {
- var move = this.battle.getMove(this.set.moves[i]);
- var moveData = pokemon.moveset[i];
- var moveName = moveData.move;
+ for (let i = 0; i < pokemon.moveset.length; i++) {
+ let move = this.battle.getMove(this.set.moves[i]);
+ let moveData = pokemon.moveset[i];
+ let moveName = moveData.move;
if (moveData.id === 'hiddenpower') {
moveName = 'Hidden Power ' + this.hpType;
}
@@ -98,7 +100,7 @@ exports.BattleScripts = {
});
this.moves.push(toId(moveName));
}
- for (var j in pokemon.boosts) {
+ for (let j in pokemon.boosts) {
this.boosts[j] = pokemon.boosts[j];
}
this.battle.add('-transform', this, pokemon);
diff --git a/mods/stadium/moves.js b/mods/stadium/moves.js
index 76c89ceda7..db14460aec 100644
--- a/mods/stadium/moves.js
+++ b/mods/stadium/moves.js
@@ -1,3 +1,5 @@
+'use strict';
+
exports.BattleMovedex = {
"acid": {
inherit: true,
@@ -74,13 +76,13 @@ exports.BattleMovedex = {
},
onAfterMoveSelfPriority: 1,
onAfterMoveSelf: function (pokemon) {
- var leecher = pokemon.side.foe.active[pokemon.volatiles['leechseed'].sourcePosition];
+ let leecher = pokemon.side.foe.active[pokemon.volatiles['leechseed'].sourcePosition];
if (!leecher || leecher.fainted || leecher.hp <= 0) {
this.debug('Nothing to leech into');
return;
}
- var toLeech = this.clampIntRange(Math.floor(pokemon.maxhp / 16), 1);
- var damage = this.damage(toLeech, pokemon, leecher);
+ let toLeech = this.clampIntRange(Math.floor(pokemon.maxhp / 16), 1);
+ let damage = this.damage(toLeech, pokemon, leecher);
if (damage) this.heal(damage, leecher, pokemon);
}
}
@@ -163,7 +165,7 @@ exports.BattleMovedex = {
return null;
}
if (move.category === 'Status') {
- var SubBlocked = {
+ let SubBlocked = {
leechseed:1, lockon:1, mindreader:1, nightmare:1
};
if (move.status || move.boosts || move.volatileStatus === 'confusion' || SubBlocked[move.id]) {
@@ -173,7 +175,7 @@ exports.BattleMovedex = {
return;
}
if (move.volatileStatus && target === source) return;
- var damage = this.getDamage(source, target, move);
+ let damage = this.getDamage(source, target, move);
if (!damage) return null;
damage = this.runEvent('SubDamage', target, source, move, damage);
if (!damage) return damage;
diff --git a/mods/stadium/rulesets.js b/mods/stadium/rulesets.js
index 3e025a60a6..816b9ff00d 100644
--- a/mods/stadium/rulesets.js
+++ b/mods/stadium/rulesets.js
@@ -1,3 +1,5 @@
+'use strict';
+
exports.BattleFormats = {
standard: {
effectType: 'Banlist',
@@ -5,12 +7,12 @@ exports.BattleFormats = {
banlist: ['Unreleased', 'Illegal'],
onValidateSet: function (set) {
// limit one of each move in Standard
- var moves = [];
+ let moves = [];
if (set.moves) {
- var hasMove = {};
- for (var i = 0; i < set.moves.length; i++) {
- var move = this.getMove(set.moves[i]);
- var moveid = move.id;
+ let hasMove = {};
+ for (let i = 0; i < set.moves.length; i++) {
+ let move = this.getMove(set.moves[i]);
+ let moveid = move.id;
if (hasMove[moveid]) continue;
hasMove[moveid] = true;
moves.push(set.moves[i]);
diff --git a/mods/stadium/scripts.js b/mods/stadium/scripts.js
index 9e3af019d1..4c81db6c9f 100644
--- a/mods/stadium/scripts.js
+++ b/mods/stadium/scripts.js
@@ -1,3 +1,5 @@
+'use strict';
+
/**
* Stadium mechanics inherit from gen 1 mechanics, but fixes some stuff.
*/
@@ -21,8 +23,8 @@ exports.BattleScripts = {
},
// This is run on Stadium after boosts and status changes.
recalculateStats: function () {
- for (var statName in this.stats) {
- var stat = this.template.baseStats[statName];
+ for (let statName in this.stats) {
+ let stat = this.template.baseStats[statName];
stat = Math.floor(Math.floor(2 * stat + this.set.ivs[statName] + Math.floor(this.set.evs[statName] / 4)) * this.level / 100 + 5);
this.baseStats[statName] = this.stats[statName] = Math.floor(stat);
this.modifiedStats[statName] = Math.floor(stat);
@@ -40,9 +42,9 @@ exports.BattleScripts = {
},
// Stadium's fixed boosting function.
boostBy: function (boost) {
- var changed = false;
- for (var i in boost) {
- var delta = boost[i];
+ let changed = false;
+ for (let i in boost) {
+ let delta = boost[i];
this.boosts[i] += delta;
if (this.boosts[i] > 6) {
delta -= this.boosts[i] - 6;
@@ -81,7 +83,7 @@ exports.BattleScripts = {
}
}
pokemon.lastDamage = 0;
- var lockedMove = this.runEvent('LockMove', pokemon);
+ let lockedMove = this.runEvent('LockMove', pokemon);
if (lockedMove === true) lockedMove = false;
if (!lockedMove && !pokemon.volatiles['partialtrappinglock']) {
pokemon.deductPP(move, null, target);
@@ -113,9 +115,9 @@ exports.BattleScripts = {
}
},
tryMoveHit: function (target, pokemon, move, spreadHit) {
- var boostTable = [1, 4 / 3, 5 / 3, 2, 7 / 3, 8 / 3, 3];
- var doSelfDestruct = true;
- var damage = 0;
+ let boostTable = [1, 4 / 3, 5 / 3, 2, 7 / 3, 8 / 3, 3];
+ let doSelfDestruct = true;
+ let damage = 0;
// First, check if the Pokémon is immune to this move.
if (move.ignoreImmunity !== true && !move.ignoreImmunity[move.type] && !target.runImmunity(move.type, true)) {
@@ -126,7 +128,7 @@ exports.BattleScripts = {
}
// Now, let's calculate the accuracy.
- var accuracy = move.accuracy;
+ let accuracy = move.accuracy;
// Partial trapping moves: true accuracy while it lasts
if (pokemon.volatiles['partialtrappinglock']) {
@@ -179,7 +181,7 @@ exports.BattleScripts = {
if (damage !== false) {
pokemon.lastDamage = 0;
if (move.multihit) {
- var hits = move.multihit;
+ let hits = move.multihit;
if (hits.length) {
// Yes, it's hardcoded... meh
if (hits[0] === 2 && hits[1] === 5) {
@@ -190,9 +192,9 @@ exports.BattleScripts = {
}
hits = Math.floor(hits);
// In gen 1, all the hits have the same damage for multihits move
- var moveDamage = 0;
- var firstDamage;
- var i;
+ let moveDamage = 0;
+ let firstDamage;
+ let i;
for (i = 0; i < hits && target.hp && pokemon.hp; i++) {
if (i === 0) {
// First hit, we calculate
@@ -243,11 +245,11 @@ exports.BattleScripts = {
return damage;
},
moveHit: function (target, pokemon, move, moveData, isSecondary, isSelf) {
- var damage = 0;
+ let damage = 0;
move = this.getMoveCopy(move);
if (!isSecondary && !isSelf) this.setActiveMove(move, pokemon, target);
- var hitResult = true;
+ let hitResult = true;
if (!moveData) moveData = move;
if (move.ignoreImmunity === undefined) {
@@ -255,8 +257,8 @@ exports.BattleScripts = {
}
// We get the sub to the target to see if it existed
- var targetSub = (target) ? target.volatiles['substitute'] : false;
- var targetHadSub = (targetSub !== null && targetSub !== false && (typeof targetSub !== 'undefined'));
+ let targetSub = (target) ? target.volatiles['substitute'] : false;
+ let targetHadSub = (targetSub !== null && targetSub !== false && (typeof targetSub !== 'undefined'));
if (target) {
hitResult = this.singleEvent('TryHit', moveData, {}, target, pokemon, move);
@@ -297,7 +299,7 @@ exports.BattleScripts = {
}
if (target) {
- var didSomething = false;
+ let didSomething = false;
damage = this.getDamage(pokemon, target, moveData);
if ((damage || damage === 0) && !target.fainted) {
@@ -317,7 +319,7 @@ exports.BattleScripts = {
this.boost(moveData.boosts, target, pokemon, move);
}
if (moveData.heal && !target.fainted) {
- var d = target.heal(Math.floor(target.maxhp * moveData.heal[0] / moveData.heal[1]));
+ let d = target.heal(Math.floor(target.maxhp * moveData.heal[0] / moveData.heal[1]));
if (!d) {
this.add('-fail', target);
return false;
@@ -382,13 +384,13 @@ exports.BattleScripts = {
// Apply move secondaries.
if (moveData.secondaries) {
- for (var i = 0; i < moveData.secondaries.length; i++) {
+ for (let i = 0; i < moveData.secondaries.length; i++) {
// We check here whether to negate the probable secondary status if it's para, burn, or freeze.
// In the game, this is checked and if true, the random number generator is not called.
// That means that a move that does not share the type of the target can status it.
// If a move that was not fire-type would exist on Gen 1, it could burn a Pokémon.
if (!(moveData.secondaries[i].status && moveData.secondaries[i].status in {'par':1, 'brn':1, 'frz':1} && target && target.hasType(move.type))) {
- var effectChance = Math.floor(moveData.secondaries[i].chance * 255 / 100);
+ let effectChance = Math.floor(moveData.secondaries[i].chance * 255 / 100);
if (typeof moveData.secondaries[i].chance === 'undefined' || this.random(256) < effectChance) {
this.moveHit(target, pokemon, move, moveData.secondaries[i], true, isSelf);
}
@@ -453,10 +455,10 @@ exports.BattleScripts = {
if (!move.defensiveCategory) move.defensiveCategory = move.category;
// '???' is typeless damage: used for Struggle and Confusion etc
if (!move.type) move.type = '???';
- var type = move.type;
+ let type = move.type;
// We get the base power and apply basePowerCallback if necessary.
- var basePower = move.basePower;
+ let basePower = move.basePower;
if (move.basePowerCallback) {
basePower = move.basePowerCallback.call(this, pokemon, target, move);
}
@@ -473,7 +475,7 @@ exports.BattleScripts = {
if (!move.crit) {
// In Stadium, the critical chance is based on speed.
// First, we get the base speed and store it. Then we add 76. This is our current crit chance.
- var critChance = pokemon.template.baseStats['spe'] + 76;
+ let critChance = pokemon.template.baseStats['spe'] + 76;
// Now we right logical shift it two places, essentially dividing by 4 and flooring it.
critChance = critChance >> 2;
@@ -524,15 +526,15 @@ exports.BattleScripts = {
basePower = this.clampIntRange(basePower, 1);
// We now check attacker's and defender's stats.
- var level = pokemon.level;
- var attacker = pokemon;
- var defender = target;
+ let level = pokemon.level;
+ let attacker = pokemon;
+ let defender = target;
if (move.useTargetOffensive) attacker = target;
if (move.useSourceDefensive) defender = pokemon;
- var atkType = (move.category === 'Physical') ? 'atk' : 'spa';
- var defType = (move.defensiveCategory === 'Physical') ? 'def' : 'spd';
- var attack = attacker.getStat(atkType);
- var defense = defender.getStat(defType);
+ let atkType = (move.category === 'Physical') ? 'atk' : 'spa';
+ let defType = (move.defensiveCategory === 'Physical') ? 'def' : 'spd';
+ let attack = attacker.getStat(atkType);
+ let defense = defender.getStat(defType);
// In gen 1, screen effect is applied here.
if ((defType === 'def' && defender.volatiles['reflect']) || (defType === 'spd' && defender.volatiles['lightscreen'])) {
this.debug('Screen doubling (Sp)Def');
@@ -573,7 +575,7 @@ exports.BattleScripts = {
// Let's go with the calculation now that we have what we need.
// We do it step by step just like the game does.
- var damage = level * 2;
+ let damage = level * 2;
damage = Math.floor(damage / 5);
damage += 2;
damage *= basePower;
@@ -589,7 +591,7 @@ exports.BattleScripts = {
// Type effectiveness.
// The order here is not correct, must change to check the move versus each type.
- var totalTypeMod = this.getEffectiveness(type, target);
+ let totalTypeMod = this.getEffectiveness(type, target);
// Super effective attack
if (totalTypeMod > 0) {
if (!suppressMessages) this.add('-supereffective', target);
@@ -647,7 +649,7 @@ exports.BattleScripts = {
target.battle.lastDamage = damage;
damage = target.damage(damage, source, effect);
if (source) source.lastDamage = damage;
- var name = effect.fullname;
+ let name = effect.fullname;
if (name === 'tox') name = 'psn';
switch (effect.id) {
case 'partiallytrapped':
diff --git a/mods/stadium/statuses.js b/mods/stadium/statuses.js
index e1d63811cc..6f54b8611a 100644
--- a/mods/stadium/statuses.js
+++ b/mods/stadium/statuses.js
@@ -1,3 +1,5 @@
+'use strict';
+
exports.BattleStatuses = {
brn: {
effectType: 'Status',
diff --git a/mods/stsr/moves.js b/mods/stsr/moves.js
index 9695016b39..5dcf557311 100644
--- a/mods/stsr/moves.js
+++ b/mods/stsr/moves.js
@@ -1,3 +1,5 @@
+'use strict';
+
exports.BattleMovedex = {
rapidspin: {
inherit: true,
@@ -6,8 +8,8 @@ exports.BattleMovedex = {
if (pokemon.hp && pokemon.removeVolatile('leechseed')) {
this.add('-end', pokemon, 'Leech Seed', '[from] move: Rapid Spin', '[of] ' + pokemon);
}
- var sideConditions = {spikes:1, toxicspikes:1, stealthrock:1, stickyweb:1};
- for (var i in sideConditions) {
+ let sideConditions = {spikes:1, toxicspikes:1, stealthrock:1, stickyweb:1};
+ for (let i in sideConditions) {
if (i === 'stealthrock' && pokemon.side.sideConditions[i] && pokemon.side.sideConditions[i].type === 'Ghost') continue;
if (pokemon.hp && pokemon.side.removeSideCondition(i)) {
this.add('-sideend', pokemon.side, this.getEffect(i).name, '[from] move: Rapid Spin', '[of] ' + pokemon);
@@ -35,7 +37,7 @@ exports.BattleMovedex = {
pokemon.side.removeSideCondition('stealthrock');
this.add('-sideend', pokemon.side, 'move: Stealth Rock', '[of] ' + pokemon);
} else if (pokemon.runImmunity(this.effectData.type)) {
- var typeMod = this.clampIntRange(this.getEffectiveness(this.effectData.type, pokemon), -6, 6);
+ let typeMod = this.clampIntRange(this.getEffectiveness(this.effectData.type, pokemon), -6, 6);
this.damage(pokemon.maxhp * Math.pow(2, typeMod) / 8);
}
}
diff --git a/mods/tiershift/scripts.js b/mods/tiershift/scripts.js
index efb6f62b49..02148371a5 100644
--- a/mods/tiershift/scripts.js
+++ b/mods/tiershift/scripts.js
@@ -1,8 +1,10 @@
+'use strict';
+
exports.BattleScripts = {
init: function () {
- for (var i in this.data.Pokedex) {
- var tier = null;
- var adjustment = 0;
+ for (let i in this.data.Pokedex) {
+ let tier = null;
+ let adjustment = 0;
if (this.data.FormatsData[i]) tier = this.data.FormatsData[i].tier;
if (!tier && this.data.Pokedex[i].baseSpecies) tier = this.data.FormatsData[toId(this.data.Pokedex[i].baseSpecies)].tier;
@@ -26,7 +28,7 @@ exports.BattleScripts = {
}
if (adjustment) {
- for (var j in this.data.Pokedex[i].baseStats) {
+ for (let j in this.data.Pokedex[i].baseStats) {
this.modData('Pokedex', i).baseStats[j] = this.clampIntRange(this.data.Pokedex[i].baseStats[j] + adjustment, 1, 255);
}
}
diff --git a/monitor.js b/monitor.js
index d2af43ddbe..1f9e557485 100644
--- a/monitor.js
+++ b/monitor.js
@@ -6,12 +6,13 @@
*
* @license MIT license
*/
+'use strict';
-var fs = require('fs');
-var path = require('path');
+const fs = require('fs');
+const path = require('path');
/* global Monitor: true */
-var Monitor = module.exports = {
+const Monitor = module.exports = {
/*********************************************************
* Logging
@@ -68,8 +69,8 @@ var Monitor = module.exports = {
* Counts a connection. Returns true if the connection should be terminated for abuse.
*/
countConnection: function (ip, name) {
- var now = Date.now();
- var duration = now - this.connectionTimes[ip];
+ let now = Date.now();
+ let duration = now - this.connectionTimes[ip];
name = (name ? ': ' + name : '');
if (ip in this.connections && duration < 30 * 60 * 1000) {
this.connections[ip]++;
@@ -78,7 +79,7 @@ var Monitor = module.exports = {
return true;
} else if (this.connections[ip] > 500) {
if (this.connections[ip] % 500 === 0) {
- var c = this.connections[ip] / 500;
+ let c = this.connections[ip] / 500;
if (c < 5 || c % 2 === 0 && c < 10 || c % 5 === 0) {
this.adminlog('[ResourceMonitor] Banned IP ' + ip + ' has connected ' + this.connections[ip] + ' times in the last ' + duration.duration() + name);
}
@@ -94,8 +95,8 @@ var Monitor = module.exports = {
* Counts a battle. Returns true if the connection should be terminated for abuse.
*/
countBattle: function (ip, name) {
- var now = Date.now();
- var duration = now - this.battleTimes[ip];
+ let now = Date.now();
+ let duration = now - this.battleTimes[ip];
name = (name ? ': ' + name : '');
if (ip in this.battles && duration < 30 * 60 * 1000) {
this.battles[ip]++;
@@ -113,8 +114,8 @@ var Monitor = module.exports = {
* Counts battle prep. Returns true if too much
*/
countPrepBattle: function (ip) {
- var now = Date.now();
- var duration = now - this.battlePrepTimes[ip];
+ let now = Date.now();
+ let duration = now - this.battlePrepTimes[ip];
if (ip in this.battlePreps && duration < 3 * 60 * 1000) {
this.battlePreps[ip]++;
if (this.battlePreps[ip] > 6) {
@@ -129,8 +130,8 @@ var Monitor = module.exports = {
* Counts group chat creation. Returns true if too much.
*/
countGroupChat: function (ip) {
- var now = Date.now();
- var duration = now - this.groupChatTimes[ip];
+ let now = Date.now();
+ let duration = now - this.groupChatTimes[ip];
if (ip in this.groupChats && duration < 60 * 60 * 1000) {
this.groupChats[ip]++;
if (this.groupChats[ip] > 4) {
@@ -154,8 +155,8 @@ var Monitor = module.exports = {
}
},
writeNetworkUse: function () {
- var buf = '';
- for (var i in this.networkUse) {
+ let buf = '';
+ for (let i in this.networkUse) {
buf += '' + this.networkUse[i] + '\t' + this.networkCount[i] + '\t' + i + '\n';
}
fs.writeFile(path.resolve(__dirname, 'logs/networkuse.tsv'), buf);
@@ -168,12 +169,12 @@ var Monitor = module.exports = {
* Counts roughly the size of an object to have an idea of the server load.
*/
sizeOfObject: function (object) {
- var objectList = [];
- var stack = [object];
- var bytes = 0;
+ let objectList = [];
+ let stack = [object];
+ let bytes = 0;
while (stack.length) {
- var value = stack.pop();
+ let value = stack.pop();
if (typeof value === 'boolean') {
bytes += 4;
} else if (typeof value === 'string') {
@@ -182,7 +183,7 @@ var Monitor = module.exports = {
bytes += 8;
} else if (typeof value === 'object' && objectList.indexOf(value) < 0) {
objectList.push(value);
- for (var i in value) stack.push(value[i]);
+ for (let i in value) stack.push(value[i]);
}
}
@@ -192,8 +193,8 @@ var Monitor = module.exports = {
* Controls the amount of times a cmd command is used
*/
countCmd: function (ip, name) {
- var now = Date.now();
- var duration = now - this.cmdsTimes[ip];
+ let now = Date.now();
+ let duration = now - this.cmdsTimes[ip];
name = (name ? ': ' + name : '');
if (!this.cmdsTotal) this.cmdsTotal = {lastCleanup: 0, count: 0};
if (now - this.cmdsTotal.lastCleanup > 60 * 1000) {
diff --git a/repl.js b/repl.js
index 6d764762d0..f1bcc269a8 100644
--- a/repl.js
+++ b/repl.js
@@ -1,13 +1,15 @@
+'use strict';
+
const REPL_ENABLED = false;
-var fs = require('fs');
-var path = require('path');
-var net = require('net');
+const fs = require('fs');
+const path = require('path');
+const net = require('net');
-var sockets = [];
+let sockets = [];
function cleanup() {
- for (var s = 0; s < sockets.length; ++s) {
+ for (let s = 0; s < sockets.length; ++s) {
try {
fs.unlinkSync(sockets[s]);
} catch (e) {}
@@ -28,23 +30,23 @@ exports.start = function (prefix, suffix, evalFunction) {
if (!REPL_ENABLED) return;
if (process.platform === 'win32') return; // Windows doesn't support sockets mounted in the filesystem
- var resolvedPrefix = path.resolve(__dirname, Config.replsocketprefix || 'logs/repl', prefix);
+ let resolvedPrefix = path.resolve(__dirname, Config.replsocketprefix || 'logs/repl', prefix);
if (!evalFunction) {
evalFunction = suffix;
suffix = "";
}
- var name = resolvedPrefix + suffix;
+ let name = resolvedPrefix + suffix;
if (prefix === 'app') {
// Clear out any old sockets
- var directory = path.dirname(resolvedPrefix);
+ let directory = path.dirname(resolvedPrefix);
fs.readdirSync(directory).forEach(function (file) {
- var stat = fs.statSync(directory + '/' + file);
+ let stat = fs.statSync(directory + '/' + file);
if (!stat.isSocket()) {
return;
}
- var socket = net.connect(directory + '/' + file, function () {
+ let socket = net.connect(directory + '/' + file, function () {
socket.end();
socket.destroy();
}).on('error', function () {
@@ -67,7 +69,7 @@ exports.start = function (prefix, suffix, evalFunction) {
}).on('exit', socket.end.bind(socket));
socket.on('error', socket.destroy.bind(socket));
}).listen(name, function () {
- fs.chmodSync(name, Config.replsocketmode || 0600);
+ fs.chmodSync(name, Config.replsocketmode || '0600');
sockets.push(name);
}).on('error', function (e) {
if (e.code === "EADDRINUSE") {
diff --git a/rooms.js b/rooms.js
index 24de13c370..e0ee3aa242 100644
--- a/rooms.js
+++ b/rooms.js
@@ -9,21 +9,23 @@
* @license MIT license
*/
+'use strict';
+
const TIMEOUT_EMPTY_DEALLOCATE = 10 * 60 * 1000;
const TIMEOUT_INACTIVE_DEALLOCATE = 40 * 60 * 1000;
const REPORT_USER_STATS_INTERVAL = 10 * 60 * 1000;
const PERIODIC_MATCH_INTERVAL = 60 * 1000;
-var fs = require('fs');
+const fs = require('fs');
/* global Rooms: true */
-var Rooms = module.exports = getRoom;
+let Rooms = module.exports = getRoom;
-var rooms = Rooms.rooms = Object.create(null);
+let rooms = Rooms.rooms = Object.create(null);
-var aliases = Object.create(null);
+let aliases = Object.create(null);
-var Room = (function () {
+let Room = (function () {
function Room(roomid, title) {
this.id = roomid;
this.title = (title || roomid);
@@ -51,8 +53,8 @@ var Room = (function () {
Sockets.channelBroadcast(this.id, message);
};
Room.prototype.sendAuth = function (message) {
- for (var i in this.users) {
- var user = this.users[i];
+ for (let i in this.users) {
+ let user = this.users[i];
if (user.connected && user.can('receiveauthmessages', null, this)) {
user.sendTo(this, message);
}
@@ -75,7 +77,7 @@ var Room = (function () {
return this.add('|raw|' + message);
};
Room.prototype.getLogSlice = function (amount) {
- var log = this.log.slice(amount);
+ let log = this.log.slice(amount);
log.unshift('|:|' + (~~(Date.now() / 1000)));
return log;
};
@@ -109,20 +111,20 @@ var Room = (function () {
}
}
if (this.bannedIps) {
- for (var ip in user.ips) {
+ for (let ip in user.ips) {
if (ip in this.bannedIps) return this.bannedIps[ip];
}
}
};
Room.prototype.roomBan = function (user, noRecurse, userid) {
if (!userid) userid = user.userid;
- var alts;
+ let alts;
if (!noRecurse) {
alts = [];
- for (var i in Users.users) {
- var otherUser = Users.users[i];
+ for (let i in Users.users) {
+ let otherUser = Users.users[i];
if (otherUser === user) continue;
- for (var myIp in user.ips) {
+ for (let myIp in user.ips) {
if (myIp in otherUser.ips) {
alts.push(otherUser.name);
this.roomBan(otherUser, true, userid);
@@ -133,7 +135,7 @@ var Room = (function () {
}
this.bannedUsers[userid] = userid;
if (user.autoconfirmed) this.bannedUsers[user.autoconfirmed] = userid;
- for (var ip in user.ips) {
+ for (let ip in user.ips) {
this.bannedIps[ip] = userid;
}
if (!user.can('bypassall')) user.leaveRoom(this.id);
@@ -141,9 +143,9 @@ var Room = (function () {
};
Room.prototype.unRoomBan = function (userid, noRecurse) {
userid = toId(userid);
- var successUserid = false;
- for (var i in this.bannedUsers) {
- var entry = this.bannedUsers[i];
+ let successUserid = false;
+ for (let i in this.bannedUsers) {
+ let entry = this.bannedUsers[i];
if (i === userid || entry === userid) {
delete this.bannedUsers[i];
successUserid = entry;
@@ -152,7 +154,7 @@ var Room = (function () {
}
}
}
- for (var i in this.bannedIps) {
+ for (let i in this.bannedIps) {
if (this.bannedIps[i] === userid) {
delete this.bannedIps[i];
successUserid = userid;
@@ -161,7 +163,7 @@ var Room = (function () {
return successUserid;
};
Room.prototype.checkBanned = function (user) {
- var userid = this.isRoomBanned(user);
+ let userid = this.isRoomBanned(user);
if (userid) {
this.roomBan(user, true, userid);
return false;
@@ -172,13 +174,13 @@ var Room = (function () {
Room.prototype.runMuteTimer = function () {
if (this.muteTimer || this.muteQueue.length === 0) return;
- var timeUntilExpire = this.muteQueue[0].time - Date.now();
+ let timeUntilExpire = this.muteQueue[0].time - Date.now();
if (timeUntilExpire <= 0) {
this.unmute(this.muteQueue[0].userid, "Your mute in '" + this.title + "' has expired.");
//runMuteTimer() is called again in unmute() so this function instance should be closed
return;
}
- var self = this;
+ let self = this;
this.muteTimer = setTimeout(function () {
self.muteTimer = null;
self.runMuteTimer();
@@ -187,8 +189,8 @@ var Room = (function () {
Room.prototype.isMuted = function (user) {
if (!user) return;
if (this.muteQueue) {
- for (var i = 0; i < this.muteQueue.length; i++) {
- var entry = this.muteQueue[i];
+ for (let i = 0; i < this.muteQueue.length; i++) {
+ let entry = this.muteQueue[i];
if (user.userid === entry.userid ||
user.guestNum === entry.guestNum ||
(user.autoconfirmed && user.autoconfirmed === entry.autoconfirmed)) {
@@ -198,16 +200,16 @@ var Room = (function () {
}
};
Room.prototype.getMuteTime = function (user) {
- var userid = this.isMuted(user);
+ let userid = this.isMuted(user);
if (!userid) return;
- for (var i = 0; i < this.muteQueue.length; i++) {
+ for (let i = 0; i < this.muteQueue.length; i++) {
if (userid === this.muteQueue[i].userid) {
return this.muteQueue[i].time - Date.now();
}
}
};
Room.prototype.mute = function (user, setTime) {
- var userid = user.userid;
+ let userid = user.userid;
if (!setTime) setTime = 7 * 60000; // default time: 7 minutes
if (setTime > 90 * 60000) setTime = 90 * 60000; // limit 90 minutes
@@ -216,10 +218,10 @@ var Room = (function () {
if (this.isMuted(user)) this.unmute(userid);
// Place the user in a queue for the unmute timer
- for (var i = 0; i <= this.muteQueue.length; i++) {
- var time = Date.now() + setTime;
+ for (let i = 0; i <= this.muteQueue.length; i++) {
+ let time = Date.now() + setTime;
if (i === this.muteQueue.length || time < this.muteQueue[i].time) {
- var entry = {
+ let entry = {
userid: userid,
time: time,
guestNum: user.guestNum,
@@ -241,8 +243,8 @@ var Room = (function () {
return userid;
};
Room.prototype.unmute = function (userid, notifyText) {
- var successUserid = false;
- var user = Users(userid);
+ let successUserid = false;
+ let user = Users.get(userid);
if (!user) {
// If the user is not found, construct a dummy user object for them.
user = {
@@ -251,8 +253,8 @@ var Room = (function () {
};
}
- for (var i = 0; i < this.muteQueue.length; i++) {
- var entry = this.muteQueue[i];
+ for (let i = 0; i < this.muteQueue.length; i++) {
+ let entry = this.muteQueue[i];
if (entry.userid === user.userid ||
entry.guestNum === user.guestNum ||
(user.autoconfirmed && entry.autoconfirmed === user.autoconfirmed)) {
@@ -279,7 +281,7 @@ var Room = (function () {
return Room;
})();
-var GlobalRoom = (function () {
+let GlobalRoom = (function () {
function GlobalRoom(roomid) {
this.id = roomid;
@@ -317,16 +319,16 @@ var GlobalRoom = (function () {
this.autojoin = []; // rooms that users autojoin upon connecting
this.staffAutojoin = []; // rooms that staff autojoin upon connecting
- for (var i = 0; i < this.chatRoomData.length; i++) {
+ for (let i = 0; i < this.chatRoomData.length; i++) {
if (!this.chatRoomData[i] || !this.chatRoomData[i].title) {
console.log('ERROR: Room number ' + i + ' has no data.');
continue;
}
- var id = toId(this.chatRoomData[i].title);
+ let id = toId(this.chatRoomData[i].title);
if (!Config.quietconsole) console.log("NEW CHATROOM: " + id);
- var room = Rooms.createChatRoom(id, this.chatRoomData[i].title, this.chatRoomData[i]);
+ let room = Rooms.createChatRoom(id, this.chatRoomData[i].title, this.chatRoomData[i]);
if (room.aliases) {
- for (var a = 0; a < room.aliases.length; a++) {
+ for (let a = 0; a < room.aliases.length; a++) {
aliases[room.aliases[a]] = id;
}
}
@@ -336,11 +338,11 @@ var GlobalRoom = (function () {
}
// this function is complex in order to avoid several race conditions
- var self = this;
+ let self = this;
this.writeNumRooms = (function () {
- var writing = false;
- var lastBattle; // last lastBattle to be written to file
- var finishWriting = function () {
+ let writing = false;
+ let lastBattle; // last lastBattle to be written to file
+ let finishWriting = function () {
writing = false;
if (lastBattle < self.lastBattle) {
self.writeNumRooms();
@@ -369,9 +371,9 @@ var GlobalRoom = (function () {
})();
this.writeChatRoomData = (function () {
- var writing = false;
- var writePending = false; // whether or not a new write is pending
- var finishWriting = function () {
+ let writing = false;
+ let writePending = false; // whether or not a new write is pending
+ let finishWriting = function () {
writing = false;
if (writePending) {
writePending = false;
@@ -384,7 +386,7 @@ var GlobalRoom = (function () {
return;
}
writing = true;
- var data = JSON.stringify(self.chatRoomData).replace(/\{"title"\:/g, '\n{"title":').replace(/\]$/, '\n]');
+ let data = JSON.stringify(self.chatRoomData).replace(/\{"title"\:/g, '\n{"title":').replace(/\]$/, '\n]');
fs.writeFile('config/chatrooms.json.0', data, function () {
// rename is atomic on POSIX, but will throw an error on Windows
fs.rename('config/chatrooms.json.0', 'config/chatrooms.json', function (err) {
@@ -434,13 +436,13 @@ var GlobalRoom = (function () {
};
GlobalRoom.prototype.getFormatListText = function () {
- var formatListText = '|formats' + (Ladders.formatsListPrefix || '');
- var curSection = '';
- for (var i in Tools.data.Formats) {
- var format = Tools.data.Formats[i];
+ let formatListText = '|formats' + (Ladders.formatsListPrefix || '');
+ let curSection = '';
+ for (let i in Tools.data.Formats) {
+ let format = Tools.data.Formats[i];
if (!format.challengeShow && !format.searchShow && !format.tournamentShow) continue;
- var section = format.section;
+ let section = format.section;
if (section === undefined) section = format.mod;
if (!section) section = '';
if (section !== curSection) {
@@ -448,7 +450,7 @@ var GlobalRoom = (function () {
formatListText += '|,' + (format.column || 1) + '|' + section;
}
formatListText += '|' + format.name;
- var displayCode = 0;
+ let displayCode = 0;
if (format.team) displayCode |= 1;
if (format.searchShow) displayCode |= 2;
if (format.challengeShow) displayCode |= 4;
@@ -459,18 +461,18 @@ var GlobalRoom = (function () {
};
GlobalRoom.prototype.getRoomList = function (filter) {
- var roomList = {};
- var total = 0;
- var skipCount = 0;
+ let roomList = {};
+ let total = 0;
+ let skipCount = 0;
if (this.battleCount > 150) {
skipCount = this.battleCount - 150;
}
- for (var i in Rooms.rooms) {
- var room = Rooms.rooms[i];
+ for (let i in Rooms.rooms) {
+ let room = Rooms.rooms[i];
if (!room || !room.active || room.isPrivate) continue;
if (filter && filter !== room.format && filter !== true) continue;
if (skipCount && skipCount--) continue;
- var roomData = {};
+ let roomData = {};
if (room.active && room.battle) {
if (room.battle.players[0]) roomData.p1 = room.battle.players[0].getIdentity();
if (room.battle.players[1]) roomData.p2 = room.battle.players[1].getIdentity();
@@ -484,9 +486,9 @@ var GlobalRoom = (function () {
return roomList;
};
GlobalRoom.prototype.getRooms = function (user) {
- var roomsData = {official:[], chat:[], userCount: this.userCount, battleCount: this.battleCount};
- for (var i = 0; i < this.chatRooms.length; i++) {
- var room = this.chatRooms[i];
+ let roomsData = {official:[], chat:[], userCount: this.userCount, battleCount: this.battleCount};
+ for (let i = 0; i < this.chatRooms.length; i++) {
+ let room = this.chatRooms[i];
if (!room) continue;
if (room.isPrivate && !(room.isPrivate === 'voice' && user.group !== ' ')) continue;
(room.isOfficial ? roomsData.official : roomsData.chat).push({
@@ -500,14 +502,14 @@ var GlobalRoom = (function () {
GlobalRoom.prototype.cancelSearch = function (user, format) {
if (format && !user.searching[format]) return false;
- var searchedFormats = Object.keys(user.searching);
+ let searchedFormats = Object.keys(user.searching);
if (!searchedFormats.length) return false;
- for (var i = 0; i < searchedFormats.length; i++) {
+ for (let i = 0; i < searchedFormats.length; i++) {
if (format && searchedFormats[i] !== format) continue;
- var formatSearches = this.searches[searchedFormats[i]];
- for (var j = 0, len = formatSearches.length; j < len; j++) {
- var search = formatSearches[j];
+ let formatSearches = this.searches[searchedFormats[i]];
+ for (let j = 0, len = formatSearches.length; j < len; j++) {
+ let search = formatSearches[j];
if (search.userid !== user.userid) continue;
formatSearches.splice(j, 1);
delete user.searching[searchedFormats[i]];
@@ -531,16 +533,16 @@ var GlobalRoom = (function () {
// tell the user they've started searching
user.send('|updatesearch|' + JSON.stringify({searching: Object.keys(user.searching).concat(formatid)}));
- var newSearch = {
+ let newSearch = {
userid: '',
team: user.team,
rating: 1000,
time: new Date().getTime()
};
- var self = this;
+ let self = this;
// Get the user's rating before actually starting to search.
- Ladders(formatid).getRating(user.userid).then(function (rating) {
+ Ladders.get(formatid).getRating(user.userid).then(function (rating) {
newSearch.rating = rating;
newSearch.userid = user.userid;
self.addSearch(newSearch, user, formatid);
@@ -563,7 +565,7 @@ var GlobalRoom = (function () {
if (user1.lastMatch === user2.userid || user2.lastMatch === user1.userid) return false;
// search must be within range
- var searchRange = 100, elapsed = Date.now() - Math.min(search1.time, search2.time);
+ let searchRange = 100, elapsed = Date.now() - Math.min(search1.time, search2.time);
if (formatid === 'ou' || formatid === 'oucurrent' || formatid === 'randombattle') searchRange = 50;
searchRange += elapsed / 300; // +1 every .3 seconds
if (searchRange > 300) searchRange = 300;
@@ -579,17 +581,17 @@ var GlobalRoom = (function () {
if (user.searching[formatid]) return;
if (!this.searches[formatid]) this.searches[formatid] = [];
- var formatSearches = this.searches[formatid];
+ let formatSearches = this.searches[formatid];
// Prioritize players who have been searching for a match the longest.
- for (var i = 0; i < formatSearches.length; i++) {
- var search = formatSearches[i];
- var searchUser = Users.getExact(search.userid);
+ for (let i = 0; i < formatSearches.length; i++) {
+ let search = formatSearches[i];
+ let searchUser = Users.getExact(search.userid);
if (this.matchmakingOK(search, newSearch, searchUser, user, formatid)) {
- var usersToUpdate = [user, searchUser];
- for (var j = 0; j < 2; j++) {
+ let usersToUpdate = [user, searchUser];
+ for (let j = 0; j < 2; j++) {
delete usersToUpdate[j].searching[formatid];
- var searchedFormats = Object.keys(usersToUpdate[j].searching);
+ let searchedFormats = Object.keys(usersToUpdate[j].searching);
usersToUpdate[j].send('|updatesearch|' + JSON.stringify({searching: searchedFormats}));
}
formatSearches.splice(i, 1);
@@ -601,22 +603,22 @@ var GlobalRoom = (function () {
formatSearches.push(newSearch);
};
GlobalRoom.prototype.periodicMatch = function () {
- for (var formatid in this.searches) {
- var formatSearches = this.searches[formatid];
+ for (let formatid in this.searches) {
+ let formatSearches = this.searches[formatid];
if (formatSearches.length < 2) continue;
- var longestSearch = formatSearches[0];
- var longestSearcher = Users.getExact(longestSearch.userid);
+ let longestSearch = formatSearches[0];
+ let longestSearcher = Users.getExact(longestSearch.userid);
// Prioritize players who have been searching for a match the longest.
- for (var i = 1; i < formatSearches.length; i++) {
- var search = formatSearches[i];
- var searchUser = Users.getExact(search.userid);
+ for (let i = 1; i < formatSearches.length; i++) {
+ let search = formatSearches[i];
+ let searchUser = Users.getExact(search.userid);
if (this.matchmakingOK(search, longestSearch, searchUser, longestSearcher, formatid)) {
- var usersToUpdate = [longestSearcher, searchUser];
- for (var j = 0; j < 2; j++) {
+ let usersToUpdate = [longestSearcher, searchUser];
+ for (let j = 0; j < 2; j++) {
delete usersToUpdate[j].searching[formatid];
- var searchedFormats = Object.keys(usersToUpdate[j].searching);
+ let searchedFormats = Object.keys(usersToUpdate[j].searching);
usersToUpdate[j].send('|updatesearch|' + JSON.stringify({searching: searchedFormats}));
}
formatSearches.splice(i, 1);
@@ -635,8 +637,8 @@ var GlobalRoom = (function () {
}
};
GlobalRoom.prototype.sendAuth = function (message) {
- for (var i in this.users) {
- var user = this.users[i];
+ for (let i in this.users) {
+ let user = this.users[i];
if (user.connected && user.can('receiveauthmessages', null, this)) {
user.sendTo(this, message);
}
@@ -651,13 +653,13 @@ var GlobalRoom = (function () {
return this;
};
GlobalRoom.prototype.addChatRoom = function (title) {
- var id = toId(title);
+ let id = toId(title);
if (rooms[id]) return false;
- var chatRoomData = {
+ let chatRoomData = {
title: title
};
- var room = Rooms.createChatRoom(id, title, chatRoomData);
+ let room = Rooms.createChatRoom(id, title, chatRoomData);
this.chatRoomData.push(chatRoomData);
this.chatRooms.push(room);
this.writeChatRoomData();
@@ -665,14 +667,14 @@ var GlobalRoom = (function () {
};
GlobalRoom.prototype.deregisterChatRoom = function (id) {
id = toId(id);
- var room = rooms[id];
+ let room = rooms[id];
if (!room) return false; // room doesn't exist
if (!room.chatRoomData) return false; // room isn't registered
// deregister from global chatRoomData
// looping from the end is a pretty trivial optimization, but the
// assumption is that more recently added rooms are more likely to
// be deleted
- for (var i = this.chatRoomData.length - 1; i >= 0; i--) {
+ for (let i = this.chatRoomData.length - 1; i >= 0; i--) {
if (id === toId(this.chatRoomData[i].title)) {
this.chatRoomData.splice(i, 1);
this.writeChatRoomData();
@@ -685,7 +687,7 @@ var GlobalRoom = (function () {
GlobalRoom.prototype.delistChatRoom = function (id) {
id = toId(id);
if (!rooms[id]) return false; // room doesn't exist
- for (var i = this.chatRooms.length - 1; i >= 0; i--) {
+ for (let i = this.chatRooms.length - 1; i >= 0; i--) {
if (id === this.chatRooms[i].id) {
this.chatRooms.splice(i, 1);
break;
@@ -694,7 +696,7 @@ var GlobalRoom = (function () {
};
GlobalRoom.prototype.removeChatRoom = function (id) {
id = toId(id);
- var room = rooms[id];
+ let room = rooms[id];
if (!room) return false; // room doesn't exist
room.destroy();
return true;
@@ -702,14 +704,14 @@ var GlobalRoom = (function () {
GlobalRoom.prototype.autojoinRooms = function (user, connection) {
// we only autojoin regular rooms if the client requests it with /autojoin
// note that this restriction doesn't apply to staffAutojoin
- for (var i = 0; i < this.autojoin.length; i++) {
+ for (let i = 0; i < this.autojoin.length; i++) {
user.joinRoom(this.autojoin[i], connection);
}
};
GlobalRoom.prototype.checkAutojoin = function (user, connection) {
if (!user.named) return;
- for (var i = 0; i < this.staffAutojoin.length; i++) {
- var room = Rooms.get(this.staffAutojoin[i]);
+ for (let i = 0; i < this.staffAutojoin.length; i++) {
+ let room = Rooms.get(this.staffAutojoin[i]);
if (!room) {
this.staffAutojoin.splice(i, 1);
i--;
@@ -722,11 +724,11 @@ var GlobalRoom = (function () {
user.joinRoom(room.id, connection);
}
}
- for (var i = 0; i < user.connections.length; i++) {
+ for (let i = 0; i < user.connections.length; i++) {
connection = user.connections[i];
if (connection.autojoins) {
- var autojoins = connection.autojoins.split(',');
- for (var j = 0; j < autojoins.length; j++) {
+ let autojoins = connection.autojoins.split(',');
+ for (let j = 0; j < autojoins.length; j++) {
user.tryJoinRoom(autojoins[j], connection);
}
connection.autojoins = '';
@@ -734,7 +736,7 @@ var GlobalRoom = (function () {
}
};
GlobalRoom.prototype.onJoinConnection = function (user, connection) {
- var initdata = '|updateuser|' + user.name + '|' + (user.named ? '1' : '0') + '|' + user.avatar + '\n';
+ let initdata = '|updateuser|' + user.name + '|' + (user.named ? '1' : '0') + '|' + user.avatar + '\n';
connection.send(initdata + this.formatListText);
if (this.chatRooms.length > 2) connection.send('|queryresponse|rooms|null'); // should display room list
};
@@ -749,7 +751,7 @@ var GlobalRoom = (function () {
}
if (!merging) {
- var initdata = '|updateuser|' + user.name + '|' + (user.named ? '1' : '0') + '|' + user.avatar + '\n';
+ let initdata = '|updateuser|' + user.name + '|' + (user.named ? '1' : '0') + '|' + user.avatar + '\n';
connection.send(initdata + this.formatListText);
if (this.chatRooms.length > 2) connection.send('|queryresponse|rooms|null'); // should display room list
}
@@ -770,7 +772,7 @@ var GlobalRoom = (function () {
this.cancelSearch(user);
};
GlobalRoom.prototype.startBattle = function (p1, p2, format, p1team, p2team, options) {
- var newRoom;
+ let newRoom;
p1 = Users.get(p1);
p2 = Users.get(p2);
@@ -796,8 +798,8 @@ var GlobalRoom = (function () {
}
//console.log('BATTLE START BETWEEN: ' + p1.userid + ' ' + p2.userid);
- var i = this.lastBattle + 1;
- var formaturlid = format.toLowerCase().replace(/[^a-z0-9]+/g, '');
+ let i = this.lastBattle + 1;
+ let formaturlid = format.toLowerCase().replace(/[^a-z0-9]+/g, '');
while (rooms['battle-' + formaturlid + i]) {
i++;
}
@@ -836,7 +838,7 @@ var GlobalRoom = (function () {
return GlobalRoom;
})();
-var BattleRoom = (function () {
+let BattleRoom = (function () {
function BattleRoom(roomid, format, p1, p2, options) {
Room.call(this, roomid, "" + p1.name + " vs. " + p2.name);
this.modchat = (Config.battlemodchat || false);
@@ -847,14 +849,14 @@ var BattleRoom = (function () {
this.auth = {};
//console.log("NEW BATTLE");
- var formatid = toId(format);
+ let formatid = toId(format);
// Sometimes we might allow BattleRooms to have no options
if (!options) {
options = {};
}
- var rated;
+ let rated;
if (options.rated && Tools.getFormat(formatid).rated !== false) {
rated = {
p1: p1.userid,
@@ -906,12 +908,12 @@ var BattleRoom = (function () {
};
BattleRoom.prototype.win = function (winner) {
// Declare variables here in case we need them for non-rated battles logging.
- var p1score = 0.5;
- var winnerid = toId(winner);
+ let p1score = 0.5;
+ let winnerid = toId(winner);
// Check if the battle was rated to update the ladder, return its response, and log the battle.
if (this.rated) {
- var rated = this.rated;
+ let rated = this.rated;
this.rated = false;
if (winnerid === rated.p1) {
@@ -920,10 +922,10 @@ var BattleRoom = (function () {
p1score = 0;
}
- var p1 = Users.getExact(rated.p1);
- var p1name = p1 ? p1.name : rated.p1;
- var p2 = Users.getExact(rated.p2);
- var p2name = p2 ? p2.name : rated.p2;
+ let p1 = Users.getExact(rated.p1);
+ let p1name = p1 ? p1.name : rated.p1;
+ let p2 = Users.getExact(rated.p2);
+ let p2name = p2 ? p2.name : rated.p2;
//update.updates.push('[DEBUG] uri: ' + Config.loginserver + 'action.php?act=ladderupdate&serverid=' + Config.serverid + '&p1=' + encodeURIComponent(p1) + '&p2=' + encodeURIComponent(p2) + '&score=' + p1score + '&format=' + toId(rated.format) + '&servertoken=[token]');
@@ -935,7 +937,7 @@ var BattleRoom = (function () {
this.sendUser(winner, '|askreg|' + winner.userid);
}
// update rankings
- Ladders(rated.format).updateRating(p1name, p2name, p1score, this);
+ Ladders.get(rated.format).updateRating(p1name, p2name, p1score, this);
}
} else if (Config.logchallenges) {
// Log challenges if the challenge logging config is enabled.
@@ -948,15 +950,15 @@ var BattleRoom = (function () {
this.logBattle(p1score);
}
if (Config.autosavereplays) {
- var uploader = Users.get(winnerid);
+ let uploader = Users.get(winnerid);
if (uploader && uploader.connections[0]) {
CommandParser.parse('/savereplay', this, uploader, uploader.connections[0]);
}
}
if (this.tour) {
- var winnerid = toId(winner);
+ let winnerid = toId(winner);
winner = Users.get(winner);
- var tour = this.tour.tour;
+ let tour = this.tour.tour;
tour.onBattleWin(this, winner);
}
rooms.global.battleCount += 0 - (this.active ? 1 : 0);
@@ -967,9 +969,9 @@ var BattleRoom = (function () {
// logNum = 1, 2 : player log
// logNum = 3 : replay log
BattleRoom.prototype.getLog = function (logNum) {
- var log = [];
- for (var i = 0; i < this.log.length; ++i) {
- var line = this.log[i];
+ let log = [];
+ for (let i = 0; i < this.log.length; ++i) {
+ let line = this.log[i];
if (line === '|split') {
log.push(this.log[i + logNum + 1]);
i += 4;
@@ -980,7 +982,7 @@ var BattleRoom = (function () {
return log;
};
BattleRoom.prototype.getLogForUser = function (user) {
- var logNum = this.battle.getSlot(user) + 1;
+ let logNum = this.battle.getSlot(user) + 1;
if (logNum < 0) logNum = 0;
return this.getLog(logNum);
};
@@ -992,8 +994,8 @@ var BattleRoom = (function () {
this.lastUpdate = this.log.length;
// empty rooms time out after ten minutes
- var hasUsers = false;
- for (var i in this.users) {
+ let hasUsers = false;
+ for (let i in this.users) {
hasUsers = true;
break;
}
@@ -1006,19 +1008,19 @@ var BattleRoom = (function () {
}
};
BattleRoom.prototype.logBattle = function (p1score, p1rating, p2rating) {
- var logData = this.battle.logData;
+ let logData = this.battle.logData;
logData.p1rating = p1rating;
logData.p2rating = p2rating;
logData.endType = this.battle.endType;
if (!p1rating) logData.ladderError = true;
logData.log = BattleRoom.prototype.getLog.call(logData, 3); // replay log (exact damage)
- var date = new Date();
- var logfolder = date.format('{yyyy}-{MM}');
- var logsubfolder = date.format('{yyyy}-{MM}-{dd}');
- var curpath = 'logs/' + logfolder;
- var self = this;
+ let date = new Date();
+ let logfolder = date.format('{yyyy}-{MM}');
+ let logsubfolder = date.format('{yyyy}-{MM}-{dd}');
+ let curpath = 'logs/' + logfolder;
+ let self = this;
fs.mkdir(curpath, '0755', function () {
- var tier = self.format.toLowerCase().replace(/[^a-z0-9]+/g, '');
+ let tier = self.format.toLowerCase().replace(/[^a-z0-9]+/g, '');
curpath += '/' + tier;
fs.mkdir(curpath, '0755', function () {
curpath += '/' + logsubfolder;
@@ -1048,10 +1050,10 @@ var BattleRoom = (function () {
}
if (side === undefined) return false;
- var ids = ['p1', 'p2'];
- var otherids = ['p2', 'p1'];
+ let ids = ['p1', 'p2'];
+ let otherids = ['p2', 'p1'];
- var name = 'Player ' + (side + 1);
+ let name = 'Player ' + (side + 1);
if (user) {
name = user.name;
} else if (this.rated) {
@@ -1067,7 +1069,7 @@ var BattleRoom = (function () {
return true;
};
BattleRoom.prototype.sendPlayer = function (num, message) {
- var player = this.battle.getPlayer(num);
+ let player = this.battle.getPlayer(num);
if (!player) return false;
this.sendUser(player, message);
};
@@ -1077,9 +1079,9 @@ var BattleRoom = (function () {
if (!this.battle || this.battle.ended || !this.battle.started) return false;
- var inactiveSide = this.getInactiveSide();
+ let inactiveSide = this.getInactiveSide();
- var ticksLeft = [0, 0];
+ let ticksLeft = [0, 0];
if (inactiveSide !== 1) {
// side 0 is inactive
this.sideTurnTicks[0]--;
@@ -1096,19 +1098,19 @@ var BattleRoom = (function () {
if (ticksLeft[0] && ticksLeft[1]) {
if (inactiveSide === 0 || inactiveSide === 1) {
// one side is inactive
- var inactiveTicksLeft = ticksLeft[inactiveSide];
- var inactiveUser = this.battle.getPlayer(inactiveSide);
+ let inactiveTicksLeft = ticksLeft[inactiveSide];
+ let inactiveUser = this.battle.getPlayer(inactiveSide);
if (inactiveTicksLeft % 3 === 0 || inactiveTicksLeft <= 4) {
this.send('|inactive|' + (inactiveUser ? inactiveUser.name : 'Player ' + (inactiveSide + 1)) + ' has ' + (inactiveTicksLeft * 10) + ' seconds left.');
}
} else {
// both sides are inactive
- var inactiveUser0 = this.battle.getPlayer(0);
+ let inactiveUser0 = this.battle.getPlayer(0);
if (inactiveUser0 && (ticksLeft[0] % 3 === 0 || ticksLeft[0] <= 4)) {
this.sendUser(inactiveUser0, '|inactive|' + inactiveUser0.name + ' has ' + (ticksLeft[0] * 10) + ' seconds left.');
}
- var inactiveUser1 = this.battle.getPlayer(1);
+ let inactiveUser1 = this.battle.getPlayer(1);
if (inactiveUser1 && (ticksLeft[1] % 3 === 0 || ticksLeft[1] <= 4)) {
this.sendUser(inactiveUser1, '|inactive|' + inactiveUser1.name + ' has ' + (ticksLeft[1] * 10) + ' seconds left.');
}
@@ -1144,7 +1146,7 @@ var BattleRoom = (function () {
// a tick is 10 seconds
- var maxTicksLeft = 15; // 2 minutes 30 seconds
+ let maxTicksLeft = 15; // 2 minutes 30 seconds
if (!this.battle.p1 || !this.battle.p2) {
// if a player has left, don't wait longer than 6 ticks (1 minute)
maxTicksLeft = 6;
@@ -1153,7 +1155,7 @@ var BattleRoom = (function () {
this.sideTurnTicks = [maxTicksLeft, maxTicksLeft];
- var inactiveSide = this.getInactiveSide();
+ let inactiveSide = this.getInactiveSide();
if (inactiveSide < 0) {
// add 10 seconds to bank if they're below 160 seconds
if (this.sideTicksLeft[0] < 16) this.sideTicksLeft[0]++;
@@ -1163,12 +1165,12 @@ var BattleRoom = (function () {
this.sideTicksLeft[1]++;
if (inactiveSide !== 1) {
// side 0 is inactive
- var ticksLeft0 = Math.min(this.sideTicksLeft[0] + 1, maxTicksLeft);
+ let ticksLeft0 = Math.min(this.sideTicksLeft[0] + 1, maxTicksLeft);
this.sendPlayer(0, '|inactive|You have ' + (ticksLeft0 * 10) + ' seconds to make your decision.');
}
if (inactiveSide !== 0) {
// side 1 is inactive
- var ticksLeft1 = Math.min(this.sideTicksLeft[1] + 1, maxTicksLeft);
+ let ticksLeft1 = Math.min(this.sideTicksLeft[1] + 1, maxTicksLeft);
this.sendPlayer(1, '|inactive|You have ' + (ticksLeft1 * 10) + ' seconds to make your decision.');
}
@@ -1196,12 +1198,12 @@ var BattleRoom = (function () {
BattleRoom.prototype.kickInactiveUpdate = function () {
if (!this.rated && !this.tour) return false;
if (this.resetTimer) {
- var inactiveSide = this.getInactiveSide();
- var changed = false;
+ let inactiveSide = this.getInactiveSide();
+ let changed = false;
if ((!this.battle.p1 || !this.battle.p2) && !this.disconnectTickDiff[0] && !this.disconnectTickDiff[1]) {
if ((!this.battle.p1 && inactiveSide === 0) || (!this.battle.p2 && inactiveSide === 1)) {
- var inactiveUser = this.battle.getPlayer(inactiveSide);
+ let inactiveUser = this.battle.getPlayer(inactiveSide);
if (!this.battle.p1 && inactiveSide === 0 && this.sideTurnTicks[0] > 7) {
this.disconnectTickDiff[0] = this.sideTurnTicks[0] - 7;
@@ -1234,7 +1236,7 @@ var BattleRoom = (function () {
}
if (changed !== false) {
- var user = this.battle.getPlayer(changed);
+ let user = this.battle.getPlayer(changed);
this.send('|inactive|' + (user ? user.name : 'Player ' + (changed + 1)) + ' reconnected and has ' + (this.sideTurnTicks[changed] * 10) + ' seconds left!');
return true;
}
@@ -1287,7 +1289,7 @@ var BattleRoom = (function () {
this.add('|J|' + user.name);
}
}
- var resend = joining || !this.battle.playerTable[oldid];
+ let resend = joining || !this.battle.playerTable[oldid];
if (this.battle.playerTable[oldid]) {
this.battle.rename();
if (this.rated) {
@@ -1333,7 +1335,7 @@ var BattleRoom = (function () {
this.kickInactiveUpdate();
};
BattleRoom.prototype.joinBattle = function (user, team) {
- var slot;
+ let slot;
if (this.rated || this.tour) {
slot = this.battle.lastPlayers.indexOf(user.userid);
if (slot < 0) {
@@ -1380,7 +1382,7 @@ var BattleRoom = (function () {
// deallocate ourself
// remove references to ourself
- for (var i in this.users) {
+ for (let i in this.users) {
this.users[i].leaveRoom(this);
delete this.users[i];
}
@@ -1412,7 +1414,7 @@ var BattleRoom = (function () {
return BattleRoom;
})();
-var ChatRoom = (function () {
+let ChatRoom = (function () {
function ChatRoom(roomid, title, options) {
Room.call(this, roomid, title);
if (options) {
@@ -1429,7 +1431,7 @@ var ChatRoom = (function () {
if (Config.logchat) {
this.rollLogFile(true);
this.logEntry = function (entry, date) {
- var timestamp = (new Date()).format('{HH}:{mm}:{ss} ');
+ let timestamp = (new Date()).format('{HH}:{mm}:{ss} ');
this.logFile.write(timestamp + entry + '\n');
};
this.logEntry('NEW CHATROOM: ' + this.id);
@@ -1460,17 +1462,17 @@ var ChatRoom = (function () {
};
ChatRoom.prototype.rollLogFile = function (sync) {
- var mkdir = sync ? function (path, mode, callback) {
+ let mkdir = sync ? function (path, mode, callback) {
try {
fs.mkdirSync(path, mode);
} catch (e) {} // directory already exists
callback();
} : fs.mkdir;
- var date = new Date();
- var basepath = 'logs/chat/' + this.id + '/';
- var self = this;
+ let date = new Date();
+ let basepath = 'logs/chat/' + this.id + '/';
+ let self = this;
mkdir(basepath, '0755', function () {
- var path = date.format('{yyyy}-{MM}');
+ let path = date.format('{yyyy}-{MM}');
mkdir(basepath + path, '0755', function () {
if (self.destroyingLog) return;
path += '/' + date.format('{yyyy}-{MM}-{dd}') + '.txt';
@@ -1481,7 +1483,7 @@ var ChatRoom = (function () {
// Create a symlink to today's lobby log.
// These operations need to be synchronous, but it's okay
// because this code is only executed once every 24 hours.
- var link0 = basepath + 'today.txt.0';
+ let link0 = basepath + 'today.txt.0';
try {
fs.unlinkSync(link0);
} catch (e) {} // file doesn't exist
@@ -1492,7 +1494,7 @@ var ChatRoom = (function () {
} catch (e) {} // OS doesn't support atomic rename
} catch (e) {} // OS doesn't support symlinks
}
- var timestamp = +date;
+ let timestamp = +date;
date.advance('1 hour').reset('minutes').advance('1 second');
setTimeout(self.rollLogFile.bind(self), +date - timestamp);
});
@@ -1510,14 +1512,14 @@ var ChatRoom = (function () {
}
};
ChatRoom.prototype.logUserStats = function () {
- var total = 0;
- var guests = 0;
- var groups = {};
+ let total = 0;
+ let guests = 0;
+ let groups = {};
Config.groupsranking.forEach(function (group) {
groups[group] = 0;
});
- for (var i in this.users) {
- var user = this.users[i];
+ for (let i in this.users) {
+ let user = this.users[i];
++total;
if (!user.named) {
++guests;
@@ -1528,24 +1530,24 @@ var ChatRoom = (function () {
++groups[user.group];
}
}
- var entry = '|userstats|total:' + total + '|guests:' + guests;
- for (var i in groups) {
+ let entry = '|userstats|total:' + total + '|guests:' + guests;
+ for (let i in groups) {
entry += '|' + i + ':' + groups[i];
}
this.logEntry(entry);
};
ChatRoom.prototype.getUserList = function () {
- var buffer = '';
- var counter = 0;
- for (var i in this.users) {
+ let buffer = '';
+ let counter = 0;
+ for (let i in this.users) {
if (!this.users[i].named) {
continue;
}
counter++;
buffer += ',' + this.users[i].getIdentity(this.id);
}
- var msg = '|users|' + counter + buffer;
+ let msg = '|users|' + counter + buffer;
return msg;
};
ChatRoom.prototype.reportJoin = function (entry) {
@@ -1564,7 +1566,7 @@ var ChatRoom = (function () {
};
ChatRoom.prototype.update = function () {
if (this.log.length <= this.lastUpdate) return;
- var entries = this.log.slice(this.lastUpdate);
+ let entries = this.log.slice(this.lastUpdate);
if (this.reportJoinsQueue && this.reportJoinsQueue.length) {
clearInterval(this.reportJoinsInterval);
delete this.reportJoinsInterval;
@@ -1572,7 +1574,7 @@ var ChatRoom = (function () {
this.reportJoinsQueue.length = 0;
this.userList = this.getUserList();
}
- var update = entries.join('\n');
+ let update = entries.join('\n');
if (this.log.length > 100) {
this.log.splice(0, this.log.length - 100);
}
@@ -1590,7 +1592,7 @@ var ChatRoom = (function () {
this.destroy();
};
ChatRoom.prototype.getIntroMessage = function (user) {
- var message = '';
+ let message = '';
if (this.introMessage) message += '\n|raw|' + this.introMessage + '
';
if (this.staffMessage && user.can('mute', null, this)) message += (message ? '
' : '\n|raw|
') + '(Staff intro:)
' + this.staffMessage + '
';
if (this.modchat) {
@@ -1602,7 +1604,7 @@ var ChatRoom = (function () {
return message;
};
ChatRoom.prototype.onJoinConnection = function (user, connection) {
- var userList = this.userList ? this.userList : this.getUserList();
+ let userList = this.userList ? this.userList : this.getUserList();
this.sendUser(connection, '|init|chat\n|title|' + this.title + '\n' + userList + '\n' + this.getLogSlice(-25).join('\n') + this.getIntroMessage(user));
if (this.poll) this.poll.display(user, false);
if (global.Tournaments && Tournaments.get(this.id)) {
@@ -1617,7 +1619,7 @@ var ChatRoom = (function () {
this.userCount++;
if (!merging) {
- var userList = this.userList ? this.userList : this.getUserList();
+ let userList = this.userList ? this.userList : this.getUserList();
this.sendUser(connection, '|init|chat\n|title|' + this.title + '\n' + userList + '\n' + this.getLogSlice(-100).join('\n') + this.getIntroMessage(user));
if (this.poll) this.poll.display(user, false);
if (global.Tournaments && Tournaments.get(this.id)) {
@@ -1628,7 +1630,7 @@ var ChatRoom = (function () {
this.add('|j|' + user.getIdentity(this.id));
this.update();
} else if (user.named) {
- var entry = '|J|' + user.getIdentity(this.id);
+ let entry = '|J|' + user.getIdentity(this.id);
this.reportJoin(entry);
}
@@ -1637,7 +1639,7 @@ var ChatRoom = (function () {
ChatRoom.prototype.onRename = function (user, oldid, joining) {
delete this.users[oldid];
this.users[user.userid] = user;
- var entry;
+ let entry;
if (joining) {
if (Config.reportjoins) {
entry = '|j|' + user.getIdentity(this.id);
@@ -1669,7 +1671,7 @@ var ChatRoom = (function () {
ChatRoom.prototype.onUpdateIdentity = function (user) {
if (user && user.connected && user.named) {
if (!this.users[user.userid]) return false;
- var entry = '|N|' + user.getIdentity(this.id) + '|' + user.userid;
+ let entry = '|N|' + user.getIdentity(this.id) + '|' + user.userid;
this.reportJoin(entry);
}
};
@@ -1682,7 +1684,7 @@ var ChatRoom = (function () {
if (user.named && Config.reportjoins) {
this.add('|l|' + user.getIdentity(this.id));
} else if (user.named) {
- var entry = '|L|' + user.getIdentity(this.id);
+ let entry = '|L|' + user.getIdentity(this.id);
this.reportJoin(entry);
}
};
@@ -1690,7 +1692,7 @@ var ChatRoom = (function () {
// deallocate ourself
// remove references to ourself
- for (var i in this.users) {
+ for (let i in this.users) {
this.users[i].leaveRoom(this);
delete this.users[i];
}
@@ -1700,7 +1702,7 @@ var ChatRoom = (function () {
rooms.global.delistChatRoom(this.id);
if (this.aliases) {
- for (var i = 0; i < this.aliases.length; i++) {
+ for (let i = 0; i < this.aliases.length; i++) {
delete aliases[this.aliases[i]];
}
}
@@ -1752,7 +1754,7 @@ Rooms.createBattle = function (roomid, format, p1, p2, options) {
return rooms[roomid];
};
Rooms.createChatRoom = function (roomid, title, data) {
- var room;
+ let room;
if ((room = rooms[roomid])) return room;
room = rooms[roomid] = new ChatRoom(roomid, title, data);
diff --git a/simulator.js b/simulator.js
index dd28fad678..1179255d76 100644
--- a/simulator.js
+++ b/simulator.js
@@ -11,14 +11,16 @@
* @license MIT license
*/
-var battles = Object.create(null);
+'use strict';
-var SimulatorProcess = (function () {
+let battles = Object.create(null);
+
+let SimulatorProcess = (function () {
function SimulatorProcess() {
this.process = require('child_process').fork('battle-engine.js', {cwd: __dirname});
this.process.on('message', function (message) {
- var lines = message.split('\n');
- var battle = battles[lines[0]];
+ let lines = message.split('\n');
+ let battle = battles[lines[0]];
if (battle) {
battle.receive(lines);
}
@@ -30,7 +32,7 @@ var SimulatorProcess = (function () {
SimulatorProcess.processes = [];
SimulatorProcess.spawn = function (num) {
if (!num) num = Config.simulatorprocesses || 1;
- for (var i = this.processes.length; i < num; ++i) {
+ for (let i = this.processes.length; i < num; ++i) {
this.processes.push(new SimulatorProcess());
}
};
@@ -42,8 +44,8 @@ var SimulatorProcess = (function () {
this.spawn();
};
SimulatorProcess.acquire = function () {
- var process = this.processes[0];
- for (var i = 1; i < this.processes.length; ++i) {
+ let process = this.processes[0];
+ for (let i = 1; i < this.processes.length; ++i) {
if (this.processes[i].load < process.load) {
process = this.processes[i];
}
@@ -68,9 +70,9 @@ var SimulatorProcess = (function () {
// Create the initial set of simulator processes.
SimulatorProcess.spawn();
-var slice = Array.prototype.slice;
+let slice = Array.prototype.slice;
-var Battle = (function () {
+let Battle = (function () {
function Battle(id, format, rated, room) {
if (battles[id]) {
throw new Error("Battle with ID " + id + " already exists.");
@@ -119,7 +121,7 @@ var Battle = (function () {
this.process.send('' + this.id + '|' + slice.call(arguments).join('|'));
};
Battle.prototype.sendFor = function (user, action) {
- var player = this.playerTable[toId(user)];
+ let player = this.playerTable[toId(user)];
if (!player) {
Monitor.debug('SENDFOR FAILED in ' + this.id + ': Player doesn\'t exist: ' + user.name);
return;
@@ -128,8 +130,8 @@ var Battle = (function () {
this.send.apply(this, [action, player].concat(slice.call(arguments, 2)));
};
Battle.prototype.sendForOther = function (user, action) {
- var opposite = {'p1':'p2', 'p2':'p1'};
- var player = this.playerTable[toId(user)];
+ let opposite = {'p1':'p2', 'p2':'p1'};
+ let player = this.playerTable[toId(user)];
if (!player) return;
this.send.apply(this, [action, opposite[player]].concat(slice.call(arguments, 2)));
@@ -138,7 +140,6 @@ var Battle = (function () {
Battle.prototype.rqid = '';
Battle.prototype.inactiveQueued = false;
Battle.prototype.receive = function (lines) {
- var player;
Monitor.activeIp = this.activeIp;
switch (lines[1]) {
case 'update':
@@ -160,23 +161,25 @@ var Battle = (function () {
this.inactiveSide = -1;
break;
- case 'sideupdate':
- player = this.getPlayer(lines[2]);
+ case 'sideupdate': {
+ let player = this.getPlayer(lines[2]);
if (player) {
player.sendTo(this.id, lines[3]);
}
break;
+ }
- case 'callback':
- player = this.getPlayer(lines[2]);
+ case 'callback': {
+ let player = this.getPlayer(lines[2]);
if (player) {
player.sendTo(this.id, '|callback|' + lines[3]);
}
break;
+ }
- case 'request':
- player = this.getPlayer(lines[2]);
- var rqid = lines[3];
+ case 'request': {
+ let player = this.getPlayer(lines[2]);
+ let rqid = lines[3];
if (player) {
this.requests[player.userid] = lines[4];
player.sendTo(this.id, '|request|' + lines[4]);
@@ -186,6 +189,7 @@ var Battle = (function () {
this.inactiveQueued = true;
}
break;
+ }
case 'log':
this.logData = JSON.parse(lines[2]);
@@ -203,7 +207,7 @@ var Battle = (function () {
};
Battle.prototype.resendRequest = function (connection) {
- var request = this.requests[connection.user];
+ let request = this.requests[connection.user];
if (request) {
connection.sendTo(this.id, '|request|' + request);
}
@@ -247,7 +251,7 @@ var Battle = (function () {
user.battles[this.id] = true;
}
this.players[slot] = (user || null);
- var oldplayerid = this.playerids[slot];
+ let oldplayerid = this.playerids[slot];
if (oldplayerid) {
if (user) {
this.requests[user.userid] = this.requests[oldplayerid];
@@ -257,8 +261,8 @@ var Battle = (function () {
this.playerids[slot] = (user ? user.userid : null);
this.playerTable = {};
this.active = !this.ended;
- for (var i = 0, len = this.players.length; i < len; i++) {
- var player = this.players[i];
+ for (let i = 0, len = this.players.length; i < len; i++) {
+ let player = this.players[i];
this['p' + (i + 1)] = player ? player.name : '';
if (!player) {
this.active = false;
@@ -291,13 +295,13 @@ var Battle = (function () {
if (this.players[slot] || slot >= this.players.length) return false;
if (user === this.players[0] || user === this.players[1]) return false;
- for (var i = 0; i < user.connections.length; i++) {
- var connection = user.connections[i];
+ for (let i = 0; i < user.connections.length; i++) {
+ let connection = user.connections[i];
Sockets.subchannelMove(connection.worker, this.id, slot + 1, connection.socketid);
}
this.setPlayer(user, slot);
- var message = '' + user.avatar;
+ let message = '' + user.avatar;
if (!this.started) {
message += "\n" + team;
}
@@ -307,9 +311,9 @@ var Battle = (function () {
};
Battle.prototype.rename = function () {
- for (var i = 0, len = this.players.length; i < len; i++) {
- var player = this.players[i];
- var playerid = this.playerids[i];
+ for (let i = 0, len = this.players.length; i < len; i++) {
+ let player = this.players[i];
+ let playerid = this.playerids[i];
if (!player) continue;
if (player.userid !== playerid) {
this.setPlayer(player, i);
@@ -319,12 +323,12 @@ var Battle = (function () {
};
Battle.prototype.leave = function (user) {
- for (var i = 0, len = this.players.length; i < len; i++) {
- var player = this.players[i];
+ for (let i = 0, len = this.players.length; i < len; i++) {
+ let player = this.players[i];
if (player === user) {
this.sendFor(user, 'leave');
- for (var j = 0; j < user.connections.length; j++) {
- var connection = user.connections[j];
+ for (let j = 0; j < user.connections.length; j++) {
+ let connection = user.connections[j];
Sockets.subchannelMove(connection.worker, this.id, '0', connection.socketid);
}
this.setPlayer(null, i);
diff --git a/sockets.js b/sockets.js
index b51e36650e..489a0beb7e 100644
--- a/sockets.js
+++ b/sockets.js
@@ -11,7 +11,9 @@
* @license MIT license
*/
-var cluster = require('cluster');
+'use strict';
+
+const cluster = require('cluster');
global.Config = require('./config/config');
if (cluster.isMaster) {
@@ -19,46 +21,55 @@ if (cluster.isMaster) {
exec: require('path').resolve(__dirname, 'sockets.js')
});
- var workers = exports.workers = {};
+ let workers = exports.workers = {};
- var spawnWorker = exports.spawnWorker = function () {
- var worker = cluster.fork({PSPORT: Config.port, PSBINDADDR: Config.bindaddress || '', PSNOSSL: Config.ssl ? 0 : 1});
- var id = worker.id;
+ let spawnWorker = exports.spawnWorker = function () {
+ let worker = cluster.fork({PSPORT: Config.port, PSBINDADDR: Config.bindaddress || '', PSNOSSL: Config.ssl ? 0 : 1});
+ let id = worker.id;
workers[id] = worker;
worker.on('message', function (data) {
// console.log('master received: ' + data);
switch (data.charAt(0)) {
- case '*': // *socketid, ip
+ case '*': {
+ // *socketid, ip
// connect
- var nlPos = data.indexOf('\n');
+ let nlPos = data.indexOf('\n');
Users.socketConnect(worker, id, data.substr(1, nlPos - 1), data.substr(nlPos + 1));
break;
+ }
- case '!': // !socketid
+ case '!': {
+ // !socketid
// disconnect
Users.socketDisconnect(worker, id, data.substr(1));
break;
+ }
- case '<': //
" + request.socket.localAddress + ":" + request.socket.localPort + " - " + request.method + " " + request.url + " " + request.httpVersion + " - " + request.rawHeaders.join('|'));
request.resume();
request.addListener('end', function () {
@@ -159,7 +170,7 @@ if (cluster.isMaster) {
Config.customhttpresponse(request, response)) {
return;
}
- var server;
+ let server;
if (request.url === '/custom.css') {
server = cssserver;
} else if (request.url.substr(0, 9) === '/avatars/') {
@@ -192,9 +203,9 @@ if (cluster.isMaster) {
// This is the main server that handles users connecting to our server
// and doing things on our server.
- var sockjs = require('sockjs');
+ let sockjs = require('sockjs');
- var server = sockjs.createServer({
+ let server = sockjs.createServer({
sockjs_url: "//play.pokemonshowdown.com/js/lib/sockjs-0.3.min.js",
log: function (severity, message) {
if (severity === 'error') console.log('ERROR: ' + message);
@@ -203,13 +214,13 @@ if (cluster.isMaster) {
websocket: !Config.disablewebsocket
});
- var sockets = {};
- var channels = {};
- var subchannels = {};
+ let sockets = {};
+ let channels = {};
+ let subchannels = {};
// Deal with phantom connections.
- var sweepClosedSockets = function () {
- for (var s in sockets) {
+ let sweepClosedSockets = function () {
+ for (let s in sockets) {
if (sockets[s].protocol === 'xhr-streaming' &&
sockets[s]._session &&
sockets[s]._session.recv) {
@@ -229,14 +240,14 @@ if (cluster.isMaster) {
}
}
};
- var interval = setInterval(sweepClosedSockets, 1000 * 60 * 10);
+ let interval = setInterval(sweepClosedSockets, 1000 * 60 * 10);
process.on('message', function (data) {
// console.log('worker received: ' + data);
- var socket = null;
- var channel = null;
- var socketid = null;
- var channelid = null;
+ let socket = null, socketid = '';
+ let channel = null, channelid = '';
+ let subchannel = null, subchannelid = '';
+
switch (data.charAt(0)) {
case '$': // $code
eval(data.substr(1));
@@ -256,27 +267,32 @@ if (cluster.isMaster) {
}
break;
- case '>': // >socketid, message
+ case '>': {
+ // >socketid, message
// message
- var nlLoc = data.indexOf('\n');
+ let nlLoc = data.indexOf('\n');
socket = sockets[data.substr(1, nlLoc - 1)];
if (!socket) return;
socket.write(data.substr(nlLoc + 1));
break;
+ }
- case '#': // #channelid, message
+ case '#': {
+ // #channelid, message
// message to channel
- var nlLoc = data.indexOf('\n');
+ let nlLoc = data.indexOf('\n');
channel = channels[data.substr(1, nlLoc - 1)];
- var message = data.substr(nlLoc + 1);
+ let message = data.substr(nlLoc + 1);
for (socketid in channel) {
channel[socketid].write(message);
}
break;
+ }
- case '+': // +channelid, socketid
+ case '+': {
+ // +channelid, socketid
// add to channel
- var nlLoc = data.indexOf('\n');
+ let nlLoc = data.indexOf('\n');
socketid = data.substr(nlLoc + 1);
socket = sockets[socketid];
if (!socket) return;
@@ -285,18 +301,20 @@ if (cluster.isMaster) {
if (!channel) channel = channels[channelid] = Object.create(null);
channel[socketid] = socket;
break;
+ }
- case '-': // -channelid, socketid
+ case '-': {
+ // -channelid, socketid
// remove from channel
- var nlLoc = data.indexOf('\n');
- var channelid = data.slice(1, nlLoc);
+ let nlLoc = data.indexOf('\n');
+ channelid = data.slice(1, nlLoc);
channel = channels[channelid];
if (!channel) return;
- var socketid = data.slice(nlLoc + 1);
+ socketid = data.slice(nlLoc + 1);
delete channel[socketid];
if (subchannels[channelid]) delete subchannels[channelid][socketid];
- var isEmpty = true;
- for (var socketid in channel) {
+ let isEmpty = true;
+ for (let socketid in channel) {
isEmpty = false;
break;
}
@@ -305,16 +323,18 @@ if (cluster.isMaster) {
delete subchannels[channelid];
}
break;
+ }
- case '.': // .channelid, subchannelid, socketid
+ case '.': {
+ // .channelid, subchannelid, socketid
// move subchannel
- var nlLoc = data.indexOf('\n');
- var channelid = data.slice(1, nlLoc);
- var nlLoc2 = data.indexOf('\n', nlLoc + 1);
- var subchannelid = data.slice(nlLoc + 1, nlLoc2);
- var socketid = data.slice(nlLoc2 + 1);
+ let nlLoc = data.indexOf('\n');
+ channelid = data.slice(1, nlLoc);
+ let nlLoc2 = data.indexOf('\n', nlLoc + 1);
+ subchannelid = data.slice(nlLoc + 1, nlLoc2);
+ socketid = data.slice(nlLoc2 + 1);
- var subchannel = subchannels[channelid];
+ subchannel = subchannels[channelid];
if (!subchannel) subchannel = subchannels[channelid] = Object.create(null);
if (subchannelid === '0') {
delete subchannel[socketid];
@@ -322,15 +342,17 @@ if (cluster.isMaster) {
subchannel[socketid] = subchannelid;
}
break;
+ }
- case ':': // :channelid, message
+ case ':': {
+ // :channelid, message
// message to subchannel
- var nlLoc = data.indexOf('\n');
- var channelid = data.slice(1, nlLoc);
- var channel = channels[channelid];
- var subchannel = subchannels[channelid];
- var message = data.substr(nlLoc + 1);
- var messages = [null, null, null];
+ let nlLoc = data.indexOf('\n');
+ channelid = data.slice(1, nlLoc);
+ channel = channels[channelid];
+ subchannel = subchannels[channelid];
+ let message = data.substr(nlLoc + 1);
+ let messages = [null, null, null];
for (socketid in channel) {
switch (subchannel ? subchannel[socketid] : '0') {
case '1':
@@ -355,6 +377,9 @@ if (cluster.isMaster) {
}
break;
}
+
+ default:
+ }
});
process.on('disconnect', function () {
@@ -362,8 +387,8 @@ if (cluster.isMaster) {
});
// this is global so it can be hotpatched if necessary
- var isTrustedProxyIp = Cidr.checker(Config.proxyip);
- var socketCounter = 0;
+ let isTrustedProxyIp = Cidr.checker(Config.proxyip);
+ let socketCounter = 0;
server.on('connection', function (socket) {
if (!socket) {
// For reasons that are not entirely clear, SockJS sometimes triggers
@@ -376,13 +401,13 @@ if (cluster.isMaster) {
} catch (e) {}
return;
}
- var socketid = socket.id = (++socketCounter);
+ let socketid = socket.id = (++socketCounter);
sockets[socket.id] = socket;
if (isTrustedProxyIp(socket.remoteAddress)) {
- var ips = (socket.headers['x-forwarded-for'] || '').split(',');
- var ip;
+ let ips = (socket.headers['x-forwarded-for'] || '').split(',');
+ let ip;
while ((ip = ips.pop())) {
ip = ip.trim();
if (!isTrustedProxyIp(ip)) {
@@ -398,7 +423,7 @@ if (cluster.isMaster) {
// drop empty messages (DDoS?)
if (!message) return;
// drop blank messages (DDoS?)
- var pipeIndex = message.indexOf('|');
+ let pipeIndex = message.indexOf('|');
if (pipeIndex < 0 || pipeIndex === message.length - 1) return;
// drop legacy JSON messages
if (!message.charAt) throw new Error('message: ' + JSON.stringify(message));
@@ -409,7 +434,7 @@ if (cluster.isMaster) {
socket.on('close', function () {
process.send('!' + socketid);
delete sockets[socketid];
- for (var channelid in channels) {
+ for (let channelid in channels) {
delete channels[channelid][socketid];
}
});
diff --git a/team-validator.js b/team-validator.js
index 1224377832..0ca3f3ec05 100644
--- a/team-validator.js
+++ b/team-validator.js
@@ -7,23 +7,25 @@
* @license MIT license
*/
-var Validator;
+'use strict';
+
+let Validator;
if (!process.send) {
- var validationCount = 0;
- var pendingValidations = {};
+ let validationCount = 0;
+ let pendingValidations = {};
- var ValidatorProcess = (function () {
+ let ValidatorProcess = (function () {
function ValidatorProcess() {
this.process = require('child_process').fork('team-validator.js', {cwd: __dirname});
- var self = this;
+ let self = this;
this.process.on('message', function (message) {
// Protocol:
// success: "[id]|1[details]"
// failure: "[id]|0[details]"
- var pipeIndex = message.indexOf('|');
- var id = message.substr(0, pipeIndex);
- var success = (message.charAt(pipeIndex + 1) === '1');
+ let pipeIndex = message.indexOf('|');
+ let id = message.substr(0, pipeIndex);
+ let success = (message.charAt(pipeIndex + 1) === '1');
if (pendingValidations[id]) {
ValidatorProcess.release(self);
@@ -36,8 +38,8 @@ if (!process.send) {
ValidatorProcess.prototype.active = true;
ValidatorProcess.processes = [];
ValidatorProcess.spawn = function () {
- var num = Config.validatorprocesses || 1;
- for (var i = 0; i < num; ++i) {
+ let num = Config.validatorprocesses || 1;
+ for (let i = 0; i < num; ++i) {
this.processes.push(new ValidatorProcess());
}
};
@@ -49,8 +51,8 @@ if (!process.send) {
this.spawn();
};
ValidatorProcess.acquire = function () {
- var process = this.processes[0];
- for (var i = 1; i < this.processes.length; ++i) {
+ let process = this.processes[0];
+ for (let i = 1; i < this.processes.length; ++i) {
if (this.processes[i].load < process.load) {
process = this.processes[i];
}
@@ -65,7 +67,7 @@ if (!process.send) {
}
};
ValidatorProcess.send = function (format, team, callback) {
- var process = this.acquire();
+ let process = this.acquire();
pendingValidations[validationCount] = callback;
try {
process.process.send('' + validationCount + '|' + format + '|' + team);
@@ -85,7 +87,7 @@ if (!process.send) {
ValidatorProcess.send(format, team, callback);
};
- var synchronousValidators = {};
+ let synchronousValidators = {};
exports.validateTeamSync = function (format, team) {
if (!synchronousValidators[format]) synchronousValidators[format] = new Validator(format);
return synchronousValidators[format].validateTeam(team);
@@ -132,33 +134,33 @@ if (!process.send) {
require('./repl.js').start('team-validator-', process.pid, function (cmd) { return eval(cmd); });
- var validators = {};
+ let validators = {};
- var respond = function respond(id, success, details) {
+ let respond = function respond(id, success, details) {
process.send(id + (success ? '|1' : '|0') + details);
};
process.on('message', function (message) {
// protocol:
// "[id]|[format]|[team]"
- var pipeIndex = message.indexOf('|');
- var pipeIndex2 = message.indexOf('|', pipeIndex + 1);
- var id = message.substr(0, pipeIndex);
- var format = message.substr(pipeIndex + 1, pipeIndex2 - pipeIndex - 1);
+ let pipeIndex = message.indexOf('|');
+ let pipeIndex2 = message.indexOf('|', pipeIndex + 1);
+ let id = message.substr(0, pipeIndex);
+ let format = message.substr(pipeIndex + 1, pipeIndex2 - pipeIndex - 1);
if (!validators[format]) validators[format] = new Validator(format);
- var parsedTeam = [];
+ let parsedTeam = [];
parsedTeam = Tools.fastUnpackTeam(message.substr(pipeIndex2 + 1));
- var problems;
+ let problems;
try {
problems = validators[format].validateTeam(parsedTeam);
} catch (err) {
- var stack = err.stack + '\n\n' +
+ let stack = err.stack + '\n\n' +
'Additional information:\n' +
'format = ' + format + '\n' +
'team = ' + message.substr(pipeIndex2 + 1) + '\n';
- var fakeErr = {stack: stack};
+ let fakeErr = {stack: stack};
require('./crashlogger.js')(fakeErr, 'A team validation');
problems = ["Your team crashed the team validator. We've been automatically notified and will fix this crash, but you should use a different team for now."];
@@ -167,7 +169,7 @@ if (!process.send) {
if (problems && problems.length) {
respond(id, false, problems.join('\n'));
} else {
- var packedTeam = Tools.packTeam(parsedTeam);
+ let packedTeam = Tools.packTeam(parsedTeam);
// console.log('FROM: ' + message.substr(pipeIndex2 + 1));
// console.log('TO: ' + packedTeam);
respond(id, true, packedTeam);
@@ -186,16 +188,16 @@ Validator = (function () {
}
Validator.prototype.validateTeam = function (team) {
- var format = Tools.getFormat(this.format);
+ let format = Tools.getFormat(this.format);
if (format.validateTeam) return format.validateTeam.call(this, team);
return this.baseValidateTeam(team);
};
Validator.prototype.baseValidateTeam = function (team) {
- var format = this.format;
- var tools = this.tools;
+ let format = this.format;
+ let tools = this.tools;
- var problems = [];
+ let problems = [];
tools.getBanlistTable(format);
if (format.team) {
return false;
@@ -207,7 +209,7 @@ Validator = (function () {
return ["You sent invalid team data. If you're not using a custom client, please report this as a bug."];
}
- var lengthRange = format.teamLength && format.teamLength.validate;
+ let lengthRange = format.teamLength && format.teamLength.validate;
if (!lengthRange) {
lengthRange = [1, 6];
if (format.gameType === 'doubles') lengthRange[0] = 2;
@@ -216,32 +218,32 @@ Validator = (function () {
if (team.length < lengthRange[0]) return ["You must bring at least " + lengthRange[0] + " Pok\u00E9mon."];
if (team.length > lengthRange[1]) return ["You may only bring up to " + lengthRange[1] + " Pok\u00E9mon."];
- var teamHas = {};
- for (var i = 0; i < team.length; i++) {
+ let teamHas = {};
+ for (let i = 0; i < team.length; i++) {
if (!team[i]) return ["You sent invalid team data. If you're not using a custom client, please report this as a bug."];
- var setProblems = (format.validateSet || this.validateSet).call(this, team[i], teamHas);
+ let setProblems = (format.validateSet || this.validateSet).call(this, team[i], teamHas);
if (setProblems) {
problems = problems.concat(setProblems);
}
}
- for (var i = 0; i < format.teamBanTable.length; i++) {
- var bannedCombo = true;
- for (var j = 0; j < format.teamBanTable[i].length; j++) {
+ for (let i = 0; i < format.teamBanTable.length; i++) {
+ let bannedCombo = true;
+ for (let j = 0; j < format.teamBanTable[i].length; j++) {
if (!teamHas[format.teamBanTable[i][j]]) {
bannedCombo = false;
break;
}
}
if (bannedCombo) {
- var clause = format.name ? " by " + format.name : '';
+ let clause = format.name ? " by " + format.name : '';
problems.push("Your team has the combination of " + format.teamBanTable[i].join(' + ') + ", which is banned" + clause + ".");
}
}
if (format.ruleset) {
- for (var i = 0; i < format.ruleset.length; i++) {
- var subformat = tools.getFormat(format.ruleset[i]);
+ for (let i = 0; i < format.ruleset.length; i++) {
+ let subformat = tools.getFormat(format.ruleset[i]);
if (subformat.onValidateTeam) {
problems = problems.concat(subformat.onValidateTeam.call(tools, team, format, teamHas) || []);
}
@@ -256,29 +258,29 @@ Validator = (function () {
};
Validator.prototype.validateSet = function (set, teamHas, flags) {
- var format = this.format;
- var tools = this.tools;
+ let format = this.format;
+ let tools = this.tools;
- var problems = [];
+ let problems = [];
if (!set) {
return ["This is not a Pokemon."];
}
- var template = tools.getTemplate(Tools.getString(set.species));
+ let template = tools.getTemplate(Tools.getString(set.species));
if (!template.exists) {
return ["The Pokemon '" + set.species + "' does not exist."];
}
set.species = template.species;
set.name = tools.getName(set.name);
- var item = tools.getItem(Tools.getString(set.item));
+ let item = tools.getItem(Tools.getString(set.item));
set.item = item.name;
- var ability = tools.getAbility(Tools.getString(set.ability));
+ let ability = tools.getAbility(Tools.getString(set.ability));
set.ability = ability.name;
if (!Array.isArray(set.moves)) set.moves = [];
- var maxLevel = format.maxLevel || 100;
- var maxForcedLevel = format.maxForcedLevel || maxLevel;
+ let maxLevel = format.maxLevel || 100;
+ let maxForcedLevel = format.maxForcedLevel || maxLevel;
if (!set.level) {
set.level = (format.defaultLevel || maxLevel);
}
@@ -291,17 +293,17 @@ Validator = (function () {
set.level = maxLevel;
}
- var nameTemplate = tools.getTemplate(set.name);
+ let nameTemplate = tools.getTemplate(set.name);
if (nameTemplate.exists && nameTemplate.name.toLowerCase() === set.name.toLowerCase()) set.name = null;
set.species = set.species;
set.name = set.name || set.species;
- var name = set.species;
+ let name = set.species;
if (set.species !== set.name) name = set.name + " (" + set.species + ")";
- var isHidden = false;
- var lsetData = {set:set, format:format};
+ let isHidden = false;
+ let lsetData = {set:set, format:format};
if (flags) Object.merge(lsetData, flags);
- var setHas = {};
+ let setHas = {};
if (!template || !template.abilities) {
set.species = 'Unown';
@@ -309,8 +311,8 @@ Validator = (function () {
}
if (format.ruleset) {
- for (var i = 0; i < format.ruleset.length; i++) {
- var subformat = tools.getFormat(format.ruleset[i]);
+ for (let i = 0; i < format.ruleset.length; i++) {
+ let subformat = tools.getFormat(format.ruleset[i]);
if (subformat.onChangeSet) {
problems = problems.concat(subformat.onChangeSet.call(tools, set, format) || []);
}
@@ -335,10 +337,10 @@ Validator = (function () {
}
}
- var banlistTable = tools.getBanlistTable(format);
+ let banlistTable = tools.getBanlistTable(format);
- var check = template.id;
- var clause = '';
+ let check = template.id;
+ let clause = '';
setHas[check] = true;
if (banlistTable[check]) {
clause = typeof banlistTable[check] === 'string' ? " by " + banlistTable[check] : '';
@@ -412,9 +414,9 @@ Validator = (function () {
// in the cartridge-compliant set validator: rulesets.js:pokemon
set.moves = set.moves.slice(0, 24);
- for (var i = 0; i < set.moves.length; i++) {
+ for (let i = 0; i < set.moves.length; i++) {
if (!set.moves[i]) continue;
- var move = tools.getMove(Tools.getString(set.moves[i]));
+ let move = tools.getMove(Tools.getString(set.moves[i]));
if (!move.exists) return ['"' + move.name + '" is an invalid move.'];
set.moves[i] = move.name;
check = move.id;
@@ -429,9 +431,9 @@ Validator = (function () {
}
if (banlistTable['illegal']) {
- var problem = this.checkLearnset(move, template, lsetData);
+ let problem = this.checkLearnset(move, template, lsetData);
if (problem) {
- var problemString = name + " can't learn " + move.name;
+ let problemString = name + " can't learn " + move.name;
if (problem.type === 'incompatible') {
if (isHidden) {
problemString = problemString.concat(" because it's incompatible with its ability or another move.");
@@ -452,12 +454,12 @@ Validator = (function () {
if (lsetData.sources && lsetData.sources.length === 1 && !lsetData.sourcesBefore) {
// we're restricted to a single source
- var source = lsetData.sources[0];
+ let source = lsetData.sources[0];
if (source.charAt(1) === 'S') {
// it's an event
- var eventData = null;
- var splitSource = source.substr(2).split(' ');
- var eventTemplate = tools.getTemplate(splitSource[1]);
+ let eventData = null;
+ let splitSource = source.substr(2).split(' ');
+ let eventTemplate = tools.getTemplate(splitSource[1]);
if (eventTemplate.eventPokemon) eventData = eventTemplate.eventPokemon[parseInt(splitSource[0], 10)];
if (eventData) {
if (eventData.nature && eventData.nature !== set.nature) {
@@ -487,8 +489,8 @@ Validator = (function () {
if (!lsetData.sources && lsetData.sourcesBefore < 5) {
problems.push(name + " has a hidden ability - it can't have moves only learned before gen 5.");
} else if (lsetData.sources && template.gender && template.gender !== 'F' && !{'Nidoran-M':1, 'Nidorino':1, 'Nidoking':1, 'Volbeat':1}[template.species]) {
- var compatibleSource = false;
- for (var i = 0, len = lsetData.sources.length; i < len; i++) {
+ let compatibleSource = false;
+ for (let i = 0, len = lsetData.sources.length; i < len; i++) {
if (lsetData.sources[i].charAt(1) === 'E' || (lsetData.sources[i].substr(0, 2) === '5D' && set.level >= 10)) {
compatibleSource = true;
break;
@@ -507,7 +509,7 @@ Validator = (function () {
problems.push(name + " has a gen 4 ability and isn't evolved - it can't use anything from gen 3.");
}
if (!lsetData.sources && lsetData.sourcesBefore >= 3 && (isHidden || tools.gen <= 5) && template.gen <= lsetData.sourcesBefore) {
- var oldAbilities = tools.mod('gen' + lsetData.sourcesBefore).getTemplate(set.species).abilities;
+ let oldAbilities = tools.mod('gen' + lsetData.sourcesBefore).getTemplate(set.species).abilities;
if (ability.name !== oldAbilities['0'] && ability.name !== oldAbilities['1'] && !oldAbilities['H']) {
problems.push(name + " has moves incompatible with its ability.");
}
@@ -517,7 +519,7 @@ Validator = (function () {
template = tools.getTemplate(item.megaStone);
}
if (template.tier) {
- var tier = template.tier;
+ let tier = template.tier;
if (tier.charAt(0) === '(') tier = tier.slice(1, -1);
setHas[toId(tier)] = true;
if (banlistTable[tier]) {
@@ -526,13 +528,13 @@ Validator = (function () {
}
if (teamHas) {
- for (var i in setHas) {
+ for (let i in setHas) {
teamHas[i] = true;
}
}
- for (var i = 0; i < format.setBanTable.length; i++) {
- var bannedCombo = true;
- for (var j = 0; j < format.setBanTable[i].length; j++) {
+ for (let i = 0; i < format.setBanTable.length; i++) {
+ let bannedCombo = true;
+ for (let j = 0; j < format.setBanTable[i].length; j++) {
if (!setHas[format.setBanTable[i][j]]) {
bannedCombo = false;
break;
@@ -545,8 +547,8 @@ Validator = (function () {
}
if (format.ruleset) {
- for (var i = 0; i < format.ruleset.length; i++) {
- var subformat = tools.getFormat(format.ruleset[i]);
+ for (let i = 0; i < format.ruleset.length; i++) {
+ let subformat = tools.getFormat(format.ruleset[i]);
if (subformat.onValidateSet) {
problems = problems.concat(subformat.onValidateSet.call(tools, set, format, setHas, teamHas) || []);
}
@@ -565,27 +567,27 @@ Validator = (function () {
};
Validator.prototype.checkLearnset = function (move, template, lsetData) {
- var tools = this.tools;
+ let tools = this.tools;
move = toId(move);
template = tools.getTemplate(template);
lsetData = lsetData || {};
lsetData.eggParents = lsetData.eggParents || [];
- var set = (lsetData.set || (lsetData.set = {}));
- var format = (lsetData.format || (lsetData.format = {}));
- var alreadyChecked = {};
- var level = set.level || 100;
+ let set = (lsetData.set || (lsetData.set = {}));
+ let format = (lsetData.format || (lsetData.format = {}));
+ let alreadyChecked = {};
+ let level = set.level || 100;
- var isHidden = false;
+ let isHidden = false;
if (set.ability && tools.getAbility(set.ability).name === template.abilities['H']) isHidden = true;
- var incompatibleHidden = false;
+ let incompatibleHidden = false;
- var limit1 = true;
- var sketch = false;
- var blockedHM = false;
+ let limit1 = true;
+ let sketch = false;
+ let blockedHM = false;
- var sometimesPossible = false; // is this move in the learnset at all?
+ let sometimesPossible = false; // is this move in the learnset at all?
// This is a pretty complicated algorithm
@@ -602,18 +604,18 @@ Validator = (function () {
// source at or before this gen is possible."
// set of possible sources of a pokemon with this move, represented as an array
- var sources = [];
+ let sources = [];
// the equivalent of adding "every source at or before this gen" to sources
- var sourcesBefore = 0;
- var noPastGen = !!format.requirePentagon;
+ let sourcesBefore = 0;
+ let noPastGen = !!format.requirePentagon;
// since Gen 3, Pokemon cannot be traded to past generations
- var noFutureGen = tools.gen >= 3 ? true : !!(format.banlistTable && format.banlistTable['tradeback']);
+ let noFutureGen = tools.gen >= 3 ? true : !!(format.banlistTable && format.banlistTable['tradeback']);
do {
alreadyChecked[template.speciesid] = true;
// STABmons hack to avoid copying all of validateSet to formats
if (move !== 'chatter' && lsetData['ignorestabmoves'] && lsetData['ignorestabmoves'][this.tools.getMove(move).category]) {
- var types = template.types;
+ let types = template.types;
if (template.species === 'Shaymin') types = ['Grass', 'Flying'];
if (template.baseSpecies === 'Hoopa') types = ['Psychic', 'Ghost', 'Dark'];
if (types.indexOf(tools.getMove(move).type) >= 0) return false;
@@ -621,7 +623,7 @@ Validator = (function () {
if (template.learnset) {
if (template.learnset[move] || template.learnset['sketch']) {
sometimesPossible = true;
- var lset = template.learnset[move];
+ let lset = template.learnset[move];
if (!lset || template.speciesid === 'smeargle') {
if (tools.getMove(move).noSketch) return true;
lset = template.learnset['sketch'];
@@ -629,8 +631,8 @@ Validator = (function () {
}
if (typeof lset === 'string') lset = [lset];
- for (var i = 0, len = lset.length; i < len; i++) {
- var learned = lset[i];
+ for (let i = 0, len = lset.length; i < len; i++) {
+ let learned = lset[i];
if (noPastGen && learned.charAt(0) !== '6') continue;
if (noFutureGen && parseInt(learned.charAt(0), 10) > tools.gen) continue;
if (learned.charAt(0) !== '6' && isHidden && !tools.mod('gen' + learned.charAt(0)).getTemplate(template.species).abilities['H']) {
@@ -681,14 +683,14 @@ Validator = (function () {
sources.push(learned);
continue;
}
- var eggGroups = template.eggGroups;
+ let eggGroups = template.eggGroups;
if (!eggGroups) continue;
if (eggGroups[0] === 'Undiscovered') eggGroups = tools.getTemplate(template.evos[0]).eggGroups;
- var atLeastOne = false;
- var fromSelf = (learned.substr(1) === 'Eany');
+ let atLeastOne = false;
+ let fromSelf = (learned.substr(1) === 'Eany');
learned = learned.substr(0, 2);
- for (var templateid in tools.data.Pokedex) {
- var dexEntry = tools.getTemplate(templateid);
+ for (let templateid in tools.data.Pokedex) {
+ let dexEntry = tools.getTemplate(templateid);
if (
// CAP pokemon can't breed
!dexEntry.isNonstandard &&
@@ -706,20 +708,20 @@ Validator = (function () {
// If the mon already has an egg move by a father, other different father can't give it another egg move.
if (lsetData.eggParents.indexOf(dexEntry.species) >= 0) {
// We have to test here that the father of both moves doesn't get both by egg breeding
- var learnsFrom = false;
- var lsetToCheck = (dexEntry.learnset[lsetData.hasEggMove]) ? dexEntry.learnset[lsetData.hasEggMove] : dexEntry.learnset['sketch'];
+ let learnsFrom = false;
+ let lsetToCheck = (dexEntry.learnset[lsetData.hasEggMove]) ? dexEntry.learnset[lsetData.hasEggMove] : dexEntry.learnset['sketch'];
if (!lsetToCheck || !lsetToCheck.length) continue;
- for (var ltype = 0; ltype < lsetToCheck.length; ltype++) {
+ for (let ltype = 0; ltype < lsetToCheck.length; ltype++) {
// Save first learning type. After that, only save it if we have egg and it's not egg.
learnsFrom = !learnsFrom || learnsFrom === 'E' ? lsetToCheck[ltype].charAt(1) : learnsFrom;
}
// If the previous egg move was learnt by the father through an egg as well:
if (learnsFrom === 'E') {
- var secondLearnsFrom = false;
- var lsetToCheck = (dexEntry.learnset[move]) ? dexEntry.learnset[move] : dexEntry.learnset['sketch'];
+ let secondLearnsFrom = false;
+ let lsetToCheck = (dexEntry.learnset[move]) ? dexEntry.learnset[move] : dexEntry.learnset['sketch'];
// Have here either the move learnset or sketch learnset for Smeargle.
if (lsetToCheck) {
- for (var ltype = 0; ltype < lsetToCheck.length; ltype++) {
+ for (let ltype = 0; ltype < lsetToCheck.length; ltype++) {
// Save first learning type. After that, only save it if we have egg and it's not egg.
secondLearnsFrom = !secondLearnsFrom || secondLearnsFrom === 'E' ? dexEntry.learnset[move][ltype].charAt(1) : secondLearnsFrom;
}
@@ -761,7 +763,7 @@ Validator = (function () {
lsetData.blockedGen2Move = lsetData.hasGen2Move && tools.gen === 2 && (lsetData.sourcesBefore ? lsetData.sourcesBefore : sourcesBefore) > 0 && (lsetData.sourcesBefore ? lsetData.sourcesBefore : sourcesBefore) < parseInt(learned.charAt(0), 10);
} else {
// DW Pokemon are at level 10 or at the evolution level
- var minLevel = (template.evoLevel && template.evoLevel > 10) ? template.evoLevel : 10;
+ let minLevel = (template.evoLevel && template.evoLevel > 10) ? template.evoLevel : 10;
if (set.level < minLevel) continue;
sources.push(learned);
}
@@ -770,9 +772,9 @@ Validator = (function () {
}
if (format.mimicGlitch && template.gen < 5) {
// include the Mimic Glitch when checking this mon's learnset
- var glitchMoves = {metronome:1, copycat:1, transform:1, mimic:1, assist:1};
- var getGlitch = false;
- for (var i in glitchMoves) {
+ let glitchMoves = {metronome:1, copycat:1, transform:1, mimic:1, assist:1};
+ let getGlitch = false;
+ for (let i in glitchMoves) {
if (template.learnset[i]) {
if (!(i === 'mimic' && tools.getAbility(set.ability).gen === 4 && !template.prevo)) {
getGlitch = true;
@@ -832,10 +834,10 @@ Validator = (function () {
if (sourcesBefore || lsetData.sourcesBefore) {
// having sourcesBefore is the equivalent of having everything before that gen
// in sources, so we fill the other array in preparation for intersection
- var learned;
+ let learned;
if (sourcesBefore && lsetData.sources) {
if (!sources) sources = [];
- for (var i = 0, len = lsetData.sources.length; i < len; i++) {
+ for (let i = 0, len = lsetData.sources.length; i < len; i++) {
learned = lsetData.sources[i];
if (parseInt(learned.charAt(0), 10) <= sourcesBefore) {
sources.push(learned);
@@ -845,7 +847,7 @@ Validator = (function () {
}
if (lsetData.sourcesBefore && sources) {
if (!lsetData.sources) lsetData.sources = [];
- for (var i = 0, len = sources.length; i < len; i++) {
+ for (let i = 0, len = sources.length; i < len; i++) {
learned = sources[i];
if (parseInt(learned.charAt(0), 10) <= lsetData.sourcesBefore) {
lsetData.sources.push(learned);
@@ -856,7 +858,7 @@ Validator = (function () {
}
if (sources) {
if (lsetData.sources) {
- var intersectSources = lsetData.sources.intersect(sources);
+ let intersectSources = lsetData.sources.intersect(sources);
if (!intersectSources.length && !(sourcesBefore && lsetData.sourcesBefore)) {
return {type:'incompatible'};
}
diff --git a/test/application/rooms.js b/test/application/rooms.js
index 62cd5cf0da..09048ac437 100644
--- a/test/application/rooms.js
+++ b/test/application/rooms.js
@@ -1,8 +1,10 @@
-var assert = require('assert');
-var room;
+'use strict';
-var userUtils = require('./../../dev-tools/users-utils.js');
-var User = userUtils.User;
+const assert = require('assert');
+let room;
+
+let userUtils = require('./../../dev-tools/users-utils.js');
+let User = userUtils.User;
describe('Rooms features', function () {
describe('Rooms', function () {
@@ -27,16 +29,16 @@ describe('Rooms features', function () {
});
describe('BattleRoom', function () {
- var room;
+ let room;
afterEach(function () {
if (room) room.expire();
});
it('should allow two users to join the battle', function () {
- var p1 = new User();
- var p2 = new User();
- var packedTeam = 'Weavile||lifeorb||swordsdance,knockoff,iceshard,iciclecrash|Jolly|,252,,,4,252|||||';
- var options = [{rated: false, tour: false}, {rated: false, tour: true}, {rated: true, tour: false}, {rated: true, tour: true}];
+ let p1 = new User();
+ let p2 = new User();
+ let packedTeam = 'Weavile||lifeorb||swordsdance,knockoff,iceshard,iciclecrash|Jolly|,252,,,4,252|||||';
+ let options = [{rated: false, tour: false}, {rated: false, tour: true}, {rated: true, tour: false}, {rated: true, tour: true}];
options.forEach(function (option) {
room = Rooms.global.startBattle(p1, p2, 'customgame', packedTeam, packedTeam, option);
if (room.active) return assert.ok(room.battle.players.none(null)); // Automatically joined
diff --git a/test/application/simulator.js b/test/application/simulator.js
index f03b3c2df5..2d77d4c1ec 100644
--- a/test/application/simulator.js
+++ b/test/application/simulator.js
@@ -1,11 +1,13 @@
-var assert = require('assert');
-var userUtils = require('./../../dev-tools/users-utils.js');
-var User = userUtils.User;
+'use strict';
+
+const assert = require('assert');
+let userUtils = require('./../../dev-tools/users-utils.js');
+let User = userUtils.User;
describe('Simulator abstraction layer features', function () {
describe('Battle', function () {
describe('player identifiers', function () {
- var p1, p2, room;
+ let p1, p2, room;
afterEach(function () {
if (p1) {
p1.disconnectAll();
@@ -19,7 +21,7 @@ describe('Simulator abstraction layer features', function () {
});
it('should not get out of sync in rated battles on rename', function () {
- var packedTeam = 'Weavile||lifeorb||swordsdance,knockoff,iceshard,iciclecrash|Jolly|,252,,,4,252|||||';
+ let packedTeam = 'Weavile||lifeorb||swordsdance,knockoff,iceshard,iciclecrash|Jolly|,252,,,4,252|||||';
p1 = new User();
p2 = new User();
p1.forceRename("Missingno."); // Don't do this at home
@@ -29,8 +31,8 @@ describe('Simulator abstraction layer features', function () {
room.joinBattle(p2, packedTeam);
}
p1.resetName();
- for (var i = 0; i < room.battle.playerids.length; i++) {
- var curId = room.battle.playerids[i];
+ for (let i = 0; i < room.battle.playerids.length; i++) {
+ let curId = room.battle.playerids[i];
assert.strictEqual(room.battle.playerTable[curId], 'p' + (i + 1));
if (!curId) {
assert.ok(!room.battle.players[i]);
diff --git a/test/application/users.js b/test/application/users.js
index 89b7b9c65d..d2816a1233 100644
--- a/test/application/users.js
+++ b/test/application/users.js
@@ -1,8 +1,10 @@
-var assert = require('assert');
+'use strict';
-var userUtils = require('./../../dev-tools/users-utils.js');
-var Connection = userUtils.Connection;
-var User = userUtils.User;
+const assert = require('assert');
+
+let userUtils = require('./../../dev-tools/users-utils.js');
+let Connection = userUtils.Connection;
+let User = userUtils.User;
describe('Users features', function () {
describe('Users', function () {
@@ -28,8 +30,8 @@ describe('Users features', function () {
describe('#disconnectAll', function () {
[1, 2].forEach(function (totalConnections) {
it('should drop all ' + totalConnections + ' connection(s) and mark as inactive', function () {
- var user = new User();
- var iterations = totalConnections;
+ let user = new User();
+ let iterations = totalConnections;
while (--iterations) user.mergeConnection(new Connection());
user.disconnectAll();
@@ -38,26 +40,26 @@ describe('Users features', function () {
});
it('should unref all ' + totalConnections + ' connection(s)', function () {
- var user = new User();
- var iterations = totalConnections;
+ let user = new User();
+ let iterations = totalConnections;
while (--iterations) user.mergeConnection(new Connection());
- var connections = user.connections.slice();
+ let connections = user.connections.slice();
user.disconnectAll();
- for (var i = 0; i < totalConnections; i++) {
+ for (let i = 0; i < totalConnections; i++) {
assert.strictEqual(Users.connections[connections[i].id], undefined);
}
});
it('should clear `user` property for all ' + totalConnections + ' connection(s)', function () {
- var user = new User();
- var iterations = totalConnections;
+ let user = new User();
+ let iterations = totalConnections;
while (--iterations) user.mergeConnection(new Connection());
- var connections = user.connections.slice();
+ let connections = user.connections.slice();
user.disconnectAll();
- for (var i = 0; i < totalConnections; i++) {
+ for (let i = 0; i < totalConnections; i++) {
assert.strictEqual(connections[i].user, null);
}
});
@@ -65,28 +67,28 @@ describe('Users features', function () {
});
describe('#ban', function () {
afterEach(function () {
- for (var ip in Users.bannedIps) {
+ for (let ip in Users.bannedIps) {
delete Users.bannedIps[ip];
}
});
it('should disconnect every user at that IP', function () {
- var users = ['127.0.0.1', '127.0.0.1'].map(function (ip) {return new User(new Connection(ip));});
+ let users = ['127.0.0.1', '127.0.0.1'].map(function (ip) {return new User(new Connection(ip));});
users[0].ban();
assert.strictEqual(users[0].connected, false);
assert.strictEqual(users[1].connected, false);
});
it('should not disconnect users at other IPs', function () {
- var users = ['127.0.0.1', '127.0.0.2'].map(function (ip) {return new User(new Connection(ip));});
+ let users = ['127.0.0.1', '127.0.0.2'].map(function (ip) {return new User(new Connection(ip));});
users[0].ban();
assert.strictEqual(users[1].connected, true);
});
it('should update IP count properly', function () {
- var user = new User();
+ let user = new User();
user.ban();
- for (var ip in user.ips) {
+ for (let ip in user.ips) {
assert.strictEqual(user.ips[ip], 0);
}
});
diff --git a/test/dev-tools/jscs-custom-rules/validate-case-indentation.js b/test/dev-tools/jscs-custom-rules/validate-case-indentation.js
index fa0777e2bd..cfd7a8bf4d 100644
--- a/test/dev-tools/jscs-custom-rules/validate-case-indentation.js
+++ b/test/dev-tools/jscs-custom-rules/validate-case-indentation.js
@@ -1,8 +1,10 @@
-var Checker = require('jscs');
-var assert = require('assert');
+'use strict';
+
+const Checker = require('jscs');
+const assert = require('assert');
describe('rules/validate-case-indentation', function () {
- var checker;
+ let checker;
before(function () {
checker = new Checker();
@@ -14,7 +16,7 @@ describe('rules/validate-case-indentation', function () {
describe('option value true', function () {
it('should report cases not aligned with switch keyword', function () {
- var src = 'switch (Number.isFinite) {\n';
+ let src = 'switch (Number.isFinite) {\n';
src += '\tcase isFinite:\n';
src += '\t\tbreak;\n';
src += '}';
@@ -22,7 +24,7 @@ describe('rules/validate-case-indentation', function () {
});
it('should not report cases aligned with switch keyword', function () {
- var src = 'switch (Number.isFinite) {\n';
+ let src = 'switch (Number.isFinite) {\n';
src += 'case isFinite:\n';
src += '\tbreak;\n';
src += '}';
@@ -30,14 +32,14 @@ describe('rules/validate-case-indentation', function () {
});
it('should report default case not aligned with switch keyword', function () {
- var src = 'switch (Number.isFinite) {\n';
+ let src = 'switch (Number.isFinite) {\n';
src += '\tdefault:\n';
src += '}';
assert(!checker.checkString(src).isEmpty());
});
it('should not report default case aligned with switch keyword', function () {
- var src = 'switch (Number.isFinite) {\n';
+ let src = 'switch (Number.isFinite) {\n';
src += 'default:\n';
src += '}';
assert(checker.checkString(src).isEmpty());
diff --git a/test/dev-tools/jscs-custom-rules/validate-conditionals.js b/test/dev-tools/jscs-custom-rules/validate-conditionals.js
index f80bae3cdc..b71cdc90d9 100644
--- a/test/dev-tools/jscs-custom-rules/validate-conditionals.js
+++ b/test/dev-tools/jscs-custom-rules/validate-conditionals.js
@@ -1,8 +1,10 @@
-var Checker = require('jscs');
-var assert = require('assert');
+'use strict';
+
+const Checker = require('jscs');
+const assert = require('assert');
describe('rules/validate-conditionals', function () {
- var checker;
+ let checker;
before(function () {
checker = new Checker();
diff --git a/test/main.js b/test/main.js
index 541ab05c6b..9b4f1bfd35 100644
--- a/test/main.js
+++ b/test/main.js
@@ -1,14 +1,16 @@
-var assert = require('assert');
-var stream = require('stream');
-var path = require('path');
-var net = require('net');
-var fs = require('fs');
-var noop = function () {};
+'use strict';
-var testPort;
+const assert = require('assert');
+const stream = require('stream');
+const path = require('path');
+const net = require('net');
+const fs = require('fs');
+const noop = function () {};
+
+let testPort;
function getPort(callback) {
- var port = testPort;
- var server = net.createServer();
+ let port = testPort;
+ let server = net.createServer();
server.listen(port, function (err) {
server.once('close', function onclose() {
@@ -29,7 +31,7 @@ function init(callback) {
});
// Run the battle engine in the main process to keep our sanity
- var BattleEngine = global.BattleEngine = require('./../battle-engine.js');
+ let BattleEngine = global.BattleEngine = require('./../battle-engine.js');
process.listeners('message').forEach(function (listener) {
process.removeListener('message', listener);
});
@@ -38,7 +40,7 @@ function init(callback) {
BattleEngine.Battle.prototype.send = noop;
BattleEngine.Battle.prototype.receive = noop;
- var Simulator = global.Simulator;
+ let Simulator = global.Simulator;
Simulator.Battle.prototype.send = noop;
Simulator.Battle.prototype.receive = noop;
Simulator.SimulatorProcess.processes.forEach(function (process) {
@@ -62,7 +64,7 @@ before('initialization', function (done) {
this.timeout(0); // Remove timeout limitation
// Load and override configuration before starting the server
- var config;
+ let config;
try {
config = require('./../config/config.js');
} catch (err) {
@@ -75,7 +77,7 @@ before('initialization', function (done) {
config = require('./../config/config.js');
}
try {
- var chatRoomsPath = require.resolve('./../config/chatrooms.json');
+ let chatRoomsPath = require.resolve('./../config/chatrooms.json');
require.cache[chatRoomsPath] = [];
} catch (e) {}
@@ -91,8 +93,8 @@ before('initialization', function (done) {
config.logchat = false;
// TODO: Use a proper fs sandbox
- var fsMethodsNullify = ['chmod', 'rename', 'rmdir', 'symlink', 'unlink', 'writeFile'];
- for (var i = 0; i < fsMethodsNullify.length; i++) {
+ let fsMethodsNullify = ['chmod', 'rename', 'rmdir', 'symlink', 'unlink', 'writeFile'];
+ for (let i = 0; i < fsMethodsNullify.length; i++) {
fs[fsMethodsNullify[i]] = noop;
fs[fsMethodsNullify[i] + 'Sync'] = noop;
}
@@ -114,7 +116,7 @@ before('initialization', function (done) {
});
describe('Native timer/event loop globals', function () {
- var globalList = ['setTimeout', 'clearTimeout', 'setImmediate', 'clearImmediate'];
+ let globalList = ['setTimeout', 'clearTimeout', 'setImmediate', 'clearImmediate'];
globalList.forEach(function (elem) {
describe('`' + elem + '`', function () {
it('should be a global function', function () {
diff --git a/test/simulator/abilities/arenatrap.js b/test/simulator/abilities/arenatrap.js
index e1c9254c0e..8b9a1f06f1 100644
--- a/test/simulator/abilities/arenatrap.js
+++ b/test/simulator/abilities/arenatrap.js
@@ -1,5 +1,7 @@
-var assert = require('assert');
-var battle;
+'use strict';
+
+const assert = require('assert');
+let battle;
describe('Arena Trap', function () {
afterEach(function () {
diff --git a/test/simulator/abilities/battlearmor.js b/test/simulator/abilities/battlearmor.js
index 754eea7a48..ef417f61f9 100644
--- a/test/simulator/abilities/battlearmor.js
+++ b/test/simulator/abilities/battlearmor.js
@@ -1,5 +1,7 @@
-var assert = require('assert');
-var battle;
+'use strict';
+
+const assert = require('assert');
+let battle;
describe('Battle Armor', function () {
afterEach(function () {
@@ -11,7 +13,7 @@ describe('Battle Armor', function () {
battle.join('p1', 'Guest 1', 1, [{species: 'Slowbro', ability: 'battlearmor', moves: ['quickattack']}]);
battle.join('p2', 'Guest 2', 1, [{species: 'Cyrogonal', ability: 'noguard', moves: ['frostbreath']}]);
battle.commitDecisions(); // Team Preview
- var successfulEvent = false;
+ let successfulEvent = false;
battle.on('ModifyDamage', battle.getFormat(), function (damage, attacker, defender, move) {
if (move.id === 'frostbreath') {
successfulEvent = true;
@@ -27,7 +29,7 @@ describe('Battle Armor', function () {
battle.join('p1', 'Guest 1', 1, [{species: 'Slowbro', ability: 'battlearmor', moves: ['quickattack']}]);
battle.join('p2', 'Guest 2', 1, [{species: 'Cyrogonal', ability: 'moldbreaker', item: 'zoomlens', moves: ['frostbreath']}]);
battle.commitDecisions(); // Team Preview
- var successfulEvent = false;
+ let successfulEvent = false;
battle.on('ModifyDamage', battle.getFormat(), function (damage, attacker, defender, move) {
if (move.id === 'frostbreath') {
successfulEvent = true;
diff --git a/test/simulator/abilities/clearbody.js b/test/simulator/abilities/clearbody.js
index 40601abaec..ad40c57ccd 100644
--- a/test/simulator/abilities/clearbody.js
+++ b/test/simulator/abilities/clearbody.js
@@ -1,5 +1,7 @@
-var assert = require('assert');
-var battle;
+'use strict';
+
+const assert = require('assert');
+let battle;
describe('Clear Body', function () {
afterEach(function () {
@@ -10,11 +12,11 @@ describe('Clear Body', function () {
battle = BattleEngine.Battle.construct();
battle.join('p1', 'Guest 1', 1, [{species: 'Tentacruel', ability: 'clearbody', moves: ['recover']}]);
battle.join('p2', 'Guest 2', 1, [{species: 'Arbok', ability: 'intimidate', moves: ['acidspray', 'leer', 'icywind', 'charm', 'confide']}]);
- var stats = Object.keys(battle.p1.active[0].boosts);
- for (var i = 1; i <= 5; i++) {
+ let stats = Object.keys(battle.p1.active[0].boosts);
+ for (let i = 1; i <= 5; i++) {
battle.choose('p2', 'move ' + i);
battle.commitDecisions();
- for (var j = 0; j < stats.length; j++) {
+ for (let j = 0; j < stats.length; j++) {
assert.strictEqual(battle.p1.active[0].boosts[stats[j]], 0);
}
}
diff --git a/test/simulator/abilities/cloudnine.js b/test/simulator/abilities/cloudnine.js
index dd0f458a05..e50f83e870 100644
--- a/test/simulator/abilities/cloudnine.js
+++ b/test/simulator/abilities/cloudnine.js
@@ -1,5 +1,7 @@
-var assert = require('assert');
-var battle;
+'use strict';
+
+const assert = require('assert');
+let battle;
describe('Cloud Nine', function () {
afterEach(function () {
@@ -18,7 +20,7 @@ describe('Cloud Nine', function () {
it('should negate the effects of Sun on Fire-type and Water-type attacks', function () {
battle = BattleEngine.Battle.construct();
- var move, basePower;
+ let move, basePower;
battle.join('p1', 'Guest 1', 1, [{species: 'Groudon', ability: 'drought', moves: ['rest']}]);
battle.join('p2', 'Guest 2', 1, [{species: 'Golduck', ability: 'cloudnine', moves: ['calmmind']}]);
battle.commitDecisions();
@@ -32,7 +34,7 @@ describe('Cloud Nine', function () {
it('should negate the effects of Rain on Fire-type and Water-type attacks', function () {
battle = BattleEngine.Battle.construct();
- var move, basePower;
+ let move, basePower;
battle.join('p1', 'Guest 1', 1, [{species: 'Kyogre', ability: 'drizzle', moves: ['rest']}]);
battle.join('p2', 'Guest 2', 1, [{species: 'Golduck', ability: 'cloudnine', moves: ['calmmind']}]);
battle.commitDecisions();
@@ -90,7 +92,7 @@ describe('Cloud Nine', function () {
battle.join('p2', 'Guest 2', 1, [{species: 'Sunkern', ability: 'solarpower', moves: ['sunnyday']}]);
battle.commitDecisions();
assert.strictEqual(battle.log[battle.lastMoveLine + 1], '|-weather|SunnyDay');
- for (var i = 0; i < 4; i++) {
+ for (let i = 0; i < 4; i++) {
assert.strictEqual(battle.log[battle.lastMoveLine + 3], '|-weather|SunnyDay|[upkeep]');
battle.commitDecisions();
}
diff --git a/test/simulator/abilities/colorchange.js b/test/simulator/abilities/colorchange.js
index 677dc11fa5..baf8da871d 100644
--- a/test/simulator/abilities/colorchange.js
+++ b/test/simulator/abilities/colorchange.js
@@ -1,5 +1,7 @@
-var assert = require('assert');
-var battle;
+'use strict';
+
+const assert = require('assert');
+let battle;
describe('Color Change', function () {
afterEach(function () {
diff --git a/test/simulator/abilities/contrary.js b/test/simulator/abilities/contrary.js
index 2bb8dbb763..d4373c57dd 100644
--- a/test/simulator/abilities/contrary.js
+++ b/test/simulator/abilities/contrary.js
@@ -1,5 +1,7 @@
-var assert = require('assert');
-var battle;
+'use strict';
+
+const assert = require('assert');
+let battle;
describe('Contrary', function () {
afterEach(function () {
diff --git a/test/simulator/abilities/damp.js b/test/simulator/abilities/damp.js
index dbe932c690..07056e2629 100644
--- a/test/simulator/abilities/damp.js
+++ b/test/simulator/abilities/damp.js
@@ -1,5 +1,7 @@
-var assert = require('assert');
-var battle;
+'use strict';
+
+const assert = require('assert');
+let battle;
describe('Damp', function () {
afterEach(function () {
diff --git a/test/simulator/abilities/deltastream.js b/test/simulator/abilities/deltastream.js
index 025a1e3b70..aafecdf56a 100644
--- a/test/simulator/abilities/deltastream.js
+++ b/test/simulator/abilities/deltastream.js
@@ -1,5 +1,7 @@
-var assert = require('assert');
-var battle;
+'use strict';
+
+const assert = require('assert');
+let battle;
describe('Delta Stream', function () {
afterEach(function () {
@@ -17,7 +19,7 @@ describe('Delta Stream', function () {
battle = BattleEngine.Battle.construct();
battle.join('p1', 'Guest 1', 1, [{species: "Tornadus", ability: 'deltastream', item: 'weaknesspolicy', moves: ['recover']}]);
battle.join('p2', 'Guest 2', 1, [{species: "Smeargle", ability: 'owntempo', moves: ['thundershock', 'powdersnow', 'powergem']}]);
- for (var i = 0; i < 3; i++) {
+ for (let i = 0; i < 3; i++) {
battle.choose('p2', 'move ' + i);
battle.commitDecisions();
assert.strictEqual(battle.p1.active[0].boosts.atk, 0);
@@ -44,7 +46,7 @@ describe('Delta Stream', function () {
{species: "Tyranitar", ability: 'sandstream', moves: ['sandstorm']},
{species: "Abomasnow", ability: 'snowwarning', moves: ['hail']}
]);
- for (var i = 2; i <= 5; i++) {
+ for (let i = 2; i <= 5; i++) {
battle.choose('p1', 'switch ' + i);
battle.commitDecisions();
assert.ok(battle.isWeather('deltastream'));
diff --git a/test/simulator/abilities/desolateland.js b/test/simulator/abilities/desolateland.js
index 5ea0e13280..e354a9af3e 100644
--- a/test/simulator/abilities/desolateland.js
+++ b/test/simulator/abilities/desolateland.js
@@ -1,5 +1,7 @@
-var assert = require('assert');
-var battle;
+'use strict';
+
+const assert = require('assert');
+let battle;
describe('Desolate Land', function () {
afterEach(function () {
@@ -18,8 +20,8 @@ describe('Desolate Land', function () {
battle.join('p1', 'Guest 1', 1, [{species: "Groudon", ability: 'desolateland', moves: ['helpinghand']}]);
battle.join('p2', 'Guest 2', 1, [{species: "Charizard", ability: 'blaze', moves: ['firepledge']}]);
battle.commitDecisions();
- var move = Tools.getMove('firepledge');
- var basePower = battle.runEvent('BasePower', battle.p2.active[0], battle.p1.active[0], move, move.basePower, true);
+ let move = Tools.getMove('firepledge');
+ let basePower = battle.runEvent('BasePower', battle.p2.active[0], battle.p1.active[0], move, move.basePower, true);
assert.strictEqual(basePower, move.basePower);
});
@@ -50,7 +52,7 @@ describe('Desolate Land', function () {
{species: "Tyranitar", ability: 'sandstream', moves: ['sandstorm']},
{species: "Abomasnow", ability: 'snowwarning', moves: ['hail']}
]);
- for (var i = 2; i <= 5; i++) {
+ for (let i = 2; i <= 5; i++) {
battle.choose('p1', 'switch ' + i);
battle.commitDecisions();
assert.ok(battle.isWeather('desolateland'));
diff --git a/test/simulator/abilities/dryskin.js b/test/simulator/abilities/dryskin.js
index 1c51d052cb..8fc0f22da1 100644
--- a/test/simulator/abilities/dryskin.js
+++ b/test/simulator/abilities/dryskin.js
@@ -1,5 +1,7 @@
-var assert = require('assert');
-var battle;
+'use strict';
+
+const assert = require('assert');
+let battle;
describe('Dry Skin', function () {
afterEach(function () {
@@ -35,7 +37,7 @@ describe('Dry Skin', function () {
battle.join('p1', 'Guest 1', 1, [{species: 'Toxicroak', ability: 'dryskin', moves: ['bulkup']}]);
battle.join('p2', 'Guest 2', 1, [{species: 'Haxorus', ability: 'unnerve', moves: ['incinerate']}]);
battle.commitDecisions();
- var damage = battle.p1.active[0].maxhp - battle.p1.active[0].hp;
+ let damage = battle.p1.active[0].maxhp - battle.p1.active[0].hp;
assert.ok(damage >= 51 && damage <= 61);
});
@@ -44,8 +46,8 @@ describe('Dry Skin', function () {
battle.join('p1', 'Guest 1', 1, [{species: 'Toxicroak', ability: 'dryskin', moves: ['bulkup']}]);
battle.join('p2', 'Guest 2', 1, [{species: 'Haxorus', ability: 'moldbreaker', moves: ['incinerate', 'surf']}]);
battle.commitDecisions();
- var pokemon = battle.p1.active[0];
- var damage = pokemon.maxhp - pokemon.hp;
+ let pokemon = battle.p1.active[0];
+ let damage = pokemon.maxhp - pokemon.hp;
assert.ok(damage >= 41 && damage <= 49);
pokemon.hp = pokemon.maxhp;
battle.choose('p2', 'move 2');
diff --git a/test/simulator/abilities/flashfire.js b/test/simulator/abilities/flashfire.js
index 814f2eed52..8f91e50488 100644
--- a/test/simulator/abilities/flashfire.js
+++ b/test/simulator/abilities/flashfire.js
@@ -1,5 +1,7 @@
-var assert = require('assert');
-var battle;
+'use strict';
+
+const assert = require('assert');
+let battle;
describe('Flash Fire', function () {
afterEach(function () {
@@ -12,7 +14,7 @@ describe('Flash Fire', function () {
battle.join('p2', 'Guest 2', 1, [{species: 'Talonflame', ability: 'galewings', moves: ['flareblitz']}]);
battle.commitDecisions();
assert.strictEqual(battle.p1.active[0].hp, battle.p1.active[0].maxhp);
- var damage = battle.p2.active[0].maxhp - battle.p2.active[0].hp;
+ let damage = battle.p2.active[0].maxhp - battle.p2.active[0].hp;
assert.ok(damage >= 82 && damage <= 97);
});
@@ -41,7 +43,7 @@ describe('Flash Fire', function () {
battle.seed = battle.startingSeed.slice();
battle.choose('p1', 'move 2');
battle.choose('p2', 'move 2');
- var damage = battle.p2.active[0].maxhp - battle.p2.active[0].hp;
+ let damage = battle.p2.active[0].maxhp - battle.p2.active[0].hp;
assert.ok(damage >= 54 && damage <= 65);
});
});
diff --git a/test/simulator/abilities/flowergift.js b/test/simulator/abilities/flowergift.js
index 8f89730003..db1b411f0f 100644
--- a/test/simulator/abilities/flowergift.js
+++ b/test/simulator/abilities/flowergift.js
@@ -1,5 +1,7 @@
-var assert = require('assert');
-var battle;
+'use strict';
+
+const assert = require('assert');
+let battle;
describe('Flower Gift', function () {
afterEach(function () {
@@ -17,10 +19,10 @@ describe('Flower Gift', function () {
{species: "Blissey", ability: 'serenegrace', moves: ['healbell']}
]);
battle.commitDecisions();
- var cherAtk = battle.p1.active[0].getStat('atk');
- var cherSpd = battle.p1.active[0].getStat('spd');
- var baseAtk = battle.p1.active[1].getStat('atk');
- var baseSpd = battle.p1.active[1].getStat('spd');
+ let cherAtk = battle.p1.active[0].getStat('atk');
+ let cherSpd = battle.p1.active[0].getStat('spd');
+ let baseAtk = battle.p1.active[1].getStat('atk');
+ let baseSpd = battle.p1.active[1].getStat('spd');
// Set the weather to sun and re-check
battle.setWeather('sunnyday');
@@ -43,10 +45,10 @@ describe('Flower Gift', function () {
battle.commitDecisions();
battle.choose('p1', 'move 1 1, move 1');
battle.choose('p2', 'move 1, move 1');
- var cherAtk = battle.p1.active[0].getStat('atk');
- var cherSpd = battle.p1.active[0].getStat('spd');
- var baseAtk = battle.p1.active[1].getStat('atk');
- var baseSpd = battle.p1.active[1].getStat('spd');
+ let cherAtk = battle.p1.active[0].getStat('atk');
+ let cherSpd = battle.p1.active[0].getStat('spd');
+ let baseAtk = battle.p1.active[1].getStat('atk');
+ let baseSpd = battle.p1.active[1].getStat('spd');
// Set the weather to sun and re-check
battle.setWeather('sunnyday');
diff --git a/test/simulator/abilities/immunity.js b/test/simulator/abilities/immunity.js
index 01a45ca245..6d4f24b59b 100644
--- a/test/simulator/abilities/immunity.js
+++ b/test/simulator/abilities/immunity.js
@@ -1,5 +1,7 @@
-var assert = require('assert');
-var battle;
+'use strict';
+
+const assert = require('assert');
+let battle;
describe('Immunity', function () {
afterEach(function () {
diff --git a/test/simulator/abilities/intimidate.js b/test/simulator/abilities/intimidate.js
index 373436a5a9..62c2a2f14f 100644
--- a/test/simulator/abilities/intimidate.js
+++ b/test/simulator/abilities/intimidate.js
@@ -1,5 +1,7 @@
-var assert = require('assert');
-var battle;
+'use strict';
+
+const assert = require('assert');
+let battle;
describe('Intimidate', function () {
afterEach(function () {
@@ -49,7 +51,7 @@ describe('Intimidate', function () {
battle = BattleEngine.Battle.construct('battle-intimidate-order1', 'customgame');
battle.join('p1', 'Guest 1', 1, [{species: "Arcanine", ability: 'intimidate', moves: ['morningsun']}]);
battle.join('p2', 'Guest 2', 1, [{species: "Gyarados", ability: 'intimidate', moves: ['dragondance']}]);
- var intimidateCount = 0;
+ let intimidateCount = 0;
battle.on('Boost', battle.getFormat(), function (boost, target, source) {
assert.strictEqual(source.template.speciesid, intimidateCount === 0 ? 'arcanine' : 'gyarados');
intimidateCount++;
@@ -87,7 +89,7 @@ describe('Intimidate', function () {
{species: "Gyarados", ability: 'intimidate', moves: ['healingwish']},
{species: "Arcanine", ability: 'intimidate', moves: ['healingwish']}
]);
- var intimidateCount = 0;
+ let intimidateCount = 0;
battle.on('Boost', battle.getFormat(), function (boost, target, source) {
assert.strictEqual(source.template.speciesid, intimidateCount % 2 === 0 ? 'arcanine' : 'gyarados');
intimidateCount++;
diff --git a/test/simulator/abilities/klutz.js b/test/simulator/abilities/klutz.js
index d425600ba2..120d583323 100644
--- a/test/simulator/abilities/klutz.js
+++ b/test/simulator/abilities/klutz.js
@@ -1,5 +1,7 @@
-var assert = require('assert');
-var battle;
+'use strict';
+
+const assert = require('assert');
+let battle;
describe('Klutz', function () {
afterEach(function () {
diff --git a/test/simulator/abilities/levitate.js b/test/simulator/abilities/levitate.js
index 72005ee3a8..90b027a504 100644
--- a/test/simulator/abilities/levitate.js
+++ b/test/simulator/abilities/levitate.js
@@ -1,5 +1,7 @@
-var assert = require('assert');
-var battle;
+'use strict';
+
+const assert = require('assert');
+let battle;
describe('Levitate', function () {
afterEach(function () {
diff --git a/test/simulator/abilities/lightningrod.js b/test/simulator/abilities/lightningrod.js
index 25839c0a7d..3df0858aaa 100644
--- a/test/simulator/abilities/lightningrod.js
+++ b/test/simulator/abilities/lightningrod.js
@@ -1,5 +1,7 @@
-var assert = require('assert');
-var battle;
+'use strict';
+
+const assert = require('assert');
+let battle;
describe('Lightning Rod', function () {
afterEach(function () {
diff --git a/test/simulator/abilities/magicbounce.js b/test/simulator/abilities/magicbounce.js
index a4047e7e40..8da5be4c05 100644
--- a/test/simulator/abilities/magicbounce.js
+++ b/test/simulator/abilities/magicbounce.js
@@ -1,5 +1,7 @@
-var assert = require('assert');
-var battle;
+'use strict';
+
+const assert = require('assert');
+let battle;
describe('Magic Bounce', function () {
afterEach(function () {
diff --git a/test/simulator/abilities/magicguard.js b/test/simulator/abilities/magicguard.js
index 865ba5fdac..a6705e375a 100644
--- a/test/simulator/abilities/magicguard.js
+++ b/test/simulator/abilities/magicguard.js
@@ -1,5 +1,7 @@
-var assert = require('assert');
-var battle;
+'use strict';
+
+const assert = require('assert');
+let battle;
describe('Magic Guard', function () {
afterEach(function () {
diff --git a/test/simulator/abilities/multiscale.js b/test/simulator/abilities/multiscale.js
index 6c9d0254bf..8ad609f3b6 100644
--- a/test/simulator/abilities/multiscale.js
+++ b/test/simulator/abilities/multiscale.js
@@ -1,5 +1,7 @@
-var assert = require('assert');
-var battle;
+'use strict';
+
+const assert = require('assert');
+let battle;
describe('Multiscale', function () {
afterEach(function () {
@@ -10,8 +12,8 @@ describe('Multiscale', function () {
battle = BattleEngine.Battle.construct();
battle.join('p1', 'Guest 1', 1, [{species: "Dragonite", ability: 'multiscale', moves: ['splash']}]);
battle.join('p2', 'Guest 2', 1, [{species: "Gyarados", ability: 'moxie', moves: ['incinerate']}]);
- var damage, curhp;
- var pokemon = battle.p1.active[0];
+ let damage, curhp;
+ let pokemon = battle.p1.active[0];
battle.commitDecisions();
damage = pokemon.maxhp - pokemon.hp;
curhp = pokemon.hp;
@@ -24,8 +26,8 @@ describe('Multiscale', function () {
battle = BattleEngine.Battle.construct();
battle.join('p1', 'Guest 1', 1, [{species: "Dragonite", ability: 'multiscale', moves: ['splash']}]);
battle.join('p2', 'Guest 2', 1, [{species: "Gyarados", ability: 'moldbreaker', moves: ['incinerate']}]);
- var damage, curhp;
- var pokemon = battle.p1.active[0];
+ let damage, curhp;
+ let pokemon = battle.p1.active[0];
battle.commitDecisions();
damage = pokemon.maxhp - pokemon.hp;
curhp = pokemon.hp;
diff --git a/test/simulator/abilities/pickup.js b/test/simulator/abilities/pickup.js
index 5416c648ef..78125671b2 100644
--- a/test/simulator/abilities/pickup.js
+++ b/test/simulator/abilities/pickup.js
@@ -1,5 +1,7 @@
-var assert = require('assert');
-var battle;
+'use strict';
+
+const assert = require('assert');
+let battle;
describe('Pickup', function () {
afterEach(function () {
diff --git a/test/simulator/abilities/pressure.js b/test/simulator/abilities/pressure.js
index 78411f65e7..87b3647e30 100644
--- a/test/simulator/abilities/pressure.js
+++ b/test/simulator/abilities/pressure.js
@@ -1,5 +1,7 @@
-var assert = require('assert');
-var battle;
+'use strict';
+
+const assert = require('assert');
+let battle;
describe('Pressure', function () {
afterEach(function () {
@@ -19,7 +21,7 @@ describe('Pressure', function () {
battle.commitDecisions(); // Team Preview
battle.choose('p1', 'move 1, move 1 -1');
battle.choose('p2', 'move 1, move 1 1');
- var move = Tools.getMove('peck');
+ let move = Tools.getMove('peck');
assert.strictEqual(battle.p1.active[1].getMoveData(move).pp, 55);
assert.strictEqual(battle.p2.active[1].getMoveData(move).pp, 54);
});
@@ -37,7 +39,7 @@ describe('Pressure', function () {
battle.commitDecisions(); // Team Preview
battle.choose('p1', 'move 1, move 1 2');
battle.choose('p2', 'move 1, move 1 2');
- var move = Tools.getMove('peck');
+ let move = Tools.getMove('peck');
assert.strictEqual(battle.p1.active[1].getMoveData(move).pp, 55);
assert.strictEqual(battle.p2.active[1].getMoveData(move).pp, 54);
});
@@ -114,7 +116,7 @@ describe('Pressure [Gen 4]', function () {
]);
battle.choose('p1', 'move 1, move 1 -1');
battle.choose('p2', 'move 1, move 1 1');
- var move = Tools.getMove('peck');
+ let move = Tools.getMove('peck');
assert.strictEqual(battle.p1.active[1].getMoveData(move).pp, 54);
assert.strictEqual(battle.p2.active[1].getMoveData(move).pp, 54);
});
@@ -131,7 +133,7 @@ describe('Pressure [Gen 4]', function () {
]);
battle.choose('p1', 'move 1, move 1 2');
battle.choose('p2', 'move 1, move 1 2');
- var move = Tools.getMove('peck');
+ let move = Tools.getMove('peck');
assert.strictEqual(battle.p1.active[1].getMoveData(move).pp, 55);
assert.strictEqual(battle.p2.active[1].getMoveData(move).pp, 54);
});
@@ -167,7 +169,7 @@ describe('Pressure [Gen 4]', function () {
battle.join('p1', 'Guest 1', 1, [{species: "Palkia", ability: 'pressure', moves: ['calmmind']}]);
battle.join('p2', 'Guest 2', 1, [{species: "Dialga", ability: 'pressure', moves: ['calmmind']}]);
battle.commitDecisions();
- var move = Tools.getMove('calmmind');
+ let move = Tools.getMove('calmmind');
assert.strictEqual(battle.p1.active[0].getMoveData(move).pp, 31);
assert.strictEqual(battle.p1.active[0].getMoveData(move).pp, 31);
});
diff --git a/test/simulator/abilities/primordialsea.js b/test/simulator/abilities/primordialsea.js
index 5ee8bd23a4..55b579fe4c 100644
--- a/test/simulator/abilities/primordialsea.js
+++ b/test/simulator/abilities/primordialsea.js
@@ -1,5 +1,7 @@
-var assert = require('assert');
-var battle;
+'use strict';
+
+const assert = require('assert');
+let battle;
describe('Primordial Sea', function () {
afterEach(function () {
@@ -18,8 +20,8 @@ describe('Primordial Sea', function () {
battle.join('p1', 'Guest 1', 1, [{species: "Kyogre", ability: 'primordialsea', moves: ['helpinghand']}]);
battle.join('p2', 'Guest 2', 1, [{species: "Blastoise", ability: 'torrent', moves: ['waterpledge']}]);
battle.commitDecisions();
- var move = Tools.getMove('waterpledge');
- var basePower = battle.runEvent('BasePower', battle.p2.active[0], battle.p1.active[0], move, move.basePower, true);
+ let move = Tools.getMove('waterpledge');
+ let basePower = battle.runEvent('BasePower', battle.p2.active[0], battle.p1.active[0], move, move.basePower, true);
assert.strictEqual(basePower, move.basePower);
});
@@ -49,7 +51,7 @@ describe('Primordial Sea', function () {
{species: "Tyranitar", ability: 'sandstream', moves: ['sandstorm']},
{species: "Abomasnow", ability: 'snowwarning', moves: ['hail']}
]);
- for (var i = 2; i <= 5; i++) {
+ for (let i = 2; i <= 5; i++) {
battle.choose('p1', 'switch ' + i);
battle.commitDecisions();
assert.ok(battle.isWeather('primordialsea'));
diff --git a/test/simulator/abilities/rockhead.js b/test/simulator/abilities/rockhead.js
index 9f965eabc1..218e48e4f3 100644
--- a/test/simulator/abilities/rockhead.js
+++ b/test/simulator/abilities/rockhead.js
@@ -1,5 +1,7 @@
-var assert = require('assert');
-var battle;
+'use strict';
+
+const assert = require('assert');
+let battle;
describe('Rock Head', function () {
afterEach(function () {
diff --git a/test/simulator/abilities/sheerforce.js b/test/simulator/abilities/sheerforce.js
index c03e766df8..7354403a27 100644
--- a/test/simulator/abilities/sheerforce.js
+++ b/test/simulator/abilities/sheerforce.js
@@ -1,5 +1,7 @@
-var assert = require('assert');
-var battle;
+'use strict';
+
+const assert = require('assert');
+let battle;
describe('Sheer Force', function () {
afterEach(function () {
diff --git a/test/simulator/abilities/shellarmor.js b/test/simulator/abilities/shellarmor.js
index 24aef45c3c..6646027d2e 100644
--- a/test/simulator/abilities/shellarmor.js
+++ b/test/simulator/abilities/shellarmor.js
@@ -1,5 +1,7 @@
-var assert = require('assert');
-var battle;
+'use strict';
+
+const assert = require('assert');
+let battle;
describe('Shell Armor', function () {
afterEach(function () {
@@ -11,7 +13,7 @@ describe('Shell Armor', function () {
battle.join('p1', 'Guest 1', 1, [{species: 'Slowbro', ability: 'shellarmor', moves: ['quickattack']}]);
battle.join('p2', 'Guest 2', 1, [{species: 'Cyrogonal', ability: 'noguard', moves: ['frostbreath']}]);
battle.commitDecisions(); // Team Preview
- var successfulEvent = false;
+ let successfulEvent = false;
battle.on('ModifyDamage', battle.getFormat(), function (damage, attacker, defender, move) {
if (move.id === 'frostbreath') {
successfulEvent = true;
@@ -27,7 +29,7 @@ describe('Shell Armor', function () {
battle.join('p1', 'Guest 1', 1, [{species: 'Slowbro', ability: 'shellarmor', moves: ['quickattack']}]);
battle.join('p2', 'Guest 2', 1, [{species: 'Cyrogonal', ability: 'moldbreaker', item: 'zoomlens', moves: ['frostbreath']}]);
battle.commitDecisions(); // Team Preview
- var successfulEvent = false;
+ let successfulEvent = false;
battle.on('ModifyDamage', battle.getFormat(), function (damage, attacker, defender, move) {
if (move.id === 'frostbreath') {
successfulEvent = true;
diff --git a/test/simulator/abilities/shielddust.js b/test/simulator/abilities/shielddust.js
index 418b3a6ab4..bdbd50e566 100644
--- a/test/simulator/abilities/shielddust.js
+++ b/test/simulator/abilities/shielddust.js
@@ -1,5 +1,7 @@
-var assert = require('assert');
-var battle;
+'use strict';
+
+const assert = require('assert');
+let battle;
describe('Shield Dust', function () {
afterEach(function () {
@@ -36,7 +38,7 @@ describe('Shield Dust', function () {
battle.join('p2', 'Guest 2', 1, [{species: 'Clefable', ability: 'shielddust', moves: ['cottonguard']}]);
battle.on('ModifyMove', battle.getFormat(), function (move) {
if (move.secondaries) {
- for (var i = 0; i < move.secondaries.length; i++) {
+ for (let i = 0; i < move.secondaries.length; i++) {
move.secondaries[i].chance = 100;
}
}
diff --git a/test/simulator/abilities/simple.js b/test/simulator/abilities/simple.js
index a5d5c42092..b63ad0b8c5 100644
--- a/test/simulator/abilities/simple.js
+++ b/test/simulator/abilities/simple.js
@@ -1,5 +1,7 @@
-var assert = require('assert');
-var battle;
+'use strict';
+
+const assert = require('assert');
+let battle;
describe('Simple', function () {
afterEach(function () {
@@ -26,7 +28,7 @@ describe('Simple [Gen 4]', function () {
battle = BattleEngine.Battle.construct('battle-simple-dpp-boosts', 'gen4customgame');
battle.join('p1', 'Guest 1', 1, [{species: "Bibarel", ability: 'simple', moves: ['defensecurl']}]);
battle.join('p2', 'Guest 2', 1, [{species: "Gyarados", ability: 'moxie', moves: ['splash']}]);
- var defense = battle.p1.active[0].getStat('def');
+ let defense = battle.p1.active[0].getStat('def');
battle.commitDecisions();
assert.strictEqual(battle.p1.active[0].boosts['def'], 1);
assert.strictEqual(battle.p1.active[0].getStat('def'), 2 * defense);
@@ -50,7 +52,7 @@ describe('Simple [Gen 4]', function () {
battle.join('p1', 'Guest 1', 1, [{species: "Bibarel", ability: 'simple', moves: ['defensecurl']}]);
battle.join('p2', 'Guest 2', 1, [{species: "Haxorus", ability: 'moldbreaker', item: 'laggingtail', moves: ['earthquake']}]);
battle.commitDecisions();
- var hploss = battle.p1.active[0].maxhp - battle.p1.active[0].hp;
+ let hploss = battle.p1.active[0].maxhp - battle.p1.active[0].hp;
assert(hploss >= 102 && hploss <= 120);
});
});
diff --git a/test/simulator/abilities/stickyhold.js b/test/simulator/abilities/stickyhold.js
index a3875224e5..be81e56c5f 100644
--- a/test/simulator/abilities/stickyhold.js
+++ b/test/simulator/abilities/stickyhold.js
@@ -1,5 +1,7 @@
-var assert = require('assert');
-var battle;
+'use strict';
+
+const assert = require('assert');
+let battle;
describe('Sticky Hold', function () {
afterEach(function () {
diff --git a/test/simulator/abilities/stormdrain.js b/test/simulator/abilities/stormdrain.js
index 93b674292b..90e173bbc1 100644
--- a/test/simulator/abilities/stormdrain.js
+++ b/test/simulator/abilities/stormdrain.js
@@ -1,5 +1,7 @@
-var assert = require('assert');
-var battle;
+'use strict';
+
+const assert = require('assert');
+let battle;
describe('Storm Drain', function () {
afterEach(function () {
diff --git a/test/simulator/abilities/sturdy.js b/test/simulator/abilities/sturdy.js
index 44fb2b85bc..1130556184 100644
--- a/test/simulator/abilities/sturdy.js
+++ b/test/simulator/abilities/sturdy.js
@@ -1,5 +1,7 @@
-var assert = require('assert');
-var battle;
+'use strict';
+
+const assert = require('assert');
+let battle;
describe('Sturdy', function () {
afterEach(function () {
diff --git a/test/simulator/abilities/suctioncups.js b/test/simulator/abilities/suctioncups.js
index 7e688a420d..42237007cf 100644
--- a/test/simulator/abilities/suctioncups.js
+++ b/test/simulator/abilities/suctioncups.js
@@ -1,5 +1,7 @@
-var assert = require('assert');
-var battle;
+'use strict';
+
+const assert = require('assert');
+let battle;
describe('Suction Cups', function () {
afterEach(function () {
@@ -16,7 +18,7 @@ describe('Suction Cups', function () {
battle.commitDecisions();
assert.strictEqual(battle.p2.active[0].item, ''); // If Red Card is not working properly, this will fail
assert.strictEqual(battle.p1.active[0].template.speciesid, 'shuckle');
- for (var i = 2; i <= 4; i++) {
+ for (let i = 2; i <= 4; i++) {
battle.choose('p2', 'move ' + i);
battle.commitDecisions();
assert.strictEqual(battle.p1.active[0].template.speciesid, 'shuckle');
diff --git a/test/simulator/abilities/thickfat.js b/test/simulator/abilities/thickfat.js
index c2945d02f4..7f970696c1 100644
--- a/test/simulator/abilities/thickfat.js
+++ b/test/simulator/abilities/thickfat.js
@@ -1,5 +1,7 @@
-var assert = require('assert');
-var battle;
+'use strict';
+
+const assert = require('assert');
+let battle;
describe('Thick Fat', function () {
afterEach(function () {
@@ -10,8 +12,8 @@ describe('Thick Fat', function () {
battle = BattleEngine.Battle.construct();
battle.join('p1', 'Guest 1', 1, [{species: "Hariyama", ability: 'thickfat', moves: ['splash']}]);
battle.join('p2', 'Guest 2', 1, [{species: "Nidoking", ability: 'sheerforce', moves: ['incinerate', 'icebeam']}]);
- var damage;
- var pokemon = battle.p1.active[0];
+ let damage;
+ let pokemon = battle.p1.active[0];
battle.commitDecisions();
damage = pokemon.maxhp - pokemon.hp;
assert.ok(damage >= 29 && damage <= 35);
@@ -26,8 +28,8 @@ describe('Thick Fat', function () {
battle = BattleEngine.Battle.construct();
battle.join('p1', 'Guest 1', 1, [{species: "Hariyama", ability: 'thickfat', moves: ['splash']}]);
battle.join('p2', 'Guest 2', 1, [{species: "Nidoking", ability: 'moldbreaker', moves: ['incinerate', 'icebeam']}]);
- var damage;
- var pokemon = battle.p1.active[0];
+ let damage;
+ let pokemon = battle.p1.active[0];
battle.commitDecisions();
damage = pokemon.maxhp - pokemon.hp;
assert.ok(damage >= 57 && damage <= 68);
diff --git a/test/simulator/abilities/unaware.js b/test/simulator/abilities/unaware.js
index 8340340300..9a5d22adc7 100644
--- a/test/simulator/abilities/unaware.js
+++ b/test/simulator/abilities/unaware.js
@@ -1,5 +1,7 @@
-var assert = require('assert');
-var battle;
+'use strict';
+
+const assert = require('assert');
+let battle;
describe('Unaware', function () {
afterEach(function () {
@@ -11,8 +13,8 @@ describe('Unaware', function () {
battle.join('p1', 'Guest 1', 1, [{species: 'Clefable', ability: 'unaware', moves: ['softboiled']}]);
battle.join('p2', 'Guest 2', 1, [{species: 'Hariyama', ability: 'thickfat', moves: ['vitalthrow', 'bellydrum']}]);
battle.commitDecisions();
- var pokemon = battle.p1.active[0];
- var damage = pokemon.maxhp - pokemon.hp;
+ let pokemon = battle.p1.active[0];
+ let damage = pokemon.maxhp - pokemon.hp;
battle.choose('p2', 'move 2');
battle.commitDecisions();
battle.seed = battle.startingSeed.slice();
@@ -25,8 +27,8 @@ describe('Unaware', function () {
battle.join('p1', 'Guest 1', 1, [{species: 'Clefable', ability: 'unaware', moves: ['moonblast', 'nastyplot']}]);
battle.join('p2', 'Guest 2', 1, [{species: 'Registeel', ability: 'prankster', moves: ['splash']}]);
battle.commitDecisions();
- var pokemon = battle.p2.active[0];
- var damage = pokemon.maxhp - pokemon.hp;
+ let pokemon = battle.p2.active[0];
+ let damage = pokemon.maxhp - pokemon.hp;
battle.choose('p1', 'move 2');
battle.commitDecisions();
pokemon.hp = pokemon.maxhp;
@@ -40,8 +42,8 @@ describe('Unaware', function () {
battle.join('p1', 'Guest 1', 1, [{species: 'Clefable', ability: 'unaware', moves: ['moonblast']}]);
battle.join('p2', 'Guest 2', 1, [{species: 'Hariyama', ability: 'thickfat', item: 'laggingtail', moves: ['amnesia']}]);
battle.commitDecisions();
- var pokemon = battle.p2.active[0];
- var damage = pokemon.maxhp - pokemon.hp;
+ let pokemon = battle.p2.active[0];
+ let damage = pokemon.maxhp - pokemon.hp;
pokemon.hp = pokemon.maxhp;
battle.seed = battle.startingSeed.slice();
battle.commitDecisions();
@@ -53,8 +55,8 @@ describe('Unaware', function () {
battle.join('p1', 'Guest 1', 1, [{species: 'Clefable', ability: 'unaware', moves: ['irondefense']}]);
battle.join('p2', 'Guest 2', 1, [{species: 'Registeel', ability: 'clearbody', moves: ['shadowsneak']}]);
battle.commitDecisions();
- var pokemon = battle.p1.active[0];
- var damage = pokemon.maxhp - pokemon.hp;
+ let pokemon = battle.p1.active[0];
+ let damage = pokemon.maxhp - pokemon.hp;
pokemon.hp = pokemon.maxhp;
battle.seed = battle.startingSeed.slice();
battle.commitDecisions();
@@ -66,8 +68,8 @@ describe('Unaware', function () {
battle.join('p1', 'Guest 1', 1, [{species: 'Clefable', ability: 'unaware', moves: ['splash']}]);
battle.join('p2', 'Guest 2', 1, [{species: 'Haxorus', ability: 'moldbreaker', moves: ['shadowsneak']}]);
battle.commitDecisions();
- var pokemon = battle.p1.active[0];
- var damage = pokemon.maxhp - pokemon.hp;
+ let pokemon = battle.p1.active[0];
+ let damage = pokemon.maxhp - pokemon.hp;
battle.boost({atk: 2}, battle.p2.active[0]);
pokemon.hp = pokemon.maxhp;
battle.seed = battle.startingSeed.slice();
diff --git a/test/simulator/abilities/unburden.js b/test/simulator/abilities/unburden.js
index 2e535af772..1c07b0e68d 100644
--- a/test/simulator/abilities/unburden.js
+++ b/test/simulator/abilities/unburden.js
@@ -1,5 +1,7 @@
-var assert = require('assert');
-var battle;
+'use strict';
+
+const assert = require('assert');
+let battle;
describe('Unburden', function () {
afterEach(function () {
@@ -10,7 +12,7 @@ describe('Unburden', function () {
battle = BattleEngine.Battle.construct();
battle.join('p1', 'Guest 1', 1, [{species: 'Hitmonlee', ability: 'unburden', item: 'whiteherb', moves: ['closecombat']}]);
battle.join('p2', 'Guest 2', 1, [{species: 'Scizor', ability: 'swarm', item: 'focussash', moves: ['swordsdance']}]);
- var speed = battle.p1.active[0].getStat('spe');
+ let speed = battle.p1.active[0].getStat('spe');
battle.commitDecisions();
assert.strictEqual(battle.p1.active[0].getStat('spe'), 2 * speed);
});
@@ -19,7 +21,7 @@ describe('Unburden', function () {
battle = BattleEngine.Battle.construct();
battle.join('p1', 'Guest 1', 1, [{species: 'Drifblim', ability: 'unburden', item: 'airballoon', moves: ['endure']}]);
battle.join('p2', 'Guest 2', 1, [{species: 'Machamp', ability: 'noguard', moves: ['stoneedge']}]);
- var speed = battle.p1.active[0].getStat('spe');
+ let speed = battle.p1.active[0].getStat('spe');
battle.commitDecisions();
assert.strictEqual(battle.p1.active[0].getStat('spe'), 2 * speed);
});
@@ -28,7 +30,7 @@ describe('Unburden', function () {
battle = BattleEngine.Battle.construct();
battle.join('p1', 'Guest 1', 1, [{species: 'Sceptile', ability: 'unburden', item: 'oranberry', moves: ['naturalgift']}]);
battle.join('p2', 'Guest 2', 1, [{species: 'Scizor', ability: 'swarm', item: 'focussash', moves: ['swordsdance']}]);
- var speed = battle.p1.active[0].getStat('spe');
+ let speed = battle.p1.active[0].getStat('spe');
battle.commitDecisions();
assert.strictEqual(battle.p1.active[0].getStat('spe'), 2 * speed);
});
@@ -37,7 +39,7 @@ describe('Unburden', function () {
battle = BattleEngine.Battle.construct();
battle.join('p1', 'Guest 1', 1, [{species: 'Sceptile', ability: 'unburden', item: 'whiteherb', moves: ['fling']}]);
battle.join('p2', 'Guest 2', 1, [{species: 'Scizor', ability: 'swarm', item: 'focussash', moves: ['swordsdance']}]);
- var speed = battle.p1.active[0].getStat('spe');
+ let speed = battle.p1.active[0].getStat('spe');
battle.commitDecisions();
assert.strictEqual(battle.p1.active[0].getStat('spe'), 2 * speed);
});
@@ -46,7 +48,7 @@ describe('Unburden', function () {
battle = BattleEngine.Battle.construct();
battle.join('p1', 'Guest 1', 1, [{species: 'Sceptile', ability: 'unburden', item: 'whiteherb', moves: ['leechseed']}]);
battle.join('p2', 'Guest 2', 1, [{species: 'Scizor', ability: 'swarm', moves: ['knockoff']}]);
- var speed = battle.p1.active[0].getStat('spe');
+ let speed = battle.p1.active[0].getStat('spe');
battle.commitDecisions();
assert.strictEqual(battle.p1.active[0].getStat('spe'), 2 * speed);
});
@@ -55,7 +57,7 @@ describe('Unburden', function () {
battle = BattleEngine.Battle.construct();
battle.join('p1', 'Guest 1', 1, [{species: 'Sceptile', ability: 'unburden', item: 'whiteherb', moves: ['leechseed']}]);
battle.join('p2', 'Guest 2', 1, [{species: 'Scizor', ability: 'moldbreaker', moves: ['knockoff']}]);
- var speed = battle.p1.active[0].getStat('spe');
+ let speed = battle.p1.active[0].getStat('spe');
battle.commitDecisions();
assert.strictEqual(battle.p1.active[0].getStat('spe'), 2 * speed);
});
@@ -64,7 +66,7 @@ describe('Unburden', function () {
battle = BattleEngine.Battle.construct();
battle.join('p1', 'Guest 1', 1, [{species: 'Hitmonlee', ability: 'unburden', item: 'fightinggem', moves: ['machpunch']}]);
battle.join('p2', 'Guest 2', 1, [{species: 'Togekiss', ability: 'serenegrace', item: 'laggingtail', moves: ['bestow', 'followme']}]);
- var speed = battle.p1.active[0].getStat('spe');
+ let speed = battle.p1.active[0].getStat('spe');
battle.choose('p2', 'move followme');
battle.commitDecisions();
assert.strictEqual(battle.p1.active[0].getStat('spe'), 2 * speed);
diff --git a/test/simulator/abilities/wonderguard.js b/test/simulator/abilities/wonderguard.js
index 8970f42c28..76c8a73b76 100644
--- a/test/simulator/abilities/wonderguard.js
+++ b/test/simulator/abilities/wonderguard.js
@@ -1,5 +1,7 @@
-var assert = require('assert');
-var battle;
+'use strict';
+
+const assert = require('assert');
+let battle;
describe('Wonder Guard', function () {
afterEach(function () {
@@ -10,7 +12,7 @@ describe('Wonder Guard', function () {
battle = BattleEngine.Battle.construct();
battle.join('p1', 'Guest 1', 1, [{species: "Aerodactyl", ability: 'wonderguard', moves: ['sleeptalk']}]);
battle.join('p2', 'Guest 2', 1, [{species: "Smeargle", ability: 'owntempo', moves: ['knockoff', 'flamethrower', 'thousandarrows', 'moonblast']}]);
- for (var i = 1; i <= 4; i++) {
+ for (let i = 1; i <= 4; i++) {
battle.choose('p2', 'move ' + i);
battle.commitDecisions();
assert.strictEqual(battle.p1.active[0].hp, battle.p1.active[0].maxhp);
diff --git a/test/simulator/index.js b/test/simulator/index.js
index 69cab43aab..4847b9815f 100644
--- a/test/simulator/index.js
+++ b/test/simulator/index.js
@@ -1,10 +1,12 @@
-var fs = require('fs');
-var path = require('path');
+'use strict';
+
+const fs = require('fs');
+const path = require('path');
function loadTests (desc, dir) {
- var contents = fs.readdirSync(path.join(__dirname, dir));
+ let contents = fs.readdirSync(path.join(__dirname, dir));
describe(desc, function () {
- for (var i = 0; i < contents.length; i++) {
+ for (let i = 0; i < contents.length; i++) {
if (contents[i].substr(-3) === '.js') require('./' + path.join(dir, contents[i]));
}
});
diff --git a/test/simulator/items/assaultvest.js b/test/simulator/items/assaultvest.js
index e9ebe61307..1f3a1a788e 100644
--- a/test/simulator/items/assaultvest.js
+++ b/test/simulator/items/assaultvest.js
@@ -1,5 +1,7 @@
-var assert = require('assert');
-var battle;
+'use strict';
+
+const assert = require('assert');
+let battle;
describe('Assault Vest', function () {
afterEach(function () {
diff --git a/test/simulator/items/drives.js b/test/simulator/items/drives.js
index 4be753ff34..ef207743cc 100644
--- a/test/simulator/items/drives.js
+++ b/test/simulator/items/drives.js
@@ -1,11 +1,13 @@
-var assert = require('assert');
-var battle;
-var drives = ['Burn Drive', 'Chill Drive', 'Douse Drive', 'Shock Drive'];
+'use strict';
+
+const assert = require('assert');
+let battle;
+let drives = ['Burn Drive', 'Chill Drive', 'Douse Drive', 'Shock Drive'];
describe('Drives', function () {
- for (var i = 0; i < drives.length; i++) {
+ for (let i = 0; i < drives.length; i++) {
describe(drives[i], function () {
- var id = drives[i].replace(/\W+/g, '').toLowerCase();
+ let id = drives[i].replace(/\W+/g, '').toLowerCase();
afterEach(function () {
battle.destroy();
diff --git a/test/simulator/items/flameorb.js b/test/simulator/items/flameorb.js
index 99e6c855c6..dfc05ecc1b 100644
--- a/test/simulator/items/flameorb.js
+++ b/test/simulator/items/flameorb.js
@@ -1,5 +1,7 @@
-var assert = require('assert');
-var battle;
+'use strict';
+
+const assert = require('assert');
+let battle;
describe('Flame Orb', function () {
afterEach(function () {
diff --git a/test/simulator/items/focussash.js b/test/simulator/items/focussash.js
index 3842898b5f..75497d13a4 100644
--- a/test/simulator/items/focussash.js
+++ b/test/simulator/items/focussash.js
@@ -1,5 +1,7 @@
-var assert = require('assert');
-var battle;
+'use strict';
+
+const assert = require('assert');
+let battle;
describe('Focus Sash', function () {
afterEach(function () {
diff --git a/test/simulator/items/ironball.js b/test/simulator/items/ironball.js
index 8ac4f5662b..44eed055b3 100644
--- a/test/simulator/items/ironball.js
+++ b/test/simulator/items/ironball.js
@@ -1,5 +1,7 @@
-var battle;
-var assert = require('assert');
+'use strict';
+
+let battle;
+const assert = require('assert');
describe('Iron Ball', function () {
afterEach(function () {
@@ -10,7 +12,7 @@ describe('Iron Ball', function () {
battle = BattleEngine.Battle.construct();
battle.join('p1', 'Guest 1', 1, [{species: "Smeargle", ability: 'owntempo', item: 'ironball', moves: ['bestow']}]);
battle.join('p2', 'Guest 2', 1, [{species: "Aerodactyl", ability: 'pressure', moves: ['stealthrock']}]);
- var speed = battle.p2.active[0].getStat('spe');
+ let speed = battle.p2.active[0].getStat('spe');
battle.commitDecisions();
assert.strictEqual(battle.p2.active[0].getStat('spe'), battle.modify(speed, 0.5));
});
diff --git a/test/simulator/items/leftovers.js b/test/simulator/items/leftovers.js
index 6edefe3e70..03f4f46f82 100644
--- a/test/simulator/items/leftovers.js
+++ b/test/simulator/items/leftovers.js
@@ -1,5 +1,7 @@
-var assert = require('assert');
-var battle;
+'use strict';
+
+const assert = require('assert');
+let battle;
describe('Leftovers [Gen 2]', function () {
afterEach(function () {
diff --git a/test/simulator/items/mail.js b/test/simulator/items/mail.js
index 44911528b5..ea8f2250a4 100644
--- a/test/simulator/items/mail.js
+++ b/test/simulator/items/mail.js
@@ -1,5 +1,7 @@
-var assert = require('assert');
-var battle;
+'use strict';
+
+const assert = require('assert');
+let battle;
describe('Mail', function () {
afterEach(function () {
diff --git a/test/simulator/items/plates.js b/test/simulator/items/plates.js
index 039bea3f10..7098d1f096 100644
--- a/test/simulator/items/plates.js
+++ b/test/simulator/items/plates.js
@@ -1,13 +1,15 @@
-var assert = require('assert');
-var battle;
-var plates = ['Draco Plate', 'Dread Plate', 'Earth Plate', 'Fist Plate', 'Flame Plate', 'Icicle Plate',
+'use strict';
+
+const assert = require('assert');
+let battle;
+let plates = ['Draco Plate', 'Dread Plate', 'Earth Plate', 'Fist Plate', 'Flame Plate', 'Icicle Plate',
'Insect Plate', 'Iron Plate', 'Meadow Plate', 'Mind Plate', 'Pixie Plate', 'Sky Plate',
'Splash Plate', 'Spooky Plate', 'Stone Plate', 'Toxic Plate', 'Zap Plate'];
describe('Plates', function () {
- for (var i = 0; i < plates.length; i++) {
+ for (let i = 0; i < plates.length; i++) {
describe(plates[i], function () {
- var id = plates[i].replace(/\W+/g, '').toLowerCase();
+ let id = plates[i].replace(/\W+/g, '').toLowerCase();
afterEach(function () {
battle.destroy();
diff --git a/test/simulator/items/ringtarget.js b/test/simulator/items/ringtarget.js
index c34e62e6d3..5ddecde877 100644
--- a/test/simulator/items/ringtarget.js
+++ b/test/simulator/items/ringtarget.js
@@ -1,5 +1,7 @@
-var battle;
-var assert = require('assert');
+'use strict';
+
+let battle;
+const assert = require('assert');
describe('Ring Target', function () {
afterEach(function () {
diff --git a/test/simulator/items/weaknesspolicy.js b/test/simulator/items/weaknesspolicy.js
index 3e6d043eb7..90854dfecb 100644
--- a/test/simulator/items/weaknesspolicy.js
+++ b/test/simulator/items/weaknesspolicy.js
@@ -1,5 +1,7 @@
-var assert = require('assert');
-var battle;
+'use strict';
+
+const assert = require('assert');
+let battle;
describe('Weakness Policy', function () {
afterEach(function () {
diff --git a/test/simulator/misc/choice-parser.js b/test/simulator/misc/choice-parser.js
index 06709742e1..bf4a5d3b26 100644
--- a/test/simulator/misc/choice-parser.js
+++ b/test/simulator/misc/choice-parser.js
@@ -1,5 +1,7 @@
-var assert = require('assert');
-var battle;
+'use strict';
+
+const assert = require('assert');
+let battle;
describe('Choice parser', function () {
afterEach(function () {
diff --git a/test/simulator/misc/eventemitter.js b/test/simulator/misc/eventemitter.js
index 766452b2cf..c960351b5f 100644
--- a/test/simulator/misc/eventemitter.js
+++ b/test/simulator/misc/eventemitter.js
@@ -1,5 +1,7 @@
-var assert = require('assert');
-var battle;
+'use strict';
+
+const assert = require('assert');
+let battle;
describe('Battle#on', function () {
afterEach(function () {
@@ -11,8 +13,8 @@ describe('Battle#on', function () {
battle.join('p1', 'Guest 1', 1, [{species: 'Pidgeot', ability: 'keeneye', moves: ['bulkup']}]);
battle.join('p2', 'Guest 2', 1, [{species: 'Talonflame', ability: 'galewings', moves: ['peck']}]);
battle.commitDecisions(); // Team Preview
- var eventCount = 0;
- var eventCount2 = 0;
+ let eventCount = 0;
+ let eventCount2 = 0;
battle.on('Hit', battle.getFormat(), function () {
eventCount++;
});
@@ -34,14 +36,14 @@ describe('Battle#on', function () {
battle.join('p1', 'Guest 1', 1, [{species: 'Pidgeot', ability: 'keeneye', moves: ['bulkup']}]);
battle.join('p2', 'Guest 2', 1, [{species: 'Talonflame', ability: 'galewings', moves: ['peck']}]);
battle.commitDecisions(); // Team Preview
- var eventCount = 0;
- var callback = function (count) {
+ let eventCount = 0;
+ let callback = function (count) {
return function () {
assert.strictEqual(eventCount, count);
eventCount++;
};
};
- for (var i = 0; i < 9; i++) {
+ for (let i = 0; i < 9; i++) {
battle.on('ModifyDamage', battle.getFormat(), -i, callback(i));
}
battle.commitDecisions();
diff --git a/test/simulator/misc/inversebattle.js b/test/simulator/misc/inversebattle.js
index 065d469e1f..38fbbd43c3 100644
--- a/test/simulator/misc/inversebattle.js
+++ b/test/simulator/misc/inversebattle.js
@@ -1,8 +1,10 @@
-var battle;
-var assert = require('assert');
+'use strict';
+
+let battle;
+const assert = require('assert');
describe('Inverse Battle', function () {
- var battleCounter = 0;
+ let battleCounter = 0;
beforeEach(function () {
battle = BattleEngine.Battle.construct('battle-inverse-' + battleCounter++, 'inversebattle');
diff --git a/test/simulator/misc/statuses.js b/test/simulator/misc/statuses.js
index 082b067f96..da53f5ef7b 100644
--- a/test/simulator/misc/statuses.js
+++ b/test/simulator/misc/statuses.js
@@ -1,5 +1,7 @@
-var assert = require('assert');
-var battle;
+'use strict';
+
+const assert = require('assert');
+let battle;
describe('Burn', function () {
afterEach(function () {
@@ -11,7 +13,7 @@ describe('Burn', function () {
battle.join('p1', 'Guest 1', 1, [{species: 'Machamp', ability: 'noguard', moves: ['bulkup']}]);
battle.join('p2', 'Guest 2', 1, [{species: 'Sableye', ability: 'prankster', moves: ['willowisp']}]);
battle.commitDecisions();
- var pokemon = battle.p1.active[0];
+ let pokemon = battle.p1.active[0];
assert.strictEqual(pokemon.maxhp - pokemon.hp, Math.floor(pokemon.maxhp / 8));
});
@@ -20,8 +22,8 @@ describe('Burn', function () {
battle.join('p1', 'Guest 1', 1, [{species: 'Machamp', ability: 'noguard', moves: ['boneclub']}]);
battle.join('p2', 'Guest 2', 1, [{species: 'Sableye', ability: 'prankster', moves: ['splash', 'willowisp']}]);
battle.commitDecisions();
- var pokemon = battle.p2.active[0];
- var damage = pokemon.maxhp - pokemon.hp;
+ let pokemon = battle.p2.active[0];
+ let damage = pokemon.maxhp - pokemon.hp;
pokemon.hp = pokemon.maxhp;
battle.seed = battle.startingSeed.slice();
battle.choose('p2', 'move 2');
@@ -47,7 +49,7 @@ describe('Paralysis', function () {
battle = BattleEngine.Battle.construct();
battle.join('p1', 'Guest 1', 1, [{species: 'Vaporeon', ability: 'waterabsorb', moves: ['aquaring']}]);
battle.join('p2', 'Guest 2', 1, [{species: 'Jolteon', ability: 'voltabsorb', moves: ['thunderwave']}]);
- var speed = battle.p1.active[0].getStat('spe');
+ let speed = battle.p1.active[0].getStat('spe');
battle.commitDecisions();
assert.strictEqual(battle.p1.active[0].getStat('spe'), battle.modify(speed, 0.25));
});
@@ -62,8 +64,8 @@ describe('Toxic Poison', function () {
battle = BattleEngine.Battle.construct();
battle.join('p1', 'Guest 1', 1, [{species: 'Chansey', ability: 'naturalcure', moves: ['softboiled']}]);
battle.join('p2', 'Guest 2', 1, [{species: 'Gengar', ability: 'levitate', moves: ['toxic']}]);
- var pokemon = battle.p1.active[0];
- for (var i = 1; i <= 8; i++) {
+ let pokemon = battle.p1.active[0];
+ for (let i = 1; i <= 8; i++) {
battle.commitDecisions();
assert.strictEqual(pokemon.maxhp - pokemon.hp, Math.floor(pokemon.maxhp / 16) * i);
}
@@ -76,10 +78,10 @@ describe('Toxic Poison', function () {
{species: 'Snorlax', ability: 'immunity', moves: ['curse']}
]);
battle.join('p2', 'Guest 2', 1, [{species: 'Crobat', ability: 'infiltrator', moves: ['toxic', 'whirlwind']}]);
- for (var i = 0; i < 4; i++) {
+ for (let i = 0; i < 4; i++) {
battle.commitDecisions();
}
- var pokemon = battle.p1.active[0];
+ let pokemon = battle.p1.active[0];
pokemon.hp = pokemon.maxhp;
battle.choose('p1', 'switch 2');
battle.choose('p2', 'move 2');
@@ -97,7 +99,7 @@ describe('Toxic Poison [Gen 1]', function () {
battle.join('p1', 'Guest 1', 1, [{species: 'Venusaur', moves: ['toxic', 'leechseed']}]);
battle.join('p2', 'Guest 2', 1, [{species: 'Chansey', moves: ['splash']}]);
battle.commitDecisions();
- var pokemon = battle.p2.active[0];
+ let pokemon = battle.p2.active[0];
assert.strictEqual(pokemon.maxhp - pokemon.hp, Math.floor(pokemon.maxhp / 16));
battle.choose('p1', 'move 2');
battle.commitDecisions();
diff --git a/test/simulator/misc/statusmoves.js b/test/simulator/misc/statusmoves.js
index 2900c5b604..59898ed938 100644
--- a/test/simulator/misc/statusmoves.js
+++ b/test/simulator/misc/statusmoves.js
@@ -1,5 +1,7 @@
-var assert = require('assert');
-var battle;
+'use strict';
+
+const assert = require('assert');
+let battle;
describe('Most status moves', function () {
afterEach(function () {
diff --git a/test/simulator/misc/typechange.js b/test/simulator/misc/typechange.js
index b8682375ee..f1ba80db70 100644
--- a/test/simulator/misc/typechange.js
+++ b/test/simulator/misc/typechange.js
@@ -1,7 +1,9 @@
-var assert = require('assert');
-var battle;
+'use strict';
-var adderMoves = [
+const assert = require('assert');
+let battle;
+
+let adderMoves = [
{name: 'Trick-or-Treat', type: 'Ghost'},
{name: 'Forest\'s Curse', type: 'Grass'}
];
@@ -44,7 +46,7 @@ describe('Type addition', function () {
battle.join('p1', 'Guest 1', 1, [{species: "Gourgeist", ability: 'frisk', moves: [moveData.name]}]);
battle.join('p2', 'Guest 2', 1, [{species: "Deoxys-Speed", ability: 'pressure', moves: ['spikes']}]);
battle.commitDecisions();
- var cachedTypes = battle.p2.active[0].getTypes();
+ let cachedTypes = battle.p2.active[0].getTypes();
battle.commitDecisions();
assert.deepEqual(battle.p2.active[0].getTypes(), cachedTypes);
assert.ok(battle.log[battle.lastMoveLine + 1].startsWith('|-fail|'));
@@ -56,7 +58,7 @@ describe('Type addition', function () {
battle.join('p2', 'Guest 2', 1, [{species: "Deoxys-Speed", ability: 'pressure', moves: ['spikes']}]);
battle.choose('p1', 'move 2');
battle.commitDecisions();
- var cachedTypes = battle.p2.active[0].getTypes();
+ let cachedTypes = battle.p2.active[0].getTypes();
battle.commitDecisions();
assert.notDeepEqual(battle.p2.active[0].getTypes(), cachedTypes);
assert.deepEqual(battle.p2.active[0].getTypes(), ['Psychic', moveData.type]);
diff --git a/test/simulator/misc/weather.js b/test/simulator/misc/weather.js
index afdd5e2dbb..893ab1b37a 100644
--- a/test/simulator/misc/weather.js
+++ b/test/simulator/misc/weather.js
@@ -1,5 +1,7 @@
-var assert = require('assert');
-var battle;
+'use strict';
+
+const assert = require('assert');
+let battle;
describe('Weather damage calculation', function () {
afterEach(function () {
@@ -12,7 +14,7 @@ describe('Weather damage calculation', function () {
battle.join('p1', 'Guest 1', 1, [{species: 'Ninetales', ability: 'drought', moves: ['incinerate']}]);
battle.join('p2', 'Guest 2', 1, [{species: 'Cryogonal', ability: 'levitate', moves: ['splash']}]);
battle.commitDecisions();
- var pokemon = battle.p2.active[0];
+ let pokemon = battle.p2.active[0];
assert.strictEqual(pokemon.maxhp - pokemon.hp, 152);
});
@@ -22,7 +24,7 @@ describe('Weather damage calculation', function () {
battle.join('p1', 'Guest 1', 1, [{species: 'Ninetales', ability: 'drizzle', moves: ['incinerate']}]);
battle.join('p2', 'Guest 2', 1, [{species: 'Cryogonal', ability: 'levitate', moves: ['splash']}]);
battle.commitDecisions();
- var pokemon = battle.p2.active[0];
+ let pokemon = battle.p2.active[0];
assert.strictEqual(pokemon.maxhp - pokemon.hp, 50);
});
});
diff --git a/test/simulator/misc/weight.js b/test/simulator/misc/weight.js
index faef860470..cae511e1c6 100644
--- a/test/simulator/misc/weight.js
+++ b/test/simulator/misc/weight.js
@@ -1,5 +1,7 @@
-var assert = require('assert');
-var battle;
+'use strict';
+
+const assert = require('assert');
+let battle;
describe('Heavy Metal', function () {
afterEach(function () {
@@ -11,7 +13,7 @@ describe('Heavy Metal', function () {
battle.join('p1', 'Guest 1', 1, [{species: "Simisear", ability: 'heavymetal', moves: ['nastyplot']}]);
battle.join('p2', 'Guest 2', 1, [{species: "Simisage", ability: 'gluttony', moves: ['grassknot']}]);
battle.commitDecisions(); // Team Preview
- var basePower = 0;
+ let basePower = 0;
battle.on('BasePower', battle.getFormat(), function (bp, attacker, defender, move) {
if (move.id === 'grassknot') {
basePower = bp;
@@ -26,7 +28,7 @@ describe('Heavy Metal', function () {
battle.join('p1', 'Guest 1', 1, [{species: "Simisear", ability: 'heavymetal', moves: ['nastyplot']}]);
battle.join('p2', 'Guest 2', 1, [{species: "Simisage", ability: 'moldbreaker', moves: ['grassknot']}]);
battle.commitDecisions(); // Team Preview
- var basePower = 0;
+ let basePower = 0;
battle.on('BasePower', battle.getFormat(), function (bp, attacker, defender, move) {
if (move.id === 'grassknot') {
basePower = bp;
@@ -47,7 +49,7 @@ describe('Light Metal', function () {
battle.join('p1', 'Guest 1', 1, [{species: "Registeel", ability: 'lightmetal', moves: ['curse']}]);
battle.join('p2', 'Guest 2', 1, [{species: "Simisage", ability: 'gluttony', moves: ['grassknot']}]);
battle.commitDecisions(); // Team Preview
- var basePower = 0;
+ let basePower = 0;
battle.on('BasePower', battle.getFormat(), function (bp, attacker, defender, move) {
if (move.id === 'grassknot') {
basePower = bp;
@@ -62,7 +64,7 @@ describe('Light Metal', function () {
battle.join('p1', 'Guest 1', 1, [{species: "Registeel", ability: 'lightmetal', moves: ['splash']}]);
battle.join('p2', 'Guest 2', 1, [{species: "Simisage", ability: 'moldbreaker', moves: ['grassknot']}]);
battle.commitDecisions(); // Team Preview
- var basePower = 0;
+ let basePower = 0;
battle.on('BasePower', battle.getFormat(), function (bp, attacker, defender, move) {
if (move.id === 'grassknot') {
basePower = bp;
@@ -83,7 +85,7 @@ describe('Float Stone', function () {
battle.join('p1', 'Guest 1', 1, [{species: "Registeel", ability: 'clearbody', item: 'floatstone', moves: ['curse']}]);
battle.join('p2', 'Guest 2', 1, [{species: "Simisage", ability: 'gluttony', moves: ['grassknot']}]);
battle.commitDecisions(); // Team Preview
- var basePower = 0;
+ let basePower = 0;
battle.on('BasePower', battle.getFormat(), function (bp, attacker, defender, move) {
if (move.id === 'grassknot') {
basePower = bp;
@@ -104,7 +106,7 @@ describe('Autotomize', function () {
battle.join('p1', 'Guest 1', 1, [{species: "Registeel", ability: 'clearbody', moves: ['autotomize']}]);
battle.join('p2', 'Guest 2', 1, [{species: "Simisage", ability: 'gluttony', item: 'laggingtail', moves: ['grassknot']}]);
battle.commitDecisions(); // Team Preview
- var basePower = 0;
+ let basePower = 0;
battle.on('BasePower', battle.getFormat(), function (bp, attacker, defender, move) {
if (move.id === 'grassknot') {
basePower = bp;
@@ -121,7 +123,7 @@ describe('Autotomize', function () {
battle.join('p1', 'Guest 1', 1, [{species: "Lairon", ability: 'heavymetal', moves: ['autotomize']}]);
battle.join('p2', 'Guest 2', 1, [{species: "Simisage", ability: 'gluttony', item: 'laggingtail', moves: ['grassknot']}]);
battle.commitDecisions(); // Team Preview
- var basePower = 0;
+ let basePower = 0;
battle.on('BasePower', battle.getFormat(), function (bp, attacker, defender, move) {
if (move.id === 'grassknot') {
basePower = bp;
diff --git a/test/simulator/moves/belch.js b/test/simulator/moves/belch.js
index 55b1517e71..f35b4c023b 100644
--- a/test/simulator/moves/belch.js
+++ b/test/simulator/moves/belch.js
@@ -1,5 +1,7 @@
-var assert = require('assert');
-var battle;
+'use strict';
+
+const assert = require('assert');
+let battle;
describe('Belch', function () {
afterEach(function () {
diff --git a/test/simulator/moves/boomburst.js b/test/simulator/moves/boomburst.js
index a8c8900402..432700d311 100644
--- a/test/simulator/moves/boomburst.js
+++ b/test/simulator/moves/boomburst.js
@@ -1,5 +1,7 @@
-var assert = require('assert');
-var battle;
+'use strict';
+
+const assert = require('assert');
+let battle;
describe('Boomburst', function () {
afterEach(function () {
diff --git a/test/simulator/moves/bugbuzz.js b/test/simulator/moves/bugbuzz.js
index 7df2c43a6f..833c0ccb10 100644
--- a/test/simulator/moves/bugbuzz.js
+++ b/test/simulator/moves/bugbuzz.js
@@ -1,5 +1,7 @@
-var assert = require('assert');
-var battle;
+'use strict';
+
+const assert = require('assert');
+let battle;
describe('Bug Buzz', function () {
afterEach(function () {
diff --git a/test/simulator/moves/chatter.js b/test/simulator/moves/chatter.js
index 5fd15ccbba..b133e5ae22 100644
--- a/test/simulator/moves/chatter.js
+++ b/test/simulator/moves/chatter.js
@@ -1,5 +1,7 @@
-var assert = require('assert');
-var battle;
+'use strict';
+
+const assert = require('assert');
+let battle;
describe('Chatter', function () {
afterEach(function () {
diff --git a/test/simulator/moves/curse.js b/test/simulator/moves/curse.js
index 925afe7c98..4099789847 100644
--- a/test/simulator/moves/curse.js
+++ b/test/simulator/moves/curse.js
@@ -1,5 +1,7 @@
-var assert = require('assert');
-var battle;
+'use strict';
+
+const assert = require('assert');
+let battle;
describe('Curse', function () {
afterEach(function () {
@@ -60,7 +62,7 @@ describe('Curse', function () {
battle.join('p2', 'Guest 2', 1, [{species: "Caterpie", ability: 'shedskin', item: '', moves: ['stringshot']}]);
battle.commitDecisions();
- var hps = [battle.p1.active[0].hp, battle.p2.active[0].hp];
+ let hps = [battle.p1.active[0].hp, battle.p2.active[0].hp];
assert.notStrictEqual(hps[0], battle.p1.active[0].maxhp); // Curse user cut its HP down + residual damage
assert.strictEqual(hps[1], battle.p2.active[0].maxhp); // Foe unaffected
@@ -76,7 +78,7 @@ describe('Curse', function () {
battle.join('p2', 'Guest 2', 1, [{species: "Caterpie", ability: 'shedskin', item: '', moves: ['stringshot']}]);
battle.commitDecisions();
- var hps = [battle.p1.active[0].hp, battle.p2.active[0].hp];
+ let hps = [battle.p1.active[0].hp, battle.p2.active[0].hp];
assert.notStrictEqual(hps[0], battle.p1.active[0].maxhp); // Curse user cut its HP down
assert.notStrictEqual(hps[1], battle.p2.active[0].maxhp); // Curse residual damage
@@ -92,7 +94,7 @@ describe('XY/ORAS Curse targetting when becoming Ghost the same turn', function
battle.destroy();
});
- var doublesTeams = [[
+ let doublesTeams = [[
{species: "Kecleon", ability: 'colorchange', item: 'laggingtail', moves: ['curse', 'calmmind']},
{species: "Greninja", ability: 'torrent', item: '', moves: ['growl', 'mudsport']}
], [
@@ -100,15 +102,15 @@ describe('XY/ORAS Curse targetting when becoming Ghost the same turn', function
{species: "Gastly", ability: 'levitate', item: '', moves: ['lick', 'calmmind']}
]];
- var triplesTeams = [
+ let triplesTeams = [
doublesTeams[0].concat({species: "Metapod", ability: 'shedskin', item: '', moves: ['harden', 'stringshot']}),
doublesTeams[1].concat({species: "Kakuna", ability: 'shedskin', item: '', moves: ['harden', 'stringshot']})
];
function runDoublesTest(battle, curseUser) {
- var p1active = battle.p1.active;
- var p2active = battle.p2.active;
- var cursePartner = curseUser.side.active[1 - curseUser.position];
+ let p1active = battle.p1.active;
+ let p2active = battle.p2.active;
+ let cursePartner = curseUser.side.active[1 - curseUser.position];
battle.choose('p1', 'move 1, move 1'); // Kecleon uses Curse last in the turn.
battle.choose('p2', 'move 1 ' + (curseUser.position + 1) + ', move 1 ' + (curseUser.position + 1)); // Electric attack on Kecleon, then Ghost.
@@ -116,7 +118,7 @@ describe('XY/ORAS Curse targetting when becoming Ghost the same turn', function
assert.ok(curseUser.hasType('Ghost')); // Curse user must be Ghost
assert.ok(curseUser.hp < curseUser.maxhp / 2); // Curse user cut its HP down
- var foeHP = [p2active[0].hp, p2active[1].hp];
+ let foeHP = [p2active[0].hp, p2active[1].hp];
battle.choose('p1', 'move 2 1, move 2 1');
battle.choose('p2', 'move 2, move 2');
@@ -133,8 +135,8 @@ describe('XY/ORAS Curse targetting when becoming Ghost the same turn', function
}
function runTriplesTest(battle, curseUser) {
- var p1active = battle.p1.active;
- var p2active = battle.p2.active;
+ let p1active = battle.p1.active;
+ let p2active = battle.p2.active;
battle.choose('p1', 'move 1, move 1, move 1'); // Kecleon uses Curse last in the turn.
battle.choose('p2', 'move 1 ' + (curseUser.position + 1) + ', move 1 ' + (curseUser.position + 1) + ', move 1'); // Electric attack on Kecleon, then Ghost.
@@ -142,20 +144,20 @@ describe('XY/ORAS Curse targetting when becoming Ghost the same turn', function
assert.ok(curseUser.hasType('Ghost')); // Curse user must be Ghost
assert.ok(curseUser.hp < curseUser.maxhp / 2); // Curse user cut its HP down
- var foeHP = [p2active[0].hp, p2active[1].hp];
+ let foeHP = [p2active[0].hp, p2active[1].hp];
battle.choose('p1', 'move 2 1, move 2 1');
battle.choose('p2', 'move 2, move 2');
- var cursedFoe = false;
- for (var i = 0; i < 3; i++) {
- var allyPokemon = p1active[i];
+ let cursedFoe = false;
+ for (let i = 0; i < 3; i++) {
+ let allyPokemon = p1active[i];
if (allyPokemon === curseUser) {
assert.notStrictEqual(allyPokemon.hp, allyPokemon.maxhp); // Curse user cut its HP down
} else {
assert.strictEqual(allyPokemon.hp, allyPokemon.maxhp); // Partners unaffected by Curse
}
- var foePokemon = p2active[i];
+ let foePokemon = p2active[i];
if (foePokemon.hp !== foePokemon.maxhp) {
cursedFoe = true;
}
@@ -184,9 +186,9 @@ describe('XY/ORAS Curse targetting when becoming Ghost the same turn', function
[0, 1, 2].forEach(function (cursePos) {
it('should target an opponent in Triples even if the user is on position ' + cursePos, function () {
battle = BattleEngine.Battle.construct('battle-cursetest-' + (3 + cursePos), 'triplescustomgame');
- var p1team = triplesTeams[0].slice(1);
+ let p1team = triplesTeams[0].slice(1);
p1team.splice(cursePos, 0, triplesTeams[0][0]);
- var p2team = triplesTeams[1].slice();
+ let p2team = triplesTeams[1].slice();
battle.join('p1', 'Guest 1', 1, p1team);
battle.join('p2', 'Guest 2', 1, p2team);
diff --git a/test/simulator/moves/disable.js b/test/simulator/moves/disable.js
index 9cd4e9a34b..5d553370b9 100644
--- a/test/simulator/moves/disable.js
+++ b/test/simulator/moves/disable.js
@@ -1,5 +1,7 @@
-var assert = require('assert');
-var battle;
+'use strict';
+
+const assert = require('assert');
+let battle;
describe('Disable', function () {
afterEach(function () {
diff --git a/test/simulator/moves/echoedvoice.js b/test/simulator/moves/echoedvoice.js
index 8fdeecd658..528c9d9098 100644
--- a/test/simulator/moves/echoedvoice.js
+++ b/test/simulator/moves/echoedvoice.js
@@ -1,5 +1,7 @@
-var assert = require('assert');
-var battle;
+'use strict';
+
+const assert = require('assert');
+let battle;
describe('Echoed Voice', function () {
afterEach(function () {
diff --git a/test/simulator/moves/electricterrain.js b/test/simulator/moves/electricterrain.js
index 4278fe4ab9..56535ddee3 100644
--- a/test/simulator/moves/electricterrain.js
+++ b/test/simulator/moves/electricterrain.js
@@ -1,5 +1,7 @@
-var assert = require('assert');
-var battle;
+'use strict';
+
+const assert = require('assert');
+let battle;
describe('Electric Terrain', function () {
afterEach(function () {
@@ -28,8 +30,8 @@ describe('Electric Terrain', function () {
battle.join('p1', 'Guest 1', 1, [{species: "Jolteon", ability: 'voltabsorb', moves: ['electricterrain']}]);
battle.join('p2', 'Guest 2', 1, [{species: "Thundurus", ability: 'defiant', moves: ['thunderwave']}]);
battle.commitDecisions();
- var basePower;
- var move = Tools.getMove('thunderbolt');
+ let basePower;
+ let move = Tools.getMove('thunderbolt');
basePower = battle.runEvent('BasePower', battle.p1.active[0], battle.p2.active[0], move, move.basePower, true);
assert.strictEqual(basePower, battle.modify(move.basePower, 1.5));
basePower = battle.runEvent('BasePower', battle.p2.active[0], battle.p1.active[0], move, move.basePower, true);
@@ -93,7 +95,7 @@ describe('Electric Terrain', function () {
battle.join('p1', 'Guest 1', 1, [{species: "Jolteon", ability: 'voltabsorb', moves: ['electricterrain']}]);
battle.join('p2', 'Guest 2', 1, [{species: "Shuckle", ability: 'sturdy', moves: ['naturepower']}]);
battle.commitDecisions();
- var resultMove = toId(battle.log[battle.lastMoveLine].split('|')[3]);
+ let resultMove = toId(battle.log[battle.lastMoveLine].split('|')[3]);
assert.strictEqual(resultMove, 'thunderbolt');
});
});
diff --git a/test/simulator/moves/embargo.js b/test/simulator/moves/embargo.js
index c06407013f..181b3a3915 100644
--- a/test/simulator/moves/embargo.js
+++ b/test/simulator/moves/embargo.js
@@ -1,5 +1,7 @@
-var assert = require('assert');
-var battle;
+'use strict';
+
+const assert = require('assert');
+let battle;
describe('Embargo', function () {
afterEach(function () {
diff --git a/test/simulator/moves/followme.js b/test/simulator/moves/followme.js
index ab4a5b7473..1058296062 100644
--- a/test/simulator/moves/followme.js
+++ b/test/simulator/moves/followme.js
@@ -1,5 +1,7 @@
-var assert = require('assert');
-var battle;
+'use strict';
+
+const assert = require('assert');
+let battle;
describe('Follow Me', function () {
afterEach(function () {
@@ -19,7 +21,7 @@ describe('Follow Me', function () {
{species: 'Alakazam', ability: 'synchronize', moves: ['lowkick']}
]);
battle.commitDecisions(); // Team Preview
- var hitCount = 0;
+ let hitCount = 0;
battle.on('Damage', battle.getFormat(), function (damage, pokemon) {
if (pokemon.template.speciesid === 'clefable') {
hitCount++;
diff --git a/test/simulator/moves/foresight.js b/test/simulator/moves/foresight.js
index d9aeabc014..dbf83adfd5 100644
--- a/test/simulator/moves/foresight.js
+++ b/test/simulator/moves/foresight.js
@@ -1,5 +1,7 @@
-var battle;
-var assert = require('assert');
+'use strict';
+
+let battle;
+const assert = require('assert');
describe('Foresight', function () {
afterEach(function () {
@@ -26,7 +28,7 @@ describe('Foresight', function () {
battle.choose('p1', 'move 2');
battle.commitDecisions();
battle.boost({evasion: 6}, battle.p2.active[0]);
- for (var i = 0; i < 16; i++) {
+ for (let i = 0; i < 16; i++) {
battle.commitDecisions();
assert.notStrictEqual(battle.p2.active[0].hp, battle.p2.active[0].maxhp);
}
@@ -39,7 +41,7 @@ describe('Foresight', function () {
battle.choose('p1', 'move 3');
battle.commitDecisions();
battle.boost({spe: 6, evasion: -6}, battle.p2.active[0]);
- for (var i = 0; i < 16; i++) {
+ for (let i = 0; i < 16; i++) {
battle.commitDecisions();
assert.notStrictEqual(battle.p2.active[0].hp, battle.p2.active[0].maxhp);
}
diff --git a/test/simulator/moves/glare.js b/test/simulator/moves/glare.js
index d58cc60635..127142fb74 100644
--- a/test/simulator/moves/glare.js
+++ b/test/simulator/moves/glare.js
@@ -1,5 +1,7 @@
-var assert = require('assert');
-var battle;
+'use strict';
+
+const assert = require('assert');
+let battle;
describe('Glare', function () {
afterEach(function () {
diff --git a/test/simulator/moves/grassyterrain.js b/test/simulator/moves/grassyterrain.js
index 2cc9b7d9be..aac3f7711c 100644
--- a/test/simulator/moves/grassyterrain.js
+++ b/test/simulator/moves/grassyterrain.js
@@ -1,5 +1,7 @@
-var assert = require('assert');
-var battle;
+'use strict';
+
+const assert = require('assert');
+let battle;
describe('Grassy Terrain', function () {
afterEach(function () {
@@ -39,8 +41,8 @@ describe('Grassy Terrain', function () {
battle.join('p1', 'Guest 1', 1, [{species: "Shaymin", ability: 'naturalcure', moves: ['grassyterrain']}]);
battle.join('p2', 'Guest 2', 1, [{species: "Shaymin-Sky", ability: 'serenegrace', moves: ['leechseed']}]);
battle.commitDecisions();
- var basePower;
- var move = Tools.getMove('gigadrain');
+ let basePower;
+ let move = Tools.getMove('gigadrain');
basePower = battle.runEvent('BasePower', battle.p1.active[0], battle.p2.active[0], move, move.basePower, true);
assert.strictEqual(basePower, battle.modify(move.basePower, 1.5));
basePower = battle.runEvent('BasePower', battle.p2.active[0], battle.p1.active[0], move, move.basePower, true);
@@ -74,7 +76,7 @@ describe('Grassy Terrain', function () {
battle.join('p1', 'Guest 1', 1, [{species: "Whimsicott", ability: 'prankster', moves: ['grassyterrain']}]);
battle.join('p2', 'Guest 2', 1, [{species: "Shuckle", ability: 'sturdy', moves: ['naturepower']}]);
battle.commitDecisions();
- var resultMove = toId(battle.log[battle.lastMoveLine].split('|')[3]);
+ let resultMove = toId(battle.log[battle.lastMoveLine].split('|')[3]);
assert.strictEqual(resultMove, 'energyball');
});
});
diff --git a/test/simulator/moves/gravity.js b/test/simulator/moves/gravity.js
index d9a9ed3fc8..0d0f85e6e7 100644
--- a/test/simulator/moves/gravity.js
+++ b/test/simulator/moves/gravity.js
@@ -1,5 +1,7 @@
-var assert = require('assert');
-var battle;
+'use strict';
+
+const assert = require('assert');
+let battle;
describe('Gravity', function () {
afterEach(function () {
diff --git a/test/simulator/moves/haze.js b/test/simulator/moves/haze.js
index 91720bc713..5e5d89216f 100644
--- a/test/simulator/moves/haze.js
+++ b/test/simulator/moves/haze.js
@@ -1,5 +1,7 @@
-var assert = require('assert');
-var battle;
+'use strict';
+
+const assert = require('assert');
+let battle;
describe('Haze - RBY', function () {
afterEach(function () {
diff --git a/test/simulator/moves/healblock.js b/test/simulator/moves/healblock.js
index 3bb573e673..4a3e06ab39 100644
--- a/test/simulator/moves/healblock.js
+++ b/test/simulator/moves/healblock.js
@@ -1,5 +1,7 @@
-var assert = require('assert');
-var battle;
+'use strict';
+
+const assert = require('assert');
+let battle;
describe('Heal Block', function () {
afterEach(function () {
@@ -45,7 +47,7 @@ describe('Heal Block', function () {
battle.join('p1', 'Guest 1', 1, [{species: 'Sableye', ability: 'prankster', moves: ['healblock', 'surf']}]);
battle.join('p2', 'Guest 2', 1, [{species: 'Quagsire', ability: 'waterabsorb', moves: ['bellydrum', 'calmmind']}]);
battle.commitDecisions();
- var hp = battle.p2.active[0].hp;
+ let hp = battle.p2.active[0].hp;
battle.choose('p1', 'move 2');
battle.choose('p2', 'move 2');
assert.strictEqual(battle.p2.active[0].hp, hp);
@@ -56,7 +58,7 @@ describe('Heal Block', function () {
battle.join('p1', 'Guest 1', 1, [{species: 'Starmie', ability: 'noguard', moves: ['healblock']}]);
battle.join('p2', 'Guest 2', 1, [{species: 'Venusaur', ability: 'overgrow', moves: ['substitute', 'leechseed']}]);
battle.commitDecisions();
- var hp = battle.p2.active[0].hp;
+ let hp = battle.p2.active[0].hp;
battle.choose('p2', 'move 2');
battle.commitDecisions();
assert.strictEqual(battle.p2.active[0].hp, hp);
@@ -104,7 +106,7 @@ describe('Heal Block [Gen 5]', function () {
battle.join('p2', 'Guest 2', 1, [{species: 'Quagsire', ability: 'waterabsorb', moves: ['bellydrum', 'calmmind']}]);
battle.commitDecisions();
battle.commitDecisions();
- var hp = battle.p2.active[0].hp;
+ let hp = battle.p2.active[0].hp;
battle.choose('p1', 'move 2');
battle.choose('p2', 'move 2');
assert.strictEqual(battle.p2.active[0].hp, hp);
@@ -116,7 +118,7 @@ describe('Heal Block [Gen 5]', function () {
battle.join('p2', 'Guest 2', 1, [{species: 'Venusaur', ability: 'overgrow', moves: ['substitute', 'gigadrain']}]);
battle.commitDecisions();
battle.commitDecisions();
- var hp = battle.p2.active[0].hp;
+ let hp = battle.p2.active[0].hp;
battle.choose('p2', 'move 2');
battle.commitDecisions();
assert.strictEqual(battle.p2.active[0].hp, hp);
@@ -128,7 +130,7 @@ describe('Heal Block [Gen 5]', function () {
battle.join('p1', 'Guest 1', 1, [{species: 'Starmie', ability: 'noguard', moves: ['healblock']}]);
battle.join('p2', 'Guest 2', 1, [{species: 'Venusaur', ability: 'overgrow', moves: ['substitute', 'leechseed']}]);
battle.commitDecisions();
- var hp = battle.p2.active[0].hp;
+ let hp = battle.p2.active[0].hp;
battle.choose('p2', 'move 2');
battle.commitDecisions();
assert.strictEqual(battle.p2.active[0].hp, hp);
@@ -164,7 +166,7 @@ describe('Heal Block [Gen 4]', function () {
battle.join('p1', 'Guest 1', 1, [{species: 'Sableye', ability: 'prankster', moves: ['healblock']}]);
battle.join('p2', 'Guest 2', 1, [{species: 'Venusaur', ability: 'overgrow', moves: ['substitute', 'gigadrain']}]);
battle.commitDecisions();
- var hp = battle.p2.active[0].hp;
+ let hp = battle.p2.active[0].hp;
battle.choose('p2', 'move 2');
battle.commitDecisions();
assert.strictEqual(battle.p2.active[0].hp, hp);
@@ -195,7 +197,7 @@ describe('Heal Block [Gen 4]', function () {
battle.join('p1', 'Guest 1', 1, [{species: 'Sableye', ability: 'keeneye', moves: ['healblock', 'surf']}]);
battle.join('p2', 'Guest 2', 1, [{species: 'Quagsire', ability: 'waterabsorb', moves: ['bellydrum', 'calmmind']}]);
battle.commitDecisions();
- var hp = battle.p2.active[0].hp;
+ let hp = battle.p2.active[0].hp;
battle.choose('p1', 'move 2');
battle.choose('p2', 'move 2');
assert.notStrictEqual(battle.p2.active[0].hp, hp);
@@ -206,7 +208,7 @@ describe('Heal Block [Gen 4]', function () {
battle.join('p1', 'Guest 1', 1, [{species: 'Starmie', ability: 'noguard', moves: ['healblock']}]);
battle.join('p2', 'Guest 2', 1, [{species: 'Venusaur', ability: 'overgrow', moves: ['substitute', 'leechseed']}]);
battle.commitDecisions();
- var hp = battle.p2.active[0].hp;
+ let hp = battle.p2.active[0].hp;
battle.choose('p2', 'move 2');
battle.commitDecisions();
assert.strictEqual(battle.p2.active[0].hp, hp);
diff --git a/test/simulator/moves/hypervoice.js b/test/simulator/moves/hypervoice.js
index 81590c3054..a142f4ba14 100644
--- a/test/simulator/moves/hypervoice.js
+++ b/test/simulator/moves/hypervoice.js
@@ -1,5 +1,7 @@
-var assert = require('assert');
-var battle;
+'use strict';
+
+const assert = require('assert');
+let battle;
describe('Hyper Voice', function () {
afterEach(function () {
diff --git a/test/simulator/moves/imprison.js b/test/simulator/moves/imprison.js
index 9b0ca64dde..856ea828ad 100644
--- a/test/simulator/moves/imprison.js
+++ b/test/simulator/moves/imprison.js
@@ -1,5 +1,7 @@
-var assert = require('assert');
-var battle;
+'use strict';
+
+const assert = require('assert');
+let battle;
describe('Imprison', function () {
afterEach(function () {
diff --git a/test/simulator/moves/ingrain.js b/test/simulator/moves/ingrain.js
index 50a64a19b6..cb0189ef81 100644
--- a/test/simulator/moves/ingrain.js
+++ b/test/simulator/moves/ingrain.js
@@ -1,5 +1,7 @@
-var assert = require('assert');
-var battle;
+'use strict';
+
+const assert = require('assert');
+let battle;
describe('Ingrain', function () {
afterEach(function () {
diff --git a/test/simulator/moves/knockoff.js b/test/simulator/moves/knockoff.js
index f261b52827..8687a0d34b 100644
--- a/test/simulator/moves/knockoff.js
+++ b/test/simulator/moves/knockoff.js
@@ -1,5 +1,7 @@
-var assert = require('assert');
-var battle;
+'use strict';
+
+const assert = require('assert');
+let battle;
describe('Knock Off', function () {
afterEach(function () {
diff --git a/test/simulator/moves/magicroom.js b/test/simulator/moves/magicroom.js
index d95cbefe7c..43197fe890 100644
--- a/test/simulator/moves/magicroom.js
+++ b/test/simulator/moves/magicroom.js
@@ -1,5 +1,7 @@
-var assert = require('assert');
-var battle;
+'use strict';
+
+const assert = require('assert');
+let battle;
describe('Magic Room', function () {
afterEach(function () {
diff --git a/test/simulator/moves/miracleeye.js b/test/simulator/moves/miracleeye.js
index d7498f26ab..7770d210b3 100644
--- a/test/simulator/moves/miracleeye.js
+++ b/test/simulator/moves/miracleeye.js
@@ -1,5 +1,7 @@
-var battle;
-var assert = require('assert');
+'use strict';
+
+let battle;
+const assert = require('assert');
describe('Miracle Eye', function () {
afterEach(function () {
@@ -23,7 +25,7 @@ describe('Miracle Eye', function () {
battle.choose('p1', 'move 2');
battle.commitDecisions();
battle.boost({evasion: 6}, battle.p2.active[0]);
- for (var i = 0; i < 16; i++) {
+ for (let i = 0; i < 16; i++) {
battle.commitDecisions();
assert.notStrictEqual(battle.p2.active[0].hp, battle.p2.active[0].maxhp);
}
@@ -36,7 +38,7 @@ describe('Miracle Eye', function () {
battle.choose('p1', 'move 3');
battle.commitDecisions();
battle.boost({spe: 6, evasion: -6}, battle.p2.active[0]);
- for (var i = 0; i < 16; i++) {
+ for (let i = 0; i < 16; i++) {
battle.commitDecisions();
assert.notStrictEqual(battle.p2.active[0].hp, battle.p2.active[0].maxhp);
}
diff --git a/test/simulator/moves/mistyterrain.js b/test/simulator/moves/mistyterrain.js
index 56dc8dc6c9..c793bd6268 100644
--- a/test/simulator/moves/mistyterrain.js
+++ b/test/simulator/moves/mistyterrain.js
@@ -1,5 +1,7 @@
-var assert = require('assert');
-var battle;
+'use strict';
+
+const assert = require('assert');
+let battle;
describe('Misty Terrain', function () {
afterEach(function () {
@@ -28,8 +30,8 @@ describe('Misty Terrain', function () {
battle.join('p1', 'Guest 1', 1, [{species: "Shaymin", ability: 'naturalcure', moves: ['mistyterrain']}]);
battle.join('p2', 'Guest 2', 1, [{species: "Shaymin-Sky", ability: 'serenegrace', moves: ['leechseed']}]);
battle.commitDecisions();
- var basePower;
- var move = Tools.getMove('dragonpulse');
+ let basePower;
+ let move = Tools.getMove('dragonpulse');
basePower = battle.runEvent('BasePower', battle.p2.active[0], battle.p1.active[0], move, move.basePower, true);
assert.strictEqual(basePower, battle.modify(move.basePower, 0.5));
basePower = battle.runEvent('BasePower', battle.p1.active[0], battle.p2.active[0], move, move.basePower, true);
@@ -63,7 +65,7 @@ describe('Misty Terrain', function () {
battle.choose('p1', 'move 2');
battle.commitDecisions();
assert.strictEqual(battle.p1.active[0].status, '');
- var dataLine = battle.log[battle.lastMoveLine + 1].split('|');
+ let dataLine = battle.log[battle.lastMoveLine + 1].split('|');
assert.strictEqual(dataLine[1], '-start');
assert.ok(toId(dataLine[3]).endsWith('yawn'));
});
@@ -95,7 +97,7 @@ describe('Misty Terrain', function () {
battle.join('p1', 'Guest 1', 1, [{species: "Whimsicott", ability: 'prankster', moves: ['mistyterrain']}]);
battle.join('p2', 'Guest 2', 1, [{species: "Shuckle", ability: 'sturdy', moves: ['naturepower']}]);
battle.commitDecisions();
- var resultMove = toId(battle.log[battle.lastMoveLine].split('|')[3]);
+ let resultMove = toId(battle.log[battle.lastMoveLine].split('|')[3]);
assert.strictEqual(resultMove, 'moonblast');
});
});
diff --git a/test/simulator/moves/quash.js b/test/simulator/moves/quash.js
index fc2b28410a..6ee02525dd 100644
--- a/test/simulator/moves/quash.js
+++ b/test/simulator/moves/quash.js
@@ -1,5 +1,7 @@
-var assert = require('assert');
-var battle;
+'use strict';
+
+const assert = require('assert');
+let battle;
describe('Quash', function () {
afterEach(function () {
diff --git a/test/simulator/moves/ragepowder.js b/test/simulator/moves/ragepowder.js
index 936a1821bb..7d8179b835 100644
--- a/test/simulator/moves/ragepowder.js
+++ b/test/simulator/moves/ragepowder.js
@@ -1,5 +1,7 @@
-var assert = require('assert');
-var battle;
+'use strict';
+
+const assert = require('assert');
+let battle;
describe('Rage Powder', function () {
afterEach(function () {
@@ -19,7 +21,7 @@ describe('Rage Powder', function () {
{species: 'Alakazam', ability: 'synchronize', moves: ['absorb']}
]);
battle.commitDecisions();
- var hitCount = [0, 0, 0];
+ let hitCount = [0, 0, 0];
battle.p1.active[0].damage = function () {
hitCount[0]++;
return BattleEngine.BattlePokemon.prototype.damage.apply(this, arguments);
@@ -52,7 +54,7 @@ describe('Rage Powder', function () {
{species: 'Alakazam', ability: 'synchronize', item: 'safetygoggles', moves: ['absorb']}
]);
battle.commitDecisions();
- var hitCount = [0, 0, 0];
+ let hitCount = [0, 0, 0];
battle.p1.active[0].damage = function () {
hitCount[0]++;
return BattleEngine.BattlePokemon.prototype.damage.apply(this, arguments);
diff --git a/test/simulator/moves/relicsong.js b/test/simulator/moves/relicsong.js
index d0a46e7cd7..acc91b6fe0 100644
--- a/test/simulator/moves/relicsong.js
+++ b/test/simulator/moves/relicsong.js
@@ -1,5 +1,7 @@
-var assert = require('assert');
-var battle;
+'use strict';
+
+const assert = require('assert');
+let battle;
describe('Relic Song', function () {
afterEach(function () {
diff --git a/test/simulator/moves/rollout.js b/test/simulator/moves/rollout.js
index 7fe2db8a56..05f4217a30 100644
--- a/test/simulator/moves/rollout.js
+++ b/test/simulator/moves/rollout.js
@@ -1,11 +1,13 @@
-var assert = require('assert');
-var battle;
+'use strict';
-var moves = ['Ice Ball', 'Rollout'];
+const assert = require('assert');
+let battle;
-for (var i = 0; i < moves.length; i++) {
+let moves = ['Ice Ball', 'Rollout'];
+
+for (let i = 0; i < moves.length; i++) {
describe(moves[i], function () {
- var id = moves[i].toLowerCase().replace(/\W+/g, '');
+ let id = moves[i].toLowerCase().replace(/\W+/g, '');
afterEach(function () {
battle.destroy();
@@ -17,8 +19,8 @@ for (var i = 0; i < moves.length; i++) {
battle.join('p2', 'Guest 2', 1, [{species: 'Steelix', ability: 'noguard', moves: ['recover']}]);
battle.commitDecisions(); // Team Preview
- var ebp = 30;
- var count = 0;
+ let ebp = 30;
+ let count = 0;
battle.on('BasePower', battle.getFormat(), function (basePower) {
count++;
assert.strictEqual(basePower, ebp);
@@ -29,7 +31,7 @@ for (var i = 0; i < moves.length; i++) {
}
});
- for (var j = 0; j < 8; j++) {
+ for (let j = 0; j < 8; j++) {
battle.commitDecisions();
}
assert.strictEqual(count, 8);
@@ -41,8 +43,8 @@ for (var i = 0; i < moves.length; i++) {
battle.join('p2', 'Guest 2', 1, [{species: 'Steelix', ability: 'furcoat', moves: ['recover']}]);
battle.commitDecisions(); // Team Preview
- var ebp = 30;
- var count = 0;
+ let ebp = 30;
+ let count = 0;
battle.on('Accuracy', battle.getFormat(), function (accuracy, target, pokemon, move) {
if (move.id === 'recover') return;
@@ -59,7 +61,7 @@ for (var i = 0; i < moves.length; i++) {
ebp *= 2;
});
- for (var j = 0; j < 5; j++) {
+ for (let j = 0; j < 5; j++) {
battle.commitDecisions();
}
assert.strictEqual(count, 5);
@@ -71,8 +73,8 @@ for (var i = 0; i < moves.length; i++) {
battle.join('p2', 'Guest 2', 1, [{species: 'Steelix', ability: 'noguard', moves: ['recover']}]);
battle.commitDecisions(); // Team Preview
- var ebp = 30;
- var count = 0;
+ let ebp = 30;
+ let count = 0;
battle.on('BeforeMove', battle.getFormat(), function (attacker, defender, move) {
if (move.id === 'recover') return;
@@ -87,7 +89,7 @@ for (var i = 0; i < moves.length; i++) {
ebp *= 2;
});
- for (var j = 0; j < 5; j++) {
+ for (let j = 0; j < 5; j++) {
battle.commitDecisions();
}
assert.strictEqual(count, 5);
@@ -99,7 +101,7 @@ for (var i = 0; i < moves.length; i++) {
battle.join('p2', 'Guest 2', 1, [{species: 'Steelix', ability: 'noguard', moves: ['recover']}]);
battle.commitDecisions(); // Team Preview
- var runCount = 0;
+ let runCount = 0;
battle.on('BasePower', battle.getFormat(), function (basePower) {
assert.strictEqual(basePower, 60);
runCount++;
@@ -117,7 +119,7 @@ for (var i = 0; i < moves.length; i++) {
battle.join('p2', 'Guest 2', 1, [{species: 'Steelix', ability: 'noguard', moves: ['recover']}]);
battle.commitDecisions(); // Team Preview
- var hitCount = 0;
+ let hitCount = 0;
battle.on('BasePower', battle.getFormat(), function (basePower) {
assert.strictEqual(basePower, 30);
hitCount++;
diff --git a/test/simulator/moves/roost.js b/test/simulator/moves/roost.js
index 8117c6f7a6..f0d555a97d 100644
--- a/test/simulator/moves/roost.js
+++ b/test/simulator/moves/roost.js
@@ -1,5 +1,7 @@
-var assert = require('assert');
-var battle;
+'use strict';
+
+const assert = require('assert');
+let battle;
describe('Roost', function () {
afterEach(function () {
@@ -60,7 +62,7 @@ describe('Roost', function () {
]);
battle.commitDecisions();
- var hitCount = 0;
+ let hitCount = 0;
battle.p2.active[0].damage = function () {
hitCount++;
return BattleEngine.BattlePokemon.prototype.damage.apply(this, arguments);
diff --git a/test/simulator/moves/round.js b/test/simulator/moves/round.js
index 53fd204e7b..08a19f9331 100644
--- a/test/simulator/moves/round.js
+++ b/test/simulator/moves/round.js
@@ -1,5 +1,7 @@
-var assert = require('assert');
-var battle;
+'use strict';
+
+const assert = require('assert');
+let battle;
describe('Round', function () {
afterEach(function () {
diff --git a/test/simulator/moves/skydrop.js b/test/simulator/moves/skydrop.js
index 21b34aa7d2..2f474ffd53 100644
--- a/test/simulator/moves/skydrop.js
+++ b/test/simulator/moves/skydrop.js
@@ -1,5 +1,7 @@
-var assert = require('assert');
-var battle;
+'use strict';
+
+const assert = require('assert');
+let battle;
describe('Sky Drop', function () {
afterEach(function () {
diff --git a/test/simulator/moves/smellingsalts.js b/test/simulator/moves/smellingsalts.js
index dc7e603ee6..974ffc4c53 100644
--- a/test/simulator/moves/smellingsalts.js
+++ b/test/simulator/moves/smellingsalts.js
@@ -1,5 +1,7 @@
-var assert = require('assert');
-var battle;
+'use strict';
+
+const assert = require('assert');
+let battle;
describe('Smelling Salts', function () {
afterEach(function () {
diff --git a/test/simulator/moves/snarl.js b/test/simulator/moves/snarl.js
index 7f08587e28..572cb3ed51 100644
--- a/test/simulator/moves/snarl.js
+++ b/test/simulator/moves/snarl.js
@@ -1,5 +1,7 @@
-var assert = require('assert');
-var battle;
+'use strict';
+
+const assert = require('assert');
+let battle;
describe('Snarl', function () {
afterEach(function () {
diff --git a/test/simulator/moves/stealthrock.js b/test/simulator/moves/stealthrock.js
index 6dd372c696..b78c3e55e0 100644
--- a/test/simulator/moves/stealthrock.js
+++ b/test/simulator/moves/stealthrock.js
@@ -1,5 +1,7 @@
-var assert = require('assert');
-var battle;
+'use strict';
+
+const assert = require('assert');
+let battle;
describe('Stealth Rock', function () {
afterEach(function () {
@@ -27,8 +29,8 @@ describe('Stealth Rock', function () {
]);
battle.choose('p1', 'move 2');
battle.commitDecisions();
- var pokemon;
- for (var i = 2; i <= 6; i++) {
+ let pokemon;
+ for (let i = 2; i <= 6; i++) {
battle.choose('p2', 'switch ' + i);
battle.commitDecisions();
pokemon = battle.p2.active[0];
diff --git a/test/simulator/moves/substitute.js b/test/simulator/moves/substitute.js
index 523dc9f059..107402c9e8 100644
--- a/test/simulator/moves/substitute.js
+++ b/test/simulator/moves/substitute.js
@@ -1,5 +1,7 @@
-var assert = require('assert');
-var battle;
+'use strict';
+
+const assert = require('assert');
+let battle;
describe('Substitute', function () {
afterEach(function () {
@@ -11,7 +13,7 @@ describe('Substitute', function () {
battle.join('p1', 'Guest 1', 1, [{species: 'Mewtwo', ability: 'pressure', moves: ['substitute']}]);
battle.join('p2', 'Guest 2', 1, [{species: 'Mewtwo', ability: 'pressure', moves: ['recover']}]);
battle.commitDecisions();
- var pokemon = battle.p1.active[0];
+ let pokemon = battle.p1.active[0];
assert.strictEqual(pokemon.maxhp - pokemon.hp, Math.floor(pokemon.maxhp / 4));
});
@@ -31,7 +33,7 @@ describe('Substitute', function () {
battle.join('p1', 'Guest 1', 1, [{species: 'Mewtwo', ability: 'pressure', moves: ['substitute']}]);
battle.join('p2', 'Guest 2', 1, [{species: 'Mewtwo', ability: 'pressure', item: 'laggingtail', moves: ['psystrike']}]);
battle.commitDecisions();
- var pokemon = battle.p1.active[0];
+ let pokemon = battle.p1.active[0];
assert.strictEqual(pokemon.maxhp - pokemon.hp, Math.floor(pokemon.maxhp / 4));
});
@@ -42,7 +44,7 @@ describe('Substitute', function () {
battle.commitDecisions();
battle.choose('p1', 'move 2');
battle.commitDecisions();
- var pokemon = battle.p1.active[0];
+ let pokemon = battle.p1.active[0];
assert.notStrictEqual(pokemon.maxhp - pokemon.hp, Math.floor(pokemon.maxhp / 4));
});
@@ -53,7 +55,7 @@ describe('Substitute', function () {
battle.commitDecisions();
battle.choose('p2', 'move 2');
battle.commitDecisions();
- var pokemon = battle.p2.active[0];
+ let pokemon = battle.p2.active[0];
assert.strictEqual(pokemon.maxhp - pokemon.hp, Math.ceil(Math.floor(battle.p1.active[0].maxhp / 4) / 2));
});
@@ -62,7 +64,7 @@ describe('Substitute', function () {
battle.join('p1', 'Guest 1', 1, [{species: 'Zangoose', ability: 'pressure', moves: ['substitute']}]);
battle.join('p2', 'Guest 2', 1, [{species: 'Zangoose', ability: 'noguard', moves: ['bellydrum', 'drainpunch']}]);
battle.commitDecisions();
- var hp = battle.p2.active[0].hp;
+ let hp = battle.p2.active[0].hp;
battle.choose('p2', 'move 2');
battle.commitDecisions();
assert.strictEqual(battle.p2.active[0].hp - hp, Math.ceil(Math.floor(battle.p1.active[0].maxhp / 4) / 2));
@@ -72,7 +74,7 @@ describe('Substitute', function () {
battle = BattleEngine.Battle.construct();
battle.join('p1', 'Guest 1', 1, [{species: 'Mewtwo', ability: 'noguard', moves: ['substitute']}]);
battle.join('p2', 'Guest 2', 1, [{species: 'Mewtwo', ability: 'pressure', item: 'laggingtail', moves: ['hypnosis', 'toxic', 'poisongas', 'thunderwave', 'willowisp']}]);
- for (var i = 1; i <= 5; i++) {
+ for (let i = 1; i <= 5; i++) {
battle.choose('p2', 'move ' + i);
battle.commitDecisions();
assert.strictEqual(battle.p1.active[0].status, '');
diff --git a/test/simulator/moves/taunt.js b/test/simulator/moves/taunt.js
index c6b93fd34e..9de723bd93 100644
--- a/test/simulator/moves/taunt.js
+++ b/test/simulator/moves/taunt.js
@@ -1,5 +1,7 @@
-var assert = require('assert');
-var battle;
+'use strict';
+
+const assert = require('assert');
+let battle;
describe('Taunt', function () {
afterEach(function () {
diff --git a/test/simulator/moves/thief.js b/test/simulator/moves/thief.js
index 441a50f675..ad821fad86 100644
--- a/test/simulator/moves/thief.js
+++ b/test/simulator/moves/thief.js
@@ -1,5 +1,7 @@
-var assert = require('assert');
-var battle;
+'use strict';
+
+const assert = require('assert');
+let battle;
describe('Thief', function () {
afterEach(function () {
diff --git a/test/simulator/moves/thousandarrows.js b/test/simulator/moves/thousandarrows.js
index 300ef49fbe..d8af23046c 100644
--- a/test/simulator/moves/thousandarrows.js
+++ b/test/simulator/moves/thousandarrows.js
@@ -1,5 +1,7 @@
-var assert = require('assert');
-var battle;
+'use strict';
+
+const assert = require('assert');
+let battle;
describe('Thousand Arrows', function () {
afterEach(function () {
@@ -43,7 +45,7 @@ describe('Thousand Arrows', function () {
battle.join('p2', 'Guest 2', 1, [{species: "Ho-Oh", ability: 'shellarmor', item: 'ironball', moves: ['recover', 'trick']}]);
battle.commitDecisions();
assert.ok(!battle.log[battle.lastMoveLine + 1].startsWith('|-supereffective|'));
- var hp = battle.p2.active[0].hp;
+ let hp = battle.p2.active[0].hp;
assert.notStrictEqual(hp, battle.p2.active[0].maxhp);
battle.choose('p1', 'move 2');
battle.choose('p2', 'move 2');
diff --git a/test/simulator/moves/thunderwave.js b/test/simulator/moves/thunderwave.js
index 344d7b76e0..a0e0426011 100644
--- a/test/simulator/moves/thunderwave.js
+++ b/test/simulator/moves/thunderwave.js
@@ -1,5 +1,7 @@
-var assert = require('assert');
-var battle;
+'use strict';
+
+const assert = require('assert');
+let battle;
describe('Thunder Wave', function () {
afterEach(function () {
diff --git a/test/simulator/moves/transform.js b/test/simulator/moves/transform.js
index d676ff4d24..0f7bc36b49 100644
--- a/test/simulator/moves/transform.js
+++ b/test/simulator/moves/transform.js
@@ -1,5 +1,7 @@
-var assert = require('assert');
-var battle;
+'use strict';
+
+const assert = require('assert');
+let battle;
describe('Transform', function () {
afterEach(function () {
@@ -19,9 +21,9 @@ describe('Transform', function () {
battle.join('p1', 'Guest 1', 1, [{species: "Ditto", ability: 'limber', moves: ['transform']}]);
battle.join('p2', 'Guest 2', 1, [{species: "Mewtwo", ability: 'pressure', moves: ['rest']}]);
battle.commitDecisions();
- var p1poke = battle.p1.active[0];
- var p2poke = battle.p2.active[0];
- for (var stat in p1poke.stats) {
+ let p1poke = battle.p1.active[0];
+ let p2poke = battle.p2.active[0];
+ for (let stat in p1poke.stats) {
assert.strictEqual(p1poke.stats[stat], p2poke.stats[stat]);
}
assert.notStrictEqual(p1poke.hp, p2poke.hp);
@@ -32,13 +34,13 @@ describe('Transform', function () {
battle = BattleEngine.Battle.construct();
battle.join('p1', 'Guest 1', 1, [{species: "Mew", ability: 'synchronize', item: 'laggingtail', moves: ['calmmind', 'agility', 'transform']}]);
battle.join('p2', 'Guest 2', 1, [{species: "Scolipede", ability: 'swarm', moves: ['honeclaws', 'irondefense', 'doubleteam']}]);
- for (var i = 1; i <= 3; i++) {
+ for (let i = 1; i <= 3; i++) {
battle.choose('p1', 'move ' + i);
battle.choose('p2', 'move ' + i);
}
- var p1poke = battle.p1.active[0];
- var p2poke = battle.p2.active[0];
- for (var stat in p1poke.boosts) {
+ let p1poke = battle.p1.active[0];
+ let p2poke = battle.p2.active[0];
+ for (let stat in p1poke.boosts) {
assert.strictEqual(p1poke.boosts[stat], p2poke.boosts[stat]);
}
});
@@ -47,15 +49,15 @@ describe('Transform', function () {
battle = BattleEngine.Battle.construct();
battle.join('p1', 'Guest 1', 1, [{species: "Ditto", ability: 'limber', moves: ['transform']}]);
battle.join('p2', 'Guest 2', 1, [{species: "Mew", ability: 'synchronize', moves: ['rest', 'psychic', 'energyball', 'hyperbeam']}]);
- var p1poke = battle.p1.active[0];
- var p2poke = battle.p2.active[0];
+ let p1poke = battle.p1.active[0];
+ let p2poke = battle.p2.active[0];
battle.commitDecisions();
assert.strictEqual(p1poke.moves.length, p2poke.moves.length);
- for (var i = 0; i < p1poke.moves.length; i++) {
- var move = p1poke.moves[i];
+ for (let i = 0; i < p1poke.moves.length; i++) {
+ let move = p1poke.moves[i];
assert.strictEqual(move, p2poke.moves[i]);
move = battle.getMove(move);
- var movepp = p1poke.getMoveData(move);
+ let movepp = p1poke.getMoveData(move);
assert.strictEqual(movepp.pp, 5);
}
});
diff --git a/test/simulator/moves/uproar.js b/test/simulator/moves/uproar.js
index 589dd40338..c8e6a93b97 100644
--- a/test/simulator/moves/uproar.js
+++ b/test/simulator/moves/uproar.js
@@ -1,5 +1,7 @@
-var assert = require('assert');
-var battle;
+'use strict';
+
+const assert = require('assert');
+let battle;
describe('Uproar', function () {
afterEach(function () {
diff --git a/tools.js b/tools.js
index eb75e0a591..547b72e1c8 100644
--- a/tools.js
+++ b/tools.js
@@ -11,14 +11,16 @@
* @license MIT license
*/
-var fs = require('fs');
-var path = require('path');
+'use strict';
+
+const fs = require('fs');
+const path = require('path');
module.exports = (function () {
- var moddedTools = {};
+ let moddedTools = {};
- var dataTypes = ['FormatsData', 'Learnsets', 'Pokedex', 'Movedex', 'Statuses', 'TypeChart', 'Scripts', 'Items', 'Abilities', 'Natures', 'Formats', 'Aliases'];
- var dataFiles = {
+ let dataTypes = ['FormatsData', 'Learnsets', 'Pokedex', 'Movedex', 'Statuses', 'TypeChart', 'Scripts', 'Items', 'Abilities', 'Natures', 'Formats', 'Aliases'];
+ let dataFiles = {
'Pokedex': 'pokedex.js',
'Movedex': 'moves.js',
'Statuses': 'statuses.js',
@@ -32,7 +34,7 @@ module.exports = (function () {
'Aliases': 'aliases.js'
};
- var BattleNatures = dataFiles.Natures = {
+ let BattleNatures = dataFiles.Natures = {
adamant: {name:"Adamant", plus:'atk', minus:'spa'},
bashful: {name:"Bashful"},
bold: {name:"Bold", plus:'def', minus:'atk'},
@@ -62,7 +64,7 @@ module.exports = (function () {
function tryRequire(filePath) {
try {
- var ret = require(filePath);
+ let ret = require(filePath);
if (!ret || typeof ret !== 'object') return new TypeError("" + filePath + " must export an object except `null`, or it should be removed");
return ret;
} catch (e) {
@@ -74,12 +76,12 @@ module.exports = (function () {
if (!mod) mod = 'base';
this.isBase = (mod === 'base');
- var path = (this.isBase ? './data/' : './mods/' + mod + '/') + dataFiles.Scripts;
- var maybeScripts = tryRequire(path);
+ let path = (this.isBase ? './data/' : './mods/' + mod + '/') + dataFiles.Scripts;
+ let maybeScripts = tryRequire(path);
if (maybeScripts instanceof Error) {
- if (maybeScripts.code !== 'MODULE_NOT_FOUND') throw new Error("CRASH LOADING DATA: " + maybeScripts.stack);
+ if (maybeScripts.code !== 'MODULE_NOT_FOUND') throw new Error("CRASH LOADING DATA IN " + path + ": " + maybeScripts.stack);
} else {
- var BattleScripts = maybeScripts.BattleScripts;
+ let BattleScripts = maybeScripts.BattleScripts;
if (!BattleScripts || typeof BattleScripts !== 'object') throw new TypeError("Exported property `BattleScripts`from `./data/scripts.js` must be an object except `null`.");
if (BattleScripts.init) Object.defineProperty(this, 'initMod', {value: BattleScripts.init, enumerable: false, writable: true, configurable: true});
if (BattleScripts.inherit) Object.defineProperty(this, 'inheritMod', {value: BattleScripts.inherit, enumerable: false, writable: true, configurable: true});
@@ -90,8 +92,8 @@ module.exports = (function () {
Tools.preloadMods = function () {
if (Tools.preloadedMods) return;
- var modList = fs.readdirSync(path.resolve(__dirname, 'mods'));
- for (var i = 0; i < modList.length; i++) {
+ let modList = fs.readdirSync(path.resolve(__dirname, 'mods'));
+ for (let i = 0; i < modList.length; i++) {
moddedTools[modList[i]] = new Tools(modList[i]);
}
Tools.preloadedMods = true;
@@ -116,29 +118,29 @@ module.exports = (function () {
Tools.prototype.getImmunity = function (source, target) {
// returns false if the target is immune; true otherwise
// also checks immunity to some statuses
- var sourceType = source.type || source;
- var targetTyping = target.getTypes && target.getTypes() || target.types || target;
+ let sourceType = source.type || source;
+ let targetTyping = target.getTypes && target.getTypes() || target.types || target;
if (Array.isArray(targetTyping)) {
- for (var i = 0; i < targetTyping.length; i++) {
+ for (let i = 0; i < targetTyping.length; i++) {
if (!this.getImmunity(sourceType, targetTyping[i])) return false;
}
return true;
}
- var typeData = this.data.TypeChart[targetTyping];
+ let typeData = this.data.TypeChart[targetTyping];
if (typeData && typeData.damageTaken[sourceType] === 3) return false;
return true;
};
Tools.prototype.getEffectiveness = function (source, target) {
- var sourceType = source.type || source;
- var totalTypeMod = 0;
- var targetTyping = target.getTypes && target.getTypes() || target.types || target;
+ let sourceType = source.type || source;
+ let totalTypeMod = 0;
+ let targetTyping = target.getTypes && target.getTypes() || target.types || target;
if (Array.isArray(targetTyping)) {
- for (var i = 0; i < targetTyping.length; i++) {
+ for (let i = 0; i < targetTyping.length; i++) {
totalTypeMod += this.getEffectiveness(sourceType, targetTyping[i]);
}
return totalTypeMod;
}
- var typeData = this.data.TypeChart[targetTyping];
+ let typeData = this.data.TypeChart[targetTyping];
if (!typeData) return 0;
switch (typeData.damageTaken[sourceType]) {
case 1: return 1; // super-effective
@@ -190,8 +192,8 @@ module.exports = (function () {
Tools.prototype.getTemplate = function (template) {
if (!template || typeof template === 'string') {
- var name = (template || '').trim();
- var id = toId(name);
+ let name = (template || '').trim();
+ let id = toId(name);
if (this.data.Aliases[id]) {
name = this.data.Aliases[id];
id = toId(name);
@@ -258,15 +260,15 @@ module.exports = (function () {
};
Tools.prototype.getMove = function (move) {
if (!move || typeof move === 'string') {
- var name = (move || '').trim();
- var id = toId(name);
+ let name = (move || '').trim();
+ let id = toId(name);
if (this.data.Aliases[id]) {
name = this.data.Aliases[id];
id = toId(name);
}
move = {};
if (id.substr(0, 11) === 'hiddenpower') {
- var matches = /([a-z]*)([0-9]*)/.exec(id);
+ let matches = /([a-z]*)([0-9]*)/.exec(id);
id = matches[1];
}
if (id && this.data.Movedex[id]) {
@@ -321,14 +323,14 @@ module.exports = (function () {
Tools.prototype.getMoveCopy = function (move) {
if (move && move.isCopy) return move;
move = this.getMove(move);
- var moveCopy = Object.clone(move, true);
+ let moveCopy = Object.clone(move, true);
moveCopy.isCopy = true;
return moveCopy;
};
Tools.prototype.getEffect = function (effect) {
if (!effect || typeof effect === 'string') {
- var name = (effect || '').trim();
- var id = toId(name);
+ let name = (effect || '').trim();
+ let id = toId(name);
effect = {};
if (id && this.data.Statuses[id]) {
effect = this.data.Statuses[id];
@@ -367,8 +369,8 @@ module.exports = (function () {
};
Tools.prototype.getFormat = function (effect) {
if (!effect || typeof effect === 'string') {
- var name = (effect || '').trim();
- var id = toId(name);
+ let name = (effect || '').trim();
+ let id = toId(name);
if (this.data.Aliases[id]) {
name = this.data.Aliases[id];
id = toId(name);
@@ -393,8 +395,8 @@ module.exports = (function () {
};
Tools.prototype.getItem = function (item) {
if (!item || typeof item === 'string') {
- var name = (item || '').trim();
- var id = toId(name);
+ let name = (item || '').trim();
+ let id = toId(name);
if (this.data.Aliases[id]) {
name = this.data.Aliases[id];
id = toId(name);
@@ -433,8 +435,8 @@ module.exports = (function () {
};
Tools.prototype.getAbility = function (ability) {
if (!ability || typeof ability === 'string') {
- var name = (ability || '').trim();
- var id = toId(name);
+ let name = (ability || '').trim();
+ let id = toId(name);
ability = {};
if (id && this.data.Abilities[id]) {
ability = this.data.Abilities[id];
@@ -466,7 +468,7 @@ module.exports = (function () {
};
Tools.prototype.getType = function (type) {
if (!type || typeof type === 'string') {
- var id = toId(type);
+ let id = toId(type);
id = id.charAt(0).toUpperCase() + id.substr(1);
type = {};
if (id && this.data.TypeChart[id]) {
@@ -487,8 +489,8 @@ module.exports = (function () {
};
Tools.prototype.getNature = function (nature) {
if (!nature || typeof nature === 'string') {
- var name = (nature || '').trim();
- var id = toId(name);
+ let name = (nature || '').trim();
+ let id = toId(name);
nature = {};
if (id && this.data.Natures[id]) {
nature = this.data.Natures[id];
@@ -511,7 +513,7 @@ module.exports = (function () {
};
Tools.prototype.getBanlistTable = function (format, subformat, depth) {
- var banlistTable;
+ let banlistTable;
if (!depth) depth = 0;
if (depth > 8) return; // avoid infinite recursion
if (format.banlistTable && !subformat) {
@@ -524,24 +526,24 @@ module.exports = (function () {
banlistTable = format.banlistTable;
if (!subformat) subformat = format;
if (subformat.banlist) {
- for (var i = 0; i < subformat.banlist.length; i++) {
+ for (let i = 0; i < subformat.banlist.length; i++) {
// don't revalidate what we already validate
if (banlistTable[toId(subformat.banlist[i])]) continue;
banlistTable[subformat.banlist[i]] = subformat.name || true;
banlistTable[toId(subformat.banlist[i])] = subformat.name || true;
- var complexList;
+ let complexList;
if (subformat.banlist[i].includes('+')) {
if (subformat.banlist[i].includes('++')) {
complexList = subformat.banlist[i].split('++');
- for (var j = 0; j < complexList.length; j++) {
+ for (let j = 0; j < complexList.length; j++) {
complexList[j] = toId(complexList[j]);
}
format.teamBanTable.push(complexList);
} else {
complexList = subformat.banlist[i].split('+');
- for (var j = 0; j < complexList.length; j++) {
+ for (let j = 0; j < complexList.length; j++) {
complexList[j] = toId(complexList[j]);
}
format.setBanTable.push(complexList);
@@ -550,14 +552,14 @@ module.exports = (function () {
}
}
if (subformat.ruleset) {
- for (var i = 0; i < subformat.ruleset.length; i++) {
+ for (let i = 0; i < subformat.ruleset.length; i++) {
// don't revalidate what we already validate
if (banlistTable['Rule:' + toId(subformat.ruleset[i])]) continue;
banlistTable['Rule:' + toId(subformat.ruleset[i])] = subformat.ruleset[i];
if (format.ruleset.indexOf(subformat.ruleset[i]) < 0) format.ruleset.push(subformat.ruleset[i]);
- var subsubformat = this.getFormat(subformat.ruleset[i]);
+ let subsubformat = this.getFormat(subformat.ruleset[i]);
if (subsubformat.ruleset || subsubformat.banlist) {
this.getBanlistTable(format, subsubformat, depth + 1);
}
@@ -569,39 +571,39 @@ module.exports = (function () {
Tools.prototype.levenshtein = function (s, t, l) { // s = string 1, t = string 2, l = limit
// Original levenshtein distance function by James Westgate, turned out to be the fastest
- var d = []; // 2d matrix
+ let d = []; // 2d matrix
// Step 1
- var n = s.length;
- var m = t.length;
+ let n = s.length;
+ let m = t.length;
if (n === 0) return m;
if (m === 0) return n;
if (l && Math.abs(m - n) > l) return Math.abs(m - n);
// Create an array of arrays in javascript (a descending loop is quicker)
- for (var i = n; i >= 0; i--) d[i] = [];
+ for (let i = n; i >= 0; i--) d[i] = [];
// Step 2
- for (var i = n; i >= 0; i--) d[i][0] = i;
- for (var j = m; j >= 0; j--) d[0][j] = j;
+ for (let i = n; i >= 0; i--) d[i][0] = i;
+ for (let j = m; j >= 0; j--) d[0][j] = j;
// Step 3
- for (var i = 1; i <= n; i++) {
- var s_i = s.charAt(i - 1);
+ for (let i = 1; i <= n; i++) {
+ let s_i = s.charAt(i - 1);
// Step 4
- for (var j = 1; j <= m; j++) {
+ for (let j = 1; j <= m; j++) {
// Check the jagged ld total so far
if (i === j && d[i][j] > 4) return n;
- var t_j = t.charAt(j - 1);
- var cost = (s_i === t_j) ? 0 : 1; // Step 5
+ let t_j = t.charAt(j - 1);
+ let cost = (s_i === t_j) ? 0 : 1; // Step 5
// Calculate the minimum
- var mi = d[i - 1][j] + 1;
- var b = d[i][j - 1] + 1;
- var c = d[i - 1][j - 1] + cost;
+ let mi = d[i - 1][j] + 1;
+ let b = d[i][j - 1] + 1;
+ let c = d[i - 1][j - 1] + cost;
if (b < mi) mi = b;
if (c < mi) mi = c;
@@ -634,11 +636,11 @@ module.exports = (function () {
searchIn = searchIn || ['Pokedex', 'Movedex', 'Abilities', 'Items', 'Natures'];
- var searchFunctions = {Pokedex: 'getTemplate', Movedex: 'getMove', Abilities: 'getAbility', Items: 'getItem', Natures: 'getNature'};
- var searchTypes = {Pokedex: 'pokemon', Movedex: 'move', Abilities: 'ability', Items: 'item', Natures: 'nature'};
- var searchResults = [];
- for (var i = 0; i < searchIn.length; i++) {
- var res = this[searchFunctions[searchIn[i]]](target);
+ let searchFunctions = {Pokedex: 'getTemplate', Movedex: 'getMove', Abilities: 'getAbility', Items: 'getItem', Natures: 'getNature'};
+ let searchTypes = {Pokedex: 'pokemon', Movedex: 'move', Abilities: 'ability', Items: 'item', Natures: 'nature'};
+ let searchResults = [];
+ for (let i = 0; i < searchIn.length; i++) {
+ let res = this[searchFunctions[searchIn[i]]](target);
if (res.exists) {
res.searchType = searchTypes[searchIn[i]];
searchResults.push(res);
@@ -648,8 +650,8 @@ module.exports = (function () {
return searchResults;
}
- var cmpTarget = target.toLowerCase();
- var maxLd = 3;
+ let cmpTarget = target.toLowerCase();
+ let maxLd = 3;
if (cmpTarget.length <= 1) {
return false;
} else if (cmpTarget.length <= 4) {
@@ -657,14 +659,14 @@ module.exports = (function () {
} else if (cmpTarget.length <= 6) {
maxLd = 2;
}
- for (var i = 0; i < searchIn.length; i++) {
- var searchObj = this.data[searchIn[i]];
+ for (let i = 0; i < searchIn.length; i++) {
+ let searchObj = this.data[searchIn[i]];
if (!searchObj) {
continue;
}
- for (var j in searchObj) {
- var word = searchObj[j];
+ for (let j in searchObj) {
+ let word = searchObj[j];
if (typeof word === "object") {
word = word.name || word.species;
}
@@ -672,7 +674,7 @@ module.exports = (function () {
continue;
}
- var ld = this.levenshtein(cmpTarget, word.toLowerCase(), maxLd);
+ let ld = this.levenshtein(cmpTarget, word.toLowerCase(), maxLd);
if (ld <= maxLd) {
searchResults.push({word: word, ld: ld});
}
@@ -680,9 +682,9 @@ module.exports = (function () {
}
if (searchResults.length) {
- var newTarget = "";
- var newLD = 10;
- for (var i = 0, l = searchResults.length; i < l; i++) {
+ let newTarget = "";
+ let newLD = 10;
+ for (let i = 0, l = searchResults.length; i < l; i++) {
if (searchResults[i].ld < newLD) {
newTarget = searchResults[i];
newLD = searchResults[i].ld;
@@ -701,25 +703,25 @@ module.exports = (function () {
Tools.prototype.packTeam = function (team) {
if (!team) return '';
- var buf = '';
+ let buf = '';
- for (var i = 0; i < team.length; i++) {
- var set = team[i];
+ for (let i = 0; i < team.length; i++) {
+ let set = team[i];
if (buf) buf += ']';
// name
buf += (set.name || set.species);
// species
- var id = toId(set.species || set.name);
+ let id = toId(set.species || set.name);
buf += '|' + (toId(set.name || set.species) === id ? '' : id);
// item
buf += '|' + toId(set.item);
// ability
- var template = moddedTools.base.getTemplate(set.species || set.name);
- var abilities = template.abilities;
+ let template = moddedTools.base.getTemplate(set.species || set.name);
+ let abilities = template.abilities;
id = toId(set.ability);
if (abilities) {
if (id === toId(abilities['0'])) {
@@ -742,7 +744,7 @@ module.exports = (function () {
buf += '|' + set.nature;
// evs
- var evs = '|';
+ let evs = '|';
if (set.evs) {
evs = '|' + (set.evs['hp'] || '') + ',' + (set.evs['atk'] || '') + ',' + (set.evs['def'] || '') + ',' + (set.evs['spa'] || '') + ',' + (set.evs['spd'] || '') + ',' + (set.evs['spe'] || '');
}
@@ -760,7 +762,7 @@ module.exports = (function () {
}
// ivs
- var ivs = '|';
+ let ivs = '|';
if (set.ivs) {
ivs = '|' + (set.ivs['hp'] === 31 || set.ivs['hp'] === undefined ? '' : set.ivs['hp']) + ',' + (set.ivs['atk'] === 31 || set.ivs['atk'] === undefined ? '' : set.ivs['atk']) + ',' + (set.ivs['def'] === 31 || set.ivs['def'] === undefined ? '' : set.ivs['def']) + ',' + (set.ivs['spa'] === 31 || set.ivs['spa'] === undefined ? '' : set.ivs['spa']) + ',' + (set.ivs['spd'] === 31 || set.ivs['spd'] === undefined ? '' : set.ivs['spd']) + ',' + (set.ivs['spe'] === 31 || set.ivs['spe'] === undefined ? '' : set.ivs['spe']);
}
@@ -798,12 +800,12 @@ module.exports = (function () {
Tools.prototype.fastUnpackTeam = function (buf) {
if (!buf) return null;
- var team = [];
- var i = 0, j = 0;
+ let team = [];
+ let i = 0, j = 0;
// limit to 24
- for (var count = 0; count < 24; count++) {
- var set = {};
+ for (let count = 0; count < 24; count++) {
+ let set = {};
team.push(set);
// name
@@ -827,8 +829,8 @@ module.exports = (function () {
// ability
j = buf.indexOf('|', i);
if (j < 0) return;
- var ability = buf.substring(i, j);
- var template = moddedTools.base.getTemplate(set.species);
+ let ability = buf.substring(i, j);
+ let template = moddedTools.base.getTemplate(set.species);
set.ability = (template.abilities && ability in {'':1, 0:1, 1:1, H:1} ? template.abilities[ability || '0'] : ability);
i = j + 1;
@@ -848,7 +850,7 @@ module.exports = (function () {
j = buf.indexOf('|', i);
if (j < 0) return;
if (j !== i) {
- var evs = buf.substring(i, j).split(',');
+ let evs = buf.substring(i, j).split(',');
set.evs = {
hp: Number(evs[0]) || 0,
atk: Number(evs[1]) || 0,
@@ -870,7 +872,7 @@ module.exports = (function () {
j = buf.indexOf('|', i);
if (j < 0) return;
if (j !== i) {
- var ivs = buf.substring(i, j).split(',');
+ let ivs = buf.substring(i, j).split(',');
set.ivs = {
hp: ivs[0] === '' ? 31 : Number(ivs[0]) || 0,
atk: ivs[1] === '' ? 31 : Number(ivs[1]) || 0,
@@ -913,7 +915,7 @@ module.exports = (function () {
if (this.modsLoaded) return this;
if (!this.isLoaded) this.includeData();
- for (var id in moddedTools) {
+ for (let id in moddedTools) {
if (moddedTools[id].isLoaded) continue;
moddedTools[id].includeData();
}
@@ -924,10 +926,10 @@ module.exports = (function () {
Tools.prototype.includeData = function () {
if (this.isLoaded) return this;
if (!this.data) this.data = {mod: this.currentMod};
- var data = this.data;
+ let data = this.data;
- var basePath = './data/';
- var parentTools;
+ let basePath = './data/';
+ let parentTools;
if (this.parentMod) {
parentTools = moddedTools[this.parentMod];
if (!parentTools || parentTools === this) throw new Error("Unable to load " + this.currentMod + ". `inherit` should specify a parent mod from which to inherit data, or must be not specified.");
@@ -941,12 +943,12 @@ module.exports = (function () {
if (data.mod === 'base') return (data[dataType] = BattleNatures);
return;
}
- var maybeData = tryRequire(basePath + dataFiles[dataType]);
+ let maybeData = tryRequire(basePath + dataFiles[dataType]);
if (maybeData instanceof Error) {
- if (maybeData.code !== 'MODULE_NOT_FOUND') throw new Error("CRASH LOADING " + data.mod.toUpperCase() + " DATA:\n" + maybeData.stack);
+ if (maybeData.code !== 'MODULE_NOT_FOUND') throw new Error("CRASH LOADING " + data.mod.toUpperCase() + " DATA in " + basePath + dataFiles[dataType] + ":\n" + maybeData.stack);
maybeData['Battle' + dataType] = {}; // Fall back to an empty object
}
- var BattleData = maybeData['Battle' + dataType];
+ let BattleData = maybeData['Battle' + dataType];
if (!BattleData || typeof BattleData !== 'object') throw new TypeError("Exported property `Battle" + dataType + "`from `" + './data/' + dataFiles[dataType] + "` must be an object except `null`.");
if (BattleData !== data[dataType]) data[dataType] = Object.merge(BattleData, data[dataType]);
});
@@ -955,9 +957,9 @@ module.exports = (function () {
this.includeFormats();
} else {
dataTypes.forEach(function (dataType) {
- var parentTypedData = parentTools.data[dataType];
+ let parentTypedData = parentTools.data[dataType];
if (!data[dataType]) data[dataType] = {};
- for (var key in parentTypedData) {
+ for (let key in parentTypedData) {
if (data[dataType][key] === null) {
// null means don't inherit
delete data[dataType][key];
@@ -997,26 +999,26 @@ module.exports = (function () {
if (!this.data.Formats) this.data.Formats = {};
// Load [formats] aliases
- var maybeAliases = tryRequire('./data/' + dataFiles.Aliases);
+ let maybeAliases = tryRequire('./data/' + dataFiles.Aliases);
if (maybeAliases instanceof Error) {
if (maybeAliases.code !== 'MODULE_NOT_FOUND') throw new Error("CRASH LOADING ALIASES:\n" + maybeAliases.stack);
maybeAliases.BattleAliases = {}; // Fall back to an empty object
}
- var BattleAliases = maybeAliases.BattleAliases;
+ let BattleAliases = maybeAliases.BattleAliases;
if (!BattleAliases || typeof BattleAliases !== 'object') throw new TypeError("Exported property `BattleAliases`from `" + "./data/aliases.js` must be an object except `null`.");
this.data.Aliases = BattleAliases;
// Load formats
- var maybeFormats = tryRequire('./config/formats.js');
+ let maybeFormats = tryRequire('./config/formats.js');
if (maybeFormats instanceof Error) {
if (maybeFormats.code !== 'MODULE_NOT_FOUND') throw new Error("CRASH LOADING FORMATS:\n" + maybeFormats.stack);
}
- var BattleFormats = maybeFormats.Formats;
+ let BattleFormats = maybeFormats.Formats;
if (!Array.isArray(BattleFormats)) throw new TypeError("Exported property `Formats`from `" + "./config/formats.js" + "` must be an array.");
- for (var i = 0; i < BattleFormats.length; i++) {
- var format = BattleFormats[i];
- var id = toId(format.name);
+ for (let i = 0; i < BattleFormats.length; i++) {
+ let format = BattleFormats[i];
+ let id = toId(format.name);
if (!id) throw new RangeError("Format #" + (i + 1) + " must have a name with alphanumeric characters");
if (this.data.Formats[id]) throw new Error("Format #" + (i + 1) + " has a duplicate ID: `" + id + "`");
format.effectType = 'Format';
@@ -1036,7 +1038,7 @@ module.exports = (function () {
* Install our Tools functions into the battle object
*/
Tools.prototype.install = function (battle) {
- for (var i in this.data.Scripts) {
+ for (let i in this.data.Scripts) {
battle[i] = this.data.Scripts[i];
}
};
diff --git a/tournaments/generator-elimination.js b/tournaments/generator-elimination.js
index 07a4dc71df..4c5ce9886f 100644
--- a/tournaments/generator-elimination.js
+++ b/tournaments/generator-elimination.js
@@ -1,4 +1,6 @@
-var TreeNode = require('./lib/closure-goog.structs.TreeNode-c8e0b2dcd892.min.js').goog.structs.TreeNode;
+'use strict';
+
+let TreeNode = require('./lib/closure-goog.structs.TreeNode-c8e0b2dcd892.min.js').goog.structs.TreeNode;
const nameMap = {
'1': "Single",
@@ -10,7 +12,7 @@ const nameMap = {
// Feel free to add more
};
-var Elimination = (function () {
+let Elimination = (function () {
function Elimination(maxSubtrees) {
maxSubtrees = maxSubtrees || 1;
if (typeof maxSubtrees === 'string' && maxSubtrees.toLowerCase() === 'infinity') {
@@ -57,13 +59,13 @@ var Elimination = (function () {
this.users.delete(user);
this.users.set(user, {});
- var targetNode;
- for (var n = 0; n < this.tree.currentLayerLeafNodes.length && !targetNode; ++n) {
+ let targetNode;
+ for (let n = 0; n < this.tree.currentLayerLeafNodes.length && !targetNode; ++n) {
if (this.tree.currentLayerLeafNodes[n].getValue().user === user) {
targetNode = this.tree.currentLayerLeafNodes[n];
}
}
- for (var n = 0; n < this.tree.nextLayerLeafNodes.length && !targetNode; ++n) {
+ for (let n = 0; n < this.tree.nextLayerLeafNodes.length && !targetNode; ++n) {
if (this.tree.nextLayerLeafNodes[n].getValue().user === user) {
targetNode = this.tree.nextLayerLeafNodes[n];
}
@@ -71,7 +73,7 @@ var Elimination = (function () {
targetNode.getValue().user = replacementUser;
};
Elimination.prototype.getUsers = function (remaining) {
- var users = [];
+ let users = [];
this.users.forEach(function (value, key) {
if (remaining && (value.isEliminated || value.isDisqualified)) return;
users.push(key);
@@ -90,9 +92,9 @@ var Elimination = (function () {
this.tree.currentLayerLeafNodes.push(this.tree.tree);
return;
}
- var targetNode = this.tree.currentLayerLeafNodes.shift();
+ let targetNode = this.tree.currentLayerLeafNodes.shift();
- var newNode = new TreeNode(null, {user: targetNode.getValue().user});
+ let newNode = new TreeNode(null, {user: targetNode.getValue().user});
this.tree.nextLayerLeafNodes.push(newNode);
targetNode.addChild(newNode);
@@ -109,16 +111,16 @@ var Elimination = (function () {
}, this);
};
Elimination.prototype.getBracketData = function () {
- var rootNode = {children: []};
+ let rootNode = {children: []};
if (this.tree) {
- var queue = [{fromNode: this.tree.tree, toNode: rootNode}];
+ let queue = [{fromNode: this.tree.tree, toNode: rootNode}];
while (queue.length > 0) {
- var frame = queue.shift();
- var node = {children: []};
+ let frame = queue.shift();
+ let node = {children: []};
frame.toNode.children.push(node);
- var fromNodeValues = frame.fromNode.getValue();
+ let fromNodeValues = frame.fromNode.getValue();
if (frame.fromNode.isLeaf()) {
node.team = fromNodeValues.user || null;
} else {
@@ -136,7 +138,7 @@ var Elimination = (function () {
}
}
- var data = {};
+ let data = {};
data.type = 'tree';
data.rootNode = rootNode.children[0] || null;
return data;
@@ -150,11 +152,11 @@ var Elimination = (function () {
});
this.maxSubtrees = Math.min(this.maxSubtrees, this.users.size - 1);
- for (var t = 1; t < this.maxSubtrees; ++t) {
- var matchesByDepth = {};
- var queue = [{node: this.tree.tree, depth: 0}];
+ for (let t = 1; t < this.maxSubtrees; ++t) {
+ let matchesByDepth = {};
+ let queue = [{node: this.tree.tree, depth: 0}];
while (queue.length > 0) {
- var frame = queue.shift();
+ let frame = queue.shift();
if (frame.node.isLeaf() || frame.node.getValue().onLoseNode) continue;
if (!matchesByDepth[frame.depth]) matchesByDepth[frame.depth] = [];
@@ -164,16 +166,16 @@ var Elimination = (function () {
queue.push({node: frame.node.getChildAt(1), depth: frame.depth + 1});
}
- var newTree = {
+ let newTree = {
tree: new TreeNode(null, {fromNode: matchesByDepth[0][0]}),
currentLayerLeafNodes: [],
nextLayerLeafNodes: []
};
newTree.currentLayerLeafNodes.push(newTree.tree);
- for (var m in matchesByDepth) {
+ for (let m in matchesByDepth) {
if (m === '0') continue;
- var n = 0;
+ let n = 0;
for (; n < matchesByDepth[m].length - 1; n += 2) {
// Replace old leaf with:
// old leaf --+
@@ -181,14 +183,14 @@ var Elimination = (function () {
// +--+
// new leaf --+
- var oldLeaf = newTree.currentLayerLeafNodes.shift();
+ let oldLeaf = newTree.currentLayerLeafNodes.shift();
oldLeaf.addChild(new TreeNode(null, {fromNode: oldLeaf.getValue().fromNode}));
delete oldLeaf.getValue().fromNode;
- var newBranch = new TreeNode(null, {});
+ let newBranch = new TreeNode(null, {});
oldLeaf.addChild(newBranch);
- var newLeaf = new TreeNode(null, {fromNode: matchesByDepth[m][n]});
+ let newLeaf = new TreeNode(null, {fromNode: matchesByDepth[m][n]});
newBranch.addChild(newLeaf);
newTree.nextLayerLeafNodes.push(newLeaf);
@@ -202,11 +204,11 @@ var Elimination = (function () {
// +-->
// new leaf --+
- var oldLeaf = newTree.currentLayerLeafNodes.shift();
+ let oldLeaf = newTree.currentLayerLeafNodes.shift();
oldLeaf.addChild(new TreeNode(null, {fromNode: oldLeaf.getValue().fromNode}));
delete oldLeaf.getValue().fromNode;
- var newLeaf = new TreeNode(null, {fromNode: matchesByDepth[m][n]});
+ let newLeaf = new TreeNode(null, {fromNode: matchesByDepth[m][n]});
oldLeaf.addChild(newLeaf);
newTree.nextLayerLeafNodes.push(newLeaf);
}
@@ -222,7 +224,7 @@ var Elimination = (function () {
}
});
- var newRoot = new TreeNode(null, {});
+ let newRoot = new TreeNode(null, {});
newRoot.addChild(this.tree.tree);
newRoot.addChild(newTree.tree);
this.tree.tree = newRoot;
@@ -243,8 +245,8 @@ var Elimination = (function () {
this.users.get(user).isDisqualified = true;
// The user either has a single available battle or no available battles
- var match = null;
- var result;
+ let match = null;
+ let result;
this.tree.tree.traverse(function (node) {
if (node.getValue().state === 'available') {
if (node.getChildAt(0).getValue().user === user) {
@@ -259,7 +261,7 @@ var Elimination = (function () {
return !match;
});
if (match) {
- var error = this.setMatchResult(match, result);
+ let error = this.setMatchResult(match, result);
if (error) {
throw new Error("Unexpected " + error + " from setMatchResult([" + match.join(", ") + "], " + result + ")");
}
@@ -281,11 +283,11 @@ var Elimination = (function () {
Elimination.prototype.getAvailableMatches = function () {
if (!this.isBracketFrozen) return 'BracketNotFrozen';
- var matches = [];
+ let matches = [];
this.tree.tree.traverse(function (node) {
if (node.getValue().state === 'available') {
- var userA = node.getChildAt(0).getValue().user;
- var userB = node.getChildAt(1).getValue().user;
+ let userA = node.getChildAt(0).getValue().user;
+ let userB = node.getChildAt(1).getValue().user;
if (!this.users.get(userA).isBusy && !this.users.get(userB).isBusy) {
matches.push([userA, userB]);
}
@@ -300,7 +302,7 @@ var Elimination = (function () {
if (!this.users.has(match[0]) || !this.users.has(match[1])) return 'UserNotAdded';
- var targetNode = null;
+ let targetNode = null;
this.tree.tree.traverse(function (node) {
if (node.getValue().state === 'available' &&
node.getChildAt(0).getValue().user === match[0] &&
@@ -324,21 +326,21 @@ var Elimination = (function () {
match.result = result;
match.score = score.slice(0);
- var winner = targetNode.getChildAt(result === 'win' ? 0 : 1).getValue().user;
- var loser = targetNode.getChildAt(result === 'loss' ? 0 : 1).getValue().user;
+ let winner = targetNode.getChildAt(result === 'win' ? 0 : 1).getValue().user;
+ let loser = targetNode.getChildAt(result === 'loss' ? 0 : 1).getValue().user;
match.user = winner;
- var loserData = this.users.get(loser);
+ let loserData = this.users.get(loser);
++loserData.loseCount;
if (loserData.loseCount === this.maxSubtrees) loserData.isEliminated = true;
if (targetNode.getParent()) {
- var userA = targetNode.getParent().getChildAt(0).getValue().user;
- var userB = targetNode.getParent().getChildAt(1).getValue().user;
+ let userA = targetNode.getParent().getChildAt(0).getValue().user;
+ let userB = targetNode.getParent().getChildAt(1).getValue().user;
if (userA && userB) {
targetNode.getParent().getValue().state = 'available';
- var error = '';
+ let error = '';
if (this.users.get(userA).isDisqualified) {
error = this.setMatchResult([userA, userB], 'loss');
} else if (this.users.get(userB).isDisqualified) {
@@ -350,7 +352,7 @@ var Elimination = (function () {
}
}
} else if (loserData.loseCount < this.maxSubtrees && !loserData.isDisqualified) {
- var newRoot = new TreeNode(null, {state: 'available'});
+ let newRoot = new TreeNode(null, {state: 'available'});
newRoot.addChild(targetNode);
newRoot.addChild(new TreeNode(null, {user: loser}));
this.tree.tree = newRoot;
@@ -358,12 +360,12 @@ var Elimination = (function () {
if (match.onLoseNode) {
match.onLoseNode.getValue().user = loser;
- var userA = match.onLoseNode.getParent().getChildAt(0).getValue().user;
- var userB = match.onLoseNode.getParent().getChildAt(1).getValue().user;
+ let userA = match.onLoseNode.getParent().getChildAt(0).getValue().user;
+ let userB = match.onLoseNode.getParent().getChildAt(1).getValue().user;
if (userA && userB) {
match.onLoseNode.getParent().getValue().state = 'available';
- var error = '';
+ let error = '';
if (this.users.get(userA).isDisqualified) {
error = this.setMatchResult([userA, userB], 'loss');
} else if (this.users.get(userB).isDisqualified) {
@@ -384,9 +386,9 @@ var Elimination = (function () {
Elimination.prototype.getResults = function () {
if (!this.isTournamentEnded()) return 'TournamentNotEnded';
- var results = [];
- var currentNode = this.tree.tree;
- for (var n = 0; n < this.maxSubtrees; ++n) {
+ let results = [];
+ let currentNode = this.tree.tree;
+ for (let n = 0; n < this.maxSubtrees; ++n) {
results.push([currentNode.getValue().user]);
currentNode = currentNode.getChildAt(currentNode.getValue().result === 'loss' ? 0 : 1);
if (!currentNode) break;
diff --git a/tournaments/generator-round-robin.js b/tournaments/generator-round-robin.js
index ce256dc6f4..6c275f55c7 100644
--- a/tournaments/generator-round-robin.js
+++ b/tournaments/generator-round-robin.js
@@ -1,4 +1,6 @@
-var RoundRobin = (function () {
+'use strict';
+
+let RoundRobin = (function () {
function RoundRobin(isDoubles) {
this.isDoubles = !!isDoubles;
this.isBracketFrozen = false;
@@ -24,13 +26,13 @@ var RoundRobin = (function () {
RoundRobin.prototype.removeUser = function (user) {
if (this.isBracketFrozen) return 'BracketFrozen';
- var userIndex = this.users.indexOf(user);
+ let userIndex = this.users.indexOf(user);
if (userIndex < 0) return 'UserNotAdded';
this.users.splice(userIndex, 1);
};
RoundRobin.prototype.replaceUser = function (user, replacementUser) {
- var userIndex = this.users.indexOf(user);
+ let userIndex = this.users.indexOf(user);
if (userIndex < 0) return 'UserNotAdded';
if (this.users.indexOf(replacementUser) >= 0) return 'UserAlreadyAdded';
@@ -42,7 +44,7 @@ var RoundRobin = (function () {
};
RoundRobin.prototype.getBracketData = function () {
- var data = {};
+ let data = {};
data.type = 'table';
data.tableHeaders = {
cols: this.users.slice(0),
@@ -53,11 +55,11 @@ var RoundRobin = (function () {
if (!this.isDoubles && col >= row) return null;
if (userA === userB) return null;
- var cell = {};
+ let cell = {};
if (!this.isBracketFrozen) {
cell.state = 'unavailable';
} else {
- var match = this.matches[row][col];
+ let match = this.matches[row][col];
cell.state = match.state;
if (match.state === 'finished') {
cell.result = match.result;
@@ -89,7 +91,7 @@ var RoundRobin = (function () {
RoundRobin.prototype.disqualifyUser = function (user) {
if (!this.isBracketFrozen) return 'BracketNotFrozen';
- var userIndex = this.users.indexOf(user);
+ let userIndex = this.users.indexOf(user);
if (userIndex < 0) return 'UserNotAdded';
this.matches[userIndex].forEach(function (match, col) {
@@ -102,7 +104,7 @@ var RoundRobin = (function () {
}, this);
this.matches.forEach(function (challenges, row) {
- var match = challenges[userIndex];
+ let match = challenges[userIndex];
if (!match || match.state !== 'available') return;
match.state = 'finished';
match.result = 'win';
@@ -114,14 +116,14 @@ var RoundRobin = (function () {
RoundRobin.prototype.getUserBusy = function (user) {
if (!this.isBracketFrozen) return 'BracketNotFrozen';
- var userIndex = this.users.indexOf(user);
+ let userIndex = this.users.indexOf(user);
if (userIndex < 0) return 'UserNotAdded';
return this.isUsersBusy[userIndex];
};
RoundRobin.prototype.setUserBusy = function (user, isBusy) {
if (!this.isBracketFrozen) return 'BracketNotFrozen';
- var userIndex = this.users.indexOf(user);
+ let userIndex = this.users.indexOf(user);
if (userIndex < 0) return 'UserNotAdded';
this.isUsersBusy[userIndex] = isBusy;
};
@@ -129,7 +131,7 @@ var RoundRobin = (function () {
RoundRobin.prototype.getAvailableMatches = function () {
if (!this.isBracketFrozen) return 'BracketNotFrozen';
- var matches = [];
+ let matches = [];
this.matches.forEach(function (challenges, row) {
challenges.forEach(function (match, col) {
if (!match) return;
@@ -145,14 +147,14 @@ var RoundRobin = (function () {
if (!(result in {win:1, loss:1, draw:1})) return 'InvalidMatchResult';
- var userIndexA = this.users.indexOf(match[0]);
- var userIndexB = this.users.indexOf(match[1]);
+ let userIndexA = this.users.indexOf(match[0]);
+ let userIndexB = this.users.indexOf(match[1]);
if (userIndexA < 0 || userIndexB < 0) return 'UserNotAdded';
match = this.matches[userIndexA][userIndexB];
if (!match || match.state !== 'available') return 'InvalidMatch';
- var virtualScore;
+ let virtualScore;
if (result === 'win') {
virtualScore = [1, 0];
} else if (result === 'loss') {
@@ -177,13 +179,13 @@ var RoundRobin = (function () {
RoundRobin.prototype.getResults = function () {
if (!this.isTournamentEnded()) return 'TournamentNotEnded';
- var sortedScores = this.userScores.map(function (score, userIndex) {
+ let sortedScores = this.userScores.map(function (score, userIndex) {
return {userIndex: userIndex, score: score};
}).sort(function (a, b) { return b.score - a.score; });
- var results = [];
- var currentScore = sortedScores[0].score;
- var currentRank = [];
+ let results = [];
+ let currentScore = sortedScores[0].score;
+ let currentRank = [];
results.push(currentRank);
sortedScores.forEach(function (score) {
if (score.score < currentScore) {
diff --git a/tournaments/index.js b/tournaments/index.js
index 736f2897ec..6fa26af8be 100644
--- a/tournaments/index.js
+++ b/tournaments/index.js
@@ -1,14 +1,16 @@
+'use strict';
+
const BRACKET_MINIMUM_UPDATE_INTERVAL = 2 * 1000;
const AUTO_DISQUALIFY_WARNING_TIMEOUT = 30 * 1000;
const AUTO_START_MINIMUM_TIMEOUT = 30 * 1000;
const MAX_REASON_LENGTH = 300;
-var TournamentGenerators = {
+let TournamentGenerators = {
roundrobin: require('./generator-round-robin.js').RoundRobin,
elimination: require('./generator-elimination.js').Elimination
};
-var Tournament;
+let Tournament;
exports.tournaments = {};
@@ -17,7 +19,7 @@ function usersToNames(users) {
}
function createTournamentGenerator(generator, args, output) {
- var Generator = TournamentGenerators[toId(generator)];
+ let Generator = TournamentGenerators[toId(generator)];
if (!Generator) {
output.errorReply(generator + " is not a valid type.");
output.errorReply("Valid types: " + Object.keys(TournamentGenerators).join(", "));
@@ -57,7 +59,7 @@ function createTournament(room, format, generator, playerCap, isRated, args, out
return (exports.tournaments[room.id] = new Tournament(room, format, createTournamentGenerator(generator, args, output), playerCap, isRated));
}
function deleteTournament(id, output) {
- var tournament = exports.tournaments[id];
+ let tournament = exports.tournaments[id];
if (!tournament) {
output.errorReply(id + " doesn't exist.");
return false;
@@ -119,9 +121,9 @@ Tournament = (function () {
return;
}
- var isErrored = false;
+ let isErrored = false;
this.generator.getUsers().forEach(function (user) {
- var error = generator.addUser(user);
+ let error = generator.addUser(user);
if (typeof error === 'string') {
output.sendReply('|tournament|error|' + error);
isErrored = true;
@@ -166,7 +168,7 @@ Tournament = (function () {
);
return;
}
- var isJoined = this.generator.getUsers().indexOf(targetUser) >= 0;
+ let isJoined = this.generator.getUsers().indexOf(targetUser) >= 0;
connection.sendTo(this.room, '|tournament|update|' + JSON.stringify({
format: this.format,
generator: this.generator.name,
@@ -180,7 +182,7 @@ Tournament = (function () {
challengeBys: usersToNames(this.availableMatchesCache.challengeBys.get(targetUser))
}));
- var pendingChallenge = this.pendingChallenges.get(targetUser);
+ let pendingChallenge = this.pendingChallenges.get(targetUser);
if (pendingChallenge && pendingChallenge.to) {
connection.sendTo(this.room, '|tournament|update|' + JSON.stringify({challenging: pendingChallenge.to.name}));
} else if (pendingChallenge && pendingChallenge.from) {
@@ -227,7 +229,7 @@ Tournament = (function () {
// "Ghost" users sometimes end up in the tournament because they've merged with another user.
// This function is to remove those ghost users from the tournament.
this.generator.getUsers(true).forEach(function (user) {
- var realUser = Users.getExact(user.userid);
+ let realUser = Users.getExact(user.userid);
if (!realUser || realUser !== user) {
// The two following functions are called without their second argument,
// but the second argument will not be used in this situation
@@ -249,14 +251,14 @@ Tournament = (function () {
return;
}
- var users = this.generator.getUsers();
+ let users = this.generator.getUsers();
if (this.playerCap && users.length >= this.playerCap) {
output.sendReply('|tournament|error|Full');
return;
}
if (!isAllowAlts) {
- for (var i = 0; i < users.length; i++) {
+ for (let i = 0; i < users.length; i++) {
if (users[i].latestIp === user.latestIp) {
output.sendReply('|tournament|error|AltUserAlreadyAdded');
return;
@@ -264,7 +266,7 @@ Tournament = (function () {
}
}
- var error = this.generator.addUser(user);
+ let error = this.generator.addUser(user);
if (typeof error === 'string') {
output.sendReply('|tournament|error|' + error);
return;
@@ -277,7 +279,7 @@ Tournament = (function () {
if (this.playerCap === (users.length + 1)) this.room.add("The tournament is now full.");
};
Tournament.prototype.removeUser = function (user, output) {
- var error = this.generator.removeUser(user);
+ let error = this.generator.removeUser(user);
if (typeof error === 'string') {
output.sendReply('|tournament|error|' + error);
return;
@@ -289,7 +291,7 @@ Tournament = (function () {
this.update();
};
Tournament.prototype.replaceUser = function (user, replacementUser, output) {
- var error = this.generator.replaceUser(user, replacementUser);
+ let error = this.generator.replaceUser(user, replacementUser);
if (typeof error === 'string') {
output.sendReply('|tournament|error|' + error);
return;
@@ -303,23 +305,23 @@ Tournament = (function () {
};
Tournament.prototype.getBracketData = function () {
- var data = this.generator.getBracketData();
+ let data = this.generator.getBracketData();
if (data.type === 'tree') {
if (!data.rootNode) {
data.users = usersToNames(this.generator.getUsers()).sort();
return data;
}
- var queue = [data.rootNode];
+ let queue = [data.rootNode];
while (queue.length > 0) {
- var node = queue.shift();
+ let node = queue.shift();
if (node.state === 'available') {
- var pendingChallenge = this.pendingChallenges.get(node.children[0].team);
+ let pendingChallenge = this.pendingChallenges.get(node.children[0].team);
if (pendingChallenge && node.children[1].team === pendingChallenge.to) {
node.state = 'challenging';
}
- var inProgressMatch = this.inProgressMatches.get(node.children[0].team);
+ let inProgressMatch = this.inProgressMatches.get(node.children[0].team);
if (inProgressMatch && node.children[1].team === inProgressMatch.to) {
node.state = 'inprogress';
node.room = inProgressMatch.room.id;
@@ -335,8 +337,8 @@ Tournament = (function () {
} else if (data.type === 'table') {
if (this.isTournamentStarted) {
data.tableContents.forEach(function (row, r) {
- var pendingChallenge = this.pendingChallenges.get(data.tableHeaders.rows[r]);
- var inProgressMatch = this.inProgressMatches.get(data.tableHeaders.rows[r]);
+ let pendingChallenge = this.pendingChallenges.get(data.tableHeaders.rows[r]);
+ let inProgressMatch = this.inProgressMatches.get(data.tableHeaders.rows[r]);
if (pendingChallenge || inProgressMatch) {
row.forEach(function (cell, c) {
if (!cell) return;
@@ -366,7 +368,7 @@ Tournament = (function () {
}
this.purgeGhostUsers();
- var users = this.generator.getUsers();
+ let users = this.generator.getUsers();
if (users.length < 2) {
output.sendReply('|tournament|error|NotEnoughUsers');
return false;
@@ -399,23 +401,23 @@ Tournament = (function () {
return true;
};
Tournament.prototype.getAvailableMatches = function () {
- var matches = this.generator.getAvailableMatches();
+ let matches = this.generator.getAvailableMatches();
if (typeof matches === 'string') {
this.room.add("Unexpected error from getAvailableMatches(): " + matches + ". Please report this to an admin.");
return;
}
- var users = this.generator.getUsers();
- var challenges = new Map();
- var challengeBys = new Map();
- var oldAvailableMatches = new Map();
+ let users = this.generator.getUsers();
+ let challenges = new Map();
+ let challengeBys = new Map();
+ let oldAvailableMatches = new Map();
users.forEach(function (user) {
challenges.set(user, []);
challengeBys.set(user, []);
- var oldAvailableMatch = false;
- var availableMatches = this.availableMatches.get(user);
+ let oldAvailableMatch = false;
+ let availableMatches = this.availableMatches.get(user);
if (availableMatches.size) {
oldAvailableMatch = true;
availableMatches.clear();
@@ -443,7 +445,7 @@ Tournament = (function () {
};
Tournament.prototype.disqualifyUser = function (user, output, reason) {
- var error = this.generator.disqualifyUser(user);
+ let error = this.generator.disqualifyUser(user);
if (error) {
output.sendReply('|tournament|error|' + error);
return false;
@@ -456,7 +458,7 @@ Tournament = (function () {
this.disqualifiedUsers.set(user, true);
this.generator.setUserBusy(user, false);
- var challenge = this.pendingChallenges.get(user);
+ let challenge = this.pendingChallenges.get(user);
if (challenge) {
this.pendingChallenges.set(user, null);
if (challenge.to) {
@@ -470,7 +472,7 @@ Tournament = (function () {
}
}
- var matchFrom = this.inProgressMatches.get(user);
+ let matchFrom = this.inProgressMatches.get(user);
if (matchFrom) {
this.generator.setUserBusy(matchFrom.to, false);
this.inProgressMatches.set(user, null);
@@ -478,13 +480,13 @@ Tournament = (function () {
matchFrom.room.forfeit(user);
}
- var matchTo = null;
+ let matchTo = null;
this.inProgressMatches.forEach(function (match, userFrom) {
if (match && match.to === user) matchTo = userFrom;
});
if (matchTo) {
this.generator.setUserBusy(matchTo, false);
- var matchRoom = this.inProgressMatches.get(matchTo).room;
+ let matchRoom = this.inProgressMatches.get(matchTo).room;
delete matchRoom.tour;
matchRoom.forfeit(user);
this.inProgressMatches.set(matchTo, null);
@@ -550,9 +552,9 @@ Tournament = (function () {
}
if (this.autoDisqualifyTimer) clearTimeout(this.autoDisqualifyTimer);
this.lastActionTimes.forEach(function (time, user) {
- var availableMatches = false;
+ let availableMatches = false;
if (this.availableMatches.get(user).size) availableMatches = true;
- var pendingChallenge = this.pendingChallenges.get(user);
+ let pendingChallenge = this.pendingChallenges.get(user);
if (!availableMatches && !pendingChallenge) return;
if (pendingChallenge && pendingChallenge.to) return;
@@ -561,7 +563,7 @@ Tournament = (function () {
this.disqualifyUser(user, output, "You failed to make or accept the challenge in time.");
this.room.update();
} else if (Date.now() > time + this.autoDisqualifyTimeout - AUTO_DISQUALIFY_WARNING_TIMEOUT && !this.isAutoDisqualifyWarned.get(user)) {
- var remainingTime = this.autoDisqualifyTimeout - Date.now() + time;
+ let remainingTime = this.autoDisqualifyTimeout - Date.now() + time;
if (remainingTime <= 0) {
remainingTime = AUTO_DISQUALIFY_WARNING_TIMEOUT;
this.lastActionTimes.set(user, Date.now() - this.autoDisqualifyTimeout + AUTO_DISQUALIFY_WARNING_TIMEOUT);
@@ -627,7 +629,7 @@ Tournament = (function () {
return;
}
- var challenge = this.pendingChallenges.get(user);
+ let challenge = this.pendingChallenges.get(user);
if (!challenge || challenge.from) return;
this.generator.setUserBusy(user, false);
@@ -647,7 +649,7 @@ Tournament = (function () {
return;
}
- var challenge = this.pendingChallenges.get(user);
+ let challenge = this.pendingChallenges.get(user);
if (!challenge || !challenge.from) return;
user.prepBattle(this.format, 'tournament', user, this.finishAcceptChallenge.bind(this, user, challenge));
@@ -662,7 +664,7 @@ Tournament = (function () {
if (!this.pendingChallenges.get(challenge.from)) return;
if (!this.pendingChallenges.get(user)) return;
- var room = Rooms.global.startBattle(challenge.from, user, this.format, challenge.team, user.team, {rated: this.isRated, tour: this});
+ let room = Rooms.global.startBattle(challenge.from, user, this.format, challenge.team, user.team, {rated: this.isRated, tour: this});
if (!room) return;
this.pendingChallenges.set(challenge.from, null);
@@ -679,19 +681,19 @@ Tournament = (function () {
};
Tournament.prototype.onBattleJoin = function (room, user) {
if (this.scouting || this.isEnded || user.latestIp === room.p1.latestIp || user.latestIp === room.p2.latestIp) return;
- var roomid = (room && room.id ? room.id : room);
- var users = this.generator.getUsers(true);
- for (var i = 0; i < users.length; i++) {
+ let roomid = (room && room.id ? room.id : room);
+ let users = this.generator.getUsers(true);
+ for (let i = 0; i < users.length; i++) {
if (users[i].latestIp === user.latestIp) {
return "Scouting is banned: tournament players can't watch other tournament battles.";
}
}
};
Tournament.prototype.onBattleWin = function (room, winner) {
- var from = Users.get(room.p1);
- var to = Users.get(room.p2);
+ let from = Users.get(room.p1);
+ let to = Users.get(room.p2);
- var result = 'draw';
+ let result = 'draw';
if (from === winner) {
result = 'win';
} else if (to === winner) {
@@ -713,7 +715,7 @@ Tournament = (function () {
return this.room.update();
}
- var error = this.generator.setMatchResult([from, to], result, room.battle.score);
+ let error = this.generator.setMatchResult([from, to], result, room.battle.score);
if (error) {
// Should never happen
return this.room.add("Unexpected " + error + " from setMatchResult([" + from.userid + ", " + to.userid + "], " + result + ", " + room.battle.score + ") in onBattleWin(" + room.id + ", " + winner.userid + "). Please report this to an admin.").update();
@@ -751,7 +753,7 @@ Tournament = (function () {
return Tournament;
})();
-var commands = {
+let commands = {
basic: {
j: 'join',
in: 'join',
@@ -769,7 +771,7 @@ var commands = {
},
getusers: function (tournament) {
if (!this.canBroadcast()) return;
- var users = usersToNames(tournament.generator.getUsers(true).sort());
+ let users = usersToNames(tournament.generator.getUsers(true).sort());
this.sendReplyBox("" + users.length + " users remain in this tournament:
" + Tools.escapeHTML(users.join(", ")));
},
getupdate: function (tournament, user) {
@@ -780,7 +782,7 @@ var commands = {
if (params.length < 1) {
return this.sendReply("Usage: " + cmd + " ");
}
- var targetUser = Users.get(params[0]);
+ let targetUser = Users.get(params[0]);
if (!targetUser) {
return this.errorReply("User " + params[0] + " not found.");
}
@@ -798,8 +800,8 @@ var commands = {
if (params.length < 1) {
return this.sendReply("Usage: " + cmd + " [, ]");
}
- var playerCap = parseInt(params.splice(1, 1));
- var generator = createTournamentGenerator(params.shift(), params, this);
+ let playerCap = parseInt(params.splice(1, 1));
+ let generator = createTournamentGenerator(params.shift(), params, this);
if (generator && tournament.setGenerator(generator, this)) {
if (playerCap && playerCap >= 2) {
tournament.playerCap = playerCap;
@@ -823,11 +825,11 @@ var commands = {
if (params.length < 1) {
return this.sendReply("Usage: " + cmd + " ");
}
- var targetUser = Users.get(params[0]);
+ let targetUser = Users.get(params[0]);
if (!targetUser) {
return this.errorReply("User " + params[0] + " not found.");
}
- var reason = '';
+ let reason = '';
if (params[1]) {
reason = params[1].trim();
if (reason.length > MAX_REASON_LENGTH) return this.errorReply("The reason is too long. It cannot exceed " + MAX_REASON_LENGTH + " characters.");
@@ -842,7 +844,7 @@ var commands = {
return this.sendReply("Usage: " + cmd + " ");
}
if (params[0].toLowerCase() === 'infinity' || params[0] === '0') params[0] = 'off';
- var timeout = params[0].toLowerCase() === 'off' ? Infinity : params[0];
+ let timeout = params[0].toLowerCase() === 'off' ? Infinity : params[0];
if (tournament.setAutoStartTimeout(timeout * 60 * 1000, this)) {
this.privateModCommand("(The tournament auto start timeout was set to " + params[0] + " by " + user.name + ")");
}
@@ -853,7 +855,7 @@ var commands = {
return this.sendReply("Usage: " + cmd + " ");
}
if (params[0].toLowerCase() === 'infinity' || params[0] === '0') params[0] = 'off';
- var timeout = params[0].toLowerCase() === 'off' ? Infinity : params[0];
+ let timeout = params[0].toLowerCase() === 'off' ? Infinity : params[0];
if (tournament.setAutoDisqualifyTimeout(timeout * 60 * 1000, this)) {
this.privateModCommand("(The tournament auto disqualify timeout was set to " + params[0] + " by " + user.name + ")");
}
@@ -873,7 +875,7 @@ var commands = {
}
}
- var option = params[0].toLowerCase();
+ let option = params[0].toLowerCase();
if (option === 'on' || option === 'true' || option === 'allow' || option === 'allowed') {
tournament.scouting = true;
this.room.add('|tournament|scouting|allow');
@@ -900,9 +902,9 @@ CommandParser.commands.tour = 'tournament';
CommandParser.commands.tours = 'tournament';
CommandParser.commands.tournaments = 'tournament';
CommandParser.commands.tournament = function (paramString, room, user) {
- var cmdParts = paramString.split(' ');
- var cmd = cmdParts.shift().trim().toLowerCase();
- var params = cmdParts.join(' ').split(',').map(function (param) { return param.trim(); });
+ let cmdParts = paramString.split(' ');
+ let cmd = cmdParts.shift().trim().toLowerCase();
+ let params = cmdParts.join(' ').split(',').map(function (param) { return param.trim(); });
if (!params[0]) params = [];
if (cmd === '') {
@@ -950,21 +952,21 @@ CommandParser.commands.tournament = function (paramString, room, user) {
return this.sendReply("Usage: " + cmd + " , [, ]");
}
- var tour = createTournament(room, params.shift(), params.shift(), params.shift(), Config.istournamentsrated, params, this);
+ let tour = createTournament(room, params.shift(), params.shift(), params.shift(), Config.istournamentsrated, params, this);
if (tour) {
this.privateModCommand("(" + user.name + " created a tournament in " + tour.format + " format.)");
if (Config.tourannouncements && Config.tourannouncements.indexOf(room.id) >= 0) {
- var tourRoom = Rooms.search(Config.tourroom || 'tournaments');
+ let tourRoom = Rooms.search(Config.tourroom || 'tournaments');
if (tourRoom) tourRoom.addRaw('');
}
}
} else {
- var tournament = getTournament(room.id);
+ let tournament = getTournament(room.id);
if (!tournament) {
return this.sendReply("There is currently no tournament running in this room.");
}
- var commandHandler = null;
+ let commandHandler = null;
if (commands.basic[cmd]) {
commandHandler = typeof commands.basic[cmd] === 'string' ? commands.basic[commands.basic[cmd]] : commands.basic[cmd];
}
diff --git a/users.js b/users.js
index b80be7ee6d..36255b152e 100644
--- a/users.js
+++ b/users.js
@@ -23,21 +23,23 @@
* @license MIT license
*/
+'use strict';
+
const THROTTLE_DELAY = 600;
const THROTTLE_BUFFER_LIMIT = 6;
const THROTTLE_MULTILINE_WARN = 4;
-var fs = require('fs');
+const fs = require('fs');
/* global Users: true */
-var Users = module.exports = getUser;
+let Users = module.exports = getUser;
-var User, Connection;
+let User, Connection;
// basic initialization
-var users = Users.users = Object.create(null);
-var prevUsers = Users.prevUsers = Object.create(null);
-var numUsers = 0;
+let users = Users.users = Object.create(null);
+let prevUsers = Users.prevUsers = Object.create(null);
+let numUsers = 0;
/**
* Get a user.
@@ -57,8 +59,8 @@ var numUsers = 0;
function getUser(name, exactName) {
if (!name || name === '!') return null;
if (name && name.userid) return name;
- var userid = toId(name);
- var i = 0;
+ let userid = toId(name);
+ let i = 0;
while (!exactName && userid && !users[userid] && i < 1000) {
userid = prevUsers[userid];
i++;
@@ -79,7 +81,7 @@ Users.get = getUser;
* true = don't track across username changes, false = do track. This
* is not recommended since it's less readable.
*/
-var getExactUser = Users.getExact = function (name) {
+let getExactUser = Users.getExact = function (name) {
return getUser(name, true);
};
@@ -87,12 +89,12 @@ var getExactUser = Users.getExact = function (name) {
* Locks and bans
*********************************************************/
-var bannedIps = Users.bannedIps = Object.create(null);
-var bannedUsers = Users.bannedUsers = Object.create(null);
-var lockedIps = Users.lockedIps = Object.create(null);
-var lockedUsers = Users.lockedUsers = Object.create(null);
-var lockedRanges = Users.lockedRanges = Object.create(null);
-var rangelockedUsers = Users.rangeLockedUsers = Object.create(null);
+let bannedIps = Users.bannedIps = Object.create(null);
+let bannedUsers = Users.bannedUsers = Object.create(null);
+let lockedIps = Users.lockedIps = Object.create(null);
+let lockedUsers = Users.lockedUsers = Object.create(null);
+let lockedRanges = Users.lockedRanges = Object.create(null);
+let rangelockedUsers = Users.rangeLockedUsers = Object.create(null);
/**
* Searches for IP in table.
@@ -102,8 +104,8 @@ var rangelockedUsers = Users.rangeLockedUsers = Object.create(null);
*/
function ipSearch(ip, table) {
if (table[ip]) return table[ip];
- var dotIndex = ip.lastIndexOf('.');
- for (var i = 0; i < 4 && dotIndex > 0; i++) {
+ let dotIndex = ip.lastIndexOf('.');
+ for (let i = 0; i < 4 && dotIndex > 0; i++) {
ip = ip.substr(0, dotIndex);
if (table[ip + '.*']) return table[ip + '.*'];
dotIndex = ip.lastIndexOf('.');
@@ -125,15 +127,15 @@ Users.checkLocked = checkLocked;
Users.checkRangeBanned = function () {};
function unban(name) {
- var success;
- var userid = toId(name);
- for (var ip in bannedIps) {
+ let success;
+ let userid = toId(name);
+ for (let ip in bannedIps) {
if (bannedIps[ip] === userid) {
delete bannedIps[ip];
success = true;
}
}
- for (var id in bannedUsers) {
+ for (let id in bannedUsers) {
if (bannedUsers[id] === userid || id === userid) {
delete bannedUsers[id];
success = true;
@@ -143,9 +145,9 @@ function unban(name) {
return false;
}
function unlock(name, unlocked, noRecurse) {
- var userid = toId(name);
- var user = getUser(userid);
- var userips = null;
+ let userid = toId(name);
+ let user = getUser(userid);
+ let userips = null;
if (user) {
if (user.userid === userid) name = user.name;
if (user.locked) {
@@ -156,7 +158,7 @@ function unlock(name, unlocked, noRecurse) {
}
if (!noRecurse) userips = user.ips;
}
- for (var ip in lockedIps) {
+ for (let ip in lockedIps) {
if (userips && (ip in user.ips) && Users.lockedIps[ip] !== userid) {
unlocked = unlock(Users.lockedIps[ip], unlocked, true); // avoid infinite recursion
}
@@ -166,7 +168,7 @@ function unlock(name, unlocked, noRecurse) {
unlocked[name] = 1;
}
}
- for (var id in lockedUsers) {
+ for (let id in lockedUsers) {
if (lockedUsers[id] === userid || id === userid) {
delete lockedUsers[id];
unlocked = unlocked || {};
@@ -182,8 +184,8 @@ function lockRange(range, ip) {
lockedIps[range] = range;
ip = range.slice(0, -1);
}
- for (var i in users) {
- var curUser = users[i];
+ for (let i in users) {
+ let curUser = users[i];
if (!curUser.named || curUser.locked || curUser.confirmed) continue;
if (ip) {
if (!curUser.latestIp.startsWith(ip)) continue;
@@ -196,7 +198,7 @@ function lockRange(range, ip) {
curUser.updateIdentity();
}
- var time = 90 * 60 * 1000;
+ let time = 90 * 60 * 1000;
lockedRanges[range] = setTimeout(function () {
unlockRange(range);
}, time);
@@ -204,8 +206,8 @@ function lockRange(range, ip) {
function unlockRange(range) {
if (!lockedRanges[range]) return;
clearTimeout(lockedRanges[range]);
- for (var i in rangelockedUsers[range]) {
- var user = getUser(i);
+ for (let i in rangelockedUsers[range]) {
+ let user = getUser(i);
if (user) {
user.locked = false;
user.updateIdentity();
@@ -224,27 +226,27 @@ Users.unlockRange = unlockRange;
* Routing
*********************************************************/
-var connections = Users.connections = Object.create(null);
+let connections = Users.connections = Object.create(null);
Users.shortenHost = function (host) {
if (host.slice(-7) === '-nohost') return host;
- var dotLoc = host.lastIndexOf('.');
- var tld = host.substr(dotLoc);
+ let dotLoc = host.lastIndexOf('.');
+ let tld = host.substr(dotLoc);
if (tld === '.uk' || tld === '.au' || tld === '.br') dotLoc = host.lastIndexOf('.', dotLoc - 1);
dotLoc = host.lastIndexOf('.', dotLoc - 1);
return host.substr(dotLoc + 1);
};
Users.socketConnect = function (worker, workerid, socketid, ip) {
- var id = '' + workerid + '-' + socketid;
- var connection = connections[id] = new Connection(id, worker, socketid, null, ip);
+ let id = '' + workerid + '-' + socketid;
+ let connection = connections[id] = new Connection(id, worker, socketid, null, ip);
if (Monitor.countConnection(ip)) {
connection.destroy();
bannedIps[ip] = '#cflood';
return;
}
- var checkResult = Users.checkBanned(ip);
+ let checkResult = Users.checkBanned(ip);
if (!checkResult && Users.checkRangeBanned(ip)) {
checkResult = '#ipban';
}
@@ -269,7 +271,7 @@ Users.socketConnect = function (worker, workerid, socketid, ip) {
});
}
- var user = new User(connection);
+ let user = new User(connection);
connection.user = user;
// Generate 1024-bit challenge string.
require('crypto').randomBytes(128, function (ex, buffer) {
@@ -283,7 +285,7 @@ Users.socketConnect = function (worker, workerid, socketid, ip) {
} else if (connection.user) { // if user is still connected
connection.challenge = buffer.toString('hex');
// console.log('JOIN: ' + connection.user.name + ' [' + connection.challenge.substr(0, 15) + '] [' + socket.id + ']');
- var keyid = Config.loginserverpublickeyid || 0;
+ let keyid = Config.loginserverpublickeyid || 0;
connection.sendTo(null, '|challstr|' + keyid + '|' + connection.challenge);
}
});
@@ -293,7 +295,7 @@ Users.socketConnect = function (worker, workerid, socketid, ip) {
user.latestHost = hosts[0];
if (Config.hostfilter) Config.hostfilter(hosts[0], user, connection);
if (user.named && !user.locked && user.group === Config.groupsranking[0]) {
- var shortHost = Users.shortenHost(hosts[0]);
+ let shortHost = Users.shortenHost(hosts[0]);
if (lockedRanges[shortHost]) {
user.send("|popup|You are locked because someone on your ISP has spammed, and your ISP does not give us any way to tell you apart from them.");
rangelockedUsers[shortHost][user.userid] = 1;
@@ -318,17 +320,17 @@ Users.socketConnect = function (worker, workerid, socketid, ip) {
};
Users.socketDisconnect = function (worker, workerid, socketid) {
- var id = '' + workerid + '-' + socketid;
+ let id = '' + workerid + '-' + socketid;
- var connection = connections[id];
+ let connection = connections[id];
if (!connection) return;
connection.onDisconnect();
};
Users.socketReceive = function (worker, workerid, socketid, message) {
- var id = '' + workerid + '-' + socketid;
+ let id = '' + workerid + '-' + socketid;
- var connection = connections[id];
+ let connection = connections[id];
if (!connection) return;
// Due to a bug in SockJS or Faye, if an exception propagates out of
@@ -340,14 +342,14 @@ Users.socketReceive = function (worker, workerid, socketid, message) {
if (message.charAt(0) === '{') return;
// drop invalid messages without a pipe character
- var pipeIndex = message.indexOf('|');
+ let pipeIndex = message.indexOf('|');
if (pipeIndex < 0) return;
- var roomid = message.substr(0, pipeIndex);
- var lines = message.substr(pipeIndex + 1);
- var room = Rooms.get(roomid);
+ let roomid = message.substr(0, pipeIndex);
+ let lines = message.substr(pipeIndex + 1);
+ let room = Rooms.get(roomid);
if (!room) room = Rooms.lobby || Rooms.global;
- var user = connection.user;
+ let user = connection.user;
if (!user) return;
if (lines.substr(0, 3) === '>> ' || lines.substr(0, 4) === '>>> ') {
user.chat(lines, room, connection);
@@ -368,11 +370,11 @@ Users.socketReceive = function (worker, workerid, socketid, message) {
});
}
- var startTime = Date.now();
- for (var i = 0; i < lines.length; i++) {
+ let startTime = Date.now();
+ for (let i = 0; i < lines.length; i++) {
if (user.chat(lines[i], room, connection) === false) break;
}
- var deltaTime = Date.now() - startTime;
+ let deltaTime = Date.now() - startTime;
if (deltaTime > 500) {
Monitor.warn("[slow] " + deltaTime + "ms - " + user.name + " <" + connection.ip + ">: " + message);
}
@@ -382,24 +384,24 @@ Users.socketReceive = function (worker, workerid, socketid, message) {
* User groups
*********************************************************/
-var usergroups = Users.usergroups = Object.create(null);
+let usergroups = Users.usergroups = Object.create(null);
function importUsergroups() {
// can't just say usergroups = {} because it's exported
- for (var i in usergroups) delete usergroups[i];
+ for (let i in usergroups) delete usergroups[i];
fs.readFile('config/usergroups.csv', function (err, data) {
if (err) return;
data = ('' + data).split("\n");
- for (var i = 0; i < data.length; i++) {
+ for (let i = 0; i < data.length; i++) {
if (!data[i]) continue;
- var row = data[i].split(",");
+ let row = data[i].split(",");
usergroups[toId(row[0])] = (row[1] || Config.groupsranking[0]) + row[0];
}
});
}
function exportUsergroups() {
- var buffer = '';
- for (var i in usergroups) {
+ let buffer = '';
+ for (let i in usergroups) {
buffer += usergroups[i].substr(1).replace(/,/g, '') + ',' + usergroups[i].charAt(0) + "\n";
}
fs.writeFile('config/usergroups.csv', buffer);
@@ -419,15 +421,15 @@ function cacheGroupData() {
Config.groups = Object.create(null);
Config.groupsranking = [];
}
- var groups = Config.groups;
- var cachedGroups = {};
+ let groups = Config.groups;
+ let cachedGroups = {};
function cacheGroup(sym, groupData) {
if (cachedGroups[sym] === 'processing') return false; // cyclic inheritance.
if (cachedGroups[sym] !== true && groupData['inherit']) {
cachedGroups[sym] = 'processing';
- var inheritGroup = groups[groupData['inherit']];
+ let inheritGroup = groups[groupData['inherit']];
if (cacheGroup(groupData['inherit'], inheritGroup)) {
Object.merge(groupData, inheritGroup, false, false);
}
@@ -437,26 +439,26 @@ function cacheGroupData() {
}
if (Config.grouplist) { // Using new groups format.
- var grouplist = Config.grouplist;
- var numGroups = grouplist.length;
- for (var i = 0; i < numGroups; i++) {
- var groupData = grouplist[i];
+ let grouplist = Config.grouplist;
+ let numGroups = grouplist.length;
+ for (let i = 0; i < numGroups; i++) {
+ let groupData = grouplist[i];
groupData.rank = numGroups - i - 1;
groups[groupData.symbol] = groupData;
Config.groupsranking.unshift(groupData.symbol);
}
}
- for (var sym in groups) {
- var groupData = groups[sym];
+ for (let sym in groups) {
+ let groupData = groups[sym];
cacheGroup(sym, groupData);
}
}
cacheGroupData();
Users.setOfflineGroup = function (name, group, force) {
- var userid = toId(name);
- var user = getExactUser(userid);
+ let userid = toId(name);
+ let user = getExactUser(userid);
if (force && (user || usergroups[userid])) return false;
if (user) {
user.setGroup(group);
@@ -465,7 +467,7 @@ Users.setOfflineGroup = function (name, group, force) {
if (!group || group === Config.groupsranking[0]) {
delete usergroups[userid];
} else {
- var usergroup = usergroups[userid];
+ let usergroup = usergroups[userid];
if (!usergroup && !force) return false;
name = usergroup ? usergroup.substr(1) : name;
usergroups[userid] = group + name;
@@ -493,7 +495,7 @@ User = (function () {
this.userid = toId(this.name);
this.group = Config.groupsranking[0];
- var trainersprites = [1, 2, 101, 102, 169, 170, 265, 266];
+ let trainersprites = [1, 2, 101, 102, 169, 170, 265, 266];
this.avatar = trainersprites[Math.floor(Math.random() * trainersprites.length)];
this.connected = true;
@@ -540,14 +542,14 @@ User = (function () {
User.prototype.sendTo = function (roomid, data) {
if (roomid && roomid.id) roomid = roomid.id;
if (roomid && roomid !== 'global' && roomid !== 'lobby') data = '>' + roomid + '\n' + data;
- for (var i = 0; i < this.connections.length; i++) {
+ for (let i = 0; i < this.connections.length; i++) {
if (roomid && !this.connections[i].rooms[roomid]) continue;
this.connections[i].send(data);
Monitor.countNetworkUse(data.length);
}
};
User.prototype.send = function (data) {
- for (var i = 0; i < this.connections.length; i++) {
+ for (let i = 0; i < this.connections.length; i++) {
this.connections[i].send(data);
Monitor.countNetworkUse(data.length);
}
@@ -560,7 +562,7 @@ User = (function () {
return '‽' + this.name;
}
if (roomid) {
- var room = Rooms.rooms[roomid];
+ let room = Rooms.rooms[roomid];
if (room.isMuted(this)) {
return '!' + this.name;
}
@@ -577,10 +579,10 @@ User = (function () {
User.prototype.can = function (permission, target, room) {
if (this.hasSysopAccess()) return true;
- var group = this.group;
- var targetGroup = '';
+ let group = this.group;
+ let targetGroup = '';
if (target) targetGroup = target.group;
- var groupData = Config.groups[group];
+ let groupData = Config.groups[group];
if (groupData && groupData['root']) {
return true;
@@ -605,7 +607,7 @@ User = (function () {
if (typeof target === 'string') targetGroup = target;
if (groupData && groupData[permission]) {
- var jurisdiction = groupData[permission];
+ let jurisdiction = groupData[permission];
if (!target) {
return !!jurisdiction;
}
@@ -661,7 +663,7 @@ User = (function () {
if (this.hasSysopAccess()) return true;
if (!this.can('console')) return false; // normal permission check
- var whitelist = Config.consoleips || ['127.0.0.1'];
+ let whitelist = Config.consoleips || ['127.0.0.1'];
if (whitelist.indexOf(connection.ip) >= 0) {
return true; // on the IP whitelist
}
@@ -678,11 +680,11 @@ User = (function () {
return this.can('promote', {group:sourceGroup}) && this.can('promote', {group:targetGroup});
};
User.prototype.resetName = function () {
- var name = 'Guest ' + this.guestNum;
- var userid = toId(name);
+ let name = 'Guest ' + this.guestNum;
+ let userid = toId(name);
if (this.userid === userid) return;
- var i = 0;
+ let i = 0;
while (users[userid] && users[userid] !== this) {
this.guestNum++;
name = 'Guest ' + this.guestNum;
@@ -699,7 +701,7 @@ User = (function () {
prevUsers[this.userid] = userid;
this.name = name;
- var oldid = this.userid;
+ let oldid = this.userid;
delete users[oldid];
this.userid = userid;
users[this.userid] = this;
@@ -708,13 +710,13 @@ User = (function () {
this.isStaff = false;
this.isSysop = false;
- for (var i = 0; i < this.connections.length; i++) {
+ for (let i = 0; i < this.connections.length; i++) {
// console.log('' + name + ' renaming: connection ' + i + ' of ' + this.connections.length);
- var initdata = '|updateuser|' + this.name + '|' + (false ? '1' : '0') + '|' + this.avatar;
+ let initdata = '|updateuser|' + this.name + '|' + (false ? '1' : '0') + '|' + this.avatar;
this.connections[i].send(initdata);
}
this.named = false;
- for (var i in this.roomCount) {
+ for (let i in this.roomCount) {
Rooms.get(i, 'lobby').onRename(this, oldid, false);
}
return true;
@@ -723,7 +725,7 @@ User = (function () {
if (roomid) {
return Rooms.get(roomid, 'lobby').onUpdateIdentity(this);
}
- for (var i in this.roomCount) {
+ for (let i in this.roomCount) {
Rooms.get(i, 'lobby').onUpdateIdentity(this);
}
};
@@ -744,15 +746,15 @@ User = (function () {
* @param connection The connection asking for the rename
*/
User.prototype.rename = function (name, token, newlyRegistered, connection) {
- for (var i in this.roomCount) {
- var room = Rooms.get(i);
+ for (let i in this.roomCount) {
+ let room = Rooms.get(i);
if (room && room.rated && (this.userid === room.rated.p1 || this.userid === room.rated.p2)) {
this.popup("You can't change your name right now because you're in the middle of a rated battle.");
return false;
}
}
- var challenge = '';
+ let challenge = '';
if (connection) {
challenge = connection.challenge;
}
@@ -771,7 +773,7 @@ User = (function () {
}
name = this.filterName(name);
- var userid = toId(name);
+ let userid = toId(name);
if (this.registered) newlyRegistered = false;
if (!userid) {
@@ -788,11 +790,11 @@ User = (function () {
}
if (token && token.charAt(0) !== ';') {
- var tokenSemicolonPos = token.indexOf(';');
- var tokenData = token.substr(0, tokenSemicolonPos);
- var tokenSig = token.substr(tokenSemicolonPos + 1);
+ let tokenSemicolonPos = token.indexOf(';');
+ let tokenData = token.substr(0, tokenSemicolonPos);
+ let tokenSig = token.substr(tokenSemicolonPos + 1);
- var self = this;
+ let self = this;
Verifier.verify(tokenData, tokenSig, function (success, tokenData) {
if (!success) {
console.log('verify failed: ' + token);
@@ -808,9 +810,9 @@ User = (function () {
return false;
};
User.prototype.validateRename = function (name, tokenData, newlyRegistered, challenge) {
- var userid = toId(name);
+ let userid = toId(name);
- var tokenDataSplit = tokenData.split(',');
+ let tokenDataSplit = tokenData.split(',');
if (tokenDataSplit.length < 5) {
console.log('outdated assertion format: ' + tokenData);
@@ -833,7 +835,7 @@ User = (function () {
return;
}
- var expiry = Config.tokenexpiry || 25 * 60 * 60;
+ let expiry = Config.tokenexpiry || 25 * 60 * 60;
if (Math.abs(parseInt(tokenDataSplit[3], 10) - Date.now() / 1000) > expiry) {
console.log('stale assertion: ' + tokenData);
this.send('|nametaken|' + name + "|Your assertion is stale. This usually means that the clock on the server computer is incorrect. If this is your server, please set the clock to the correct time.");
@@ -841,7 +843,7 @@ User = (function () {
}
if (Config.tokenhosts) {
- var host = tokenDataSplit[4];
+ let host = tokenDataSplit[4];
if (Config.tokenhosts.length === 0) {
Config.tokenhosts.push(host);
console.log('Added ' + host + ' to valid tokenhosts');
@@ -874,7 +876,7 @@ User = (function () {
}
}
- var registered = false;
+ let registered = false;
// user types:
// 1: unregistered user
// 2: registered user
@@ -899,7 +901,7 @@ User = (function () {
}
if (users[userid] && users[userid] !== this) {
// This user already exists; let's merge
- var user = users[userid];
+ let user = users[userid];
if (this === user) {
// !!!
return false;
@@ -913,7 +915,7 @@ User = (function () {
delete prevUsers[userid];
prevUsers[this.userid] = userid;
}
- for (var i in this.prevNames) {
+ for (let i in this.prevNames) {
if (!user.prevNames[i]) {
user.prevNames[i] = this.prevNames[i];
}
@@ -935,7 +937,7 @@ User = (function () {
};
User.prototype.forceRename = function (name, registered) {
// skip the login server
- var userid = toId(name);
+ let userid = toId(name);
if (users[userid] && users[userid] !== this) {
return false;
@@ -944,7 +946,7 @@ User = (function () {
if (this.named) this.prevNames[this.userid] = this.name;
this.name = name;
- var oldid = this.userid;
+ let oldid = this.userid;
if (userid !== this.userid) {
// doing it this way mathematically ensures no cycles
delete prevUsers[userid];
@@ -964,20 +966,20 @@ User = (function () {
}
if (registered && userid in bannedUsers) {
- var bannedUnder = '';
+ let bannedUnder = '';
if (bannedUsers[userid] !== userid) bannedUnder = ' because of rule-breaking by your alt account ' + bannedUsers[userid];
this.send("|popup|Your username (" + name + ") is banned" + bannedUnder + "'. Your ban will expire in a few days." + (Config.appealurl ? " Or you can appeal at:\n" + Config.appealurl : ""));
this.ban(true, userid);
return;
}
if (registered && userid in lockedUsers) {
- var bannedUnder = '';
+ let bannedUnder = '';
if (lockedUsers[userid] !== userid) bannedUnder = ' because of rule-breaking by your alt account ' + lockedUsers[userid];
this.send("|popup|Your username (" + name + ") is locked" + bannedUnder + "'. Your lock will expire in a few days." + (Config.appealurl ? " Or you can appeal at:\n" + Config.appealurl : ""));
this.lock(true, userid);
}
if (this.group === Config.groupsranking[0]) {
- var range = this.locked || Users.shortenHost(this.latestHost);
+ let range = this.locked || Users.shortenHost(this.latestHost);
if (lockedRanges[range]) {
this.send("|popup|You are in a range that has been temporarily locked from talking in chats and PMing regular users.");
rangelockedUsers[range][this.userid] = 1;
@@ -987,20 +989,20 @@ User = (function () {
this.locked = false;
}
- for (var i = 0; i < this.connections.length; i++) {
+ for (let i = 0; i < this.connections.length; i++) {
//console.log('' + name + ' renaming: socket ' + i + ' of ' + this.connections.length);
- var initdata = '|updateuser|' + this.name + '|' + (true ? '1' : '0') + '|' + this.avatar;
+ let initdata = '|updateuser|' + this.name + '|' + (true ? '1' : '0') + '|' + this.avatar;
this.connections[i].send(initdata);
}
- var joining = !this.named;
+ let joining = !this.named;
this.named = (this.userid.substr(0, 5) !== 'guest');
- for (var i in this.roomCount) {
+ for (let i in this.roomCount) {
Rooms.get(i, 'lobby').onRename(this, oldid, joining);
}
return true;
};
User.prototype.merge = function (oldUser) {
- for (var i in oldUser.roomCount) {
+ for (let i in oldUser.roomCount) {
Rooms.get(i, 'lobby').onLeave(oldUser);
}
@@ -1009,7 +1011,7 @@ User = (function () {
if (oldUser.locked) this.locked = oldUser.locked;
if (oldUser.autoconfirmed) this.autoconfirmed = oldUser.autoconfirmed;
- for (var i = 0; i < oldUser.connections.length; i++) {
+ for (let i = 0; i < oldUser.connections.length; i++) {
this.mergeConnection(oldUser.connections[i]);
}
oldUser.roomCount = {};
@@ -1020,7 +1022,7 @@ User = (function () {
this.s3 = oldUser.s3;
// merge IPs
- for (var ip in oldUser.ips) {
+ for (let ip in oldUser.ips) {
if (this.ips[ip]) {
this.ips[ip] += oldUser.ips[ip];
} else {
@@ -1043,11 +1045,11 @@ User = (function () {
this.connected = true;
this.connections.push(connection);
//console.log('' + this.name + ' merging: connection ' + connection.socket.id);
- var initdata = '|updateuser|' + this.name + '|' + (true ? '1' : '0') + '|' + this.avatar;
+ let initdata = '|updateuser|' + this.name + '|' + (true ? '1' : '0') + '|' + this.avatar;
connection.send(initdata);
connection.user = this;
- for (var i in connection.rooms) {
- var room = connection.rooms[i];
+ for (let i in connection.rooms) {
+ let room = connection.rooms[i];
if (!this.roomCount[i]) {
if (room.bannedUsers && (this.userid in room.bannedUsers || this.autoconfirmed in room.bannedUsers)) {
room.bannedIps[connection.ip] = room.bannedUsers[this.userid];
@@ -1068,12 +1070,12 @@ User = (function () {
}
};
User.prototype.debugData = function () {
- var str = '' + this.group + this.name + ' (' + this.userid + ')';
- for (var i = 0; i < this.connections.length; i++) {
- var connection = this.connections[i];
+ let str = '' + this.group + this.name + ' (' + this.userid + ')';
+ for (let i = 0; i < this.connections.length; i++) {
+ let connection = this.connections[i];
str += ' socket' + i + '[';
- var first = true;
- for (var j in connection.rooms) {
+ let first = true;
+ for (let j in connection.rooms) {
if (first) {
first = false;
} else {
@@ -1107,8 +1109,8 @@ User = (function () {
this.autoconfirmed = this.userid;
} else {
this.group = Config.groupsranking[0];
- for (var i = 0; i < Rooms.global.chatRooms.length; i++) {
- var room = Rooms.global.chatRooms[i];
+ for (let i = 0; i < Rooms.global.chatRooms.length; i++) {
+ let room = Rooms.global.chatRooms[i];
if (!room.isPrivate && room.auth && this.userid in room.auth && room.auth[this.userid] !== '+') {
this.confirmed = this.userid;
this.autoconfirmed = this.userid;
@@ -1123,7 +1125,7 @@ User = (function () {
this.isStaff = (this.group in {'%':1, '@':1, '&':1, '~':1});
if (!this.isStaff) {
- var staffRoom = Rooms.get('staff');
+ let staffRoom = Rooms.get('staff');
this.isStaff = (staffRoom && staffRoom.auth && staffRoom.auth[this.userid]);
}
if (this.confirmed) {
@@ -1146,7 +1148,7 @@ User = (function () {
this.group = group.charAt(0);
this.isStaff = (this.group in {'%':1, '@':1, '&':1, '~':1});
if (!this.isStaff) {
- var staffRoom = Rooms.get('staff');
+ let staffRoom = Rooms.get('staff');
this.isStaff = (staffRoom && staffRoom.auth && staffRoom.auth[this.userid]);
}
Rooms.global.checkAutojoin(this);
@@ -1165,15 +1167,15 @@ User = (function () {
*/
User.prototype.deconfirm = function () {
if (!this.confirmed) return;
- var userid = this.confirmed;
- var removed = [];
+ let userid = this.confirmed;
+ let removed = [];
if (usergroups[userid]) {
removed.push(usergroups[userid].charAt(0));
delete usergroups[userid];
exportUsergroups();
}
- for (var i = 0; i < Rooms.global.chatRooms.length; i++) {
- var room = Rooms.global.chatRooms[i];
+ for (let i = 0; i < Rooms.global.chatRooms.length; i++) {
+ let room = Rooms.global.chatRooms[i];
if (!room.isPrivate && room.auth && userid in room.auth && room.auth[userid] !== '+') {
removed.push(room.auth[userid] + room.id);
room.auth[userid] = '+';
@@ -1194,13 +1196,13 @@ User = (function () {
}
};
User.prototype.onDisconnect = function (connection) {
- for (var i = 0; i < this.connections.length; i++) {
+ for (let i = 0; i < this.connections.length; i++) {
if (this.connections[i] === connection) {
// console.log('DISCONNECT: ' + this.userid);
if (this.connections.length <= 1) {
this.markInactive();
}
- for (var j in connection.rooms) {
+ for (let j in connection.rooms) {
this.leaveRoom(connection.rooms[j], connection, true);
}
--this.ips[connection.ip];
@@ -1210,7 +1212,7 @@ User = (function () {
}
if (!this.connections.length) {
// cleanup
- for (var i in this.roomCount) {
+ for (let i in this.roomCount) {
if (this.roomCount[i] > 0) {
// should never happen.
Monitor.debug('!! room miscount: ' + i + ' not left');
@@ -1229,12 +1231,12 @@ User = (function () {
User.prototype.disconnectAll = function () {
// Disconnects a user from the server
this.clearChatQueue();
- var connection = null;
+ let connection = null;
this.markInactive();
- for (var i = this.connections.length - 1; i >= 0; i--) {
+ for (let i = this.connections.length - 1; i >= 0; i--) {
// console.log('DESTROY: ' + this.userid);
connection = this.connections[i];
- for (var j in connection.rooms) {
+ for (let j in connection.rooms) {
this.leaveRoom(connection.rooms[j], connection, true);
}
connection.destroy();
@@ -1243,7 +1245,7 @@ User = (function () {
// should never happen
throw new Error("Failed to drop all connections for " + this.userid);
}
- for (var i in this.roomCount) {
+ for (let i in this.roomCount) {
if (this.roomCount[i] > 0) {
// should never happen.
throw new Error("Room miscount: " + i + " not left for " + this.userid);
@@ -1252,12 +1254,12 @@ User = (function () {
this.roomCount = {};
};
User.prototype.getAlts = function (getAll) {
- var alts = [];
- for (var i in users) {
+ let alts = [];
+ for (let i in users) {
if (users[i] === this) continue;
if (!users[i].named && !users[i].connected) continue;
if (!getAll && users[i].confirmed) continue;
- for (var myIp in this.ips) {
+ for (let myIp in this.ips) {
if (myIp in users[i].ips) {
alts.push(users[i].name);
break;
@@ -1270,9 +1272,9 @@ User = (function () {
// recurse only once; the root for-loop already bans everything with your IP
if (!userid) userid = this.userid;
if (!noRecurse) {
- for (var i in users) {
+ for (let i in users) {
if (users[i] === this || users[i].confirmed) continue;
- for (var myIp in this.ips) {
+ for (let myIp in this.ips) {
if (myIp in users[i].ips) {
users[i].ban(true, userid);
break;
@@ -1282,7 +1284,7 @@ User = (function () {
lockedUsers[userid] = userid;
}
- for (var ip in this.ips) {
+ for (let ip in this.ips) {
bannedIps[ip] = userid;
}
if (this.autoconfirmed) bannedUsers[this.autoconfirmed] = userid;
@@ -1298,9 +1300,9 @@ User = (function () {
// recurse only once; the root for-loop already locks everything with your IP
if (!userid) userid = this.userid;
if (!noRecurse) {
- for (var i in users) {
+ for (let i in users) {
if (users[i] === this || users[i].confirmed) continue;
- for (var myIp in this.ips) {
+ for (let myIp in this.ips) {
if (myIp in users[i].ips) {
users[i].lock(true, userid);
break;
@@ -1310,7 +1312,7 @@ User = (function () {
lockedUsers[userid] = userid;
}
- for (var ip in this.ips) {
+ for (let ip in this.ips) {
lockedIps[ip] = userid;
}
if (this.autoconfirmed) lockedUsers[this.autoconfirmed] = userid;
@@ -1320,7 +1322,7 @@ User = (function () {
this.updateIdentity();
};
User.prototype.tryJoinRoom = function (room, connection) {
- var roomid = (room && room.id ? room.id : room);
+ let roomid = (room && room.id ? room.id : room);
room = Rooms.search(room);
if (!room) {
if (!this.named) {
@@ -1330,17 +1332,17 @@ User = (function () {
return false;
}
}
- var makeRoom = this.can('makeroom');
+ let makeRoom = this.can('makeroom');
if (room.tour && !makeRoom) {
- var tour = room.tour.tour;
- var errorMessage = tour.onBattleJoin(room, this);
+ let tour = room.tour.tour;
+ let errorMessage = tour.onBattleJoin(room, this);
if (errorMessage) {
connection.sendTo(roomid, "|noinit|joinfailed|" + errorMessage);
return false;
}
}
if (room.modjoin) {
- var userGroup = this.group;
+ let userGroup = this.group;
if (room.auth && !makeRoom) {
if (room.isPrivate === true) {
userGroup = ' ';
@@ -1366,7 +1368,7 @@ User = (function () {
connection.send(">" + roomid + "\n|deinit");
}
- var joinResult = this.joinRoom(room, connection);
+ let joinResult = this.joinRoom(room, connection);
if (!joinResult) {
if (joinResult === null) {
connection.sendTo(roomid, "|noinit|joinfailed|You are banned from the room '" + roomid + "'.");
@@ -1388,7 +1390,7 @@ User = (function () {
}
}
if (!connection) {
- for (var i = 0; i < this.connections.length; i++) {
+ for (let i = 0; i < this.connections.length; i++) {
// only join full clients, not pop-out single-room
// clients
if (this.connections[i].rooms['global']) {
@@ -1415,7 +1417,7 @@ User = (function () {
// you can't leave the global room except while disconnecting
return false;
}
- for (var i = 0; i < this.connections.length; i++) {
+ for (let i = 0; i < this.connections.length; i++) {
if (this.connections[i] === connection || !connection) {
if (this.connections[i].rooms[room.id]) {
if (this.roomCount[room.id]) {
@@ -1457,7 +1459,7 @@ User = (function () {
if (!type) type = 'challenge';
if (Rooms.global.lockdown && Rooms.global.lockdown !== 'pre') {
- var message = "The server is restarting. Battles will be available again in a few minutes.";
+ let message = "The server is restarting. Battles will be available again in a few minutes.";
if (Rooms.global.lockdown === 'ddos') {
message = "The server is under attack. Battles cannot be started at this time.";
}
@@ -1471,7 +1473,7 @@ User = (function () {
return;
}
- var format = Tools.getFormat(formatid);
+ let format = Tools.getFormat(formatid);
if (!format['' + type + 'Show']) {
connection.popup("That format is not available.");
setImmediate(callback.bind(null, false));
@@ -1499,7 +1501,7 @@ User = (function () {
}
};
User.prototype.updateChallenges = function () {
- var challengeTo = this.challengeTo;
+ let challengeTo = this.challengeTo;
if (challengeTo) {
challengeTo = {
to: challengeTo.to,
@@ -1523,8 +1525,8 @@ User = (function () {
// 10 seconds ago
return false;
}
- var time = new Date().getTime();
- var challenge = {
+ let time = new Date().getTime();
+ let challenge = {
time: time,
from: this.userid,
to: user.userid,
@@ -1540,14 +1542,14 @@ User = (function () {
};
User.prototype.cancelChallengeTo = function () {
if (!this.challengeTo) return true;
- var user = getUser(this.challengeTo.to);
+ let user = getUser(this.challengeTo.to);
if (user) delete user.challengesFrom[this.userid];
this.challengeTo = null;
this.updateChallenges();
if (user) user.updateChallenges();
};
User.prototype.rejectChallengeFrom = function (user) {
- var userid = toId(user);
+ let userid = toId(user);
user = getUser(user);
if (this.challengesFrom[userid]) {
delete this.challengesFrom[userid];
@@ -1562,7 +1564,7 @@ User = (function () {
this.updateChallenges();
};
User.prototype.acceptChallengeFrom = function (user) {
- var userid = toId(user);
+ let userid = toId(user);
user = getUser(user);
if (!user || !user.challengeTo || user.challengeTo.to !== this.userid || !this.connected || !user.connected) {
if (this.challengesFrom[userid]) {
@@ -1588,7 +1590,7 @@ User = (function () {
* Returns false if the rest of the user's messages should be discarded.
*/
User.prototype.chat = function (message, room, connection) {
- var now = new Date().getTime();
+ let now = new Date().getTime();
if (message.substr(0, 16) === '/cmd userdetails') {
// certain commands are exempt from the queue
@@ -1629,7 +1631,7 @@ User = (function () {
};
User.prototype.processChatQueue = function () {
if (!this.chatQueue) return; // this should never happen
- var toChat = this.chatQueue.shift();
+ let toChat = this.chatQueue.shift();
Monitor.activeIp = toChat[2].ip;
toChat[1].chat(this, toChat[0], toChat[2]);
@@ -1653,9 +1655,9 @@ User = (function () {
};
// "static" function
User.pruneInactive = function (threshold) {
- var now = Date.now();
- for (var i in users) {
- var user = users[i];
+ let now = Date.now();
+ for (let i in users) {
+ let user = users[i];
if (user.connected) continue;
if ((now - user.lastConnected) > threshold) {
users[i].destroy();
diff --git a/verifier.js b/verifier.js
index 927feccecd..06e3805c38 100644
--- a/verifier.js
+++ b/verifier.js
@@ -12,18 +12,20 @@
* @license MIT license
*/
+'use strict';
+
// Because I don't want two files, we're going to fork ourselves.
if (!process.send) {
// This is the parent
- var guid = 1;
- var callbacks = {};
- var callbackData = {};
+ let guid = 1;
+ let callbacks = {};
+ let callbackData = {};
- var child = require('child_process').fork('verifier.js', {cwd: __dirname});
+ let child = require('child_process').fork('verifier.js', {cwd: __dirname});
exports.verify = function (data, signature, callback) {
- var localGuid = guid++;
+ let localGuid = guid++;
callbacks[localGuid] = callback;
callbackData[localGuid] = data;
child.send({data: data, sig: signature, guid: localGuid});
@@ -39,15 +41,15 @@ if (!process.send) {
// This is the child
global.Config = require('./config/config.js');
- var crypto = require('crypto');
+ let crypto = require('crypto');
- var keyalgo = Config.loginserverkeyalgo;
- var pkey = Config.loginserverpublickey;
+ let keyalgo = Config.loginserverkeyalgo;
+ let pkey = Config.loginserverpublickey;
process.on('message', function (message) {
- var verifier = crypto.createVerify(keyalgo);
+ let verifier = crypto.createVerify(keyalgo);
verifier.update(message.data);
- var success = false;
+ let success = false;
try {
success = verifier.verify(pkey, message.sig, 'hex');
} catch (e) {}