Spaces around operators and === instead of ==

This commit is contained in:
小太 2014-04-21 21:17:08 +10:00
parent 9ac8641725
commit 6fb3bc332a
51 changed files with 1674 additions and 1674 deletions

62
app.js
View File

@ -134,18 +134,18 @@ global.ResourceMonitor = {
*/
log: function(text) {
console.log(text);
if (Rooms.rooms.staff) Rooms.rooms.staff.add('||'+text);
if (Rooms.rooms.staff) Rooms.rooms.staff.add('||' + text);
},
countConnection: function(ip, name) {
var now = Date.now();
var duration = now - this.connectionTimes[ip];
name = (name ? ': '+name : '');
if (ip in this.connections && duration < 30*60*1000) {
name = (name ? ': ' + name : '');
if (ip in this.connections && duration < 30 * 60 * 1000) {
this.connections[ip]++;
if (duration < 5*60*1000 && this.connections[ip] % 20 === 0) {
this.log('[ResourceMonitor] IP '+ip+' has connected '+this.connections[ip]+' times in the last '+duration.duration()+name);
} else if (this.connections[ip] % 60 == 0) {
this.log('[ResourceMonitor] IP '+ip+' has connected '+this.connections[ip]+' times in the last '+duration.duration()+name);
if (duration < 5 * 60 * 1000 && this.connections[ip] % 20 === 0) {
this.log('[ResourceMonitor] IP ' + ip + ' has connected ' + this.connections[ip] + ' times in the last ' + duration.duration() + name);
} else if (this.connections[ip] % 60 === 0) {
this.log('[ResourceMonitor] IP ' + ip + ' has connected ' + this.connections[ip] + ' times in the last ' + duration.duration() + name);
}
} else {
this.connections[ip] = 1;
@ -158,13 +158,13 @@ global.ResourceMonitor = {
countBattle: function(ip, name) {
var now = Date.now();
var duration = now - this.battleTimes[ip];
name = (name ? ': '+name : '');
if (ip in this.battles && duration < 30*60*1000) {
name = (name ? ': ' + name : '');
if (ip in this.battles && duration < 30 * 60 * 1000) {
this.battles[ip]++;
if (duration < 5*60*1000 && this.battles[ip] % 15 == 0) {
this.log('[ResourceMonitor] IP '+ip+' has battled '+this.battles[ip]+' times in the last '+duration.duration()+name);
} else if (this.battles[ip] % 75 == 0) {
this.log('[ResourceMonitor] IP '+ip+' has battled '+this.battles[ip]+' times in the last '+duration.duration()+name);
if (duration < 5 * 60 * 1000 && this.battles[ip] % 15 === 0) {
this.log('[ResourceMonitor] IP ' + ip + ' has battled ' + this.battles[ip] + ' times in the last ' + duration.duration() + name);
} else if (this.battles[ip] % 75 === 0) {
this.log('[ResourceMonitor] IP ' + ip + ' has battled ' + this.battles[ip] + ' times in the last ' + duration.duration() + name);
}
} else {
this.battles[ip] = 1;
@ -177,7 +177,7 @@ global.ResourceMonitor = {
countPrepBattle: function(ip) {
var now = Date.now();
var duration = now - this.battlePrepTimes[ip];
if (ip in this.battlePreps && duration < 3*60*1000) {
if (ip in this.battlePreps && duration < 3 * 60 * 1000) {
this.battlePreps[ip]++;
if (this.battlePreps[ip] > 6) {
return true;
@ -202,7 +202,7 @@ global.ResourceMonitor = {
writeNetworkUse: function() {
var buf = '';
for (var i in this.networkUse) {
buf += ''+this.networkUse[i]+'\t'+this.networkCount[i]+'\t'+i+'\n';
buf += '' + this.networkUse[i] + '\t' + this.networkCount[i] + '\t' + i + '\n';
}
fs.writeFile('logs/networkuse.tsv', buf);
},
@ -237,28 +237,28 @@ global.ResourceMonitor = {
countCmd: function(ip, name) {
var now = Date.now();
var duration = now - this.cmdsTimes[ip];
name = (name ? ': '+name : '');
name = (name ? ': ' + name : '');
if (!this.cmdsTotal) this.cmdsTotal = {lastCleanup: 0, count: 0};
if (now - this.cmdsTotal.lastCleanup > 60*1000) {
if (now - this.cmdsTotal.lastCleanup > 60 * 1000) {
this.cmdsTotal.count = 0;
this.cmdsTotal.lastCleanup = now;
}
this.cmdsTotal.count++;
if (ip in this.cmds && duration < 60*1000) {
if (ip in this.cmds && duration < 60 * 1000) {
this.cmds[ip]++;
if (duration < 60*1000 && this.cmds[ip] % 5 === 0) {
if (duration < 60 * 1000 && this.cmds[ip] % 5 === 0) {
if (this.cmds[ip] >= 3) {
if (this.cmds[ip] % 30 === 0) this.log('CMD command from '+ip+' blocked for '+this.cmds[ip]+'th use in the last '+duration.duration()+name);
if (this.cmds[ip] % 30 === 0) this.log('CMD command from ' + ip + ' blocked for ' + this.cmds[ip] + 'th use in the last ' + duration.duration() + name);
return true;
}
this.log('[ResourceMonitor] IP '+ip+' has used CMD command '+this.cmds[ip]+' times in the last '+duration.duration()+name);
this.log('[ResourceMonitor] IP ' + ip + ' has used CMD command ' + this.cmds[ip] + ' times in the last ' + duration.duration() + name);
} else if (this.cmds[ip] % 15 === 0) {
this.log('CMD command from '+ip+' blocked for '+this.cmds[ip]+'th use in the last '+duration.duration()+name);
this.log('CMD command from ' + ip + ' blocked for ' + this.cmds[ip] + 'th use in the last ' + duration.duration() + name);
return true;
}
} else if (this.cmdsTotal.count > 8000) {
// One CMD check per user per minute on average (to-do: make this better)
this.log('CMD command for '+ip+' blocked because CMD has been used '+this.cmdsTotal.count+' times in the last minute.');
this.log('CMD command for ' + ip + ' blocked because CMD has been used ' + this.cmdsTotal.count + ' times in the last minute.');
return true;
} else {
this.cmds[ip] = 1;
@ -308,7 +308,7 @@ global.toId = function(text) {
global.toName = function(name) {
name = string(name);
name = name.replace(/[\|\s\[\]\,]+/g, ' ').trim();
if (name.length > 18) name = name.substr(0,18).trim();
if (name.length > 18) name = name.substr(0, 18).trim();
return name;
};
@ -317,7 +317,7 @@ global.toName = function(name) {
* If strEscape is true, escapes it for JavaScript, too
*/
global.sanitize = function(str, strEscape) {
str = (''+(str||''));
str = ('' + (str || ''));
str = str.escapeHTML();
if (strEscape) str = str.replace(/'/g, '\\\'');
return str;
@ -325,12 +325,12 @@ global.sanitize = function(str, strEscape) {
/**
* Safely ensures the passed variable is a string
* Simply doing ''+str can crash if str.toString crashes or isn't a function
* Simply doing '' + str can crash if str.toString crashes or isn't a function
* If we're expecting a string and being given anything that isn't a string
* or a number, it's safe to assume it's an error, and return ''
*/
global.string = function(str) {
if (typeof str === 'string' || typeof str === 'number') return ''+str;
if (typeof str === 'string' || typeof str === 'number') return '' + str;
return '';
};
@ -371,9 +371,9 @@ if (Config.crashguard) {
quietCrash = quietCrash || ((dateNow - lastCrash) <= 1000 * 60 * 5);
lastCrash = Date.now();
if (quietCrash) return;
var stack = (""+err.stack).split("\n").slice(0,2).join("<br />");
var stack = ("" + err.stack).split("\n").slice(0, 2).join("<br />");
if (Rooms.lobby) {
Rooms.lobby.addRaw('<div class="broadcast-red"><b>THE SERVER HAS CRASHED:</b> '+stack+'<br />Please restart the server.</div>');
Rooms.lobby.addRaw('<div class="broadcast-red"><b>THE SERVER HAS CRASHED:</b> ' + stack + '<br />Please restart the server.</div>');
Rooms.lobby.addRaw('<div class="broadcast-red">You will not be able to talk in the lobby or start new battles until the server restarts.</div>');
}
Config.modchat = 'crash';
@ -405,9 +405,9 @@ global.TeamValidator = require('./team-validator.js');
// load ipbans at our leisure
fs.readFile('./config/ipbans.txt', function (err, data) {
if (err) return;
data = (''+data).split("\n");
data = ('' + data).split("\n");
var rangebans = [];
for (var i=0; i<data.length; i++) {
for (var i = 0; i < data.length; i++) {
data[i] = data[i].split('#')[0].trim();
if (!data[i]) continue;
if (data[i].indexOf('/') >= 0) {

File diff suppressed because it is too large Load Diff

View File

@ -11,7 +11,7 @@
var ipToLong = exports.ipToLong = function(ip) {
var numIp = 0;
var parts = ip.split('.');
for (var i=0, len=parts.length; i<len; i++) {
for (var i = 0, len = parts.length; i < len; i++) {
numIp *= 256;
numIp += Number(parts[i]);
}
@ -23,7 +23,7 @@ var getPattern = exports.getPattern = function(cidr) {
var index = cidr.indexOf('/');
if (index > 0) {
var subnet = ipToLong(cidr.substr(0, index));
var bits = parseInt(cidr.substr(index+1), 10);
var bits = parseInt(cidr.substr(index + 1), 10);
var mask = -1 << (32 - bits);
return [subnet & mask, mask];
}

View File

@ -24,9 +24,9 @@ To reload chat commands:
const MAX_MESSAGE_LENGTH = 300;
const BROADCAST_COOLDOWN = 20*1000;
const BROADCAST_COOLDOWN = 20 * 1000;
const MESSAGE_COOLDOWN = 5*60*1000;
const MESSAGE_COOLDOWN = 5 * 60 * 1000;
const MAX_PARSE_RECURSION = 10;
@ -63,21 +63,21 @@ var parse = exports.parse = function(message, room, user, connection, levelsDeep
if (!message || !message.trim().length) return;
if (!levelsDeep) {
levelsDeep = 0;
// if (Config.emergencylog && (connection.ip === '62.195.195.62' || connection.ip === '86.141.154.222' || connection.ip === '189.134.175.221' || message.length > 2048 || message.length > 256 && message.substr(0,5) !== '/utm ' && message.substr(0,5) !== '/trn ')) {
// if (Config.emergencylog && (connection.ip === '62.195.195.62' || connection.ip === '86.141.154.222' || connection.ip === '189.134.175.221' || message.length > 2048 || message.length > 256 && message.substr(0, 5) !== '/utm ' && message.substr(0, 5) !== '/trn ')) {
if (Config.emergencylog && (user.userid === 'pindapinda' || connection.ip === '62.195.195.62' || connection.ip === '86.141.154.222' || connection.ip === '189.134.175.221')) {
Config.emergencylog.write('<' + user.name + '@' + connection.ip + '> ' + message + '\n');
}
}
if (message.substr(0,3) === '>> ') {
if (message.substr(0, 3) === '>> ') {
// multiline eval
message = '/eval ' + message.substr(3);
} else if (message.substr(0,4) === '>>> ') {
} else if (message.substr(0, 4) === '>>> ') {
// multiline eval
message = '/evalbattle ' + message.substr(4);
}
if (message.substr(0,2) !== '//' && message.substr(0,1) === '/') {
if (message.substr(0, 2) !== '//' && message.substr(0, 1) === '/') {
var spaceIndex = message.indexOf(' ');
if (spaceIndex > 0) {
cmd = message.substr(1, spaceIndex - 1);
@ -86,7 +86,7 @@ var parse = exports.parse = function(message, room, user, connection, levelsDeep
cmd = message.substr(1);
target = '';
}
} else if (message.substr(0,1) === '!') {
} else if (message.substr(0, 1) === '!') {
var spaceIndex = message.indexOf(' ');
if (spaceIndex > 0) {
cmd = message.substr(0, spaceIndex);
@ -217,17 +217,17 @@ var parse = exports.parse = function(message, room, user, connection, levelsDeep
for (var g in Config.groups) {
var groupid = Config.groups[g].id;
if (cmd === groupid) {
return parse('/promote ' + toId(target) + ',' + g, room, user, connection);
return parse('/promote ' + toId(target) + ', ' + g, room, user, connection);
} else if (cmd === 'de' + groupid || cmd === 'un' + groupid) {
return parse('/demote ' + toId(target), room, user, connection);
} else if (cmd === 'room' + groupid) {
return parse('/roompromote ' + toId(target) + ',' + g, room, user, connection);
return parse('/roompromote ' + toId(target) + ', ' + g, room, user, connection);
} else if (cmd === 'roomde' + groupid || cmd === 'deroom' + groupid || cmd === 'roomun' + groupid) {
return parse('/roomdemote ' + toId(target), room, user, connection);
}
}
if (message.substr(0,1) === '/' && cmd) {
if (message.substr(0, 1) === '/' && cmd) {
// To guard against command typos, we now emit an error message
return connection.sendTo(room.id, "The command '/" + cmd + "' was unrecognized. To send a message starting with '" + cmd + "', type '//" + cmd + "'.");
}
@ -244,7 +244,7 @@ function splitTarget(target, exactName) {
if (commaIndex < 0) {
targetUser = Users.get(target, exactName);
this.targetUser = targetUser;
this.targetUsername = (targetUser?targetUser.name:target);
this.targetUsername = targetUser ? targetUser.name : target;
return '';
}
var targetUser = Users.get(target.substr(0, commaIndex), exactName);
@ -252,7 +252,7 @@ function splitTarget(target, exactName) {
targetUser = null;
}
this.targetUser = targetUser;
this.targetUsername = (targetUser?targetUser.name:target.substr(0, commaIndex));
this.targetUsername = targetUser ? targetUser.name : target.substr(0, commaIndex);
return target.substr(commaIndex + 1).trim();
}
@ -318,7 +318,7 @@ function canTalk(user, room, connection, message) {
if (/\bnimp\.org\b/i.test(message)) return false;
// remove zalgo
message = message.replace(/[\u0300-\u036f\u0E31\u0E34-\u0E3A\u0E47-\u0E4E]{3,}/g,'');
message = message.replace(/[\u0300-\u036f\u0E31\u0E34-\u0E3A\u0E47-\u0E4E]{3,}/g, '');
if (room && room.id === 'lobby') {
var normalized = message.trim();

View File

@ -67,7 +67,7 @@ var commands = exports.commands = {
if (!user.lastPM) {
return this.sendReply("No one has PMed you yet.");
}
return this.parse('/msg ' + (user.lastPM||'') + ', ' + target);
return this.parse('/msg ' + (user.lastPM || '') + ', ' + target);
},
pm: 'msg',
@ -544,7 +544,7 @@ var commands = exports.commands = {
if (alts.length) this.addModCommand(targetUser.name + "'s alts were also muted: " + alts.join(", "));
this.add('|unlink|' + targetUser.userid);
targetUser.mute(room.id, 7*60*1000);
targetUser.mute(room.id, 7 * 60 * 1000);
},
hm: 'hourmute',
@ -561,7 +561,7 @@ var commands = exports.commands = {
}
if (!this.can('mute', targetUser, room)) return false;
if (((targetUser.mutedRooms[room.id] && (targetUser.muteDuration[room.id]||0) >= 50*60*1000) || targetUser.locked) && !target) {
if (((targetUser.mutedRooms[room.id] && (targetUser.muteDuration[room.id] || 0) >= 50 * 60 * 1000) || targetUser.locked) && !target) {
var problem = " but was already " + (!targetUser.connected ? "offline" : targetUser.locked ? "locked" : "muted");
return this.privateModCommand("(" + targetUser.name + " would be muted by " + user.name + problem + ".)");
}
@ -572,7 +572,7 @@ var commands = exports.commands = {
if (alts.length) this.addModCommand(targetUser.name + "'s alts were also muted: " + alts.join(", "));
this.add('|unlink|' + targetUser.userid);
targetUser.mute(room.id, 60*60*1000, true);
targetUser.mute(room.id, 60 * 60 * 1000, true);
},
um: 'unmute',
@ -829,7 +829,7 @@ var commands = exports.commands = {
room.modchat = target;
break;
}
if (currentModchat == room.modchat) {
if (currentModchat === room.modchat) {
return this.sendReply("Modchat is already set to " + currentModchat + ".");
}
if (!room.modchat) {
@ -950,7 +950,7 @@ var commands = exports.commands = {
roomNames = 'all rooms';
// Get a list of all the rooms
var fileList = fs.readdirSync('logs/modlog');
for (var i=0; i<fileList.length; ++i) {
for (var i = 0; i < fileList.length; ++i) {
filename += 'logs/modlog/' + fileList[i] + ' ';
}
} else {
@ -963,8 +963,8 @@ var commands = exports.commands = {
command = 'tail -' + lines + ' ' + filename;
var grepLimit = 100;
if (wordSearch) { // searching for a word instead
if (target.match(/^["'].+["']$/)) target = target.substring(1,target.length-1);
command = "awk '{print NR,$0}' " + filename + " | sort -nr | cut -d' ' -f2- | grep -m" + grepLimit + " -i '" + target.replace(/\\/g,'\\\\\\\\').replace(/["'`]/g,'\'\\$&\'').replace(/[\{\}\[\]\(\)\$\^\.\?\+\-\*]/g,'[$&]') + "'";
if (target.match(/^["'].+["']$/)) target = target.substring(1, target.length - 1);
command = "awk '{print NR,$0}' " + filename + " | sort -nr | cut -d' ' -f2- | grep -m" + grepLimit + " -i '" + target.replace(/\\/g, '\\\\\\\\').replace(/["'`]/g, '\'\\$&\'').replace(/[\{\}\[\]\(\)\$\^\.\?\+\-\*]/g, '[$&]') + "'";
}
// Execute the file search to see modlog
@ -1213,7 +1213,7 @@ var commands = exports.commands = {
if (err) return;
data = ('' + data).split('\n');
var rangebans = [];
for (var i=0; i<data.length; ++i) {
for (var i = 0; i < data.length; ++i) {
var line = data[i].split('#')[0].trim();
if (!line) continue;
if (line.indexOf('/') >= 0) {
@ -1389,7 +1389,7 @@ var commands = exports.commands = {
this.sendReply('||<< ' + eval(target));
} catch (e) {
this.sendReply('||<< error: ' + e.message);
var stack = '||' + ('' + e.stack).replace(/\n/g,'\n||');
var stack = '||' + ('' + e.stack).replace(/\n/g, '\n||');
connection.sendTo(room, stack);
}
},
@ -1430,7 +1430,7 @@ var commands = exports.commands = {
logidx = 3;
}
var data = room.getLog(logidx).join("\n");
var datahash = crypto.createHash('md5').update(data.replace(/[^(\x20-\x7F)]+/g,'')).digest('hex');
var datahash = crypto.createHash('md5').update(data.replace(/[^(\x20-\x7F)]+/g, '')).digest('hex');
LoginServer.request('prepreplay', {
id: room.id.substr(7),
@ -1462,7 +1462,7 @@ var commands = exports.commands = {
switch: function(target, room, user) {
if (!room.decision) return this.sendReply("You can only do this in battle rooms.");
room.decision(user, 'choose', 'switch ' + parseInt(target,10));
room.decision(user, 'choose', 'switch ' + parseInt(target, 10));
},
choose: function(target, room, user) {
@ -1543,10 +1543,10 @@ var commands = exports.commands = {
if (!this.can('autotimer')) return;
if (target === 'off' || target === 'false' || target === 'stop') {
Config.forcetimer = false;
this.addModCommand("Forcetimer is now OFF: The timer is now opt-in. (set by "+user.name+")");
this.addModCommand("Forcetimer is now OFF: The timer is now opt-in. (set by " + user.name + ")");
} else if (target === 'on' || target === 'true' || !target) {
Config.forcetimer = true;
this.addModCommand("Forcetimer is now ON: All battles will be timed. (set by "+user.name+")");
this.addModCommand("Forcetimer is now ON: All battles will be timed. (set by " + user.name + ")");
} else {
this.sendReply("'" + target + "' is not a recognized forcetimer setting.");
}
@ -1739,12 +1739,12 @@ var commands = exports.commands = {
var targetAuth = false;
var targetToken = '';
if (commaIndex >= 0) {
targetName = target.substr(0,commaIndex);
targetName = target.substr(0, commaIndex);
target = target.substr(commaIndex + 1);
commaIndex = target.indexOf(',');
targetAuth = target;
if (commaIndex >= 0) {
targetAuth = !!parseInt(target.substr(0,commaIndex),10);
targetAuth = !!parseInt(target.substr(0, commaIndex), 10);
targetToken = target.substr(commaIndex + 1);
}
}

View File

@ -206,7 +206,7 @@ var commands = exports.commands = {
for (var userid in Users.users) {
var user = Users.users[userid];
if (user.latestIp === target) {
this.sendReply((user.connected?" + ":"-") + " " + user.name);
this.sendReply((user.connected ? " + " : "-") + " " + user.name);
atLeastOne = true;
}
}
@ -264,8 +264,8 @@ var commands = exports.commands = {
if (!target) return this.parse('/help dexsearch');
var targets = target.split(',');
var searches = {};
var allTiers = {'uber':1,'ou':1,'uu':1,'lc':1,'cap':1,'bl':1};
var allColours = {'green':1,'red':1,'blue':1,'white':1,'brown':1,'yellow':1,'purple':1,'pink':1,'gray':1,'black':1};
var allTiers = {'uber':1, 'ou':1, 'uu':1, 'lc':1, 'cap':1, 'bl':1};
var allColours = {'green':1, 'red':1, 'blue':1, 'white':1, 'brown':1, 'yellow':1, 'purple':1, 'pink':1, 'gray':1, 'black':1};
var showAll = false;
var megaSearch = null;
var output = 10;
@ -273,7 +273,7 @@ var commands = exports.commands = {
for (var i in targets) {
var isNotSearch = false;
target = targets[i].trim().toLowerCase();
if (target.slice(0,1) === '!') {
if (target.slice(0, 1) === '!') {
isNotSearch = true;
target = target.slice(1);
}
@ -357,7 +357,7 @@ var commands = exports.commands = {
}
}
for (var search in {'moves':1,'types':1,'ability':1,'tier':1,'gen':1,'color':1}) {
for (var search in {'moves':1, 'types':1, 'ability':1, 'tier':1, 'gen':1, 'color':1}) {
if (!searches[search]) continue;
switch (search) {
case 'types':
@ -421,7 +421,7 @@ var commands = exports.commands = {
while (prevoTemp.prevo && prevoTemp.learnset && !(prevoTemp.learnset[move.id])) {
prevoTemp = Tools.getTemplate(prevoTemp.prevo);
}
var canLearn = (prevoTemp.learnset.sketch && !(move.id in {'chatter':1,'struggle':1,'magikarpsrevenge':1})) || prevoTemp.learnset[move.id];
var canLearn = (prevoTemp.learnset.sketch && !(move.id in {'chatter':1, 'struggle':1, 'magikarpsrevenge':1})) || prevoTemp.learnset[move.id];
if ((!canLearn && searches[search][i]) || (searches[search][i] === false && canLearn)) delete dex[mon];
}
}
@ -484,7 +484,7 @@ var commands = exports.commands = {
}
var buffer = template.name + (problem ? " <span class=\"message-learn-cannotlearn\">can't</span> learn " : " <span class=\"message-learn-canlearn\">can</span> learn ") + (targets.length > 2 ? "these moves" : move.name);
if (!problem) {
var sourceNames = {E:"egg",S:"event",D:"dream world"};
var sourceNames = {E:"egg", S:"event", D:"dream world"};
if (lsetData.sources || lsetData.sourcesBefore) buffer += " only when obtained from:<ul class=\"message-learn-list\">";
if (lsetData.sources) {
var sources = lsetData.sources.sort();
@ -492,16 +492,16 @@ var commands = exports.commands = {
var prevSourceType;
for (var i = 0, len = sources.length; i < len; ++i) {
var source = sources[i];
if (source.substr(0,2) === prevSourceType) {
if (source.substr(0, 2) === prevSourceType) {
if (prevSourceCount < 0) buffer += ": " + source.substr(2);
else if (all || prevSourceCount < 3) buffer += ", " + source.substr(2);
else if (prevSourceCount == 3) buffer += ", ...";
else if (prevSourceCount === 3) buffer += ", ...";
++prevSourceCount;
continue;
}
prevSourceType = source.substr(0,2);
prevSourceCount = source.substr(2)?0:-1;
buffer += "<li>gen " + source.substr(0,1) + " " + sourceNames[source.substr(1,1)];
prevSourceType = source.substr(0, 2);
prevSourceCount = source.substr(2) ? 0 : -1;
buffer += "<li>gen " + source.substr(0, 1) + " " + sourceNames[source.substr(1, 1)];
if (prevSourceType === '5E' && template.maleOnlyHidden) buffer += " (cannot have hidden ability)";
if (source.substr(2)) buffer += ": " + source.substr(2);
}
@ -538,8 +538,8 @@ var commands = exports.commands = {
var notImmune = Tools.getImmunity(type, pokemon);
if (notImmune) {
var typeMod = Tools.getEffectiveness(type, pokemon);
if (typeMod == 1) weaknesses.push(type);
if (typeMod == 2) weaknesses.push("<b>" + type + "</b>");
if (typeMod === 1) weaknesses.push(type);
if (typeMod === 2) weaknesses.push("<b>" + type + "</b>");
}
});
@ -791,7 +791,7 @@ var commands = exports.commands = {
"<br />" +
"Room owners (#) can also use:<br />" +
"- /roomdesc <em>description</em>: set the room description on the room join page<br />" +
"- /rules <em>rules link</em>: set the room rules link seen when using /rules<br />" +
"- /rules <em>rules link < /em>: set the room rules link seen when using /rules<br />" +
"- /roommod, /roomdriver <em>username</em>: appoint a room moderator/driver<br />" +
"- /roomdemod, /roomdedriver <em>username</em>: remove a room moderator/driver<br />" +
"- /modchat <em>[%/@/#]</em>: set modchat level<br />" +
@ -935,7 +935,7 @@ var commands = exports.commands = {
var atLeastOne = false;
var generation = (targets[1] || 'bw').trim().toLowerCase();
var genNumber = 5;
var doublesFormats = {'vgc2012':1,'vgc2013':1,'doubles':1};
var doublesFormats = {'vgc2012':1, 'vgc2013':1, 'doubles':1};
var doublesFormat = (!targets[2] && generation in doublesFormats)? generation : (targets[2] || '').trim().toLowerCase();
var doublesText = '';
if (generation === 'bw' || generation === 'bw2' || generation === '5' || generation === 'five') {
@ -957,10 +957,10 @@ var commands = exports.commands = {
}
if (doublesFormat !== '') {
// Smogon only has doubles formats analysis from gen 5 onwards.
if (!(generation in {'bw':1,'xy':1}) || !(doublesFormat in doublesFormats)) {
if (!(generation in {'bw':1, 'xy':1}) || !(doublesFormat in doublesFormats)) {
doublesFormat = '';
} else {
doublesText = {'vgc2012':"VGC 2012",'vgc2013':"VGC 2013",'doubles':"Doubles"}[doublesFormat];
doublesText = {'vgc2012':"VGC 2012", 'vgc2013':"VGC 2013", 'doubles':"Doubles"}[doublesFormat];
doublesFormat = '/' + doublesFormat;
}
}
@ -981,13 +981,13 @@ var commands = exports.commands = {
if (poke === 'farfetch\'d') poke = 'farfetchd';
if (poke === 'mr. mime') poke = 'mr_mime';
if (poke === 'mime jr.') poke = 'mime_jr';
if (poke === 'deoxys-attack' || poke === 'deoxys-defense' || poke === 'deoxys-speed' || poke === 'kyurem-black' || poke === 'kyurem-white') poke = poke.substr(0,8);
if (poke === 'deoxys-attack' || poke === 'deoxys-defense' || poke === 'deoxys-speed' || poke === 'kyurem-black' || poke === 'kyurem-white') poke = poke.substr(0, 8);
if (poke === 'wormadam-trash') poke = 'wormadam-s';
if (poke === 'wormadam-sandy') poke = 'wormadam-g';
if (poke === 'rotom-wash' || poke === 'rotom-frost' || poke === 'rotom-heat') poke = poke.substr(0,7);
if (poke === 'rotom-wash' || poke === 'rotom-frost' || poke === 'rotom-heat') poke = poke.substr(0, 7);
if (poke === 'rotom-mow') poke = 'rotom-c';
if (poke === 'rotom-fan') poke = 'rotom-s';
if (poke === 'giratina-origin' || poke === 'tornadus-therian' || poke === 'landorus-therian') poke = poke.substr(0,10);
if (poke === 'giratina-origin' || poke === 'tornadus-therian' || poke === 'landorus-therian') poke = poke.substr(0, 10);
if (poke === 'shaymin-sky') poke = 'shaymin-s';
if (poke === 'arceus') poke = 'arceus-normal';
if (poke === 'thundurus-therian') poke = 'thundurus-t';
@ -1044,7 +1044,7 @@ var commands = exports.commands = {
if (!this.canBroadcast()) return;
var d = target.indexOf("d");
if (d != -1) {
var num = parseInt(target.substring(0,d));
var num = parseInt(target.substring(0, d));
var faces;
if (target.length > d) faces = parseInt(target.substring(d + 1));
if (isNaN(num)) num = 1;
@ -1088,7 +1088,7 @@ var commands = exports.commands = {
if (!this.can('declare', null, room)) return false;
if (!this.canBroadcast()) return;
targets = target.split(', ');
targets = target.split(',');
if (targets.length != 3) {
return this.parse('/help showimage');
}

View File

@ -113,7 +113,7 @@ exports.logchat = false;
// loguserstats - how often (in milliseconds) to write user stats to the
// lobby log. This has no effect if `logchat` is disabled.
exports.loguserstats = 1000*60*10; // 10 minutes
exports.loguserstats = 1000 * 60 * 10; // 10 minutes
// validatorprocesses - the number of processes to use for validating teams
// simulatorprocesses - the number of processes to use for handling battles
@ -124,7 +124,7 @@ exports.simulatorprocesses = 1;
// inactiveuserthreshold - how long a user must be inactive before being pruned
// from the `users` array. The default is 1 hour.
exports.inactiveuserthreshold = 1000*60*60;
exports.inactiveuserthreshold = 1000 * 60 * 60;
// Set this to true if you are using Pokemon Showdown on Heroku.
exports.herokuhack = false;

View File

@ -64,9 +64,9 @@ exports.Formats = [
onBegin: function() {
this.debug('cutting down to 3');
this.p1.pokemon = this.p1.pokemon.slice(0,3);
this.p1.pokemon = this.p1.pokemon.slice(0, 3);
this.p1.pokemonLeft = this.p1.pokemon.length;
this.p2.pokemon = this.p2.pokemon.slice(0,3);
this.p2.pokemon = this.p2.pokemon.slice(0, 3);
this.p2.pokemonLeft = this.p2.pokemon.length;
},
maxForcedLevel: 50,
@ -82,9 +82,9 @@ exports.Formats = [
onBegin: function() {
this.debug('cutting down to 3');
this.p1.pokemon = this.p1.pokemon.slice(0,3);
this.p1.pokemon = this.p1.pokemon.slice(0, 3);
this.p1.pokemonLeft = this.p1.pokemon.length;
this.p2.pokemon = this.p2.pokemon.slice(0,3);
this.p2.pokemon = this.p2.pokemon.slice(0, 3);
this.p2.pokemonLeft = this.p2.pokemon.length;
},
maxForcedLevel: 50,
@ -211,9 +211,9 @@ exports.Formats = [
gameType: 'doubles',
onBegin: function() {
this.debug('cutting down to 4');
this.p1.pokemon = this.p1.pokemon.slice(0,4);
this.p1.pokemon = this.p1.pokemon.slice(0, 4);
this.p1.pokemonLeft = this.p1.pokemon.length;
this.p2.pokemon = this.p2.pokemon.slice(0,4);
this.p2.pokemon = this.p2.pokemon.slice(0, 4);
this.p2.pokemonLeft = this.p2.pokemon.length;
},
maxForcedLevel: 50,
@ -229,9 +229,9 @@ exports.Formats = [
gameType: 'doubles',
onBegin: function() {
this.debug('cutting down to 4');
this.p1.pokemon = this.p1.pokemon.slice(0,4);
this.p1.pokemon = this.p1.pokemon.slice(0, 4);
this.p1.pokemonLeft = this.p1.pokemon.length;
this.p2.pokemon = this.p2.pokemon.slice(0,4);
this.p2.pokemon = this.p2.pokemon.slice(0, 4);
this.p2.pokemonLeft = this.p2.pokemon.length;
},
maxForcedLevel: 50,
@ -276,7 +276,7 @@ exports.Formats = [
banlist: [
"Arceus", "Arceus-Bug", "Arceus-Dark", "Arceus-Dragon", "Arceus-Electric", "Arceus-Fairy", "Arceus-Fighting", "Arceus-Fire",
"Arceus-Flying", "Arceus-Ghost", "Arceus-Grass", "Arceus-Ground", "Arceus-Ice", "Arceus-Poison", "Arceus-Psychic", "Arceus-Rock", "Arceus-Steel",
"Arceus-Water", "Darkrai", "Deoxys", "Deoxys-Attack", "Dialga", "Giratina", "Giratina-Origin"," Groudon", "Ho-Oh", "Kyurem-White", "Lugia",
"Arceus-Water", "Darkrai", "Deoxys", "Deoxys-Attack", "Dialga", "Giratina", "Giratina-Origin", "Groudon", "Ho-Oh", "Kyurem-White", "Lugia",
"Mewtwo", "Mewtwo-Mega-X", "Mewtwo-Mega-Y", "Palkia", "Rayquaza", "Reshiram", "Xerneas", "Zekrom", "Regigigas", "Slaking", "Ampharosite", "Gyaradosite",
"Meloetta"
]
@ -393,7 +393,7 @@ exports.Formats = [
validateSet: function(set) {
var template = this.getTemplate(set.species || set.name);
if (template.types.indexOf('Flying') === -1 && set.ability !== 'Levitate') {
return [set.species+" is not a Flying type and does not have the ability Levitate."];
return [set.species + " is not a Flying type and does not have the ability Levitate."];
}
},
ruleset: ['Pokemon', 'Standard', 'Evasion Abilities Clause', 'Team Preview'],
@ -453,9 +453,9 @@ exports.Formats = [
section: 'Other Metagames',
onBegin: function() {
this.p1.pokemon = this.p1.pokemon.slice(0,1);
this.p1.pokemon = this.p1.pokemon.slice(0, 1);
this.p1.pokemonLeft = this.p1.pokemon.length;
this.p2.pokemon = this.p2.pokemon.slice(0,1);
this.p2.pokemon = this.p2.pokemon.slice(0, 1);
this.p2.pokemonLeft = this.p2.pokemon.length;
},
ruleset: ['Pokemon', 'Standard'],
@ -528,7 +528,7 @@ exports.Formats = [
var letters = {};
var letter = '';
for (var i = 0; i < team.length; i++) {
letter = Tools.getTemplate(team[i]).species.slice(0,1).toUpperCase();
letter = Tools.getTemplate(team[i]).species.slice(0, 1).toUpperCase();
if (letter in letters) return ['Your team cannot have more that one Pokémon starting with the letter "' + letter + '".'];
letters[letter] = 1;
}
@ -604,7 +604,7 @@ exports.Formats = [
mod: 'gen5',
ruleset: ['[Gen 5] RU'],
banlist: ['RU','BL3', 'Prankster + Assist']
banlist: ['RU', 'BL3', 'Prankster + Assist']
},
{
name: "[Gen 5] LC",
@ -626,9 +626,9 @@ exports.Formats = [
},
onBegin: function() {
this.debug('cutting down to 3');
this.p1.pokemon = this.p1.pokemon.slice(0,3);
this.p1.pokemon = this.p1.pokemon.slice(0, 3);
this.p1.pokemonLeft = this.p1.pokemon.length;
this.p2.pokemon = this.p2.pokemon.slice(0,3);
this.p2.pokemon = this.p2.pokemon.slice(0, 3);
this.p2.pokemonLeft = this.p2.pokemon.length;
},
ruleset: ['Pokemon', 'Standard GBU', 'Team Preview GBU'],
@ -683,9 +683,9 @@ exports.Formats = [
gameType: 'doubles',
onBegin: function() {
this.debug('cutting down to 4');
this.p1.pokemon = this.p1.pokemon.slice(0,4);
this.p1.pokemon = this.p1.pokemon.slice(0, 4);
this.p1.pokemonLeft = this.p1.pokemon.length;
this.p2.pokemon = this.p2.pokemon.slice(0,4);
this.p2.pokemon = this.p2.pokemon.slice(0, 4);
this.p2.pokemonLeft = this.p2.pokemon.length;
},
maxForcedLevel: 50,

View File

@ -11,12 +11,12 @@
module.exports = (function() {
var lastCrashLog = 0;
return function(err, description) {
console.log("\nCRASH: "+err.stack+"\n");
console.log("\nCRASH: " + err.stack + "\n");
require('fs').createWriteStream('logs/errors.txt', {'flags': 'a'}).on("open", function(fd) {
this.write("\n"+err.stack+"\n");
this.write("\n" + err.stack + "\n");
this.end();
}).on("error", function (err) {
console.log("\nSUBCRASH: "+err.stack+"\n");
console.log("\nSUBCRASH: " + err.stack + "\n");
});
var datenow = Date.now();
if (Config.crashguardemail && ((datenow - lastCrashLog) > 1000 * 60 * 5)) {

View File

@ -58,7 +58,7 @@ exports.BattleAbilities = {
name: "Aftermath",
onFaint: function(target, source, effect) {
if (effect && effect.effectType === 'Move' && effect.isContact && source) {
this.damage(source.maxhp/4, source, target);
this.damage(source.maxhp / 4, source, target);
}
},
rating: 3,
@ -122,7 +122,7 @@ exports.BattleAbilities = {
onCriticalHit: function(target) {
if (!target.volatiles['substitute']) {
target.setBoost({atk: 6});
this.add('-setboost',target,'atk',12,'[from] ability: Anger Point');
this.add('-setboost', target, 'atk', 12, '[from] ability: Anger Point');
}
},
id: "angerpoint",
@ -135,12 +135,12 @@ exports.BattleAbilities = {
shortDesc: "On switch-in, this Pokemon shudders if any foe has a super effective or OHKO move.",
onStart: function(pokemon) {
var targets = pokemon.side.foe.active;
for (var i=0; i<targets.length; i++) {
for (var i = 0; i < targets.length; i++) {
if (!targets[i] || targets[i].fainted) continue;
for (var j=0; j<targets[i].moveset.length; j++) {
for (var j = 0; j < targets[i].moveset.length; j++) {
var move = this.getMove(targets[i].moveset[j].move);
if (move.category !== 'Status' && (this.getImmunity(move.type, pokemon) && this.getEffectiveness(move.type, pokemon) > 0 || move.ohko)) {
this.add('-message', pokemon.name+' shuddered! (placeholder)');
this.add('-message', pokemon.name + ' shuddered! (placeholder)');
return;
}
}
@ -202,11 +202,11 @@ exports.BattleAbilities = {
onResidualSubOrder: 1,
onResidual: function(pokemon) {
if (!pokemon.hp) return;
for (var i=0; i<pokemon.side.foe.active.length; i++) {
for (var i = 0; i < pokemon.side.foe.active.length; i++) {
var target = pokemon.side.foe.active[i];
if (!target || !target.hp) continue;
if (target.status === 'slp') {
this.damage(target.maxhp/8, target);
this.damage(target.maxhp / 8, target);
}
}
},
@ -231,7 +231,7 @@ exports.BattleAbilities = {
if (source && target === source) return;
if (boost['def'] && boost['def'] < 0) {
boost['def'] = 0;
if (!effect.secondaries) this.add("-fail", target, "unboost", "Defense", "[from] ability: Big Pecks", "[of] "+target);
if (!effect.secondaries) this.add("-fail", target, "unboost", "Defense", "[from] ability: Big Pecks", "[of] " + target);
}
},
id: "bigpecks",
@ -244,14 +244,14 @@ exports.BattleAbilities = {
shortDesc: "When this Pokemon has 1/3 or less of its max HP, its Fire attacks do 1.5x damage.",
onModifyAtkPriority: 5,
onModifyAtk: function(atk, attacker, defender, move) {
if (move.type === 'Fire' && attacker.hp <= attacker.maxhp/3) {
if (move.type === 'Fire' && attacker.hp <= attacker.maxhp / 3) {
this.debug('Blaze boost');
return this.chainModify(1.5);
}
},
onModifySpAPriority: 5,
onModifySpA: function(atk, attacker, defender, move) {
if (move.type === 'Fire' && attacker.hp <= attacker.maxhp/3) {
if (move.type === 'Fire' && attacker.hp <= attacker.maxhp / 3) {
this.debug('Blaze boost');
return this.chainModify(1.5);
}
@ -280,7 +280,7 @@ exports.BattleAbilities = {
desc: "Restores HP when this Pokemon consumes a berry.",
shortDesc: "Restores HP when this Pokemon consumes a berry.",
onEatItem: function(item, pokemon) {
this.heal(pokemon.maxhp/4);
this.heal(pokemon.maxhp / 4);
},
id: "cheekpouch",
name: "Cheek Pouch",
@ -313,7 +313,7 @@ exports.BattleAbilities = {
showMsg = true;
}
}
if (showMsg && !effect.secondaries) this.add("-fail", target, "unboost", "[from] ability: Clear Body", "[of] "+target);
if (showMsg && !effect.secondaries) this.add("-fail", target, "unboost", "[from] ability: Clear Body", "[of] " + target);
},
id: "clearbody",
name: "Clear Body",
@ -474,7 +474,7 @@ exports.BattleAbilities = {
}
}
if (move.type === 'Dark') {
return this.chainModify(reverseAura? 0.75 : 4/3);
return this.chainModify(reverseAura? 0.75 : 4 / 3);
}
},
id: "darkaura",
@ -488,13 +488,13 @@ exports.BattleAbilities = {
shortDesc: "When this Pokemon has 1/2 or less of its max HP, its Attack and Sp. Atk are halved.",
onModifyAtkPriority: 5,
onModifyAtk: function(atk, pokemon) {
if (pokemon.hp < pokemon.maxhp/2) {
if (pokemon.hp < pokemon.maxhp / 2) {
return this.chainModify(0.5);
}
},
onModifySpAPriority: 5,
onModifySpA: function(atk, pokemon) {
if (pokemon.hp < pokemon.maxhp/2) {
if (pokemon.hp < pokemon.maxhp / 2) {
return this.chainModify(0.5);
}
},
@ -535,7 +535,7 @@ exports.BattleAbilities = {
var foeactive = pokemon.side.foe.active;
var totaldef = 0;
var totalspd = 0;
for (var i=0; i<foeactive.length; i++) {
for (var i = 0; i < foeactive.length; i++) {
if (!foeactive[i] || foeactive[i].fainted) continue;
totaldef += foeactive[i].getStat('def', false, true);
totalspd += foeactive[i].getStat('spd', false, true);
@ -578,7 +578,7 @@ exports.BattleAbilities = {
shortDesc: "This Pokemon is healed 1/4 by Water, 1/8 by Rain; is hurt 1.25x by Fire, 1/8 by Sun.",
onTryHit: function(target, source, move) {
if (target !== source && move.type === 'Water') {
if (!this.heal(target.maxhp/4)) {
if (!this.heal(target.maxhp / 4)) {
this.add('-immune', target, '[msg]');
}
return null;
@ -593,9 +593,9 @@ exports.BattleAbilities = {
},
onWeather: function(target, source, effect) {
if (effect.id === 'raindance') {
this.heal(target.maxhp/8);
this.heal(target.maxhp / 8);
} else if (effect.id === 'sunnyday') {
this.damage(target.maxhp/8);
this.damage(target.maxhp / 8);
}
},
id: "dryskin",
@ -650,7 +650,7 @@ exports.BattleAbilities = {
}
}
if (move.type === 'Fairy') {
return this.chainModify(reverseAura? 0.75 : 4/3);
return this.chainModify(reverseAura? 0.75 : 4 / 3);
}
},
id: "fairyaura",
@ -717,7 +717,7 @@ exports.BattleAbilities = {
effect: {
noCopy: true, // doesn't get copied by Baton Pass
onStart: function(target) {
this.add('-start',target,'ability: Flash Fire');
this.add('-start', target, 'ability: Flash Fire');
},
onModifyAtkPriority: 5,
onModifyAtk: function(atk, attacker, defender, move) {
@ -751,13 +751,13 @@ exports.BattleAbilities = {
if (this.effectData.forme !== 'Sunshine') {
this.effectData.forme = 'Sunshine';
this.add('-formechange', pokemon, 'Cherrim-Sunshine');
this.add('-message', pokemon.name+' transformed! (placeholder)');
this.add('-message', pokemon.name + ' transformed! (placeholder)');
}
} else {
if (this.effectData.forme) {
delete this.effectData.forme;
this.add('-formechange', pokemon, 'Cherrim');
this.add('-message', pokemon.name+' transformed! (placeholder)');
this.add('-message', pokemon.name + ' transformed! (placeholder)');
}
}
},
@ -792,7 +792,7 @@ exports.BattleAbilities = {
showMsg = true;
}
}
if (showMsg && !effect.secondaries) this.add("-fail", target, "unboost", "[from] ability: Flower Veil", "[of] "+target);
if (showMsg && !effect.secondaries) this.add("-fail", target, "unboost", "[from] ability: Flower Veil", "[of] " + target);
},
onAllySetStatus: function(status, target) {
if (target.hasType('Grass')) return false;
@ -826,7 +826,7 @@ exports.BattleAbilities = {
if (pokemon.isActive && forme) {
pokemon.formeChange(forme);
this.add('-formechange', pokemon, forme);
this.add('-message', pokemon.name+' transformed! (placeholder)');
this.add('-message', pokemon.name + ' transformed! (placeholder)');
}
},
id: "forecast",
@ -841,9 +841,9 @@ exports.BattleAbilities = {
var targets = pokemon.side.foe.active;
var warnMoves = [];
var warnBp = 1;
for (var i=0; i<targets.length; i++) {
for (var i = 0; i < targets.length; i++) {
if (targets[i].fainted) continue;
for (var j=0; j<targets[i].moveset.length; j++) {
for (var j = 0; j < targets[i].moveset.length; j++) {
var move = this.getMove(targets[i].moveset[j].move);
var bp = move.basePower;
if (move.ohko) bp = 160;
@ -852,7 +852,7 @@ exports.BattleAbilities = {
if (bp > warnBp) {
warnMoves = [[move, targets[i]]];
warnBp = bp;
} else if (bp == warnBp) {
} else if (bp === warnBp) {
warnMoves.push([move, targets[i]]);
}
}
@ -885,10 +885,10 @@ exports.BattleAbilities = {
shortDesc: "On switch-in, this Pokemon identifies the foe's held items.",
onStart: function(pokemon) {
var foeactive = pokemon.side.foe.active;
for (var i=0; i<foeactive.length; i++) {
for (var i = 0; i < foeactive.length; i++) {
if (!foeactive[i] || foeactive[i].fainted) continue;
if (foeactive[i].item) {
this.add('-item', foeactive[i], foeactive[i].getItem().name, '[from] ability: Frisk', '[of] '+pokemon, '[identify]');
this.add('-item', foeactive[i], foeactive[i].getItem().name, '[from] ability: Frisk', '[of] ' + pokemon, '[identify]');
}
}
},
@ -999,7 +999,7 @@ exports.BattleAbilities = {
if (allyActive.length === 1) {
return;
}
for (var i=0; i<allyActive.length; i++) {
for (var i = 0; i < allyActive.length; i++) {
if (allyActive[i] && this.isAdjacent(pokemon, allyActive[i]) && allyActive[i].status && this.random(10) < 3) {
allyActive[i].cureStatus();
}
@ -1099,7 +1099,7 @@ exports.BattleAbilities = {
if (source && target === source) return;
if (boost['atk'] && boost['atk'] < 0) {
boost['atk'] = 0;
if (!effect.secondaries) this.add("-fail", target, "unboost", "Attack", "[from] ability: Hyper Cutter", "[of] "+target);
if (!effect.secondaries) this.add("-fail", target, "unboost", "Attack", "[from] ability: Hyper Cutter", "[of] " + target);
}
},
id: "hypercutter",
@ -1112,7 +1112,7 @@ exports.BattleAbilities = {
shortDesc: "If Hail is active, this Pokemon heals 1/16 of its max HP each turn; immunity to Hail.",
onWeather: function(target, source, effect) {
if (effect.id === 'hail') {
this.heal(target.maxhp/16);
this.heal(target.maxhp / 16);
}
},
onImmunity: function(type, pokemon) {
@ -1136,7 +1136,7 @@ exports.BattleAbilities = {
shortDesc: "This Pokemon appears as the last Pokemon in the party until it takes direct damage.",
onBeforeSwitchIn: function(pokemon) {
pokemon.illusion = null;
for (var i=pokemon.side.pokemon.length-1; i>pokemon.position; i--) {
for (var i = pokemon.side.pokemon.length - 1; i > pokemon.position; i--) {
if (!pokemon.side.pokemon[i]) continue;
if (!pokemon.side.pokemon[i].fainted) break;
}
@ -1170,7 +1170,7 @@ exports.BattleAbilities = {
desc: "As soon as the user comes into battle, it Transforms into its opponent, copying the opponent's stats exactly, with the exception of HP. Imposter copies all stat changes on the target originating from moves and abilities such as Swords Dance and Intimidate, but not from items such as Choice Specs. Imposter will not Transform the user if the opponent is an Illusion or if the opponent is behind a Substitute.",
shortDesc: "On switch-in, this Pokemon copies the foe it's facing; stats, moves, types, Ability.",
onStart: function(pokemon) {
var target = pokemon.side.foe.active[pokemon.side.foe.active.length-1-pokemon.position];
var target = pokemon.side.foe.active[pokemon.side.foe.active.length - 1 - pokemon.position];
if (target) {
pokemon.transformInto(target, pokemon);
}
@ -1222,13 +1222,13 @@ exports.BattleAbilities = {
shortDesc: "On switch-in, this Pokemon lowers adjacent foes' Attack by 1.",
onStart: function(pokemon) {
var foeactive = pokemon.side.foe.active;
for (var i=0; i<foeactive.length; i++) {
for (var i = 0; i < foeactive.length; i++) {
if (!foeactive[i] || foeactive[i].fainted) continue;
if (foeactive[i].volatiles['substitute']) {
// does it give a message?
this.add('-activate',foeactive[i],'Substitute','ability: Intimidate','[of] '+pokemon);
this.add('-activate', foeactive[i], 'Substitute', 'ability: Intimidate', '[of] ' + pokemon);
} else {
this.add('-ability',pokemon,'Intimidate','[of] '+foeactive[i]);
this.add('-ability', pokemon, 'Intimidate', '[of] ' + foeactive[i]);
this.boost({atk: -1}, foeactive[i], pokemon);
}
}
@ -1244,7 +1244,7 @@ exports.BattleAbilities = {
onAfterDamageOrder: 1,
onAfterDamage: function(damage, target, source, move) {
if (source && source !== target && move && move.isContact) {
this.damage(source.maxhp/8, source, target);
this.damage(source.maxhp / 8, source, target);
}
},
id: "ironbarbs",
@ -1287,7 +1287,7 @@ exports.BattleAbilities = {
if (source && target === source) return;
if (boost['accuracy'] && boost['accuracy'] < 0) {
boost['accuracy'] = 0;
if (!effect.secondaries) this.add("-fail", target, "unboost", "accuracy", "[from] ability: Keen Eye", "[of] "+target);
if (!effect.secondaries) this.add("-fail", target, "unboost", "accuracy", "[from] ability: Keen Eye", "[of] " + target);
}
},
onModifyMove: function(move) {
@ -1394,7 +1394,7 @@ exports.BattleAbilities = {
shortDesc: "This Pokemon damages those draining HP from it for as much as they would heal.",
id: "liquidooze",
onSourceTryHeal: function(damage, target, source, effect) {
this.debug("Heal is occurring: "+target+" <- "+source+" :: "+effect.id);
this.debug("Heal is occurring: " + target + " <- " + source + " :: " + effect.id);
var canOoze = {drain: 1, leechseed: 1};
if (canOoze[effect.id]) {
this.damage(damage);
@ -1550,7 +1550,7 @@ exports.BattleAbilities = {
if (allyActive.length === 1) {
return;
}
for (var i=0; i<allyActive.length; i++) {
for (var i = 0; i < allyActive.length; i++) {
if (allyActive[i] && allyActive[i].position !== pokemon.position && !allyActive[i].fainted && allyActive[i].hasAbility(['minus', 'plus'])) {
return this.chainModify(1.5);
}
@ -1732,12 +1732,12 @@ exports.BattleAbilities = {
onUpdate: function(pokemon) {
if (pokemon.volatiles['attract']) {
pokemon.removeVolatile('attract');
this.add("-message", pokemon.name+" got over its infatuation. (placeholder)");
this.add("-message", pokemon.name + " got over its infatuation. (placeholder)");
}
if (pokemon.volatiles['taunt']) {
pokemon.removeVolatile('taunt');
// TODO: Research proper message.
this.add("-message", pokemon.name+" got over its taunt. (placeholder)");
this.add("-message", pokemon.name + " got over its taunt. (placeholder)");
}
},
onImmunity: function(type, pokemon) {
@ -1773,14 +1773,14 @@ exports.BattleAbilities = {
shortDesc: "When this Pokemon has 1/3 or less of its max HP, its Grass attacks do 1.5x damage.",
onModifyAtkPriority: 5,
onModifyAtk: function(atk, attacker, defender, move) {
if (move.type === 'Grass' && attacker.hp <= attacker.maxhp/3) {
if (move.type === 'Grass' && attacker.hp <= attacker.maxhp / 3) {
this.debug('Overgrow boost');
return this.chainModify(1.5);
}
},
onModifySpAPriority: 5,
onModifySpA: function(atk, attacker, defender, move) {
if (move.type === 'Grass' && attacker.hp <= attacker.maxhp/3) {
if (move.type === 'Grass' && attacker.hp <= attacker.maxhp / 3) {
this.debug('Overgrow boost');
return this.chainModify(1.5);
}
@ -1911,7 +1911,7 @@ exports.BattleAbilities = {
if (allyActive.length === 1) {
return;
}
for (var i=0; i<allyActive.length; i++) {
for (var i = 0; i < allyActive.length; i++) {
if (allyActive[i] && allyActive[i].position !== pokemon.position && !allyActive[i].fainted && allyActive[i].hasAbility(['minus', 'plus'])) {
return this.chainModify(1.5);
}
@ -1927,7 +1927,7 @@ exports.BattleAbilities = {
shortDesc: "This Pokemon is healed by 1/8 of its max HP each turn when poisoned; no HP loss.",
onDamage: function(damage, target, source, effect) {
if (effect.id === 'psn' || effect.id === 'tox') {
this.heal(target.maxhp/8);
this.heal(target.maxhp / 8);
return false;
}
},
@ -1991,7 +1991,7 @@ exports.BattleAbilities = {
},
onSourceDeductPP: function(pp, target, source) {
if (target.side === source.side) return;
return pp+1;
return pp + 1;
},
id: "pressure",
name: "Pressure",
@ -2045,7 +2045,7 @@ exports.BattleAbilities = {
shortDesc: "If the weather is Rain Dance, this Pokemon heals 1/16 of its max HP each turn.",
onWeather: function(target, source, effect) {
if (effect.id === 'raindance') {
this.heal(target.maxhp/16);
this.heal(target.maxhp / 16);
}
},
id: "raindish",
@ -2107,7 +2107,7 @@ exports.BattleAbilities = {
desc: "This Pokemon heals 1/3 of its max HP when it switches out.",
shortDesc: "This Pokemon heals 1/3 of its max HP when it switches out.",
onSwitchOut: function(pokemon) {
pokemon.heal(pokemon.maxhp/3);
pokemon.heal(pokemon.maxhp / 3);
},
id: "regenerator",
name: "Regenerator",
@ -2151,7 +2151,7 @@ exports.BattleAbilities = {
onAfterDamageOrder: 1,
onAfterDamage: function(damage, target, source, move) {
if (source && source !== target && move && move.isContact) {
this.damage(source.maxhp/8, source, target);
this.damage(source.maxhp / 8, source, target);
}
},
id: "roughskin",
@ -2252,7 +2252,7 @@ exports.BattleAbilities = {
desc: "This Pokemon has the ability to hit Ghost-type Pokemon with Normal-type and Fighting-type moves. Effectiveness of these moves takes into account the Ghost-type Pokemon's other weaknesses and resistances.",
shortDesc: "This Pokemon can hit Ghost-types with Normal- and Fighting-type moves.",
onModifyMove: function(move) {
if (move.type in {'Fighting':1,'Normal':1}) {
if (move.type in {'Fighting':1, 'Normal':1}) {
move.affectedByImmunities = false;
}
},
@ -2267,7 +2267,7 @@ exports.BattleAbilities = {
onModifyMove: function(move) {
if (move.secondaries) {
this.debug('doubling secondary chance');
for (var i=0; i<move.secondaries.length; i++) {
for (var i = 0; i < move.secondaries.length; i++) {
move.secondaries[i].chance *= 2;
}
}
@ -2470,7 +2470,7 @@ exports.BattleAbilities = {
},
onWeather: function(target, source, effect) {
if (effect.id === 'sunnyday') {
this.damage(target.maxhp/8);
this.damage(target.maxhp / 8);
}
},
id: "solarpower",
@ -2539,7 +2539,7 @@ exports.BattleAbilities = {
onBeforeMove: function(attacker, defender, move) {
if (attacker.template.baseSpecies !== 'Aegislash') return;
if (move.category === 'Status' && move.id !== 'kingsshield') return;
var targetSpecies = (move.id === 'kingsshield'?'Aegislash':'Aegislash-Blade');
var targetSpecies = (move.id === 'kingsshield' ? 'Aegislash' : 'Aegislash-Blade');
if (attacker.template.species !== targetSpecies && attacker.formeChange(targetSpecies)) {
this.add('-formechange', attacker, targetSpecies);
}
@ -2583,7 +2583,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 (var i = 0; i < move.secondaries.length; i++) {
if (move.secondaries[i].volatileStatus === 'flinch') return;
}
move.secondaries.push({
@ -2653,11 +2653,11 @@ exports.BattleAbilities = {
onDamagePriority: -100,
onDamage: function(damage, target, source, effect) {
if (effect && effect.ohko) {
this.add('-activate',target,'Sturdy');
this.add('-activate', target, 'Sturdy');
return 0;
}
if (target.hp === target.maxhp && damage >= target.hp && effect && effect.effectType === 'Move') {
this.add('-activate',target,'Sturdy');
this.add('-activate', target, 'Sturdy');
return target.hp - 1;
}
},
@ -2695,14 +2695,14 @@ exports.BattleAbilities = {
shortDesc: "When this Pokemon has 1/3 or less of its max HP, its Bug attacks do 1.5x damage.",
onModifyAtkPriority: 5,
onModifyAtk: function(atk, attacker, defender, move) {
if (move.type === 'Bug' && attacker.hp <= attacker.maxhp/3) {
if (move.type === 'Bug' && attacker.hp <= attacker.maxhp / 3) {
this.debug('Swarm boost');
return this.chainModify(1.5);
}
},
onModifySpAPriority: 5,
onModifySpA: function(atk, attacker, defender, move) {
if (move.type === 'Bug' && attacker.hp <= attacker.maxhp/3) {
if (move.type === 'Bug' && attacker.hp <= attacker.maxhp / 3) {
this.debug('Swarm boost');
return this.chainModify(1.5);
}
@ -2755,7 +2755,7 @@ exports.BattleAbilities = {
return;
}
if (pokemon.setItem(sourceItem)) {
this.add('-activate', pokemon, 'ability: Symbiosis', sourceItem, '[of] '+this.effectData.target);
this.add('-activate', pokemon, 'ability: Symbiosis', sourceItem, '[of] ' + this.effectData.target);
}
},
id: "symbiosis",
@ -2883,14 +2883,14 @@ exports.BattleAbilities = {
shortDesc: "When this Pokemon has 1/3 or less of its max HP, its Water attacks do 1.5x damage.",
onModifyAtkPriority: 5,
onModifyAtk: function(atk, attacker, defender, move) {
if (move.type === 'Water' && attacker.hp <= attacker.maxhp/3) {
if (move.type === 'Water' && attacker.hp <= attacker.maxhp / 3) {
this.debug('Torrent boost');
return this.chainModify(1.5);
}
},
onModifySpAPriority: 5,
onModifySpA: function(atk, attacker, defender, move) {
if (move.type === 'Water' && attacker.hp <= attacker.maxhp/3) {
if (move.type === 'Water' && attacker.hp <= attacker.maxhp / 3) {
this.debug('Torrent boost');
return this.chainModify(1.5);
}
@ -2940,7 +2940,7 @@ exports.BattleAbilities = {
if (bannedAbilities[target.ability]) {
return;
}
this.add('-ability',pokemon, ability,'[from] ability: Trace','[of] '+target);
this.add('-ability', pokemon, ability, '[from] ability: Trace', '[of] ' + target);
pokemon.setAbility(ability);
},
id: "trace",
@ -2953,7 +2953,7 @@ exports.BattleAbilities = {
shortDesc: "This Pokemon skips every other turn instead of using a move.",
onBeforeMove: function(pokemon, target, move) {
if (pokemon.removeVolatile('truant')) {
this.add('cant',pokemon,'ability: Truant', move);
this.add('cant', pokemon, 'ability: Truant', move);
return false;
}
pokemon.addVolatile('truant');
@ -3034,7 +3034,7 @@ exports.BattleAbilities = {
desc: "While this Pokemon is active, prevents opposing Pokemon from using their Berries.",
shortDesc: "While this Pokemon is active, prevents opposing Pokemon from using their Berries.",
onStart: function(pokemon) {
this.add('-ability',pokemon,'Unnerve',pokemon.side.foe);
this.add('-ability', pokemon, 'Unnerve', pokemon.side.foe);
},
onFoeEatItem: false,
id: "unnerve",
@ -3076,7 +3076,7 @@ exports.BattleAbilities = {
shortDesc: "This Pokemon heals 1/4 of its max HP when hit by Electric moves; Electric immunity.",
onTryHit: function(target, source, move) {
if (target !== source && move.type === 'Electric') {
if (!this.heal(target.maxhp/4)) {
if (!this.heal(target.maxhp / 4)) {
this.add('-immune', target, '[msg]');
}
return null;
@ -3092,7 +3092,7 @@ exports.BattleAbilities = {
shortDesc: "This Pokemon heals 1/4 of its max HP when hit by Water moves; Water immunity.",
onTryHit: function(target, source, move) {
if (target !== source && move.type === 'Water') {
if (!this.heal(target.maxhp/4)) {
if (!this.heal(target.maxhp / 4)) {
this.add('-immune', target, '[msg]');
}
return null;
@ -3144,7 +3144,7 @@ exports.BattleAbilities = {
showMsg = true;
}
}
if (showMsg && !effect.secondaries) this.add("-fail", target, "unboost", "[from] ability: White Smoke", "[of] "+target);
if (showMsg && !effect.secondaries) this.add("-fail", target, "unboost", "[from] ability: White Smoke", "[of] " + target);
},
id: "whitesmoke",
name: "White Smoke",
@ -3156,7 +3156,7 @@ exports.BattleAbilities = {
shortDesc: "This Pokemon can only be damaged by super effective moves and indirect damage.",
onTryHit: function(target, source, move) {
if (target === source || move.category === 'Status' || move.type === '???' || move.id === 'struggle') return;
this.debug('Wonder Guard immunity: '+move.id);
this.debug('Wonder Guard immunity: ' + move.id);
if (this.getEffectiveness(move, target) <= 0) {
this.add('-activate', target, 'ability: Wonder Guard');
return null;
@ -3190,9 +3190,9 @@ exports.BattleAbilities = {
if (pokemon.baseTemplate.species !== 'Darmanitan') {
return;
}
if (pokemon.hp <= pokemon.maxhp/2 && pokemon.template.speciesid==='darmanitan'){
if (pokemon.hp <= pokemon.maxhp / 2 && pokemon.template.speciesid === 'darmanitan'){
pokemon.addVolatile('zenmode');
} else if (pokemon.hp > pokemon.maxhp/2 && pokemon.template.speciesid==='darmanitanzen') {
} else if (pokemon.hp > pokemon.maxhp / 2 && pokemon.template.speciesid === 'darmanitanzen') {
pokemon.removeVolatile('zenmode');
}
},

View File

@ -98,12 +98,12 @@ exports.BattleItems = {
type: "Dragon"
},
onUpdate: function(pokemon) {
if (pokemon.hp <= pokemon.maxhp/2) {
if (pokemon.hp <= pokemon.maxhp / 2) {
pokemon.eatItem();
}
},
onEat: function(pokemon) {
this.heal(pokemon.maxhp/8);
this.heal(pokemon.maxhp / 8);
if (pokemon.getNature().minus === 'spd') {
pokemon.addVolatile('confusion');
}
@ -126,14 +126,14 @@ exports.BattleItems = {
if (type === 'Ground') return false;
},
onAfterDamage: function(damage, target, source, effect) {
this.debug('effect: '+effect.id);
this.debug('effect: ' + effect.id);
if (effect.effectType === 'Move') {
this.add('-enditem', target, 'Air Balloon');
target.setItem('');
}
},
onAfterSubDamage: function(damage, target, source, effect) {
this.debug('effect: '+effect.id);
this.debug('effect: ' + effect.id);
if (effect.effectType === 'Move') {
this.add('-enditem', target, 'Air Balloon');
target.setItem('');
@ -181,7 +181,7 @@ exports.BattleItems = {
type: "Ground"
},
onUpdate: function(pokemon) {
if (pokemon.hp <= pokemon.maxhp/4|| (pokemon.hp <= pokemon.maxhp/2 && pokemon.hasAbility('gluttony'))) {
if (pokemon.hp <= pokemon.maxhp / 4|| (pokemon.hp <= pokemon.maxhp / 2 && pokemon.hasAbility('gluttony'))) {
pokemon.eatItem();
}
},
@ -239,7 +239,7 @@ exports.BattleItems = {
},
onModifyPokemon: function(pokemon) {
var moves = pokemon.moveset;
for (var i=0; i<moves.length; i++) {
for (var i = 0; i < moves.length; i++) {
if (this.getMove(moves[i].move).category === 'Status') {
moves[i].disabled = true;
}
@ -306,7 +306,7 @@ exports.BattleItems = {
basePower: 30
},
onUpdate: function(pokemon) {
if (pokemon.hp <= pokemon.maxhp/2) {
if (pokemon.hp <= pokemon.maxhp / 2) {
if (pokemon.useItem()) {
this.heal(20);
}
@ -374,9 +374,9 @@ exports.BattleItems = {
onResidualSubOrder: 2,
onResidual: function(pokemon) {
if (pokemon.hasType('Poison')) {
this.heal(pokemon.maxhp/16);
this.heal(pokemon.maxhp / 16);
} else {
this.damage(pokemon.maxhp/8);
this.damage(pokemon.maxhp / 8);
}
},
num: 281,
@ -467,7 +467,7 @@ exports.BattleItems = {
if (target === source || move.category === 'Status') return;
if (move.type === 'Bug') {
if (source.useItem()) {
this.add('-enditem', source, 'Bug Gem', '[from] gem', '[move] '+move.name);
this.add('-enditem', source, 'Bug Gem', '[from] gem', '[move] ' + move.name);
source.addVolatile('gem');
}
}
@ -680,7 +680,7 @@ exports.BattleItems = {
},
onStart: function(pokemon) {
if (pokemon.volatiles['choicelock']) {
this.debug('removing choicelock: '+pokemon.volatiles.choicelock);
this.debug('removing choicelock: ' + pokemon.volatiles.choicelock);
}
pokemon.removeVolatile('choicelock');
},
@ -705,7 +705,7 @@ exports.BattleItems = {
},
onStart: function(pokemon) {
if (pokemon.volatiles['choicelock']) {
this.debug('removing choicelock: '+pokemon.volatiles.choicelock);
this.debug('removing choicelock: ' + pokemon.volatiles.choicelock);
}
pokemon.removeVolatile('choicelock');
},
@ -729,7 +729,7 @@ exports.BattleItems = {
},
onStart: function(pokemon) {
if (pokemon.volatiles['choicelock']) {
this.debug('removing choicelock: '+pokemon.volatiles.choicelock);
this.debug('removing choicelock: ' + pokemon.volatiles.choicelock);
}
pokemon.removeVolatile('choicelock');
},
@ -857,7 +857,7 @@ exports.BattleItems = {
type: "Ghost"
},
onModifyPriority: function(priority, pokemon) {
if (pokemon.hp <= pokemon.maxhp/4 || (pokemon.hp <= pokemon.maxhp/2 && pokemon.hasAbility('gluttony'))) {
if (pokemon.hp <= pokemon.maxhp / 4 || (pokemon.hp <= pokemon.maxhp / 2 && pokemon.hasAbility('gluttony'))) {
if (pokemon.eatItem()) {
this.add('-activate', pokemon, 'Custap Berry');
pokemon.removeVolatile('custapberry');
@ -890,7 +890,7 @@ exports.BattleItems = {
if (target === source || move.category === 'Status') return;
if (move.type === 'Dark') {
if (source.useItem()) {
this.add('-enditem', source, 'Dark Gem', '[from] gem', '[move] '+move.name);
this.add('-enditem', source, 'Dark Gem', '[from] gem', '[move] ' + move.name);
source.addVolatile('gem');
}
}
@ -942,7 +942,7 @@ exports.BattleItems = {
},
onAttractPriority: -100,
onAttract: function(target, source) {
this.debug('attract intercepted: '+target+' from '+source);
this.debug('attract intercepted: ' + target + ' from ' + source);
if (!source || source === target) return;
if (!source.volatiles.attract) source.addVolatile('attract', target);
},
@ -1032,7 +1032,7 @@ exports.BattleItems = {
if (target === source || move.category === 'Status') return;
if (move.type === 'Dragon') {
if (source.useItem()) {
this.add('-enditem', source, 'Dragon Gem', '[from] gem', '[move] '+move.name);
this.add('-enditem', source, 'Dragon Gem', '[from] gem', '[move] ' + move.name);
source.addVolatile('gem');
}
}
@ -1150,7 +1150,7 @@ exports.BattleItems = {
if (target === source || move.category === 'Status') return;
if (move.type === 'Electric') {
if (source.useItem()) {
this.add('-enditem', source, 'Electric Gem', '[from] gem', '[move] '+move.name);
this.add('-enditem', source, 'Electric Gem', '[from] gem', '[move] ' + move.name);
source.addVolatile('gem');
}
}
@ -1193,7 +1193,7 @@ exports.BattleItems = {
}
},
onEat: function(pokemon) {
this.heal(pokemon.maxhp/4);
this.heal(pokemon.maxhp / 4);
},
num: 208,
gen: 3,
@ -1256,7 +1256,7 @@ exports.BattleItems = {
if (target === source || move.category === 'Status') return;
if (move.type === 'Fighting') {
if (source.useItem()) {
this.add('-enditem', source, 'Fighting Gem', '[from] gem', '[move] '+move.name);
this.add('-enditem', source, 'Fighting Gem', '[from] gem', '[move] ' + move.name);
source.addVolatile('gem');
}
}
@ -1275,12 +1275,12 @@ exports.BattleItems = {
type: "Bug"
},
onUpdate: function(pokemon) {
if (pokemon.hp <= pokemon.maxhp/2) {
if (pokemon.hp <= pokemon.maxhp / 2) {
pokemon.eatItem();
}
},
onEat: function(pokemon) {
this.heal(pokemon.maxhp/8);
this.heal(pokemon.maxhp / 8);
if (pokemon.getNature().minus === 'atk') {
pokemon.addVolatile('confusion');
}
@ -1299,7 +1299,7 @@ exports.BattleItems = {
if (target === source || move.category === 'Status') return;
if (move.type === 'Fire') {
if (source.useItem()) {
this.add('-enditem', source, 'Fire Gem', '[from] gem', '[move] '+move.name);
this.add('-enditem', source, 'Fire Gem', '[from] gem', '[move] ' + move.name);
source.addVolatile('gem');
}
}
@ -1385,7 +1385,7 @@ exports.BattleItems = {
if (target === source || move.category === 'Status') return;
if (move.type === 'Flying') {
if (source.useItem()) {
this.add('-enditem', source, 'Flying Gem', '[from] gem', '[move] '+move.name);
this.add('-enditem', source, 'Flying Gem', '[from] gem', '[move] ' + move.name);
source.addVolatile('gem');
}
}
@ -1403,7 +1403,7 @@ exports.BattleItems = {
},
onDamage: function(damage, target, source, effect) {
if (this.random(10) === 0 && damage >= target.hp && effect && effect.effectType === 'Move') {
this.add("-message",target.name+" held on using its Focus Band! (placeholder)");
this.add("-message", target.name + " held on using its Focus Band! (placeholder)");
return target.hp - 1;
}
},
@ -1455,7 +1455,7 @@ exports.BattleItems = {
type: "Ice"
},
onUpdate: function(pokemon) {
if (pokemon.hp <= pokemon.maxhp/4 || (pokemon.hp <= pokemon.maxhp/2 && pokemon.hasAbility('gluttony'))) {
if (pokemon.hp <= pokemon.maxhp / 4 || (pokemon.hp <= pokemon.maxhp / 2 && pokemon.hasAbility('gluttony'))) {
pokemon.eatItem();
}
},
@ -1518,7 +1518,7 @@ exports.BattleItems = {
if (target === source || move.category === 'Status') return;
if (move.type === 'Ghost') {
if (source.useItem()) {
this.add('-enditem', source, 'Ghost Gem', '[from] gem', '[move] '+move.name);
this.add('-enditem', source, 'Ghost Gem', '[from] gem', '[move] ' + move.name);
source.addVolatile('gem');
}
}
@ -1537,7 +1537,7 @@ exports.BattleItems = {
if (target === source || move.category === 'Status') return;
if (move.type === 'Grass') {
if (source.useItem()) {
this.add('-enditem', source, 'Grass Gem', '[from] gem', '[move] '+move.name);
this.add('-enditem', source, 'Grass Gem', '[from] gem', '[move] ' + move.name);
source.addVolatile('gem');
}
}
@ -1612,7 +1612,7 @@ exports.BattleItems = {
if (target === source || move.category === 'Status') return;
if (move.type === 'Ground') {
if (source.useItem()) {
this.add('-enditem', source, 'Ground Gem', '[from] gem', '[move] '+move.name);
this.add('-enditem', source, 'Ground Gem', '[from] gem', '[move] ' + move.name);
source.addVolatile('gem');
}
}
@ -1763,12 +1763,12 @@ exports.BattleItems = {
type: "Dark"
},
onUpdate: function(pokemon) {
if (pokemon.hp <= pokemon.maxhp/2) {
if (pokemon.hp <= pokemon.maxhp / 2) {
pokemon.eatItem();
}
},
onEat: function(pokemon) {
this.heal(pokemon.maxhp/8);
this.heal(pokemon.maxhp / 8);
if (pokemon.getNature().minus === 'def') {
pokemon.addVolatile('confusion');
}
@ -1787,7 +1787,7 @@ exports.BattleItems = {
if (target === source || move.category === 'Status') return;
if (move.type === 'Ice') {
if (source.useItem()) {
this.add('-enditem', source, 'Ice Gem', '[from] gem', '[move] '+move.name);
this.add('-enditem', source, 'Ice Gem', '[from] gem', '[move] ' + move.name);
source.addVolatile('gem');
}
}
@ -1891,7 +1891,7 @@ exports.BattleItems = {
onAfterMoveSecondary: function(target, source, move) {
if (source && source !== target && move && move.category === 'Physical') {
if (target.eatItem()) {
this.damage(source.maxhp/8, source, target);
this.damage(source.maxhp / 8, source, target);
}
}
},
@ -2003,7 +2003,7 @@ exports.BattleItems = {
onModifyMove: function(move) {
if (move.category !== "Status") {
if (!move.secondaries) move.secondaries = [];
for (var i=0; i<move.secondaries.length; i++) {
for (var i = 0; i < move.secondaries.length; i++) {
if (move.secondaries[i].volatileStatus === 'flinch') return;
}
move.secondaries.push({
@ -2042,7 +2042,7 @@ exports.BattleItems = {
type: "Flying"
},
onUpdate: function(pokemon) {
if (pokemon.hp <= pokemon.maxhp/4 || (pokemon.hp <= pokemon.maxhp/2 && pokemon.hasAbility('gluttony'))) {
if (pokemon.hp <= pokemon.maxhp / 4 || (pokemon.hp <= pokemon.maxhp / 2 && pokemon.hasAbility('gluttony'))) {
pokemon.eatItem();
}
},
@ -2109,7 +2109,7 @@ exports.BattleItems = {
onResidualOrder: 5,
onResidualSubOrder: 2,
onResidual: function(pokemon) {
this.heal(pokemon.maxhp/16);
this.heal(pokemon.maxhp / 16);
},
num: 234,
gen: 2,
@ -2148,7 +2148,7 @@ exports.BattleItems = {
}
move.pp += 10;
if (move.pp > move.maxpp) move.pp = move.maxpp;
this.add("-message",pokemon.name+" restored "+move.move+"'s PP using its Leppa Berry! (placeholder)");
this.add("-message", pokemon.name + " restored " + move.move + "'s PP using its Leppa Berry! (placeholder)");
},
num: 154,
gen: 3,
@ -2172,7 +2172,7 @@ exports.BattleItems = {
type: "Grass"
},
onUpdate: function(pokemon) {
if (pokemon.hp <= pokemon.maxhp/4 || (pokemon.hp <= pokemon.maxhp/2 && pokemon.hasAbility('gluttony'))) {
if (pokemon.hp <= pokemon.maxhp / 4 || (pokemon.hp <= pokemon.maxhp / 2 && pokemon.hasAbility('gluttony'))) {
pokemon.eatItem();
}
},
@ -2200,7 +2200,7 @@ exports.BattleItems = {
duration: 1,
onAfterMoveSecondarySelf: function(source, target, move) {
if (move && move.effectType === 'Move' && source && source.volatiles['lifeorb']) {
this.damage(source.maxhp/10, source, source, this.getItem('lifeorb'));
this.damage(source.maxhp / 10, source, source, this.getItem('lifeorb'));
source.removeVolatile('lifeorb');
}
}
@ -2395,12 +2395,12 @@ exports.BattleItems = {
type: "Ghost"
},
onUpdate: function(pokemon) {
if (pokemon.hp <= pokemon.maxhp/2) {
if (pokemon.hp <= pokemon.maxhp / 2) {
pokemon.eatItem();
}
},
onEat: function(pokemon) {
this.heal(pokemon.maxhp/8);
this.heal(pokemon.maxhp / 8);
if (pokemon.getNature().minus === 'spe') {
pokemon.addVolatile('confusion');
}
@ -2527,10 +2527,10 @@ exports.BattleItems = {
fling: {
basePower: 10,
effect: function(pokemon) {
var conditions = ['attract','taunt','encore','torment','disable'];
for (var i=0; i<conditions.length; i++) {
var conditions = ['attract', 'taunt', 'encore', 'torment', 'disable'];
for (var i = 0; i < conditions.length; i++) {
if (pokemon.volatiles[conditions[i]]) {
for (var j=0; j<conditions.length; j++) {
for (var j = 0; j < conditions.length; j++) {
pokemon.removeVolatile(conditions[j]);
}
return;
@ -2539,11 +2539,11 @@ exports.BattleItems = {
}
},
onUpdate: function(pokemon) {
var conditions = ['attract','taunt','encore','torment','disable'];
for (var i=0; i<conditions.length; i++) {
var conditions = ['attract', 'taunt', 'encore', 'torment', 'disable'];
for (var i = 0; i < conditions.length; i++) {
if (pokemon.volatiles[conditions[i]]) {
if (!pokemon.useItem()) return;
for (var j=0; j<conditions.length; j++) {
for (var j = 0; j < conditions.length; j++) {
pokemon.removeVolatile(conditions[j]);
}
return;
@ -2660,7 +2660,7 @@ exports.BattleItems = {
type: "Rock"
},
onResidual: function(pokemon) {
if (pokemon.hp <= pokemon.maxhp/4 || (pokemon.hp <= pokemon.maxhp/2 && pokemon.hasAbility('gluttony'))) {
if (pokemon.hp <= pokemon.maxhp / 4 || (pokemon.hp <= pokemon.maxhp / 2 && pokemon.hasAbility('gluttony'))) {
pokemon.eatItem();
}
},
@ -2826,7 +2826,7 @@ exports.BattleItems = {
if (target === source || move.category === 'Status') return;
if (move.type === 'Normal') {
if (source.useItem()) {
this.add('-enditem', source, 'Normal Gem', '[from] gem', '[move] '+move.name);
this.add('-enditem', source, 'Normal Gem', '[from] gem', '[move] ' + move.name);
source.addVolatile('gem');
}
}
@ -2895,7 +2895,7 @@ exports.BattleItems = {
type: "Poison"
},
onUpdate: function(pokemon) {
if (pokemon.hp <= pokemon.maxhp/2) {
if (pokemon.hp <= pokemon.maxhp / 2) {
pokemon.eatItem();
}
},
@ -3025,7 +3025,7 @@ exports.BattleItems = {
type: "Poison"
},
onUpdate: function(pokemon) {
if (pokemon.hp <= pokemon.maxhp/4 || (pokemon.hp <= pokemon.maxhp/2 && pokemon.hasAbility('gluttony'))) {
if (pokemon.hp <= pokemon.maxhp / 4 || (pokemon.hp <= pokemon.maxhp / 2 && pokemon.hasAbility('gluttony'))) {
pokemon.eatItem();
}
},
@ -3120,7 +3120,7 @@ exports.BattleItems = {
if (target === source || move.category === 'Status') return;
if (move.type === 'Poison') {
if (source.useItem()) {
this.add('-enditem', source, 'Poison Gem', '[from] gem', '[move] '+move.name);
this.add('-enditem', source, 'Poison Gem', '[from] gem', '[move] ' + move.name);
source.addVolatile('gem');
}
}
@ -3154,7 +3154,7 @@ exports.BattleItems = {
id: "powerherb",
onChargeMove: function(pokemon, target, move) {
if (pokemon.useItem()) {
this.debug('power herb - remove charge turn for '+move.id);
this.debug('power herb - remove charge turn for ' + move.id);
return false; // skip charge turn
}
},
@ -3185,7 +3185,7 @@ exports.BattleItems = {
if (target === source || move.category === 'Status') return;
if (move.type === 'Psychic') {
if (source.useItem()) {
this.add('-enditem', source, 'Psychic Gem', '[from] gem', '[move] '+move.name);
this.add('-enditem', source, 'Psychic Gem', '[from] gem', '[move] ' + move.name);
source.addVolatile('gem');
}
}
@ -3320,7 +3320,7 @@ exports.BattleItems = {
onModifyMove: function(move) {
if (move.category !== "Status") {
if (!move.secondaries) move.secondaries = [];
for (var i=0; i<move.secondaries.length; i++) {
for (var i = 0; i < move.secondaries.length; i++) {
if (move.secondaries[i].volatileStatus === 'flinch') return;
}
move.secondaries.push({
@ -3421,7 +3421,7 @@ exports.BattleItems = {
if (target === source || move.category === 'Status') return;
if (move.type === 'Rock') {
if (source.useItem()) {
this.add('-enditem', source, 'Rock Gem', '[from] gem', '[move] '+move.name);
this.add('-enditem', source, 'Rock Gem', '[from] gem', '[move] ' + move.name);
source.addVolatile('gem');
}
}
@ -3457,7 +3457,7 @@ exports.BattleItems = {
onAfterDamageOrder: 2,
onAfterDamage: function(damage, target, source, move) {
if (source && source !== target && move && move.isContact) {
this.damage(source.maxhp/6, source, target);
this.damage(source.maxhp / 6, source, target);
}
},
num: 540,
@ -3526,7 +3526,7 @@ exports.BattleItems = {
onAfterMoveSecondary: function(target, source, move) {
if (source && source !== target && move && move.category === 'Special') {
if (target.eatItem()) {
this.damage(source.maxhp/8, source, target);
this.damage(source.maxhp / 8, source, target);
}
}
},
@ -3564,7 +3564,7 @@ exports.BattleItems = {
type: "Fighting"
},
onUpdate: function(pokemon) {
if (pokemon.hp <= pokemon.maxhp/4 || (pokemon.hp <= pokemon.maxhp/2 && pokemon.hasAbility('gluttony'))) {
if (pokemon.hp <= pokemon.maxhp / 4 || (pokemon.hp <= pokemon.maxhp / 2 && pokemon.hasAbility('gluttony'))) {
pokemon.eatItem();
}
},
@ -3661,7 +3661,7 @@ exports.BattleItems = {
},
onAfterMoveSelf: function(source, target) {
if (source.lastDamage > 0) {
this.heal(source.lastDamage/8, source);
this.heal(source.lastDamage / 8, source);
}
},
num: 253,
@ -3752,12 +3752,12 @@ exports.BattleItems = {
type: "Psychic"
},
onUpdate: function(pokemon) {
if (pokemon.hp <= pokemon.maxhp/2) {
if (pokemon.hp <= pokemon.maxhp / 2) {
pokemon.eatItem();
}
},
onEat: function(pokemon) {
this.heal(pokemon.maxhp/4);
this.heal(pokemon.maxhp / 4);
},
num: 158,
gen: 3,
@ -3944,7 +3944,7 @@ exports.BattleItems = {
type: "Psychic"
},
onUpdate: function(pokemon) {
if (pokemon.hp <= pokemon.maxhp/4 || (pokemon.hp <= pokemon.maxhp/2 && pokemon.hasAbility('gluttony'))) {
if (pokemon.hp <= pokemon.maxhp / 4 || (pokemon.hp <= pokemon.maxhp / 2 && pokemon.hasAbility('gluttony'))) {
pokemon.eatItem();
}
},
@ -3976,7 +3976,7 @@ exports.BattleItems = {
if (target === source || move.category === 'Status') return;
if (move.type === 'Steel') {
if (source.useItem()) {
this.add('-enditem', source, 'Steel Gem', '[from] gem', '[move] '+move.name);
this.add('-enditem', source, 'Steel Gem', '[from] gem', '[move] ' + move.name);
source.addVolatile('gem');
}
}
@ -4011,7 +4011,7 @@ exports.BattleItems = {
onResidualOrder: 26,
onResidualSubOrder: 2,
onResidual: function(pokemon) {
this.damage(pokemon.maxhp/8);
this.damage(pokemon.maxhp / 8);
},
onHit: function(target, source, move) {
if (source && source !== target && !source.item && move && move.isContact) {
@ -4222,7 +4222,7 @@ exports.BattleItems = {
if (target === source || move.category === 'Status') return;
if (move.type === 'Water') {
if (source.useItem()) {
this.add('-enditem', source, 'Water Gem', '[from] gem', '[move] '+move.name);
this.add('-enditem', source, 'Water Gem', '[from] gem', '[move] ' + move.name);
source.addVolatile('gem');
}
}
@ -4354,12 +4354,12 @@ exports.BattleItems = {
type: "Rock"
},
onUpdate: function(pokemon) {
if (pokemon.hp <= pokemon.maxhp/2) {
if (pokemon.hp <= pokemon.maxhp / 2) {
pokemon.eatItem();
}
},
onEat: function(pokemon) {
this.heal(pokemon.maxhp/8);
this.heal(pokemon.maxhp / 8);
if (pokemon.getNature().minus === 'spa') {
pokemon.addVolatile('confusion');
}

File diff suppressed because it is too large Load Diff

File diff suppressed because one or more lines are too long

View File

@ -17,7 +17,7 @@ exports.BattleScripts = {
// THIS IS PURELY A SANITY CHECK
// DO NOT TAKE ADVANTAGE OF THIS TO PREVENT A POKEMON FROM MOVING;
// USE this.cancelMove INSTEAD
this.debug(''+pokemon.id+' INCONSISTENT STATE, ALREADY MOVED: '+pokemon.moveThisTurn);
this.debug('' + pokemon.id + ' INCONSISTENT STATE, ALREADY MOVED: ' + pokemon.moveThisTurn);
this.clearActiveMove(true);
return;
}
@ -85,8 +85,8 @@ exports.BattleScripts = {
var movename = move.name;
if (move.id === 'hiddenpower') movename = 'Hidden Power';
if (sourceEffect) attrs += '|[from]'+this.getEffect(sourceEffect);
this.addMove('move', pokemon, movename, target+attrs);
if (sourceEffect) attrs += '|[from]' + this.getEffect(sourceEffect);
this.addMove('move', pokemon, movename, target + attrs);
if (target === false) {
this.attrLastMove('[notarget]');
@ -121,16 +121,16 @@ exports.BattleScripts = {
var targets = [];
if (move.target === 'allAdjacent') {
var allyActive = pokemon.side.active;
for (var i=0; i<allyActive.length; i++) {
if (allyActive[i] && Math.abs(i-pokemon.position)<=1 && i != pokemon.position && !allyActive[i].fainted) {
for (var i = 0; i < allyActive.length; i++) {
if (allyActive[i] && Math.abs(i - pokemon.position) <= 1 && i != pokemon.position && !allyActive[i].fainted) {
targets.push(allyActive[i]);
}
}
}
var foeActive = pokemon.side.foe.active;
var foePosition = foeActive.length-pokemon.position-1;
for (var i=0; i<foeActive.length; i++) {
if (foeActive[i] && Math.abs(i-foePosition)<=1 && !foeActive[i].fainted) {
var foePosition = foeActive.length - pokemon.position - 1;
for (var i = 0; i < foeActive.length; i++) {
if (foeActive[i] && Math.abs(i - foePosition) <= 1 && !foeActive[i].fainted) {
targets.push(foeActive[i]);
}
}
@ -144,7 +144,7 @@ exports.BattleScripts = {
}
if (targets.length > 1) move.spreadHit = true;
damage = 0;
for (var i=0; i<targets.length; i++) {
for (var i = 0; i < targets.length; i++) {
damage += (this.tryMoveHit(targets[i], pokemon, move, true) || 0);
}
if (!pokemon.hp) pokemon.faint();
@ -204,7 +204,7 @@ exports.BattleScripts = {
return false;
}
var boostTable = [1, 4/3, 5/3, 2, 7/3, 8/3, 3];
var boostTable = [1, 4 / 3, 5 / 3, 2, 7 / 3, 8 / 3, 3];
// calculate true accuracy
var accuracy = move.accuracy;
@ -249,14 +249,14 @@ exports.BattleScripts = {
// yes, it's hardcoded... meh
if (hits[0] === 2 && hits[1] === 5) {
var roll = this.random(6);
hits = [2,2,3,3,4,5][roll];
hits = [2, 2, 3, 3, 4, 5][roll];
} else {
hits = this.random(hits[0],hits[1]+1);
hits = this.random(hits[0], hits[1] + 1);
}
}
hits = Math.floor(hits);
var nullDamage = true;
for (var i=0; i<hits && target.hp && pokemon.hp; i++) {
for (var i = 0; i < hits && target.hp && pokemon.hp; i++) {
if (!move.sourceEffect && !move.sleepUsable && pokemon.status === 'slp') break;
var moveDamage = this.moveHit(target, pokemon, move);
@ -506,7 +506,7 @@ exports.BattleScripts = {
// okay, mega evolution is possible
this.add('-formechange', pokemon, template.species);
this.add('message', template.baseSpecies+" has Mega Evolved into Mega "+template.baseSpecies+"!");
this.add('message', template.baseSpecies + " has Mega Evolved into Mega " + template.baseSpecies + "!");
pokemon.formeChange(template);
pokemon.baseTemplate = template; // mega evolution is permanent :o
pokemon.setAbility(template.abilities['0']);
@ -518,7 +518,7 @@ exports.BattleScripts = {
},
isAdjacent: function(pokemon1, pokemon2) {
if (!pokemon1.fainted && !pokemon2.fainted && pokemon2.position !== pokemon1.position && Math.abs(pokemon2.position-pokemon1.position) <= 1) {
if (!pokemon1.fainted && !pokemon2.fainted && pokemon2.position !== pokemon1.position && Math.abs(pokemon2.position - pokemon1.position) <= 1) {
return true;
}
},
@ -526,7 +526,7 @@ exports.BattleScripts = {
if (!selectedAbilities.length) return true;
var selectedAbility = selectedAbilities.pop();
var isValid = false;
for (var i=0; i<defaultAbilities.length; i++) {
for (var i = 0; i < defaultAbilities.length; i++) {
var defaultAbility = defaultAbilities[i];
if (!defaultAbility) break;
if (defaultAbility.indexOf(selectedAbility) !== -1) {
@ -553,8 +553,8 @@ exports.BattleScripts = {
var format = side.battle.getFormat();
if (format.team === 'random') {
return this.randomTeam(side);
} else if (typeof format.team === 'string' && format.team.substr(0,6) === 'random') {
return this[format.team+'Team'](side);
} else if (typeof format.team === 'string' && format.team.substr(0, 6) === 'random') {
return this[format.team + 'Team'](side);
} else if (team) {
return team;
} else {
@ -568,10 +568,10 @@ exports.BattleScripts = {
//pick six random pokmeon--no repeats, even among formes
//also need to either normalize for formes or select formes at random
//unreleased are okay. No CAP for now, but maybe at some later date
for (var i=0; i<6; i++)
for (var i = 0; i < 6; i++)
{
while (true) {
var x=Math.floor(Math.random()*718)+1;
var x = Math.floor(Math.random() * 718) + 1;
if (teamdexno.indexOf(x) === -1) {
teamdexno.push(x);
break;
@ -579,7 +579,7 @@ exports.BattleScripts = {
}
}
for (var i=0; i<6; i++) {
for (var i = 0; i < 6; i++) {
//choose forme
var formes = [];
@ -597,22 +597,22 @@ exports.BattleScripts = {
var stats = template.baseStats;
//modified base stat total assumes 31 IVs, 85 EVs in every stat
var 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 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
var 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);
mbst += Math.floor(((stats["atk"]*2+31+21+100)*level/100+5)*level/100); //since damage is roughly proportional to lvl
mbst += Math.floor((stats["def"]*2+31+21+100)*level/100+5);
mbst += Math.floor(((stats["spa"]*2+31+21+100)*level/100+5)*level/100);
mbst += Math.floor((stats["spd"]*2+31+21+100)*level/100+5);
mbst += Math.floor((stats["spe"]*2+31+21+100)*level/100+5);
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); //since damage is roughly proportional to lvl
mbst += Math.floor((stats["def"] * 2 + 31 + 21 + 100) * level / 100 + 5);
mbst += Math.floor(((stats["spa"] * 2 + 31 + 21 + 100) * level / 100 + 5) * level / 100);
mbst += Math.floor((stats["spd"] * 2 + 31 + 21 + 100) * level / 100 + 5);
mbst += Math.floor((stats["spe"] * 2 + 31 + 21 + 100) * level/100 + 5);
if (mbst >= mbstmin)
break;
@ -654,12 +654,12 @@ exports.BattleScripts = {
//random IVs
var ivs = {
hp: Math.floor(Math.random()*32),
atk: Math.floor(Math.random()*32),
def: Math.floor(Math.random()*32),
spa: Math.floor(Math.random()*32),
spd: Math.floor(Math.random()*32),
spe: Math.floor(Math.random()*32)
hp: Math.floor(Math.random() * 32),
atk: Math.floor(Math.random() * 32),
def: Math.floor(Math.random() * 32),
spa: Math.floor(Math.random() * 32),
spd: Math.floor(Math.random() * 32),
spe: Math.floor(Math.random() * 32)
};
//random EVs
@ -671,21 +671,21 @@ exports.BattleScripts = {
spd: 0,
spe: 0
};
var s = ["hp","atk","def","spa","spd","spe"];
var s = ["hp", "atk", "def", "spa", "spd", "spe"];
var evpool = 510;
do
{
var x = s.sample();
var y = Math.floor(Math.random()*Math.min(256-evs[x],evpool+1));
evs[x]+=y;
evpool-=y;
var y = Math.floor(Math.random() * Math.min(256 - evs[x], evpool + 1));
evs[x] += y;
evpool -= y;
} while (evpool > 0);
//random happiness--useless, since return/frustration is currently a "cheat"
var happiness = Math.floor(Math.random()*256);
var happiness = Math.floor(Math.random() * 256);
//random shininess?
var shiny = (Math.random()*1024<=1);
var shiny = (Math.random() * 1024 <= 1);
//four random unique moves from movepool. don't worry about "attacking" or "viable"
var moves;
@ -698,7 +698,7 @@ exports.BattleScripts = {
if (pool.length <= 4) {
moves = pool;
} else {
moves=pool.sample(4);
moves = pool.sample(4);
}
team.push({
@ -727,7 +727,7 @@ exports.BattleScripts = {
// 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 stack = 'Template incompatible with random battles: ' + name;
var fakeErr = {stack: stack};
require('../crashlogger.js')(fakeErr, 'The randbat set generator');
}
@ -767,13 +767,13 @@ exports.BattleScripts = {
var counter = {};
var setupType = '';
var j=0;
var j = 0;
do {
// Choose next 4 moves from learnset/viable moves and add them to moves list:
while (moves.length<4 && j<moveKeys.length) {
while (moves.length < 4 && j < moveKeys.length) {
var moveid = toId(moveKeys[j]);
j++;
if (moveid.substr(0,11) === 'hiddenpower') {
if (moveid.substr(0, 11) === 'hiddenpower') {
if (!hasMove['hiddenpower']) {
hasMove['hiddenpower'] = true;
} else {
@ -794,7 +794,7 @@ 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++) {
for (var k = 0; k < moves.length; k++) {
var move = this.getMove(moves[k]);
var moveid = move.id;
// Keep track of all moves we have:
@ -897,7 +897,7 @@ exports.BattleScripts = {
}
// Iterate through the moves again, this time to cull them:
for (var k=0; k<moves.length; k++) {
for (var k = 0; k < moves.length; k++) {
var moveid = moves[k];
var move = this.getMove(moveid);
var rejected = false;
@ -934,7 +934,7 @@ exports.BattleScripts = {
isSetup = true;
break;
case 'shellsmash': case 'growth': case 'workup':
if (counter.Physical+counter.Special < 2 && !hasMove['batonpass']) rejected = true;
if (counter.Physical + counter.Special < 2 && !hasMove['batonpass']) rejected = true;
if (setupType !== 'Mixed' || counter['mixedsetup'] > 1) rejected = true;
isSetup = true;
break;
@ -1150,8 +1150,8 @@ exports.BattleScripts = {
}
// Remove rejected moves from the move list.
if (rejected && j<moveKeys.length) {
moves.splice(k,1);
if (rejected && j < moveKeys.length) {
moves.splice(k, 1);
break;
}
@ -1163,12 +1163,12 @@ exports.BattleScripts = {
}
}
}
if (j<moveKeys.length && moves.length === 4) {
if (j < moveKeys.length && moves.length === 4) {
// Move post-processing:
if (damagingMoves.length===0) {
if (damagingMoves.length === 0) {
// A set shouldn't have no attacking moves
moves.splice(Math.floor(Math.random()*moves.length),1);
} else if (damagingMoves.length===1) {
moves.splice(Math.floor(Math.random() * moves.length), 1);
} else if (damagingMoves.length === 1) {
// Night Shade, Seismic Toss, etc. don't count:
if (!damagingMoves[0].damage) {
var damagingid = damagingMoves[0].id;
@ -1176,11 +1176,11 @@ exports.BattleScripts = {
var 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'] && Math.random()*2>1) replace = true;
if (!hasMove['encore'] && Math.random() * 2 > 1) replace = true;
} else if (damagingid === 'focuspunch') {
// Focus Punch is a bad idea without a sub:
if (!hasMove['substitute']) replace = true;
} else if (damagingid.substr(0,11) === 'hiddenpower' && damagingType === 'Ice') {
} else if (damagingid.substr(0, 11) === 'hiddenpower' && damagingType === 'Ice') {
// Mono-HP-Ice is never acceptable.
replace = true;
} else {
@ -1196,9 +1196,9 @@ exports.BattleScripts = {
}
}
}
if (replace) moves.splice(damagingMoveIndex[damagingid],1);
if (replace) moves.splice(damagingMoveIndex[damagingid], 1);
}
} else if (damagingMoves.length===2) {
} 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('/');
@ -1208,20 +1208,20 @@ exports.BattleScripts = {
} else {
rejectCombo = false;
}
if (rejectCombo) moves.splice(Math.floor(Math.random()*moves.length),1);
if (rejectCombo) moves.splice(Math.floor(Math.random() * moves.length), 1);
} 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++) {
for (var l = 0; l < damagingMoves.length; l++) {
if (hasStab[damagingMoves[l].type]) {
isStab = true;
break;
}
}
if (!isStab) moves.splice(Math.floor(Math.random()*moves.length),1);
if (!isStab) moves.splice(Math.floor(Math.random() * moves.length), 1);
}
}
} while (moves.length<4 && j<moveKeys.length);
} while (moves.length < 4 && j < moveKeys.length);
// any moveset modification goes here
//moves[0] = 'Safeguard';
@ -1235,7 +1235,7 @@ exports.BattleScripts = {
if (template.abilities['H']) {
abilities.push(template.abilities['H']);
}
abilities.sort(function(a,b){
abilities.sort(function(a, b){
return this.getAbility(b).rating - this.getAbility(a).rating;
}.bind(this));
var ability0 = this.getAbility(abilities[0]);
@ -1244,11 +1244,11 @@ exports.BattleScripts = {
if (abilities[1]) {
if (ability0.rating <= ability1.rating) {
if (Math.random()*2<1) {
if (Math.random() * 2 < 1) {
ability = ability1.name;
}
} else if (ability0.rating - 0.6 <= ability1.rating) {
if (Math.random()*3<1) {
if (Math.random() * 3 < 1) {
ability = ability1.name;
}
}
@ -1392,10 +1392,10 @@ exports.BattleScripts = {
} else if (hasMove['trick'] && hasMove['gyroball']) {
item = 'Iron Ball';
} else if (hasMove['trick'] || hasMove['switcheroo']) {
var randomNum = Math.random()*2;
if (counter.Physical >= 3 && (template.baseStats.spe >= 95 || randomNum>1)) {
var randomNum = Math.random() * 2;
if (counter.Physical >= 3 && (template.baseStats.spe >= 95 || randomNum > 1)) {
item = 'Choice Band';
} else if (counter.Special >= 3 && (template.baseStats.spe >= 95 || randomNum>1)) {
} else if (counter.Special >= 3 && (template.baseStats.spe >= 95 || randomNum > 1)) {
item = 'Choice Specs';
} else {
item = 'Choice Scarf';
@ -1463,7 +1463,7 @@ exports.BattleScripts = {
}
if ((hasMove['return'] || hasMove['hyperfang']) && !hasMove['facade']) {
// lol no
for (var j=0; j<moves.length; j++) {
for (var j = 0; j < moves.length; j++) {
if (moves[j] === 'Return' || moves[j] === 'HyperFang') {
moves[j] = 'Facade';
break;
@ -1476,13 +1476,13 @@ exports.BattleScripts = {
// less priority than if you'd had both
item = 'Light Clay';
} else if (counter.Physical >= 4 && !hasMove['fakeout'] && !hasMove['suckerpunch'] && !hasMove['flamecharge'] && !hasMove['rapidspin']) {
if (Math.random()*3 > 1) {
if (Math.random() * 3 > 1) {
item = 'Choice Band';
} else {
item = 'Expert Belt';
}
} else if (counter.Special >= 4) {
if (Math.random()*3 > 1) {
if (Math.random() * 3 > 1) {
item = 'Choice Specs';
} else {
item = 'Expert Belt';
@ -1497,7 +1497,7 @@ exports.BattleScripts = {
item = 'Focus Sash';
} else if (ability === 'Iron Barbs' || ability === 'Rough Skin') {
item = 'Rocky Helmet';
} else if ((template.baseStats.hp+75)*(template.baseStats.def+template.baseStats.spd+175) > 60000 || template.species === 'Skarmory' || template.species === 'Forretress') {
} else if ((template.baseStats.hp + 75) * (template.baseStats.def + template.baseStats.spd + 175) > 60000 || template.species === 'Skarmory' || template.species === 'Forretress') {
// skarmory and forretress get exceptions for their typing
item = 'Leftovers';
} else if ((counter.Physical + counter.Special >= 3 || counter.Special >= 3) && setupType && ability !== 'Sturdy') {
@ -1506,7 +1506,7 @@ exports.BattleScripts = {
item = 'Assault Vest';
} else if (counter.Physical + counter.Special >= 4) {
item = 'Expert Belt';
} else if (i===0 && ability !== 'Sturdy' && !counter['recoil'] && template.baseStats.def + template.baseStats.spd + template.baseStats.hp < 300) {
} else if (i === 0 && ability !== 'Sturdy' && !counter['recoil'] && template.baseStats.def + template.baseStats.spd + template.baseStats.hp < 300) {
item = 'Focus Sash';
} else if (hasMove['outrage']) {
item = 'Lum Berry';
@ -1593,7 +1593,7 @@ exports.BattleScripts = {
ivs: ivs,
item: item,
level: level,
shiny: (Math.random()*1024<=1)
shiny: (Math.random() * 1024 <= 1)
};
},
randomTeam: function(side) {
@ -1620,7 +1620,7 @@ exports.BattleScripts = {
var nuCount = 0;
var megaCount = 0;
for (var i=0; i<keys.length && pokemonLeft < 6; i++) {
for (var i = 0; i < keys.length && pokemonLeft < 6; i++) {
var template = this.getTemplate(keys[i]);
if (!template || !template.name || !template.types) continue;
var tier = template.tier;
@ -1628,27 +1628,27 @@ exports.BattleScripts = {
// 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.
if (tier === 'LC' && nuCount > 1) continue;
if ((tier === 'NFE' || tier === 'NU') && nuCount > 1 && Math.random()*5>1) continue;
if (tier === 'Uber' && uberCount > 1 && Math.random()*5>1) continue;
if ((tier === 'NFE' || tier === 'NU') && nuCount > 1 && Math.random() * 5 > 1) continue;
if (tier === 'Uber' && uberCount > 1 && Math.random() * 5 > 1) continue;
// CAPs have 20% the normal rate
if (tier === 'CAP' && Math.random()*5>1) continue;
if (tier === 'CAP' && Math.random() * 5 > 1) continue;
// Arceus formes have 1/18 the normal rate each (so Arceus as a whole has a normal rate)
if (keys[i].substr(0,6) === 'arceus' && Math.random()*18>1) continue;
if (keys[i].substr(0, 6) === 'arceus' && Math.random() * 18 > 1) continue;
// Basculin formes have 1/2 the normal rate each (so Basculin as a whole has a normal rate)
if (keys[i].substr(0,8) === 'basculin' && Math.random()*2>1) continue;
if (keys[i].substr(0, 8) === 'basculin' && Math.random() * 2 > 1) continue;
// Genesect formes have 1/5 the normal rate each (so Genesect as a whole has a normal rate)
if (keys[i].substr(0,8) === 'genesect' && Math.random()*5>1) continue;
if (keys[i].substr(0, 8) === 'genesect' && Math.random() * 5 > 1) continue;
// Gourgeist formes have 1/4 the normal rate each (so Gourgeist as a whole has a normal rate)
if (keys[i].substr(0,9) === 'gourgeist' && Math.random()*4>1) continue;
if (keys[i].substr(0, 9) === 'gourgeist' && Math.random() * 4 > 1) continue;
// Not available on XY
if (template.species === 'Pichu-Spiky-eared') continue;
// Limit 2 of any type
var types = template.types;
var skip = false;
for (var t=0; t<types.length; t++) {
if (typeCount[types[t]] > 1 && Math.random()*5>1) {
for (var t = 0; t < types.length; t++) {
if (typeCount[types[t]] > 1 && Math.random() * 5 > 1) {
skip = true;
break;
}
@ -1657,7 +1657,7 @@ exports.BattleScripts = {
if (potd && potd.name && potd.types) {
// The Pokemon of the Day belongs in slot 2
if (i===1) {
if (i === 1) {
template = potd;
if (template.species === 'Magikarp') {
template.viableMoves = {magikarpsrevenge:1, splash:1, bounce:1};
@ -1694,7 +1694,7 @@ exports.BattleScripts = {
pokemonLeft++;
// Now that our Pokemon has passed all checks, we can increment the type counter
for (var t=0; t<types.length; t++) {
for (var t = 0; t < types.length; t++) {
if (types[t] in typeCount) {
typeCount[types[t]]++;
} else {
@ -1724,7 +1724,7 @@ exports.BattleScripts = {
}
}
keys = keys.randomize();
keys.splice(1+Math.floor(Math.random()*5), 0, 'missingno');
keys.splice(1 + Math.floor(Math.random() * 5), 0, 'missingno');
// PotD stuff
var potd = {};
@ -1739,7 +1739,7 @@ exports.BattleScripts = {
var nuCount = 0;
var megaCount = 0;
for (var i=0; i<keys.length && pokemonLeft < 6; i++) {
for (var i = 0; i < keys.length && pokemonLeft < 6; i++) {
var template = this.getTemplate(keys[i]);
if (!template || !template.name || !template.types) continue;
var tier = template.tier;
@ -1747,25 +1747,25 @@ exports.BattleScripts = {
// 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.
if (tier === 'LC' && nuCount > 1) continue;
if ((tier === 'NFE' || tier === 'NU') && nuCount > 1 && Math.random()*5>1) continue;
if (tier === 'Uber' && uberCount > 1 && Math.random()*5>1) continue;
if ((tier === 'NFE' || tier === 'NU') && nuCount > 1 && Math.random() * 5 > 1) continue;
if (tier === 'Uber' && uberCount > 1 && Math.random() * 5 > 1) continue;
// Arceus formes have 1/18 the normal rate each (so Arceus as a whole has a normal rate)
if (keys[i].substr(0,6) === 'arceus' && Math.random()*18>1) continue;
if (keys[i].substr(0, 6) === 'arceus' && Math.random() * 18 > 1) continue;
// Basculin formes have 1/2 the normal rate each (so Basculin as a whole has a normal rate)
if (keys[i].substr(0,8) === 'basculin' && Math.random()*2>1) continue;
if (keys[i].substr(0, 8) === 'basculin' && Math.random() * 2 > 1) continue;
// Genesect formes have 1/5 the normal rate each (so Genesect as a whole has a normal rate)
if (keys[i].substr(0,8) === 'genesect' && Math.random()*5>1) continue;
if (keys[i].substr(0, 8) === 'genesect' && Math.random() * 5 > 1) continue;
// Gourgeist formes have 1/4 the normal rate each (so Gourgeist as a whole has a normal rate)
if (keys[i].substr(0,9) === 'gourgeist' && Math.random()*4>1) continue;
if (keys[i].substr(0, 9) === 'gourgeist' && Math.random() * 4 > 1) continue;
// Not available on XY
if (template.species === 'Pichu-Spiky-eared') continue;
// Limit 2 of any type
var types = template.types;
var skip = false;
for (var t=0; t<types.length; t++) {
if (typeCount[types[t]] > 1 && Math.random()*5>1) {
for (var t = 0; t < types.length; t++) {
if (typeCount[types[t]] > 1 && Math.random() * 5 > 1) {
skip = true;
break;
}
@ -1774,7 +1774,7 @@ exports.BattleScripts = {
if (potd && potd.name && potd.types) {
// The Pokemon of the Day belongs in slot 2
if (i===1) {
if (i === 1) {
template = potd;
if (template.species === 'Magikarp') {
template.viableMoves = {magikarpsrevenge:1, splash:1, bounce:1};
@ -1808,7 +1808,7 @@ exports.BattleScripts = {
pokemonLeft++;
// Now that our Pokemon has passed all checks, we can increment the type counter
for (var t=0; t<types.length; t++) {
for (var t = 0; t < types.length; t++) {
if (types[t] in typeCount) {
typeCount[types[t]]++;
} else {
@ -1850,24 +1850,24 @@ exports.BattleScripts = {
var baseFormes = {};
var megaCount = 0;
for (var i=0; i<keys.length && pokemonLeft < 6; i++) {
for (var i = 0; i < keys.length && pokemonLeft < 6; i++) {
var template = this.getTemplate(keys[i]);
if (!template || !template.name || !template.types) continue;
var tier = template.tier;
// Arceus formes have 1/18 the normal rate each (so Arceus as a whole has a normal rate)
if (keys[i].substr(0,6) === 'arceus' && Math.random()*18>1) continue;
if (keys[i].substr(0, 6) === 'arceus' && Math.random() * 18 > 1) continue;
// Basculin formes have 1/2 the normal rate each (so Basculin as a whole has a normal rate)
if (keys[i].substr(0,8) === 'basculin' && Math.random()*2>1) continue;
if (keys[i].substr(0, 8) === 'basculin' && Math.random() * 2 > 1) continue;
// Genesect formes have 1/5 the normal rate each (so Genesect as a whole has a normal rate)
if (keys[i].substr(0,8) === 'genesect' && Math.random()*5>1) continue;
if (keys[i].substr(0, 8) === 'genesect' && Math.random() * 5 > 1) continue;
// Not available on XY
if (template.species === 'Pichu-Spiky-eared') continue;
// Limit 2 of any type
var types = template.types;
var skip = false;
for (var t=0; t<types.length; t++) {
if (typeCount[types[t]] > 1 && Math.random()*5>1) {
for (var t = 0; t < types.length; t++) {
if (typeCount[types[t]] > 1 && Math.random() * 5 > 1) {
skip = true;
break;
}
@ -1877,7 +1877,7 @@ exports.BattleScripts = {
// More potd stuff
if (potd && potd.name && potd.types) {
// The Pokemon of the Day belongs in slot 2
if (i===1) {
if (i === 1) {
template = potd;
if (template.species === 'Magikarp') {
template.viableMoves = {magikarpsrevenge:1, splash:1, bounce:1};
@ -1911,7 +1911,7 @@ exports.BattleScripts = {
pokemonLeft++;
// Now that our Pokemon has passed all checks, we can increment the type counter
for (var t=0; t<types.length; t++) {
for (var t = 0; t < types.length; t++) {
if (types[t] in typeCount) {
typeCount[types[t]]++;
} else {
@ -1933,7 +1933,7 @@ exports.BattleScripts = {
if (!template.exists || (!template.viableDoublesMoves && !template.viableMoves && !template.learnset)) {
template = this.getTemplate('unown');
var stack = 'Template incompatible with random battles: '+name;
var stack = 'Template incompatible with random battles: ' + name;
var fakeErr = {stack: stack};
require('../crashlogger.js')(fakeErr, 'The randbat set generator');
}
@ -1943,7 +1943,7 @@ exports.BattleScripts = {
// Delete this once all Pokémon have viable doubles sets
var hasProtectingMove = false;
for (var i = 0; i < moveKeys.length && !hasProtectingMove; i++) {
if (moveKeys[i] in {'protect':1,'detect':1,'kingsshield':1,'spikyshield':1}) hasProtectingMove = true;
if (moveKeys[i] in {'protect':1, 'detect':1, 'kingsshield':1, 'spikyshield':1}) hasProtectingMove = true;
}
if (!hasProtectingMove) {
if (template.learnset && 'protect' in template.learnset) moveKeys.push('protect');
@ -1982,13 +1982,13 @@ exports.BattleScripts = {
var counter = {};
var setupType = '';
var j=0;
var j = 0;
do {
// Choose next 4 moves from learnset/viable moves and add them to moves list:
while (moves.length<4 && j<moveKeys.length) {
while (moves.length < 4 && j < moveKeys.length) {
var moveid = toId(moveKeys[j]);
j++;
if (moveid.substr(0,11) === 'hiddenpower') {
if (moveid.substr(0, 11) === 'hiddenpower') {
if (!hasMove['hiddenpower']) {
hasMove['hiddenpower'] = true;
} else {
@ -2009,7 +2009,7 @@ 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++) {
for (var k = 0; k < moves.length; k++) {
var move = this.getMove(moves[k]);
var moveid = move.id;
// Keep track of all moves we have:
@ -2112,7 +2112,7 @@ exports.BattleScripts = {
}
// Iterate through the moves again, this time to cull them:
for (var k=0; k<moves.length; k++) {
for (var k = 0; k < moves.length; k++) {
var moveid = moves[k];
var move = this.getMove(moveid);
var rejected = false;
@ -2148,7 +2148,7 @@ exports.BattleScripts = {
isSetup = true;
break;
case 'shellsmash': case 'growth': case 'workup':
if (counter.Physical+counter.Special < 2 && !hasMove['batonpass']) rejected = true;
if (counter.Physical + counter.Special < 2 && !hasMove['batonpass']) rejected = true;
if (setupType !== 'Mixed' || counter['mixedsetup'] > 1) rejected = true;
isSetup = true;
break;
@ -2346,8 +2346,8 @@ exports.BattleScripts = {
}
// Remove rejected moves from the move list.
if (rejected && j<moveKeys.length) {
moves.splice(k,1);
if (rejected && j < moveKeys.length) {
moves.splice(k, 1);
break;
}
@ -2359,12 +2359,12 @@ exports.BattleScripts = {
}
}
}
if (j<moveKeys.length && moves.length === 4) {
if (j < moveKeys.length && moves.length === 4) {
// Move post-processing:
if (damagingMoves.length===0) {
if (damagingMoves.length === 0) {
// A set shouldn't have no attacking moves
moves.splice(Math.floor(Math.random()*moves.length),1);
} else if (damagingMoves.length===1) {
moves.splice(Math.floor(Math.random() * moves.length), 1);
} else if (damagingMoves.length === 1) {
// Night Shade, Seismic Toss, etc. don't count:
if (!damagingMoves[0].damage) {
var damagingid = damagingMoves[0].id;
@ -2372,11 +2372,11 @@ exports.BattleScripts = {
var 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'] && Math.random()*2>1) replace = true;
if (!hasMove['encore'] && Math.random() * 2 > 1) replace = true;
} else if (damagingid === 'focuspunch') {
// Focus Punch is a bad idea without a sub:
if (!hasMove['substitute']) replace = true;
} else if (damagingid.substr(0,11) === 'hiddenpower' && damagingType === 'Ice') {
} else if (damagingid.substr(0, 11) === 'hiddenpower' && damagingType === 'Ice') {
// Mono-HP-Ice is never acceptable.
replace = true;
} else {
@ -2392,9 +2392,9 @@ exports.BattleScripts = {
}
}
}
if (replace) moves.splice(damagingMoveIndex[damagingid],1);
if (replace) moves.splice(damagingMoveIndex[damagingid], 1);
}
} else if (damagingMoves.length===2) {
} 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('/');
@ -2404,20 +2404,20 @@ exports.BattleScripts = {
} else {
rejectCombo = false;
}
if (rejectCombo) moves.splice(Math.floor(Math.random()*moves.length),1);
if (rejectCombo) moves.splice(Math.floor(Math.random() * moves.length), 1);
} 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++) {
for (var l = 0; l < damagingMoves.length; l++) {
if (hasStab[damagingMoves[l].type]) {
isStab = true;
break;
}
}
if (!isStab) moves.splice(Math.floor(Math.random()*moves.length),1);
if (!isStab) moves.splice(Math.floor(Math.random() * moves.length), 1);
}
}
} while (moves.length<4 && j<moveKeys.length);
} while (moves.length < 4 && j < moveKeys.length);
{
var abilities = [template.abilities['0']];
@ -2427,7 +2427,7 @@ exports.BattleScripts = {
if (template.abilities['H']) {
abilities.push(template.abilities['H']);
}
abilities.sort(function(a,b){
abilities.sort(function(a, b){
return this.getAbility(b).rating - this.getAbility(a).rating;
}.bind(this));
var ability0 = this.getAbility(abilities[0]);
@ -2436,11 +2436,11 @@ exports.BattleScripts = {
if (abilities[1]) {
if (ability0.rating <= ability1.rating) {
if (Math.random()*2<1) {
if (Math.random() * 2 < 1) {
ability = ability1.name;
}
} else if (ability0.rating - 0.6 <= ability1.rating) {
if (Math.random()*3<1) {
if (Math.random() * 3 < 1) {
ability = ability1.name;
}
}
@ -2580,10 +2580,10 @@ exports.BattleScripts = {
} else if (hasMove['trick'] && hasMove['gyroball']) {
item = 'Iron Ball';
} else if (hasMove['trick'] || hasMove['switcheroo']) {
var randomNum = Math.random()*2;
if (counter.Physical >= 3 && (template.baseStats.spe >= 95 || randomNum>1)) {
var randomNum = Math.random() * 2;
if (counter.Physical >= 3 && (template.baseStats.spe >= 95 || randomNum > 1)) {
item = 'Choice Band';
} else if (counter.Special >= 3 && (template.baseStats.spe >= 95 || randomNum>1)) {
} else if (counter.Special >= 3 && (template.baseStats.spe >= 95 || randomNum > 1)) {
item = 'Choice Specs';
} else {
item = 'Choice Scarf';
@ -2657,7 +2657,7 @@ exports.BattleScripts = {
}
if ((hasMove['return'] || hasMove['hyperfang']) && !hasMove['facade']) {
// lol no
for (var j=0; j<moves.length; j++) {
for (var j = 0; j < moves.length; j++) {
if (moves[j] === 'Return' || moves[j] === 'HyperFang') {
moves[j] = 'Facade';
break;
@ -2685,7 +2685,7 @@ exports.BattleScripts = {
item = 'Focus Sash';
} else if (ability === 'Iron Barbs' || ability === 'Rough Skin') {
item = 'Rocky Helmet';
} else if ((template.baseStats.hp+75)*(template.baseStats.def+template.baseStats.spd+175) > 60000 || template.species === 'Skarmory' || template.species === 'Forretress') {
} else if ((template.baseStats.hp + 75) * (template.baseStats.def + template.baseStats.spd + 175) > 60000 || template.species === 'Skarmory' || template.species === 'Forretress') {
// skarmory and forretress get exceptions for their typing
item = 'Sitrus Berry';
} else if (counter.Physical + counter.Special >= 3 && setupType) {

View File

@ -15,7 +15,7 @@ exports.BattleStatuses = {
},
onResidualOrder: 9,
onResidual: function(pokemon) {
this.damage(pokemon.maxhp/8);
this.damage(pokemon.maxhp / 8);
}
},
par: {
@ -41,7 +41,7 @@ exports.BattleStatuses = {
onStart: function(target) {
this.add('-status', target, 'slp');
// 1-3 turns
this.effectData.startTime = this.random(2,5);
this.effectData.startTime = this.random(2, 5);
this.effectData.time = this.effectData.startTime;
},
onBeforeMovePriority: 2,
@ -88,7 +88,7 @@ exports.BattleStatuses = {
},
onResidualOrder: 9,
onResidual: function(pokemon) {
this.damage(pokemon.maxhp/8);
this.damage(pokemon.maxhp / 8);
}
},
tox: {
@ -109,7 +109,7 @@ exports.BattleStatuses = {
if (this.effectData.stage < 15) {
this.effectData.stage++;
}
this.damage(this.clampIntRange(pokemon.maxhp/16, 1)*this.effectData.stage);
this.damage(this.clampIntRange(pokemon.maxhp / 16, 1) * this.effectData.stage);
}
},
confusion: {
@ -118,7 +118,7 @@ exports.BattleStatuses = {
var result = this.runEvent('TryConfusion', target, source, sourceEffect);
if (!result) return result;
this.add('-start', target, 'confusion');
this.effectData.time = this.random(2,6);
this.effectData.time = this.random(2, 6);
},
onEnd: function(target) {
this.add('-end', target, 'confusion');
@ -133,7 +133,7 @@ exports.BattleStatuses = {
if (this.random(2) === 0) {
return;
}
this.directDamage(this.getDamage(pokemon,pokemon,40));
this.directDamage(this.getDamage(pokemon, pokemon, 40));
return false;
}
},
@ -165,10 +165,10 @@ exports.BattleStatuses = {
duration: 5,
durationCallback: function(target, source) {
if (source.item === 'gripclaw') return 8;
return this.random(5,7);
return this.random(5, 7);
},
onStart: function(pokemon, source) {
this.add('-activate', pokemon, 'move: ' +this.effectData.sourceEffect, '[of] '+source);
this.add('-activate', pokemon, 'move: ' +this.effectData.sourceEffect, '[of] ' + source);
},
onResidualOrder: 11,
onResidual: function(pokemon) {
@ -177,9 +177,9 @@ exports.BattleStatuses = {
return;
}
if (this.effectData.source.item === 'bindingband') {
this.damage(pokemon.maxhp/6);
this.damage(pokemon.maxhp / 6);
} else {
this.damage(pokemon.maxhp/8);
this.damage(pokemon.maxhp / 8);
}
},
onEnd: function(pokemon) {
@ -200,7 +200,7 @@ exports.BattleStatuses = {
this.effectData.trueDuration--;
},
onStart: function(target, source, effect) {
this.effectData.trueDuration = this.random(2,4);
this.effectData.trueDuration = this.random(2, 4);
this.effectData.move = effect.id;
},
onRestart: function() {
@ -251,7 +251,7 @@ exports.BattleStatuses = {
return;
}
var moves = pokemon.moveset;
for (var i=0; i<moves.length; i++) {
for (var i = 0; i < moves.length; i++) {
if (moves[i].id !== this.effectData.move) {
moves[i].disabled = true;
}
@ -271,14 +271,14 @@ exports.BattleStatuses = {
// this is a side condition
onStart: function(side) {
this.effectData.positions = [];
for (var i=0; i<side.active.length; i++) {
for (var 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++) {
for (var i = 0; i < side.active.length; i++) {
var posData = this.effectData.positions[i];
if (!posData) continue;
@ -293,12 +293,12 @@ exports.BattleStatuses = {
var target = side.foe.active[posData.targetPosition];
var move = this.getMove(posData.move);
if (target.fainted) {
this.add('-hint', ''+move.name+' did not hit because the target is fainted.');
this.add('-hint', '' + move.name + ' did not hit because the target is fainted.');
this.effectData.positions[i] = null;
continue;
}
this.add('-message', ''+move.name+' hit! (placeholder)');
this.add('-message', '' + move.name + ' hit! (placeholder)');
target.removeVolatile('Protect');
target.removeVolatile('Endure');
@ -326,7 +326,7 @@ exports.BattleStatuses = {
// this.effectData.counter should never be undefined here.
// However, just in case, use 1 if it is undefined.
var counter = this.effectData.counter || 1;
this.debug("Success chance: "+Math.round(100/counter)+"%");
this.debug("Success chance: " + Math.round(100 / counter) + "%");
return (this.random(counter) === 0);
},
onRestart: function() {
@ -370,7 +370,7 @@ exports.BattleStatuses = {
onStart: function(battle, source, effect) {
if (effect && effect.effectType === 'Ability' && this.gen <= 5) {
this.effectData.duration = 0;
this.add('-weather', 'RainDance', '[from] ability: '+effect, '[of] '+source);
this.add('-weather', 'RainDance', '[from] ability: ' + effect, '[of] ' + source);
} else {
this.add('-weather', 'RainDance');
}
@ -406,7 +406,7 @@ exports.BattleStatuses = {
onStart: function(battle, source, effect) {
if (effect && effect.effectType === 'Ability' && this.gen <= 5) {
this.effectData.duration = 0;
this.add('-weather', 'SunnyDay', '[from] ability: '+effect, '[of] '+source);
this.add('-weather', 'SunnyDay', '[from] ability: ' + effect, '[of] ' + source);
} else {
this.add('-weather', 'SunnyDay');
}
@ -443,7 +443,7 @@ exports.BattleStatuses = {
onStart: function(battle, source, effect) {
if (effect && effect.effectType === 'Ability' && this.gen <= 5) {
this.effectData.duration = 0;
this.add('-weather', 'Sandstorm', '[from] ability: '+effect, '[of] '+source);
this.add('-weather', 'Sandstorm', '[from] ability: ' + effect, '[of] ' + source);
} else {
this.add('-weather', 'Sandstorm');
}
@ -454,7 +454,7 @@ exports.BattleStatuses = {
if (this.isWeather('sandstorm')) this.eachEvent('Weather');
},
onWeather: function(target) {
this.damage(target.maxhp/16);
this.damage(target.maxhp / 16);
},
onEnd: function() {
this.add('-weather', 'none');
@ -472,7 +472,7 @@ exports.BattleStatuses = {
onStart: function(battle, source, effect) {
if (effect && effect.effectType === 'Ability' && this.gen <= 5) {
this.effectData.duration = 0;
this.add('-weather', 'Hail', '[from] ability: '+effect, '[of] '+source);
this.add('-weather', 'Hail', '[from] ability: ' + effect, '[of] ' + source);
} else {
this.add('-weather', 'Hail');
}
@ -483,7 +483,7 @@ exports.BattleStatuses = {
if (this.isWeather('hail')) this.eachEvent('Weather');
},
onWeather: function(target) {
this.damage(target.maxhp/16);
this.damage(target.maxhp / 16);
},
onEnd: function() {
this.add('-weather', 'none');

View File

@ -20,7 +20,7 @@ exports.BattleTypeChart = {
"Steel": 0,
"Water": 0
},
HPivs: {"atk":30,"def":30,"spd":30}
HPivs: {"atk":30, "def":30, "spd":30}
},
"Dark": {
damageTaken: {
@ -135,7 +135,7 @@ exports.BattleTypeChart = {
"Steel": 0,
"Water": 0
},
HPivs: {"def":30,"spa":30,"spd":30,"spe":30}
HPivs: {"def":30, "spa":30, "spd":30, "spe":30}
},
"Fire": {
damageTaken: {
@ -159,7 +159,7 @@ exports.BattleTypeChart = {
"Steel": 2,
"Water": 1
},
HPivs: {"atk":30,"spa":30,"spe":30}
HPivs: {"atk":30, "spa":30, "spe":30}
},
"Flying": {
damageTaken: {
@ -182,7 +182,7 @@ exports.BattleTypeChart = {
"Steel": 0,
"Water": 0
},
HPivs: {"hp":30,"atk":30,"def":30,"spa":30,"spd":30}
HPivs: {"hp":30, "atk":30, "def":30, "spa":30, "spd":30}
},
"Ghost": {
damageTaken: {
@ -206,7 +206,7 @@ exports.BattleTypeChart = {
"Steel": 0,
"Water": 0
},
HPivs: {"def":30,"spd":30}
HPivs: {"def":30, "spd":30}
},
"Grass": {
damageTaken: {
@ -230,7 +230,7 @@ exports.BattleTypeChart = {
"Steel": 0,
"Water": 2
},
HPivs: {"atk":30,"spa":30}
HPivs: {"atk":30, "spa":30}
},
"Ground": {
damageTaken: {
@ -254,7 +254,7 @@ exports.BattleTypeChart = {
"Steel": 0,
"Water": 1
},
HPivs: {"spa":30,"spd":30}
HPivs: {"spa":30, "spd":30}
},
"Ice": {
damageTaken: {
@ -279,7 +279,7 @@ exports.BattleTypeChart = {
"Steel": 1,
"Water": 0
},
HPivs: {"atk":30,"def":30}
HPivs: {"atk":30, "def":30}
},
"Normal": {
damageTaken: {
@ -326,7 +326,7 @@ exports.BattleTypeChart = {
"Steel": 0,
"Water": 0
},
HPivs: {"def":30,"spa":30,"spd":30}
HPivs: {"def":30, "spa":30, "spd":30}
},
"Psychic": {
damageTaken: {
@ -349,7 +349,7 @@ exports.BattleTypeChart = {
"Steel": 0,
"Water": 0
},
HPivs: {"atk":30,"spe":30}
HPivs: {"atk":30, "spe":30}
},
"Rock": {
damageTaken: {
@ -373,7 +373,7 @@ exports.BattleTypeChart = {
"Steel": 1,
"Water": 1
},
HPivs: {"def":30,"spd":30,"spe":30}
HPivs: {"def":30, "spd":30, "spe":30}
},
"Steel": {
damageTaken: {
@ -422,6 +422,6 @@ exports.BattleTypeChart = {
"Steel": 2,
"Water": 2
},
HPivs: {"atk":30,"def":30,"spa":30}
HPivs: {"atk":30, "def":30, "spa":30}
}
};

View File

@ -32,7 +32,7 @@ exports.query = function queryDnsbl(ip, callback) {
callback(dnsblCache[ip]);
return;
}
var reversedIpDot = ip.split('.').reverse().join('.')+'.';
var reversedIpDot = ip.split('.').reverse().join('.') + '.';
queryDnsblLoop(ip, callback, reversedIpDot, 0);
};
@ -43,13 +43,13 @@ function queryDnsblLoop(ip, callback, reversedIpDot, index) {
return;
}
var blocklist = BLOCKLISTS[index];
dns.resolve4(reversedIpDot+blocklist, function(err, addresses) {
dns.resolve4(reversedIpDot + blocklist, function(err, addresses) {
if (!err) {
// blocked
callback(dnsblCache[ip] = blocklist);
} else {
// not blocked, try next blocklist
queryDnsblLoop(ip, callback, reversedIpDot, index+1);
queryDnsblLoop(ip, callback, reversedIpDot, index + 1);
}
});
}

View File

@ -71,10 +71,10 @@ module.exports = (function() {
var dataString = '';
if (data) {
for (var i in data) {
dataString += '&'+i+'='+encodeURIComponent(''+data[i]);
dataString += '&' + i + '=' + encodeURIComponent('' + data[i]);
}
}
var req = http.get(url.parse(this.uri+'action.php?act='+action+'&serverid='+Config.serverid+'&servertoken='+Config.servertoken+'&nocache='+new Date().getTime()+dataString), function(res) {
var req = http.get(url.parse(this.uri + 'action.php?act=' + action + '&serverid=' + Config.serverid + '&servertoken=' + Config.servertoken + '&nocache=' + new Date().getTime() + dataString), function(res) {
var buffer = '';
res.setEncoding('utf8');
@ -132,15 +132,15 @@ module.exports = (function() {
if (!requests.length) return;
var requestCallbacks = [];
for (var i=0,len=requests.length; i<len; i++) {
for (var i = 0, len = requests.length; i < len; i++) {
var request = requests[i];
requestCallbacks[i] = request.callback;
delete request.callback;
}
this.requestStart(requests.length);
var postData = 'serverid='+Config.serverid+'&servertoken='+Config.servertoken+'&nocache='+new Date().getTime()+'&json='+encodeURIComponent(JSON.stringify(requests))+'\n';
var requestOptions = url.parse(this.uri+'action.php');
var postData = 'serverid=' + Config.serverid + '&servertoken=' + Config.servertoken + '&nocache=' + new Date().getTime() + '&json=' + encodeURIComponent(JSON.stringify(requests)) + '\n';
var requestOptions = url.parse(this.uri + 'action.php');
requestOptions.method = 'post';
requestOptions.headers = {
'Content-Type': 'application/x-www-form-urlencoded',
@ -154,7 +154,7 @@ module.exports = (function() {
self.requestTimeoutTimer = null;
}
req.abort();
for (var i=0,len=requestCallbacks.length; i<len; i++) {
for (var i = 0, len = requestCallbacks.length; i < len; i++) {
requestCallbacks[i](null, null, error);
}
self.requestEnd();
@ -181,12 +181,12 @@ module.exports = (function() {
clearTimeout(self.requestTimeoutTimer);
self.requestTimeoutTimer = null;
}
//console.log('RESPONSE: '+buffer);
//console.log('RESPONSE: ' + buffer);
var data = null;
try {
data = parseJSON(buffer);
} catch (e) {}
for (var i=0,len=requestCallbacks.length; i<len; i++) {
for (var i = 0, len = requestCallbacks.length; i < len; i++) {
if (data) {
requestCallbacks[i](data[i], res.statusCode);
} else {
@ -211,17 +211,17 @@ module.exports = (function() {
};
LoginServer.prototype.requestStart = function(size) {
this.lastRequest = Date.now();
this.requestLog += ' | '+size+' requests: ';
this.requestLog += ' | ' + size + ' requests: ';
this.openRequests++;
};
LoginServer.prototype.requestEnd = function() {
this.openRequests = 0;
this.requestLog += ''+(Date.now() - this.lastRequest).duration();
this.requestLog += '' + (Date.now() - this.lastRequest).duration();
this.requestLog = this.requestLog.substr(-1000);
this.requestTimerPoke();
};
LoginServer.prototype.getLog = function() {
return this.requestLog + (this.lastRequest?' ('+(Date.now() - this.lastRequest).duration()+' since last request)':'');
return this.requestLog + (this.lastRequest ? ' (' + (Date.now() - this.lastRequest).duration() + ' since last request)' : '');
};
return LoginServer;

View File

@ -83,10 +83,10 @@ exports.BattleMovedex = {
}
this.add('-end', pokemon, 'Bide');
var target = this.effectData.sourceSide.active[this.effectData.sourcePosition];
this.moveHit(target, pokemon, 'bide', {damage: this.effectData.totalDamage*2});
this.moveHit(target, pokemon, 'bide', {damage: this.effectData.totalDamage * 2});
return false;
}
this.add('-message', pokemon.name+' is storing energy! (placeholder)');
this.add('-message', pokemon.name + ' is storing energy! (placeholder)');
return false;
},
onModifyPokemon: function(pokemon) {
@ -94,7 +94,7 @@ exports.BattleMovedex = {
return;
}
var moves = pokemon.moveset;
for (var i=0; i<moves.length; i++) {
for (var i = 0; i < moves.length; i++) {
if (moves[i].id !== 'bide') {
moves[i].disabled = true;
}
@ -180,17 +180,17 @@ exports.BattleMovedex = {
noCopy: true,
onStart: function(target, source) {
this.effectData.typesData = [];
for (var i=0, l=target.typesData.length; i<l; i++) {
for (var 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);
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 (var 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);
this.add('-start', source, 'typechange', target.getTypes(true).join(', '), '[from] move: Conversion', '[of] ' + target);
},
onModifyPokemon: function(pokemon) {
pokemon.typesData = this.effectData.typesData;
@ -276,7 +276,7 @@ exports.BattleMovedex = {
},
onModifyPokemon: function(pokemon) {
var moves = pokemon.moveset;
for (var i=0; i<moves.length; i++) {
for (var i = 0; i < moves.length; i++) {
if (moves[i].id === this.effectData.move) {
moves[i].disabled = true;
}
@ -295,7 +295,7 @@ exports.BattleMovedex = {
basePower: 100,
desc: "Deals damage to the target. If the target lost HP, the user takes recoil damage equal to 25% that HP, rounded half up, but not less than 1HP.",
shortDesc: "Has 25% recoil.",
recoil: [25,100]
recoil: [25, 100]
},
explosion: {
inherit: true,
@ -371,7 +371,7 @@ exports.BattleMovedex = {
volatileStatus: 'focusenergy',
effect: {
onStart: function(pokemon) {
this.add('-start',pokemon,'move: Focus Energy');
this.add('-start', pokemon, 'move: Focus Energy');
},
onModifyMove: function(move) {
move.critRatio = -3;
@ -404,9 +404,9 @@ exports.BattleMovedex = {
shortDesc: "Eliminates all stat changes and status.",
onHitField: 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 hasTox = (this.sides[i].active[j].status == 'tox');
for (var i = 0; i < this.sides.length; i++) {
for (var j = 0; j < this.sides[i].active.length; j++) {
var hasTox = (this.sides[i].active[j].status === 'tox');
this.sides[i].active[j].clearBoosts();
if (this.sides[i].active[j].id !== source.id) {
// Clears the status from the opponent
@ -464,9 +464,9 @@ exports.BattleMovedex = {
if (target.newlySwitched && target.speed <= source.speed) {
if (target.status === 'tox') {
// Stage plus one since leech seed runs before Toxic
var toLeech = this.clampIntRange(target.maxhp/16, 1) * (target.statusData.stage + 1);
var toLeech = this.clampIntRange(target.maxhp / 16, 1) * (target.statusData.stage + 1);
} else {
var toLeech = this.clampIntRange(target.maxhp/16, 1);
var toLeech = this.clampIntRange(target.maxhp / 16, 1);
}
var damage = this.damage(toLeech, target, source, 'move: Leech Seed');
if (damage) {
@ -487,9 +487,9 @@ exports.BattleMovedex = {
// We check if target has Toxic to increase leeched damage
if (pokemon.status === 'tox') {
// Stage plus one since leech seed runs before Toxic
var toLeech = this.clampIntRange(pokemon.maxhp/16, 1) * (pokemon.statusData.stage + 1);
var toLeech = this.clampIntRange(pokemon.maxhp / 16, 1) * (pokemon.statusData.stage + 1);
} else {
var toLeech = this.clampIntRange(pokemon.maxhp/16, 1);
var toLeech = this.clampIntRange(pokemon.maxhp / 16, 1);
}
var damage = this.damage(toLeech, pokemon, target);
if (damage) {
@ -566,7 +566,7 @@ exports.BattleMovedex = {
if (moveslot === -1) return false;
var moves = target.moves;
moves = moves.randomize();
for (var i=0; i<moves.length; i++) {
for (var i = 0; i < moves.length; i++) {
if (!(moves[i] in disallowedMoves)) {
var move = moves[i];
break;
@ -788,12 +788,12 @@ exports.BattleMovedex = {
priority: 0,
isContact: true,
beforeMoveCallback: function(pokemon) {
this.add('-message', pokemon.name+' has no moves left! (placeholder)');
this.add('-message', pokemon.name + ' has no moves left! (placeholder)');
},
onModifyMove: function(move) {
move.type = '???';
},
recoil: [1,2],
recoil: [1, 2],
secondary: false,
target: "normal",
type: "Normal"
@ -819,8 +819,8 @@ exports.BattleMovedex = {
}
// We only prevent when hp is less than one quarter.
// If you use substitute at exactly one quarter, you faint.
if (target.hp === target.maxhp/4) target.faint();
if (target.hp < target.maxhp/4) {
if (target.hp === target.maxhp / 4) target.faint();
if (target.hp < target.maxhp / 4) {
this.add('-fail', target, 'move: Substitute', '[weak]');
return null;
}
@ -834,7 +834,7 @@ exports.BattleMovedex = {
effect: {
onStart: function(target) {
this.add('-start', target, 'Substitute');
this.effectData.hp = Math.floor(target.maxhp/4);
this.effectData.hp = Math.floor(target.maxhp / 4);
delete target.volatiles['partiallytrapped'];
},
onTryHitPriority: -1,

View File

@ -7,20 +7,20 @@ exports.BattleFormats = {
if (set.species === set.name) delete set.name;
if (template.gen > this.gen) {
problems.push(set.species+' does not exist in gen '+this.gen+'.');
problems.push(set.species + ' does not exist in gen ' + this.gen + '.');
} else if (template.isNonstandard) {
problems.push(set.species+' is not a real Pokemon.');
problems.push(set.species + ' is not a real Pokemon.');
}
if (set.moves) for (var i=0; i<set.moves.length; i++) {
if (set.moves) for (var i = 0; i < set.moves.length; i++) {
var move = this.getMove(set.moves[i]);
if (move.gen > this.gen) {
problems.push(move.name+' does not exist in gen '+this.gen+'.');
problems.push(move.name + ' does not exist in gen ' + this.gen + '.');
} else if (move.isNonstandard) {
problems.push(move.name+' is not a real move.');
problems.push(move.name + ' is not a real move.');
}
}
if (set.moves && set.moves.length > 4) {
problems.push((set.name||set.species) + ' has more than four moves.');
problems.push((set.name || set.species) + ' has more than four moves.');
}
// Let's manually delete items.

View File

@ -54,7 +54,7 @@ exports.BattleScripts = {
this.setActiveMove(move, pokemon, target);
if (pokemon.movedThisTurn || !this.runEvent('BeforeMove', pokemon, target, move)) {
this.debug(''+pokemon.id+' move interrupted; movedThisTurn: '+pokemon.movedThisTurn);
this.debug('' + pokemon.id + ' move interrupted; movedThisTurn: ' + pokemon.movedThisTurn);
this.clearActiveMove(true);
// This is only run for sleep
this.runEvent('AfterMoveSelf', pokemon, target, move);
@ -97,7 +97,7 @@ exports.BattleScripts = {
if (pokemon.volatiles['partialtrappinglock'].locked !== target && target !== pokemon) {
// The target switched, therefor, we must re-roll the duration
var roll = this.random(6);
var duration = [2,2,3,3,4,5][roll];
var duration = [2, 2, 3, 3, 4, 5][roll];
pokemon.volatiles['partialtrappinglock'].duration = duration;
pokemon.volatiles['partialtrappinglock'].locked = target;
// Duration reset thus partially trapped at 2 always
@ -160,8 +160,8 @@ exports.BattleScripts = {
var movename = move.name;
if (move.id === 'hiddenpower') movename = 'Hidden Power';
if (sourceEffect) attrs += '|[from]'+this.getEffect(sourceEffect);
this.addMove('move', pokemon, movename, target+attrs);
if (sourceEffect) attrs += '|[from]' + this.getEffect(sourceEffect);
this.addMove('move', pokemon, movename, target + attrs);
if (!this.singleEvent('Try', move, null, pokemon, target, move)) {
return true;
@ -198,14 +198,14 @@ exports.BattleScripts = {
return true;
},
rollMoveHit: function(target, pokemon, move, spreadHit) {
var boostTable = [1, 4/3, 5/3, 2, 7/3, 8/3, 3];
var boostTable = [1, 4 / 3, 5 / 3, 2, 7 / 3, 8 / 3, 3];
var doSelfDestruct = true;
var damage = 0;
// Calculate true accuracy
var accuracy = move.accuracy;
if (accuracy !== true) {
accuracy = Math.floor(accuracy*255/100);
accuracy = Math.floor(accuracy * 255 / 100);
}
// Partial trapping moves: true accuracy while it lasts
@ -255,13 +255,13 @@ exports.BattleScripts = {
var roll = this.random(6);
hits = [2, 2, 3, 3, 4, 5][roll];
} else {
hits = this.random(hits[0], hits[1]+1);
hits = this.random(hits[0], hits[1] + 1);
}
}
hits = Math.floor(hits);
// In gen 1, all the hits have the same damage for multihits move
var moveDamage = 0;
for (var i=0; i<hits && target.hp && pokemon.hp; i++) {
for (var i = 0; i < hits && target.hp && pokemon.hp; i++) {
if (i === 0) {
// First hit, we calculate
moveDamage = this.moveHit(target, pokemon, move);
@ -520,7 +520,7 @@ exports.BattleScripts = {
var effectChance;
for (var i = 0; i < moveData.secondaries.length; i++) {
secondaryRoll = this.random(256);
effectChance = Math.floor(moveData.secondaries[i].chance*255/100);
effectChance = Math.floor(moveData.secondaries[i].chance * 255 / 100);
if (typeof moveData.secondaries[i].chance === 'undefined' || secondaryRoll < effectChance) {
this.moveHit(target, pokemon, move, moveData.secondaries[i], true, isSelf);
}
@ -727,7 +727,7 @@ exports.BattleScripts = {
}
// Randomizer, it's a number between 217 and 255
var randFactor = Math.floor(Math.random()*39)+217;
var randFactor = Math.floor(Math.random() * 39) + 217;
baseDamage *= Math.floor(randFactor * 100 / 255) / 100;
// If damage is less than 1, we return 1
@ -775,7 +775,7 @@ exports.BattleScripts = {
if (effect.effectType === 'Move') {
this.add(msg, target, i, boost[i]);
} else {
this.add(msg, target, i, boost[i], '[from] '+effect.fullname);
this.add(msg, target, i, boost[i], '[from] ' + effect.fullname);
}
this.runEvent('AfterEachBoost', target, source, effect, currentBoost);
}
@ -807,15 +807,15 @@ exports.BattleScripts = {
if (name === 'tox') name = 'psn';
switch (effect.id) {
case 'partiallytrapped':
this.add('-damage', target, target.getHealth, '[from] '+this.effectData.sourceEffect.fullname, '[partiallytrapped]');
this.add('-damage', target, target.getHealth, '[from] ' + this.effectData.sourceEffect.fullname, '[partiallytrapped]');
break;
default:
if (effect.effectType === 'Move') {
this.add('-damage', target, target.getHealth);
} else if (source && source !== target) {
this.add('-damage', target, target.getHealth, '[from] '+effect.fullname, '[of] '+source);
this.add('-damage', target, target.getHealth, '[from] ' + effect.fullname, '[of] ' + source);
} else {
this.add('-damage', target, target.getHealth, '[from] '+name);
this.add('-damage', target, target.getHealth, '[from] ' + name);
}
break;
}
@ -844,10 +844,10 @@ exports.BattleScripts = {
//pick six random pokmeon--no repeats, even among formes
//also need to either normalize for formes or select formes at random
//unreleased are okay. No CAP for now, but maybe at some later date
for (var i=0; i<6; i++)
for (var i = 0; i < 6; i++)
{
while (true) {
var x=Math.floor(Math.random()*150)+1;
var x = Math.floor(Math.random() * 150) + 1;
if (teamdexno.indexOf(x) === -1) {
teamdexno.push(x);
break;
@ -855,7 +855,7 @@ exports.BattleScripts = {
}
}
for (var i=0; i<6; i++) {
for (var i = 0; i < 6; i++) {
//choose forme
var formes = [];
@ -873,22 +873,22 @@ exports.BattleScripts = {
var stats = template.baseStats;
// Modified base stat total assumes 30 IVs, 255 EVs in every stat
var 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 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
var 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);
mbst += Math.floor(((stats["atk"]*2+30+63+100)*level/100+5)*level/100); //since damage is roughly proportional to lvl
mbst += Math.floor((stats["def"]*2+30+63+100)*level/100+5);
mbst += Math.floor(((stats["spa"]*2+30+63+100)*level/100+5)*level/100);
mbst += Math.floor((stats["spd"]*2+30+63+100)*level/100+5);
mbst += Math.floor((stats["spe"]*2+30+63+100)*level/100+5);
mbst = Math.floor((stats["hp"] * 2 + 30 + 63 + 100) * level / 100 + 10);
mbst += Math.floor(((stats["atk"] * 2 + 30 + 63 + 100) * level / 100 + 5) * level / 100); //since damage is roughly proportional to lvl
mbst += Math.floor((stats["def"] * 2 + 30 + 63 + 100) * level / 100 + 5);
mbst += Math.floor(((stats["spa"] * 2 + 30 + 63 + 100) * level / 100 + 5) * level / 100);
mbst += Math.floor((stats["spd"] * 2 + 30 + 63 + 100) * level / 100 + 5);
mbst += Math.floor((stats["spe"] * 2 + 30 + 63 + 100) * level / 100 + 5);
if (mbst >= mbstmin)
break;
@ -897,12 +897,12 @@ exports.BattleScripts = {
// Random IVs
var ivs = {
hp: Math.floor(Math.random()*31),
atk: Math.floor(Math.random()*31),
def: Math.floor(Math.random()*31),
spa: Math.floor(Math.random()*31),
spd: Math.floor(Math.random()*31),
spe: Math.floor(Math.random()*31)
hp: Math.floor(Math.random() * 31),
atk: Math.floor(Math.random() * 31),
def: Math.floor(Math.random() * 31),
spa: Math.floor(Math.random() * 31),
spd: Math.floor(Math.random() * 31),
spe: Math.floor(Math.random() * 31)
};
// ALl EVs
@ -954,7 +954,7 @@ exports.BattleScripts = {
var ruleset = this.getFormat().ruleset;
for (var i=0; i<keys.length && pokemonLeft < 6; i++) {
for (var i = 0; i < keys.length && pokemonLeft < 6; i++) {
var template = this.getTemplate(keys[i]);
if (!template || !template.name || !template.types) continue;
var set = this.randomSet(template, i);
@ -979,7 +979,7 @@ exports.BattleScripts = {
var counter = {};
var setupType = '';
var j=0;
var j = 0;
do {
hasMove = {};
counter = {
@ -987,7 +987,7 @@ exports.BattleScripts = {
recoil: 0, inaccurate: 0,
physicalsetup: 0, specialsetup: 0, mixedsetup: 0
};
for (var k=0; k<moves.length; k++) {
for (var k = 0; k < moves.length; k++) {
var move = this.getMove(moves[k]);
var moveid = move.id;
hasMove[moveid] = true;
@ -1024,7 +1024,7 @@ exports.BattleScripts = {
setupType = 'Physical';
}
for (var k=0; k<moves.length; k++) {
for (var k = 0; k < moves.length; k++) {
var moveid = moves[k];
var move = this.getMove(moveid);
var rejected = false;
@ -1072,12 +1072,12 @@ exports.BattleScripts = {
rejected = true;
}
if (rejected && j<moveKeys.length) {
if (rejected && j < moveKeys.length) {
moves.splice(k, 1);
break;
}
} // End of for
} while (moves.length<4 && j<moveKeys.length);
} while (moves.length < 4 && j < moveKeys.length);
var levelScale = {
LC: 95,

View File

@ -15,12 +15,12 @@ exports.BattleStatuses = {
target.addVolatile('brnattackdrop');
},
onAfterMoveSelf: function(pokemon) {
this.damage(pokemon.maxhp/16);
this.damage(pokemon.maxhp / 16);
},
onSwitchIn: function (pokemon){
pokemon.addVolatile('brnattackdrop');
if (pokemon.side.foe.active[0] && pokemon.speed <= pokemon.side.foe.active[0].speed) {
this.damage(pokemon.maxhp/16);
this.damage(pokemon.maxhp / 16);
}
}
},
@ -58,7 +58,7 @@ exports.BattleStatuses = {
onStart: function(target) {
this.add('-status', target, 'slp');
// 1-7 turns. Put 1-7 since they awake at end of turn.
this.effectData.startTime = this.random(1,7);
this.effectData.startTime = this.random(1, 7);
this.effectData.time = this.effectData.startTime;
},
onBeforeMovePriority: 2,
@ -93,11 +93,11 @@ exports.BattleStatuses = {
this.add('-status', target, 'psn');
},
onAfterMoveSelf: function(pokemon) {
this.damage(pokemon.maxhp/16);
this.damage(pokemon.maxhp / 16);
},
onSwitchIn: function (pokemon) {
if (pokemon.side.foe.active[0] && pokemon.speed <= pokemon.side.foe.active[0].speed) {
this.damage(pokemon.maxhp/16);
this.damage(pokemon.maxhp / 16);
}
}
},
@ -111,14 +111,14 @@ exports.BattleStatuses = {
if (this.effectData.stage < 15) {
this.effectData.stage++;
}
this.damage(this.clampIntRange(pokemon.maxhp/16, 1)*this.effectData.stage);
this.damage(this.clampIntRange(pokemon.maxhp / 16, 1) * this.effectData.stage);
},
onSwitchIn: function (pokemon) {
this.effectData.stage = 0; // probably unnecessary...
pokemon.setStatus('psn');
// normal poison damage...
if (pokemon.side.foe.active[0] && pokemon.speed <= pokemon.side.foe.active[0].speed) {
this.damage(pokemon.maxhp/16);
this.damage(pokemon.maxhp / 16);
}
}
},
@ -128,7 +128,7 @@ exports.BattleStatuses = {
var result = this.runEvent('TryConfusion');
if (!result) return result;
this.add('-start', target, 'confusion');
this.effectData.time = this.random(2,6);
this.effectData.time = this.random(2, 6);
},
onEnd: function(target) {
this.add('-end', target, 'confusion');
@ -143,7 +143,7 @@ exports.BattleStatuses = {
if (this.random(2) === 0) {
return;
}
this.directDamage(this.getDamage(pokemon,pokemon,40));
this.directDamage(this.getDamage(pokemon, pokemon, 40));
return false;
}
},
@ -185,7 +185,7 @@ exports.BattleStatuses = {
partialtrappinglock: {
durationCallback: function() {
var roll = this.random(6);
duration = [2,2,3,3,4,5][roll];
duration = [2, 2, 3, 3, 4, 5][roll];
return duration;
},
onResidual: function(target) {
@ -201,7 +201,7 @@ exports.BattleStatuses = {
return;
}
var moves = pokemon.moveset;
for (var i=0; i<moves.length; i++) {
for (var i = 0; i < moves.length; i++) {
if (moves[i].id !== this.effectData.move) {
moves[i].disabled = true;
}
@ -229,7 +229,7 @@ exports.BattleStatuses = {
lockedmove: {
// Outrage, Thrash, Petal Dance...
durationCallback: function() {
return this.random(2,4);
return this.random(2, 4);
},
onResidual: function(target) {
if (target.lastMove === 'struggle' || target.status === 'slp') {
@ -250,7 +250,7 @@ exports.BattleStatuses = {
onBeforeTurn: function(pokemon) {
var move = this.getMove(this.effectData.move);
if (move.id) {
this.debug('Forcing into '+move.id);
this.debug('Forcing into ' + move.id);
this.changeDecision(pokemon, {move: move.id});
}
}
@ -268,14 +268,14 @@ exports.BattleStatuses = {
// this is a side condition
onStart: function(side) {
this.effectData.positions = [];
for (var i=0; i<side.active.length; i++) {
for (var 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++) {
for (var i = 0; i < side.active.length; i++) {
var posData = this.effectData.positions[i];
if (!posData) continue;
@ -290,12 +290,12 @@ exports.BattleStatuses = {
var target = side.foe.active[posData.targetPosition];
var move = this.getMove(posData.move);
if (target.fainted) {
this.add('-hint', ''+move.name+' did not hit because the target is fainted.');
this.add('-hint', '' + move.name + ' did not hit because the target is fainted.');
this.effectData.positions[i] = null;
continue;
}
this.add('-message', ''+move.name+' hit! (placeholder)');
this.add('-message', '' + move.name + ' hit! (placeholder)');
target.removeVolatile('Protect');
target.removeVolatile('Endure');
@ -325,9 +325,9 @@ exports.BattleStatuses = {
var 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);
return (this.random() * 4294967296 < 1);
}
this.debug("Success chance: "+Math.round(100/counter)+"%");
this.debug("Success chance: " + Math.round(100 / counter) + "%");
return (this.random(counter) === 0);
},
onRestart: function() {

View File

@ -19,7 +19,7 @@ The type was decided with the following operation:
4 * (atkDV % 4) + (defDV % 4)
Which gives as a number from 0 to 16, giving us the index in the type table to use.
The Hidden Power base power was decided with the following formula:
Math.floor((5 * ((spcDV >> 3) + (2 * (speDV >> 3)) + (4 * (defDV >> 3)) + (8 * (atkDV >> 3))) + (spcDV>2?3:spcDV)) / 2 + 31);
Math.floor((5 * ((spcDV >> 3) + (2 * (speDV >> 3)) + (4 * (defDV >> 3)) + (8 * (atkDV >> 3))) + (spcDV > 2 ? 3 : spcDV)) / 2 + 31);
The DVs are shifted 3 positions, taking thus the most important byte, thus having no value under 8 DVs and a value on 8 and higher.
The most important DV was attack and special.
@ -29,4 +29,4 @@ Critical hits ignore defensive boosts but not defensive drops.
Status
------
Sleep lasts 1-5 turns and you the counter is not reset upon switch.
Sleep lasts 1-5 turns and you the counter is not reset upon switch.

View File

@ -67,7 +67,7 @@ exports.BattleItems = {
}
move.pp += 5;
if (move.pp > move.maxpp) move.pp = move.maxpp;
this.add("-message",pokemon.name+" restored "+move.move+"'s PP using its Leppa Berry! (placeholder)");
this.add("-message", pokemon.name + " restored " + move.move + "'s PP using its Leppa Berry! (placeholder)");
},
gen: 2,
desc: "Restores 5PP to the first of the holder's moves to reach 0PP. Single use."

View File

@ -8,11 +8,11 @@ exports.BattleMovedex = {
if (target.boosts.atk >= 6) {
return false;
}
if (target.hp <= target.maxhp/2) {
if (target.hp <= target.maxhp / 2) {
this.boost({atk: 2});
return false;
}
this.directDamage(target.maxhp/2);
this.directDamage(target.maxhp / 2);
target.setBoost({atk: 6});
this.add('-setboost', target, 'atk', '6', '[from] move: Belly Drum');
}
@ -26,7 +26,7 @@ exports.BattleMovedex = {
return;
}
if (target.newlySwitched && target.speed <= source.speed) {
var toLeech = this.clampIntRange(target.maxhp/8, 1);
var toLeech = this.clampIntRange(target.maxhp / 8, 1);
var damage = this.damage(toLeech, target, source, 'move: Leech Seed');
if (damage) {
this.heal(damage, source, target);
@ -43,7 +43,7 @@ exports.BattleMovedex = {
this.debug('Nothing to leech into');
return;
}
var toLeech = this.clampIntRange(pokemon.maxhp/8, 1);
var toLeech = this.clampIntRange(pokemon.maxhp / 8, 1);
var damage = this.damage(toLeech, pokemon, target);
if (damage) {
this.heal(damage, target, pokemon);
@ -59,11 +59,11 @@ exports.BattleMovedex = {
return spd * 2;
},
onStart: function(side) {
this.add('-sidestart',side,'move: Light Screen');
this.add('-sidestart', side, 'move: Light Screen');
},
onResidualOrder: 21,
onEnd: function(side) {
this.add('-sideend',side,'move: Light Screen');
this.add('-sideend', side, 'move: Light Screen');
}
}
},
@ -102,11 +102,11 @@ exports.BattleMovedex = {
return def * 2;
},
onStart: function(side) {
this.add('-sidestart',side,'Reflect');
this.add('-sidestart', side, 'Reflect');
},
onResidualOrder: 21,
onEnd: function(side) {
this.add('-sideend',side,'Reflect');
this.add('-sideend', side, 'Reflect');
}
}
},
@ -130,7 +130,7 @@ exports.BattleMovedex = {
inherit: true,
onHit: function(pokemon) {
var moves = [];
for (var i=0; i<pokemon.moveset.length; i++) {
for (var i = 0; i < pokemon.moveset.length; i++) {
var move = pokemon.moveset[i].id;
var NoSleepTalk = {
bide:1, dig:1, fly:1, metronome:1, mirrormove:1,
@ -162,8 +162,8 @@ exports.BattleMovedex = {
onSwitchIn: function(pokemon) {
var side = pokemon.side;
if (!pokemon.runImmunity('Ground')) return;
var damageAmounts = [0,3];
var damage = this.damage(damageAmounts[this.effectData.layers]*pokemon.maxhp/24);
var damageAmounts = [0, 3];
var damage = this.damage(damageAmounts[this.effectData.layers] * pokemon.maxhp / 24);
}
}
},
@ -172,7 +172,7 @@ exports.BattleMovedex = {
effect: {
onStart: function(target) {
this.add('-start', target, 'Substitute');
this.effectData.hp = Math.floor(target.maxhp/4);
this.effectData.hp = Math.floor(target.maxhp / 4);
delete target.volatiles['partiallytrapped'];
},
onTryPrimaryHitPriority: -1,

View File

@ -7,30 +7,30 @@ exports.BattleFormats = {
if (set.species === set.name) delete set.name;
if (template.gen > this.gen) {
problems.push(set.species+' does not exist in gen '+this.gen+'.');
problems.push(set.species + ' does not exist in gen ' + this.gen + '.');
} else if (template.isNonstandard) {
problems.push(set.species+' is not a real Pokemon.');
problems.push(set.species + ' is not a real Pokemon.');
}
var hasHP = false;
if (set.item) {
var item = this.getItem(set.item);
if (item.gen > this.gen) {
problems.push(item.name+' does not exist in gen '+this.gen+'.');
problems.push(item.name + ' does not exist in gen ' + this.gen + '.');
} else if (item.isNonstandard) {
problems.push(item.name + ' is not a real item.');
}
}
if (set.moves) for (var i=0; i<set.moves.length; i++) {
if (set.moves) for (var i = 0; i < set.moves.length; i++) {
var move = this.getMove(set.moves[i]);
if (move.gen > this.gen) {
problems.push(move.name+' does not exist in gen '+this.gen+'.');
problems.push(move.name + ' does not exist in gen ' + this.gen + '.');
} else if (move.isNonstandard) {
problems.push(move.name+' is not a real move.');
problems.push(move.name + ' is not a real move.');
}
if (move.id === 'hiddenpower') hasHP = true;
}
if (set.moves && set.moves.length > 4) {
problems.push((set.name||set.species) + ' has more than four moves.');
problems.push((set.name || set.species) + ' has more than four moves.');
}
// Automatically set ability to None
@ -111,7 +111,7 @@ exports.BattleFormats = {
var moves = [];
if (set.moves) {
var hasMove = {};
for (var i=0; i<set.moves.length; i++) {
for (var i = 0; i < set.moves.length; i++) {
var move = this.getMove(set.moves[i]);
var moveid = move.id;
if (hasMove[moveid]) continue;

View File

@ -123,19 +123,19 @@ exports.BattleScripts = {
move.ignoreNegativeOffensive = true;
move.ignorePositiveDefensive = true;
}
if (move.ignoreNegativeOffensive && attack < attacker.getStat(move.category==='Physical'?'atk':'spa', true, true)) {
if (move.ignoreNegativeOffensive && attack < attacker.getStat(move.category === 'Physical' ? 'atk' : 'spa', true, true)) {
move.ignoreOffensive = true;
}
if (move.ignoreOffensive) {
this.debug('Negating (sp)atk boost/penalty.');
attack = attacker.getStat(move.category==='Physical'?'atk':'spa', true, true);
attack = attacker.getStat(move.category === 'Physical' ? 'atk' : 'spa', true, true);
}
if (move.ignorePositiveDefensive && defense > target.getStat(move.defensiveCategory==='Physical'?'def':'spd', true, true)) {
if (move.ignorePositiveDefensive && defense > target.getStat(move.defensiveCategory === 'Physical' ? 'def' : 'spd', true, true)) {
move.ignoreDefensive = true;
}
if (move.ignoreDefensive) {
this.debug('Negating (sp)def boost/penalty.');
defense = target.getStat(move.defensiveCategory==='Physical'?'def':'spd', true, true);
defense = target.getStat(move.defensiveCategory === 'Physical' ? 'def' : 'spd', true, true);
}
// Gen 2 damage formula
@ -173,7 +173,7 @@ exports.BattleScripts = {
}
// Randomizer, it's a number between 217 and 255
var randFactor = Math.floor(Math.random()*39)+217;
var randFactor = Math.floor(Math.random() * 39) + 217;
baseDamage *= Math.floor(randFactor * 100 / 255) / 100;
// If damage is less than 1, we return 1
@ -197,10 +197,10 @@ exports.BattleScripts = {
b.speed = b.speed || 0;
if ((typeof a.order === 'number' || typeof b.order === 'number') && a.order !== b.order) {
if (typeof a.order !== 'number') {
return -(1);
return -1;
}
if (typeof b.order !== 'number') {
return -(-1);
return 1;
}
if (b.order - a.order) {
return -(b.order - a.order);
@ -216,16 +216,16 @@ exports.BattleScripts = {
if (b.subOrder - a.subOrder) {
return -(b.subOrder - a.subOrder);
}
return Math.random()-0.5;
return Math.random() - 0.5;
},
getResidualStatuses: function(thing, callbackType) {
var statuses = this.getRelevantEffectsInner(thing || this, callbackType || 'residualCallback', null, null, false, true, 'duration');
statuses.sort(this.comparePriority);
//if (statuses[0]) this.debug('match '+(callbackType||'residualCallback')+': '+statuses[0].status.id);
//if (statuses[0]) this.debug('match ' + (callbackType || 'residualCallback') + ': ' + statuses[0].status.id);
return statuses;
},
residualEvent: function(eventid, relayVar) {
var statuses = this.getRelevantEffectsInner(this, 'on'+eventid, null, null, false, true, 'duration');
var statuses = this.getRelevantEffectsInner(this, 'on' + eventid, null, null, false, true, 'duration');
statuses.sort(this.comparePriority);
while (statuses.length) {
var statusObj = statuses.shift();
@ -244,13 +244,13 @@ exports.BattleScripts = {
getRelevantEffects: function(thing, callbackType, foeCallbackType, foeThing, checkChildren) {
var statuses = this.getRelevantEffectsInner(thing, callbackType, foeCallbackType, foeThing, true, false);
statuses.sort(this.comparePriority);
//if (statuses[0]) this.debug('match '+callbackType+': '+statuses[0].status.id);
//if (statuses[0]) this.debug('match ' + callbackType + ': ' + statuses[0].status.id);
return statuses;
},
addQueue: function(decision, noSort, side) {
if (decision) {
if (Array.isArray(decision)) {
for (var i=0; i<decision.length; i++) {
for (var i = 0; i < decision.length; i++) {
this.addQueue(decision[i], noSort);
}
return;
@ -315,4 +315,4 @@ exports.BattleScripts = {
this.queue.sort(this.comparePriority);
}
}
};
};

View File

@ -5,7 +5,7 @@ exports.BattleStatuses = {
this.add('-status', target, 'brn');
},
onAfterMoveSelf: function(pokemon) {
this.damage(pokemon.maxhp/8);
this.damage(pokemon.maxhp / 8);
},
onBasePower: function(basePower, attacker, defender, move) {
if (move && move.category === 'Physical' && attacker && attacker.ability !== 'guts') {
@ -15,7 +15,7 @@ exports.BattleStatuses = {
onSwitchIn: function (pokemon){
pokemon.addVolatile('brnattackdrop');
if (pokemon.side.foe.active[0] && pokemon.speed <= pokemon.side.foe.active[0].speed) {
this.damage(pokemon.maxhp/8);
this.damage(pokemon.maxhp / 8);
}
}
},
@ -34,7 +34,7 @@ exports.BattleStatuses = {
onStart: function(target) {
this.add('-status', target.id, 'slp');
// 1-5 turns
this.effectData.time = this.random(2,6);
this.effectData.time = this.random(2, 6);
},
onBeforeMovePriority: 2,
onBeforeMove: function(pokemon, target, move) {
@ -56,11 +56,11 @@ exports.BattleStatuses = {
this.add('-status', target, 'psn');
},
onAfterMoveSelf: function(pokemon) {
this.damage(pokemon.maxhp/8);
this.damage(pokemon.maxhp / 8);
},
onSwitchIn: function (pokemon) {
if (pokemon.side.foe.active[0] && pokemon.speed <= pokemon.side.foe.active[0].speed) {
this.damage(pokemon.maxhp/8);
this.damage(pokemon.maxhp / 8);
}
}
},
@ -74,13 +74,13 @@ exports.BattleStatuses = {
if (this.effectData.stage < 15) {
this.effectData.stage++;
}
this.damage(this.clampIntRange(pokemon.maxhp/16, 1)*this.effectData.stage);
this.damage(this.clampIntRange(pokemon.maxhp / 16, 1) * this.effectData.stage);
},
onSwitchIn: function (pokemon) {
this.effectData.stage = 0;
pokemon.setStatus('psn');
if (pokemon.side.foe.active[0] && pokemon.speed <= pokemon.side.foe.active[0].speed) {
this.damage(pokemon.maxhp/8);
this.damage(pokemon.maxhp / 8);
}
}
},

View File

@ -1,66 +1,66 @@
exports.BattleTypeChart = {
"Bug": {
inherit: true,
HPivs: {"atk":26,"def":26,"spa":30,"spd":30,"spe":30,"hp":30}
HPivs: {"atk":26, "def":26, "spa":30, "spd":30, "spe":30, "hp":30}
},
"Dark": {
inherit: true,
HPivs: {"atk":30,"def":30,"spa":30,"spd":30,"spe":30,"hp":30}
HPivs: {"atk":30, "def":30, "spa":30, "spd":30, "spe":30, "hp":30}
},
"Dragon": {
inherit: true,
HPivs: {"atk":30,"def":28,"spa":30,"spd":30,"spe":30,"hp":30}
HPivs: {"atk":30, "def":28, "spa":30, "spd":30, "spe":30, "hp":30}
},
"Electric": {
inherit: true,
HPivs: {"atk":28,"def":30,"spa":30,"spd":30,"spe":30,"hp":30}
HPivs: {"atk":28, "def":30, "spa":30, "spd":30, "spe":30, "hp":30}
},
"Fighting": {
inherit: true,
HPivs: {"atk":24,"def":24,"spa":30,"spd":30,"spe":30,"hp":30}
HPivs: {"atk":24, "def":24, "spa":30, "spd":30, "spe":30, "hp":30}
},
"Fire": {
inherit: true,
HPivs: {"atk":28,"def":24,"spa":30,"spd":30,"spe":30,"hp":30}
HPivs: {"atk":28, "def":24, "spa":30, "spd":30, "spe":30, "hp":30}
},
"Flying": {
inherit: true,
HPivs: {"atk":24,"def":26,"spa":30,"spd":30,"spe":30,"hp":30}
HPivs: {"atk":24, "def":26, "spa":30, "spd":30, "spe":30, "hp":30}
},
"Ghost": {
inherit: true,
HPivs: {"atk":26,"def":28,"spa":30,"spd":30,"spe":30,"hp":30}
HPivs: {"atk":26, "def":28, "spa":30, "spd":30, "spe":30, "hp":30}
},
"Grass": {
inherit: true,
HPivs: {"atk":28,"def":28,"spa":30,"spd":30,"spe":30,"hp":30}
HPivs: {"atk":28, "def":28, "spa":30, "spd":30, "spe":30, "hp":30}
},
"Ground": {
inherit: true,
HPivs: {"atk":24,"def":30,"spa":30,"spd":30,"spe":30,"hp":30}
HPivs: {"atk":24, "def":30, "spa":30, "spd":30, "spe":30, "hp":30}
},
"Ice": {
inherit: true,
HPivs: {"atk":30,"def":26,"spa":30,"spd":30,"spe":30,"hp":30}
HPivs: {"atk":30, "def":26, "spa":30, "spd":30, "spe":30, "hp":30}
},
"Poison": {
inherit: true,
HPivs: {"atk":24,"def":28,"spa":30,"spd":30,"spe":30,"hp":30}
HPivs: {"atk":24, "def":28, "spa":30, "spd":30, "spe":30, "hp":30}
},
"Psychic": {
inherit: true,
HPivs: {"atk":30,"def":24,"spa":30,"spd":30,"spe":30,"hp":30}
HPivs: {"atk":30, "def":24, "spa":30, "spd":30, "spe":30, "hp":30}
},
"Rock": {
inherit: true,
HPivs: {"atk":26,"def":24,"spa":30,"spd":30,"spe":30,"hp":30}
HPivs: {"atk":26, "def":24, "spa":30, "spd":30, "spe":30, "hp":30}
},
"Steel": {
inherit: true,
HPivs: {"atk":26,"def":30,"spa":30,"spd":30,"spe":30,"hp":30}
HPivs: {"atk":26, "def":30, "spa":30, "spd":30, "spe":30, "hp":30}
},
"Water": {
inherit: true,
HPivs: {"atk":28,"def":26,"spa":30,"spd":30,"spe":30,"hp":30}
HPivs: {"atk":28, "def":26, "spa":30, "spd":30, "spe":30, "hp":30}
}
};

View File

@ -89,7 +89,7 @@ exports.BattleAbilities = {
inherit: true,
onAfterDamage: function(damage, target, source, move) {
if (source && source !== target && move && move.isContact) {
this.damage(source.maxhp/16, source, target);
this.damage(source.maxhp / 16, source, target);
}
}
},
@ -117,7 +117,7 @@ exports.BattleAbilities = {
inherit: true,
onDamage: function(damage, target, source, effect) {
if (effect && effect.ohko) {
this.add('-activate',target,'Sturdy');
this.add('-activate', target, 'Sturdy');
return 0;
}
}
@ -145,11 +145,11 @@ exports.BattleAbilities = {
if (ability === 'Intimidate')
{
if (pokemon.setAbility('Illuminate')) { // Temporary fix so Intimidate doesn't activate in third gen when traced
this.add('-ability',pokemon, ability,'[from] ability: Trace','[of] '+target);
this.add('-ability', pokemon, ability, '[from] ability: Trace', '[of] ' + target);
}
}
else if (pokemon.setAbility(ability)) {
this.add('-ability',pokemon, ability,'[from] ability: Trace','[of] '+target);
this.add('-ability', pokemon, ability, '[from] ability: Trace', '[of] ' + target);
}
}
},
@ -157,7 +157,7 @@ exports.BattleAbilities = {
inherit: true,
onTryHit: function(target, source, move) {
if (target !== source && move.type === 'Electric' && move.id !== 'thunderwave') {
if (!this.heal(target.maxhp/4)) {
if (!this.heal(target.maxhp / 4)) {
this.add('-immune', target, '[msg]');
}
return null;

View File

@ -24,10 +24,10 @@ exports.BattleMovedex = {
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++) {
for (var j = 0; j < target.side.pokemon.length; j++) {
var pokemon = target.side.pokemon[j];
if (pokemon === target) continue;
for (var i=0; i<pokemon.moves.length; i++) {
for (var i = 0; i < pokemon.moves.length; i++) {
var move = pokemon.moves[i];
var 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
@ -145,7 +145,7 @@ exports.BattleMovedex = {
volatileStatus: 'disable',
effect: {
durationCallback: function() {
return this.random(2,6);
return this.random(2, 6);
},
noCopy: true,
onStart: function(pokemon) {
@ -156,7 +156,7 @@ exports.BattleMovedex = {
return false;
}
var moves = pokemon.moveset;
for (var i=0; i<moves.length; i++) {
for (var i = 0; i < moves.length; i++) {
if (moves[i].id === pokemon.lastMove) {
if (!moves[i].pp) {
return false;
@ -170,7 +170,7 @@ exports.BattleMovedex = {
return false;
},
onEnd: function(pokemon) {
this.add('-message', pokemon.name+' is no longer disabled! (placeholder)');
this.add('-message', pokemon.name + ' is no longer disabled! (placeholder)');
},
onBeforeMove: function(attacker, defender, move) {
if (move.id === this.effectData.move) {
@ -180,7 +180,7 @@ exports.BattleMovedex = {
},
onModifyPokemon: function(pokemon) {
var moves = pokemon.moveset;
for (var i=0; i<moves.length; i++) {
for (var i = 0; i < moves.length; i++) {
if (moves[i].id === this.effectData.move) {
moves[i].disabled = true;
}
@ -216,7 +216,7 @@ exports.BattleMovedex = {
volatileStatus: 'encore',
effect: {
durationCallback: function() {
return this.random(3,7);
return this.random(3, 7);
},
onStart: function(target) {
var noEncore = {encore:1, mimic:1, mirrormove:1, sketch:1, transform:1};
@ -251,7 +251,7 @@ exports.BattleMovedex = {
if (!this.effectData.move || !pokemon.hasMove(this.effectData.move)) {
return;
}
for (var i=0; i<pokemon.moveset.length; i++) {
for (var i = 0; i < pokemon.moveset.length; i++) {
if (pokemon.moveset[i].id !== this.effectData.move) {
pokemon.moveset[i].disabled = true;
}
@ -390,7 +390,7 @@ exports.BattleMovedex = {
onMoveFail: function(target, source, move) {
if (target.runImmunity('Fighting')) {
var damage = this.getDamage(source, target, move, true);
this.damage(this.clampIntRange(damage/2, 1, Math.floor(target.maxhp/2)), source);
this.damage(this.clampIntRange(damage / 2, 1, Math.floor(target.maxhp / 2)), source);
}
}
},
@ -409,7 +409,7 @@ exports.BattleMovedex = {
onMoveFail: function(target, source, move) {
if (target.runImmunity('Fighting')) {
var damage = this.getDamage(source, target, move, true);
this.damage(this.clampIntRange(damage/2, 1, Math.floor(target.maxhp/2)), source);
this.damage(this.clampIntRange(damage / 2, 1, Math.floor(target.maxhp / 2)), source);
}
}
},
@ -569,7 +569,7 @@ exports.BattleMovedex = {
inherit: true,
isBounceable: false,
onHit: function(target) {
var roll = this.random(2,6);
var roll = this.random(2, 6);
if (target.deductPP(target.lastMove, roll)) {
this.add("-activate", target, 'move: Spite', target.lastMove, roll);
return;
@ -591,12 +591,12 @@ exports.BattleMovedex = {
priority: 0,
isContact: true,
beforeMoveCallback: function(pokemon) {
this.add('-message', pokemon.name+' has no moves left! (placeholder)');
this.add('-message', pokemon.name + ' has no moves left! (placeholder)');
},
onModifyMove: function(move) {
move.type = '???';
},
recoil: [1,2],
recoil: [1, 2],
secondary: false,
target: "normal",
type: "Normal"
@ -626,7 +626,7 @@ exports.BattleMovedex = {
},
onModifyPokemon: function(pokemon) {
var moves = pokemon.moveset;
for (var i=0; i<moves.length; i++) {
for (var i = 0; i < moves.length; i++) {
if (this.getMove(moves[i].move).category === 'Status') {
moves[i].disabled = true;
}
@ -667,7 +667,7 @@ exports.BattleMovedex = {
},
volttackle: {
inherit: true,
recoil: [1,3],
recoil: [1, 3],
secondary: false
},
waterfall: {
@ -692,8 +692,8 @@ exports.BattleMovedex = {
var target = side.active[this.effectData.sourcePosition];
if (!target.fainted) {
var source = this.effectData.source;
var damage = this.heal(target.maxhp/2, target, target);
if (damage) this.add('-heal', target, target.getHealth, '[from] move: Wish', '[wisher] '+source.name);
var damage = this.heal(target.maxhp / 2, target, target);
if (damage) this.add('-heal', target, target.getHealth, '[from] move: Wish', '[wisher] ' + source.name);
}
}
}

View File

@ -4,7 +4,7 @@ exports.BattleStatuses = {
onStart: function(target) {
this.add('-status', target, 'slp');
// 1-4 turns
this.effectData.time = this.random(2,6);
this.effectData.time = this.random(2, 6);
},
onBeforeMovePriority: 2,
onBeforeMove: function(pokemon, target, move) {
@ -27,7 +27,7 @@ exports.BattleStatuses = {
inherit: true,
durationCallback: function(target, source) {
if (source.item === 'gripclaw') return 6;
return this.random(3,7);
return this.random(3, 7);
}
},
sandstorm: {

View File

@ -5,7 +5,7 @@ exports.BattleAbilities = {
shortDesc: "If this Pokemon is hit by a critical hit, its Attack is boosted by 12.",
onCriticalHit: function(target) {
target.setBoost({atk: 6});
this.add('-setboost',target,'atk',12,'[from] ability: Anger Point');
this.add('-setboost', target, 'atk', 12, '[from] ability: Anger Point');
}
},
"lightningrod": {
@ -43,7 +43,7 @@ exports.BattleAbilities = {
if (allyActive.length === 1) {
return;
}
for (var i=0; i<allyActive.length; i++) {
for (var 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
}
@ -70,7 +70,7 @@ exports.BattleAbilities = {
if (allyActive.length === 1) {
return;
}
for (var i=0; i<allyActive.length; i++) {
for (var 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
}
@ -104,7 +104,7 @@ exports.BattleAbilities = {
onDamagePriority: -100,
onDamage: function(damage, target, source, effect) {
if (effect && effect.ohko) {
this.add('-activate',target,'Sturdy');
this.add('-activate', target, 'Sturdy');
return 0;
}
},
@ -134,7 +134,7 @@ exports.BattleAbilities = {
return;
}
if (pokemon.setAbility(ability)) {
this.add('-ability',pokemon, ability,'[from] ability: Trace','[of] '+target);
this.add('-ability', pokemon, ability, '[from] ability: Trace', '[of] ' + target);
}
}
},
@ -142,7 +142,7 @@ exports.BattleAbilities = {
inherit: true,
onTryHit: function(target, source, move) {
if (target === source || move.category === 'Status' || move.type === '???' || move.id === 'struggle' || move.id === 'firefang') return;
this.debug('Wonder Guard immunity: '+move.id);
this.debug('Wonder Guard immunity: ' + move.id);
if (this.getEffectiveness(move.type, target) <= 0) {
this.add('-activate', target, 'ability: Wonder Guard');
return null;

View File

@ -21,7 +21,7 @@ exports.BattleItems = {
type: "Ghost"
},
onBeforeTurn: function(pokemon) {
if (pokemon.hp <= pokemon.maxhp/4 || (pokemon.hp <= pokemon.maxhp/2 && pokemon.ability === 'gluttony')) {
if (pokemon.hp <= pokemon.maxhp / 4 || (pokemon.hp <= pokemon.maxhp / 2 && pokemon.ability === 'gluttony')) {
var decision = this.willMove(pokemon);
if (!decision) return;
this.addQueue({
@ -36,14 +36,14 @@ exports.BattleItems = {
},
onCustap: function(pokemon) {
var decision = this.willMove(pokemon);
this.debug('custap decision: '+decision);
this.debug('custap decision: ' + decision);
if (decision) {
pokemon.eatItem();
}
},
onEat: function(pokemon) {
var decision = this.willMove(pokemon);
this.debug('custap eaten: '+decision);
this.debug('custap eaten: ' + decision);
if (decision) {
this.cancelDecision(pokemon);
this.add('-message', "Custap Berry activated.");
@ -76,7 +76,7 @@ exports.BattleItems = {
duration: 1,
onAfterMoveSecondarySelf: function(source, target, move) {
if (move && move.effectType === 'Move' && source && source.volatiles['lifeorb']) {
this.damage(source.maxhp/10, source, source, this.getItem('lifeorb'));
this.damage(source.maxhp / 10, source, source, this.getItem('lifeorb'));
source.removeVolatile('lifeorb');
}
}
@ -116,7 +116,7 @@ exports.BattleItems = {
} else if (this.effectData.numConsecutive < 10) {
this.effectData.numConsecutive++;
}
return basePower * (1+(this.effectData.numConsecutive/10));
return basePower * (1 + (this.effectData.numConsecutive / 10));
}
}
}

View File

@ -28,10 +28,10 @@ exports.BattleMovedex = {
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++) {
for (var j = 0; j < target.side.pokemon.length; j++) {
var pokemon = target.side.pokemon[j];
if (pokemon === target) continue;
for (var i=0; i<pokemon.moves.length; i++) {
for (var i = 0; i < pokemon.moves.length; i++) {
var move = pokemon.moves[i];
var 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
@ -120,7 +120,7 @@ exports.BattleMovedex = {
}
this.add('-end', pokemon, 'Bide');
var target = this.effectData.sourceSide.active[this.effectData.sourcePosition];
this.moveHit(target, pokemon, 'bide', {damage: this.effectData.totalDamage*2});
this.moveHit(target, pokemon, 'bide', {damage: this.effectData.totalDamage * 2});
return false;
}
this.add('-activate', pokemon, 'Bide');
@ -193,7 +193,7 @@ exports.BattleMovedex = {
crushgrip: {
inherit: true,
basePowerCallback: function(pokemon) {
return Math.floor(pokemon.hp*120/pokemon.maxhp) + 1;
return Math.floor(pokemon.hp * 120 / pokemon.maxhp) + 1;
}
},
curse: {
@ -205,12 +205,12 @@ exports.BattleMovedex = {
this.add('-fail', pokemon);
return false;
}
this.add('-start', pokemon, 'Curse', '[of] '+source);
this.directDamage(source.maxhp/2, source, source);
this.add('-start', pokemon, 'Curse', '[of] ' + source);
this.directDamage(source.maxhp / 2, source, source);
},
onResidualOrder: 10,
onResidual: function(pokemon) {
this.damage(pokemon.maxhp/4);
this.damage(pokemon.maxhp / 4);
}
},
type: "???"
@ -233,7 +233,7 @@ exports.BattleMovedex = {
volatileStatus: 'disable',
effect: {
durationCallback: function() {
return this.random(4,8);
return this.random(4, 8);
},
noCopy: true,
onStart: function(pokemon) {
@ -244,7 +244,7 @@ exports.BattleMovedex = {
return false;
}
var moves = pokemon.moveset;
for (var i=0; i<moves.length; i++) {
for (var i = 0; i < moves.length; i++) {
if (moves[i].id === pokemon.lastMove) {
if (!moves[i].pp) {
return false;
@ -258,7 +258,7 @@ exports.BattleMovedex = {
return false;
},
onEnd: function(pokemon) {
this.add('-message', pokemon.name+' is no longer disabled! (placeholder)');
this.add('-message', pokemon.name + ' is no longer disabled! (placeholder)');
},
onBeforeMove: function(attacker, defender, move) {
if (move.id === this.effectData.move) {
@ -268,7 +268,7 @@ exports.BattleMovedex = {
},
onModifyPokemon: function(pokemon) {
var moves = pokemon.moveset;
for (var i=0; i<moves.length; i++) {
for (var i = 0; i < moves.length; i++) {
if (moves[i].id === this.effectData.move) {
moves[i].disabled = true;
}
@ -317,14 +317,14 @@ exports.BattleMovedex = {
volatileStatus: 'encore',
effect: {
durationCallback: function() {
return this.random(4,9);
return this.random(4, 9);
},
onStart: function(target) {
var noEncore = {encore:1, mimic:1, mirrormove:1, sketch:1, transform:1};
var 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);
this.add('-fail', target);
delete target.volatiles['encore'];
return;
}
@ -352,7 +352,7 @@ exports.BattleMovedex = {
if (!this.effectData.move || !pokemon.hasMove(this.effectData.move)) {
return;
}
for (var i=0; i<pokemon.moveset.length; i++) {
for (var i = 0; i < pokemon.moveset.length; i++) {
if (pokemon.moveset[i].id !== this.effectData.move) {
pokemon.moveset[i].disabled = true;
}
@ -362,7 +362,7 @@ exports.BattleMovedex = {
},
endeavor: {
inherit: true,
damageCallback: function(pokemon,target) {
damageCallback: function(pokemon, target) {
if (target.hp > pokemon.hp) {
return target.hp - pokemon.hp;
}
@ -465,7 +465,7 @@ exports.BattleMovedex = {
effect: {
duration: 2,
onStart: function(side) {
this.debug('Healing Wish started on '+side.name);
this.debug('Healing Wish started on ' + side.name);
},
onSwitchInPriority: -6,
// Accounting for the offchance that 5 remaining pokemon are KO'd by entry hazards
@ -477,7 +477,7 @@ exports.BattleMovedex = {
var source = this.effectData.source;
var damage = target.heal(target.maxhp);
target.setStatus('');
this.add('-heal',target,target.getHealth,'[from] move: Healing Wish');
this.add('-heal', target, target.getHealth, '[from] move: Healing Wish');
target.side.removeSideCondition('healingwish');
}
}
@ -564,7 +564,7 @@ exports.BattleMovedex = {
pp: 20,
onMoveFail: function(target, source, move) {
var damage = this.getDamage(source, target, move, true);
this.damage(this.clampIntRange(damage/2, 1, Math.floor(target.maxhp/2)), source);
this.damage(this.clampIntRange(damage / 2, 1, Math.floor(target.maxhp / 2)), source);
}
},
iciclespear: {
@ -576,9 +576,9 @@ exports.BattleMovedex = {
isSnatchable: false,
onTryHit: function(pokemon) {
var targets = pokemon.side.foe.active;
for (var i=0; i<targets.length; i++) {
for (var i = 0; i < targets.length; i++) {
if (!targets[i] || targets[i].fainted) continue;
for (var j=0; j<pokemon.moves.length; j++) {
for (var j = 0; j < pokemon.moves.length; j++) {
if (targets[i].moves.indexOf(pokemon.moves[j]) >= 0) return;
}
}
@ -593,7 +593,7 @@ exports.BattleMovedex = {
pp: 25,
onMoveFail: function(target, source, move) {
var damage = this.getDamage(source, target, move, true);
this.damage(this.clampIntRange(damage/2, 1, Math.floor(target.maxhp/2)), source);
this.damage(this.clampIntRange(damage / 2, 1, Math.floor(target.maxhp / 2)), source);
}
},
lastresort: {
@ -703,12 +703,12 @@ exports.BattleMovedex = {
move: move.name,
id: move.id,
pp: 5,
maxpp: move.pp * 8/5,
maxpp: move.pp * 8 / 5,
disabled: false,
used: false
};
source.moves[moveslot] = toId(move.name);
this.add('-message', source.name+' learned '+move.name+'! (placeholder)');
this.add('-message', source.name + ' learned ' + move.name + '! (placeholder)');
}
},
minimize: {
@ -831,7 +831,7 @@ exports.BattleMovedex = {
source.moveset[moveslot] = sketchedMove;
source.baseMoveset[moveslot] = sketchedMove;
source.moves[moveslot] = toId(move.name);
this.add('-message', source.name+' learned '+move.name+'! (placeholder)');
this.add('-message', source.name + ' learned ' + move.name + '! (placeholder)');
}
},
skillswap: {
@ -941,7 +941,7 @@ exports.BattleMovedex = {
if (!pokemon.runImmunity('Ground')) return;
if (!pokemon.runImmunity('Poison')) return;
if (pokemon.hasType('Poison')) {
this.add('-sideend', pokemon.side, 'move: Toxic Spikes', '[of] '+pokemon);
this.add('-sideend', pokemon.side, 'move: Toxic Spikes', '[of] ' + pokemon);
pokemon.side.removeSideCondition('toxicspikes');
}
if (pokemon.volatiles['substitute']) {
@ -980,8 +980,8 @@ exports.BattleMovedex = {
var target = side.active[this.effectData.sourcePosition];
if (!target.fainted) {
var source = this.effectData.source;
var damage = this.heal(target.maxhp/2, target, target);
if (damage) this.add('-heal', target, target.getHealth, '[from] move: Wish', '[wisher] '+source.name);
var damage = this.heal(target.maxhp / 2, target, target);
if (damage) this.add('-heal', target, target.getHealth, '[from] move: Wish', '[wisher] ' + source.name);
}
}
}
@ -1003,7 +1003,7 @@ exports.BattleMovedex = {
wringout: {
inherit: true,
basePowerCallback: function(pokemon) {
return Math.floor(pokemon.hp*120/pokemon.maxhp) + 1;
return Math.floor(pokemon.hp * 120 / pokemon.maxhp) + 1;
}
},
magikarpsrevenge: null

View File

@ -14,7 +14,7 @@ exports.BattleStatuses = {
onStart: function(target) {
this.add('-status', target, 'slp');
// 1-4 turns
this.effectData.time = this.random(2,6);
this.effectData.time = this.random(2, 6);
},
onBeforeMovePriority: 2,
onBeforeMove: function(pokemon, target, move) {
@ -41,7 +41,7 @@ exports.BattleStatuses = {
inherit: true,
durationCallback: function(target, source) {
if (source.item === 'gripclaw') return 6;
return this.random(3,7);
return this.random(3, 7);
}
},
stall: {

View File

@ -6,7 +6,7 @@ exports.BattleAbilities = {
onStart: function(pokemon) {
var target = pokemon.side.foe.randomActive();
if (target && target.item) {
this.add('-item', target, target.getItem().name, '[from] ability: Frisk', '[of] '+pokemon);
this.add('-item', target, target.getItem().name, '[from] ability: Frisk', '[of] ' + pokemon);
}
}
},
@ -27,7 +27,7 @@ exports.BattleAbilities = {
onUpdate: function(pokemon) {
if (pokemon.volatiles['attract']) {
pokemon.removeVolatile('attract');
this.add("-message", pokemon.name+" got over its infatuation. (placeholder)");
this.add("-message", pokemon.name + " got over its infatuation. (placeholder)");
}
},
onTryHit: function(pokemon, target, move) {

View File

@ -16,10 +16,10 @@ exports.BattleMovedex = {
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++) {
for (var j = 0; j < target.side.pokemon.length; j++) {
var pokemon = target.side.pokemon[j];
if (pokemon === target) continue;
for (var i=0; i<pokemon.moves.length; i++) {
for (var i = 0; i < pokemon.moves.length; i++) {
var move = pokemon.moves[i];
var 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
@ -128,7 +128,7 @@ exports.BattleMovedex = {
var sideConditions = {reflect:1, lightscreen:1, safeguard:1, mist:1, spikes:1, toxicspikes:1, stealthrock:1};
for (var i in sideConditions) {
if (pokemon.side.removeSideCondition(i)) {
this.add('-sideend', pokemon.side, this.getEffect(i).name, '[from] move: Defog', '[of] '+pokemon);
this.add('-sideend', pokemon.side, this.getEffect(i).name, '[from] move: Defog', '[of] ' + pokemon);
}
}
}
@ -251,7 +251,7 @@ exports.BattleMovedex = {
},
healpulse: {
inherit: true,
heal: [1,2],
heal: [1, 2],
onHit: function() {}
},
heatwave: {

View File

@ -9,7 +9,7 @@ exports.BattleScripts = {
// 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 stack = 'Template incompatible with random battles: ' + name;
var fakeErr = {stack: stack};
require('../crashlogger.js')(fakeErr, 'The randbat set generator');
}
@ -49,13 +49,13 @@ exports.BattleScripts = {
var counter = {};
var setupType = '';
var j=0;
var j = 0;
do {
// Choose next 4 moves from learnset/viable moves and add them to moves list:
while (moves.length<4 && j<moveKeys.length) {
while (moves.length < 4 && j < moveKeys.length) {
var moveid = toId(moveKeys[j]);
j++;
if (moveid.substr(0,11) === 'hiddenpower') {
if (moveid.substr(0, 11) === 'hiddenpower') {
if (!hasMove['hiddenpower']) {
hasMove['hiddenpower'] = true;
} else {
@ -76,7 +76,7 @@ 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++) {
for (var k = 0; k < moves.length; k++) {
var move = this.getMove(moves[k]);
var moveid = move.id;
// Keep track of all moves we have:
@ -179,7 +179,7 @@ exports.BattleScripts = {
}
// Iterate through the moves again, this time to cull them:
for (var k=0; k<moves.length; k++) {
for (var k = 0; k < moves.length; k++) {
var moveid = moves[k];
var move = this.getMove(moveid);
var rejected = false;
@ -216,7 +216,7 @@ exports.BattleScripts = {
isSetup = true;
break;
case 'shellsmash': case 'growth': case 'workup':
if (counter.Physical+counter.Special < 2 && !hasMove['batonpass']) rejected = true;
if (counter.Physical + counter.Special < 2 && !hasMove['batonpass']) rejected = true;
if (setupType !== 'Mixed' || counter['mixedsetup'] > 1) rejected = true;
isSetup = true;
break;
@ -404,8 +404,8 @@ exports.BattleScripts = {
}
// Remove rejected moves from the move list.
if (rejected && j<moveKeys.length) {
moves.splice(k,1);
if (rejected && j < moveKeys.length) {
moves.splice(k, 1);
break;
}
@ -417,12 +417,12 @@ exports.BattleScripts = {
}
}
}
if (j<moveKeys.length && moves.length === 4) {
if (j < moveKeys.length && moves.length === 4) {
// Move post-processing:
if (damagingMoves.length===0) {
if (damagingMoves.length === 0) {
// Have a 60% chance of rejecting one move at random:
if (Math.random()*1.66<1) moves.splice(Math.floor(Math.random()*moves.length),1);
} else if (damagingMoves.length===1) {
if (Math.random() * 1.66 < 1) moves.splice(Math.floor(Math.random() * moves.length), 1);
} else if (damagingMoves.length === 1) {
// Night Shade, Seismic Toss, etc. don't count:
if (!damagingMoves[0].damage) {
var damagingid = damagingMoves[0].id;
@ -430,11 +430,11 @@ exports.BattleScripts = {
var 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'] && Math.random()*2>1) replace = true;
if (!hasMove['encore'] && Math.random() * 2 > 1) replace = true;
} else if (damagingid === 'focuspunch') {
// Focus Punch is a bad idea without a sub:
if (!hasMove['substitute']) replace = true;
} else if (damagingid.substr(0,11) === 'hiddenpower' && damagingType === 'Ice') {
} else if (damagingid.substr(0, 11) === 'hiddenpower' && damagingType === 'Ice') {
// Mono-HP-Ice is never acceptable.
replace = true;
} else {
@ -450,9 +450,9 @@ exports.BattleScripts = {
}
}
}
if (replace) moves.splice(damagingMoveIndex[damagingid],1);
if (replace) moves.splice(damagingMoveIndex[damagingid], 1);
}
} else if (damagingMoves.length===2) {
} 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('/');
@ -462,20 +462,20 @@ exports.BattleScripts = {
} else {
rejectCombo = false;
}
if (rejectCombo) moves.splice(Math.floor(Math.random()*moves.length),1);
if (rejectCombo) moves.splice(Math.floor(Math.random() * moves.length), 1);
} 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++) {
for (var l = 0; l < damagingMoves.length; l++) {
if (hasStab[damagingMoves[l].type]) {
isStab = true;
break;
}
}
if (!isStab) moves.splice(Math.floor(Math.random()*moves.length),1);
if (!isStab) moves.splice(Math.floor(Math.random() * moves.length), 1);
}
}
} while (moves.length<4 && j<moveKeys.length);
} while (moves.length < 4 && j < moveKeys.length);
// any moveset modification goes here
//moves[0] = 'Safeguard';
@ -487,7 +487,7 @@ exports.BattleScripts = {
if (template.abilities['H']) {
abilities.push(template.abilities['H']);
}
abilities.sort(function(a,b){
abilities.sort(function(a, b){
return this.getAbility(b).rating - this.getAbility(a).rating;
}.bind(this));
var ability0 = this.getAbility(abilities[0]);
@ -496,11 +496,11 @@ exports.BattleScripts = {
if (abilities[1]) {
if (ability0.rating <= ability1.rating) {
if (Math.random()*2<1) {
if (Math.random() * 2 < 1) {
ability = ability1.name;
}
} else if (ability0.rating - 0.6 <= ability1.rating) {
if (Math.random()*3<1) {
if (Math.random() * 3 < 1) {
ability = ability1.name;
}
}
@ -620,17 +620,17 @@ exports.BattleScripts = {
item = 'Focus Sash';
} else if (template.species === 'Unown') {
item = 'Choice Specs';
} else if ((template.species === 'Wynaut' || template.species === 'Wobbuffet') && hasMove['destinybond'] && Math.random()*2 > 1) {
} else if ((template.species === 'Wynaut' || template.species === 'Wobbuffet') && hasMove['destinybond'] && Math.random() * 2 > 1) {
item = 'Custap Berry';
} else if (hasMove['trick'] && hasMove['gyroball'] && (ability === 'Levitate' || hasType['Flying'])) {
item = 'Macho Brace';
} else if (hasMove['trick'] && hasMove['gyroball']) {
item = 'Iron Ball';
} else if (hasMove['trick'] || hasMove['switcheroo']) {
var randomNum = Math.random()*2;
if (counter.Physical >= 3 && (template.baseStats.spe >= 95 || randomNum>1)) {
var randomNum = Math.random() * 2;
if (counter.Physical >= 3 && (template.baseStats.spe >= 95 || randomNum > 1)) {
item = 'Choice Band';
} else if (counter.Special >= 3 && (template.baseStats.spe >= 95 || randomNum>1)) {
} else if (counter.Special >= 3 && (template.baseStats.spe >= 95 || randomNum > 1)) {
item = 'Choice Specs';
} else {
item = 'Choice Scarf';
@ -685,7 +685,7 @@ exports.BattleScripts = {
}
if ((hasMove['return'] || hasMove['hyperfang']) && !hasMove['facade']) {
// lol no
for (var j=0; j<moves.length; j++) {
for (var j = 0; j < moves.length; j++) {
if (moves[j] === 'Return' || moves[j] === 'HyperFang') {
moves[j] = 'Facade';
break;
@ -698,13 +698,13 @@ exports.BattleScripts = {
// less priority than if you'd had both
item = 'Light Clay';
} else if (counter.Physical >= 4 && !hasMove['fakeout'] && !hasMove['suckerpunch'] && !hasMove['flamecharge'] && !hasMove['rapidspin']) {
if (Math.random()*3 > 1) {
if (Math.random() * 3 > 1) {
item = 'Choice Band';
} else {
item = 'Expert Belt';
}
} else if (counter.Special >= 4) {
if (Math.random()*3 > 1) {
if (Math.random() * 3 > 1) {
item = 'Choice Specs';
} else {
item = 'Expert Belt';
@ -729,7 +729,7 @@ exports.BattleScripts = {
} else if (ability === 'Iron Barbs') {
// only Iron Barbs for now
item = 'Rocky Helmet';
} else if ((template.baseStats.hp+75)*(template.baseStats.def+template.baseStats.spd+175) > 60000 || template.species === 'Skarmory' || template.species === 'Forretress') {
} else if ((template.baseStats.hp + 75) * (template.baseStats.def + template.baseStats.spd + 175) > 60000 || template.species === 'Skarmory' || template.species === 'Forretress') {
// skarmory and forretress get exceptions for their typing
item = 'Leftovers';
} else if (counter.Physical + counter.Special >= 3 && setupType) {
@ -738,7 +738,7 @@ exports.BattleScripts = {
item = 'Life Orb';
} else if (counter.Physical + counter.Special >= 4) {
item = 'Expert Belt';
} else if (i===0 && ability !== 'Sturdy' && !counter['recoil']) {
} else if (i === 0 && ability !== 'Sturdy' && !counter['recoil']) {
item = 'Focus Sash';
} else if (hasMove['outrage']) {
item = 'Lum Berry';
@ -814,7 +814,7 @@ exports.BattleScripts = {
ivs: ivs,
item: item,
level: level,
shiny: (Math.random()*1024<=1)
shiny: (Math.random() * 1024 <= 1)
};
},
randomTeam: function(side) {
@ -839,7 +839,7 @@ exports.BattleScripts = {
var uberCount = 0;
var nuCount = 0;
for (var i=0; i<keys.length && pokemonLeft < 6; i++) {
for (var i = 0; i < keys.length && pokemonLeft < 6; i++) {
var template = this.getTemplate(keys[i]);
if (!template || !template.name || !template.types) continue;
var tier = template.tier;
@ -847,23 +847,23 @@ exports.BattleScripts = {
// 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.
if (tier === 'LC' && nuCount > 1) continue;
if ((tier === 'NFE' || tier === 'NU') && nuCount > 1 && Math.random()*5>1) continue;
if (tier === 'Uber' && uberCount > 1 && Math.random()*5>1) continue;
if ((tier === 'NFE' || tier === 'NU') && nuCount > 1 && Math.random() * 5 > 1) continue;
if (tier === 'Uber' && uberCount > 1 && Math.random() * 5 > 1) continue;
// CAPs have 20% the normal rate
if (tier === 'CAP' && Math.random()*5>1) continue;
if (tier === 'CAP' && Math.random() * 5 > 1) continue;
// Arceus formes have 1/17 the normal rate each (so Arceus as a whole has a normal rate)
if (keys[i].substr(0,6) === 'arceus' && Math.random()*17>1) continue;
if (keys[i].substr(0, 6) === 'arceus' && Math.random() * 17 > 1) continue;
// Basculin formes have 1/2 the normal rate each (so Basculin as a whole has a normal rate)
if (keys[i].substr(0,8) === 'basculin' && Math.random()*2>1) continue;
if (keys[i].substr(0, 8) === 'basculin' && Math.random() * 2 > 1) continue;
// Not available on BW
if (template.species === 'Pichu-Spiky-eared') continue;
// Limit 2 of any type
var types = template.types;
var skip = false;
for (var t=0; t<types.length; t++) {
if (typeCount[types[t]] > 1 && Math.random()*5>1) {
for (var t = 0; t < types.length; t++) {
if (typeCount[types[t]] > 1 && Math.random() * 5 > 1) {
skip = true;
break;
}
@ -872,7 +872,7 @@ exports.BattleScripts = {
if (potd && potd.name && potd.types) {
// The Pokemon of the Day belongs in slot 2
if (i===1) {
if (i === 1) {
template = potd;
if (template.species === 'Magikarp') {
template.viableMoves = {magikarpsrevenge:1, splash:1, bounce:1};
@ -899,7 +899,7 @@ exports.BattleScripts = {
pokemonLeft++;
// Now that our Pokemon has passed all checks, we can increment the type counter
for (var t=0; t<types.length; t++) {
for (var t = 0; t < types.length; t++) {
if (types[t] in typeCount) {
typeCount[types[t]]++;
} else {

View File

@ -21,9 +21,9 @@ exports.BattleStatuses = {
return;
}
if (this.effectData.source.item === 'bindingband') {
this.damage(pokemon.maxhp/8);
this.damage(pokemon.maxhp / 8);
} else {
this.damage(pokemon.maxhp/16);
this.damage(pokemon.maxhp / 16);
}
}
},
@ -40,9 +40,9 @@ exports.BattleStatuses = {
var 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);
return (this.random() * 4294967296 < 1);
}
this.debug("Success chance: "+Math.round(100/counter)+"%");
this.debug("Success chance: " + Math.round(100 / counter) + "%");
return (this.random(counter) === 0);
},
onRestart: function() {

View File

@ -62,9 +62,9 @@ exports.BattleAbilities = {
},
onSourceBasePower: function(basePower) {
if (this.isWeather('hail')) {
return basePower * 3/4;
return basePower * 3 / 4;
}
return basePower * 7/8;
return basePower * 7 / 8;
},
onAccuracy: function() {}
},
@ -75,7 +75,7 @@ exports.BattleAbilities = {
},
onSourceBasePower: function(basePower) {
if (this.isWeather('sandstorm')) {
return basePower * 4/5;
return basePower * 4 / 5;
}
},
onAccuracy: function() {}
@ -84,9 +84,9 @@ exports.BattleAbilities = {
inherit: true,
onSourceBasePower: function(basePower) {
if (this.isWeather('raindance')) {
return basePower * 3/4;
return basePower * 3 / 4;
}
return basePower * 7/8;
return basePower * 7 / 8;
}
},
"icebody": {
@ -95,7 +95,7 @@ exports.BattleAbilities = {
if (type === 'hail') return false;
},
onResidual: function(target, source, effect) {
this.heal(target.maxhp/16);
this.heal(target.maxhp / 16);
},
onAfterDamage: function(damage, target, source, move) {
if (move && move.isContact && this.isWeather('hail')) {
@ -147,13 +147,13 @@ exports.BattleAbilities = {
if (pokemon.isActive && pokemon.speciesid === 'cherrim' && this.effectData.forme !== 'Sunshine') {
this.effectData.forme = 'Sunshine';
this.add('-formechange', pokemon, 'Cherrim-Sunshine');
this.add('-message', pokemon.name+' transformed!');
this.add('-message', pokemon.name + ' transformed!');
this.boost({spd:1});
}
} else if (pokemon.isActive && pokemon.speciesid === 'cherrim' && this.effectData.forme) {
delete this.effectData.forme;
this.add('-formechange', pokemon, 'Cherrim');
this.add('-message', pokemon.name+' transformed!');
this.add('-message', pokemon.name + ' transformed!');
}
},
effect: {
@ -223,7 +223,7 @@ exports.BattleAbilities = {
onFoeBasePower: function(basePower, attacker, defender, move) {
if (this.getEffectiveness(move.type, defender) > 0) {
this.add('-message', "The attack was weakened by Solid Rock!");
return basePower * 1/2;
return basePower * 1 / 2;
}
}
},
@ -232,7 +232,7 @@ exports.BattleAbilities = {
onFoeBasePower: function(basePower, attacker, defender, move) {
if (this.getEffectiveness(move.type, defender) > 0) {
this.add('-message', "The attack was weakened by Filter!");
return basePower * 1/2;
return basePower * 1 / 2;
}
}
},
@ -250,7 +250,7 @@ exports.BattleAbilities = {
onBasePower: function(basePower, attacker, defender, move) {
if (move.recoil || move.hasCustomRecoil || attacker.item === 'lifeorb') {
this.debug('Reckless boost');
return basePower * 12/10;
return basePower * 12 / 10;
}
}
},
@ -260,7 +260,7 @@ exports.BattleAbilities = {
for (var i in boost) {
if (boost[i] < 0) {
delete boost[i];
this.add("-message", target.name+"'s stats were not lowered! (placeholder)");
this.add("-message", target.name + "'s stats were not lowered! (placeholder)");
}
}
}
@ -283,7 +283,7 @@ exports.BattleAbilities = {
var foeactive = pokemon.side.foe.active;
var totaldef = 0;
var totalspd = 0;
for (var i=0; i<foeactive.length; i++) {
for (var i = 0; i < foeactive.length; i++) {
if (!foeactive[i] || foeactive[i].fainted) continue;
totaldef += foeactive[i].stats.def;
totalspd += foeactive[i].stats.spd;
@ -308,7 +308,7 @@ exports.BattleAbilities = {
onDamage: function(damage, target, source, effect) {
if (effect && effect.effectType === 'Move') {
this.add('-message', "Its damage was reduced by Shell Armor!");
damage -= target.maxhp/8;
damage -= target.maxhp / 8;
if (damage < 0) damage = 0;
return damage;
}
@ -324,7 +324,7 @@ exports.BattleAbilities = {
onDamage: function(damage, target, source, effect) {
if (effect && effect.effectType === 'Move') {
this.add('-message', "Its damage was reduced by Battle Armor!");
damage -= target.maxhp/8;
damage -= target.maxhp / 8;
if (damage < 0) damage = 0;
return damage;
}
@ -334,7 +334,7 @@ exports.BattleAbilities = {
onDamage: function(damage, target, source, effect) {
if (effect && effect.effectType === 'Move') {
this.add('-message', "Its damage was reduced by Weak Armor!");
damage -= target.maxhp/8;
damage -= target.maxhp / 8;
if (damage < 0) damage = 0;
target.setAbility('');
this.boost({spe: 1});
@ -351,7 +351,7 @@ exports.BattleAbilities = {
},
onDamage: function(damage, target, source, effect) {
if (effect && effect.effectType === 'Move') {
damage -= target.maxhp/8;
damage -= target.maxhp / 8;
if (damage < 0) damage = 0;
if (effect.type === 'Ice' || effect.type === 'Water') {
this.add('-activate', target, 'ability: Magma Armor');
@ -369,7 +369,7 @@ exports.BattleAbilities = {
onSourceModifyDamage: function(damage, source, target, move) {
if (target.hp >= target.maxhp) {
this.add('-message', "The attack was slightly weakened by Multiscale!");
return this.chainModify(2/3);
return this.chainModify(2 / 3);
}
}
},
@ -387,7 +387,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 (var i = 0; i < move.secondaries.length; i++) {
if (move.secondaries[i].volatileStatus === 'flinch') return;
}
move.secondaries.push({
@ -401,7 +401,7 @@ exports.BattleAbilities = {
inherit: true,
onFaint: function(target, source, effect) {
if (effect && effect.effectType === 'Move' && source) {
this.damage(source.maxhp/3, source, target);
this.damage(source.maxhp / 3, source, target);
}
}
},
@ -467,7 +467,7 @@ exports.BattleAbilities = {
onBeforeMove: function(pokemon, target, move) {
if (pokemon.removeVolatile('truant')) {
this.add('cant', pokemon, 'ability: Truant');
this.heal(pokemon.maxhp/3);
this.heal(pokemon.maxhp / 3);
return false;
}
}
@ -488,7 +488,7 @@ exports.BattleAbilities = {
},
onFoeModifyPokemon: function(pokemon) {
var foeMoves = this.effectData.target.moveset;
for (var f=0; f<foeMoves.length; f++) {
for (var f = 0; f < foeMoves.length; f++) {
pokemon.disabledMoves[foeMoves[f].id] = true;
}
},

View File

@ -101,7 +101,7 @@ exports.BattleItems = {
onAfterMoveSelf: function(source, target) {
if (source.hasType('Grass')) {
if (source.lastDamage > 0) {
this.heal(source.lastDamage/8, source);
this.heal(source.lastDamage / 8, source);
}
}
},
@ -109,7 +109,7 @@ exports.BattleItems = {
onResidualSubOrder: 2,
onResidual: function(pokemon) {
if (pokemon.hasType('Grass')) {
this.heal(pokemon.maxhp/16);
this.heal(pokemon.maxhp / 16);
}
}
},
@ -119,9 +119,9 @@ exports.BattleItems = {
onResidualSubOrder: 2,
onResidual: function(pokemon) {
if (pokemon.hasType('Poison')) {
this.heal(pokemon.maxhp/(pokemon.getTypes().length===1 ? 8 : 16));
this.heal(pokemon.maxhp / (pokemon.getTypes().length === 1 ? 8 : 16));
} else {
this.damage(pokemon.maxhp/8);
this.damage(pokemon.maxhp / 8);
}
}
},
@ -138,10 +138,10 @@ exports.BattleItems = {
effect && effect.effectType === 'Move' &&
target.useItem()) {
if (damage >= target.hp) {
this.add("-message",target.name+" held on using its Focus Band!");
this.add("-message", target.name + " held on using its Focus Band!");
return target.hp - 1;
} else {
this.add("-message",target.name+"'s Focus Band broke!");
this.add("-message", target.name + "'s Focus Band broke!");
}
}
},
@ -189,25 +189,25 @@ exports.BattleItems = {
},
onModifyDef: function(def, pokemon) {
if (pokemon.template.species === 'Shuckle') {
return def*1.5;
return def * 1.5;
}
},
onModifySpA: function(spa, pokemon) {
if (pokemon.template.species === 'Unown') {
return spa*2;
return spa * 2;
}
},
onModifySpD: function(spd, pokemon) {
if (pokemon.template.species === 'Unown') {
return spd*2;
return spd * 2;
}
if (pokemon.template.species === 'Shuckle') {
return spd*1.5;
return spd * 1.5;
}
},
onModifySpe: function(spe, pokemon) {
if (pokemon.template.species === 'Unown') {
return spe*2;
return spe * 2;
}
},
onFoeBasePower: function(basePower, attacker, defender, move) {
@ -229,7 +229,7 @@ exports.BattleItems = {
},
// onResidual: function(pokemon) {
// if (pokemon.template.species === 'Shuckle') {
// this.heal(this.clampIntRange(pokemon.maxhp/16, 1));
// this.heal(this.clampIntRange(pokemon.maxhp / 16, 1));
// }
// },
desc: "Raises Farfetch'd's critical hit rate two stages."

View File

@ -130,7 +130,7 @@ exports.BattleMovedex = {
effect: {
onStart: function(target) {
this.add('-start', target, 'Substitute');
this.effectData.hp = Math.floor(target.maxhp/4);
this.effectData.hp = Math.floor(target.maxhp / 4);
delete target.volatiles['partiallytrapped'];
},
onAccuracyPriority: -100,
@ -226,12 +226,12 @@ exports.BattleMovedex = {
if (target.boosts.evasion >= 6) {
return false;
}
if (target.hp <= target.maxhp/4 || target.maxhp === 1) { // Shedinja clause
if (target.hp <= target.maxhp / 4 || target.maxhp === 1) { // Shedinja clause
return false;
}
},
onHit: function(target) {
this.directDamage(target.maxhp/4);
this.directDamage(target.maxhp / 4);
},
boosts: {
evasion: 1
@ -260,7 +260,7 @@ exports.BattleMovedex = {
duration: 2,
onLockMove: 'solarbeam',
onStart: function(pokemon) {
this.heal(pokemon.maxhp/2);
this.heal(pokemon.maxhp / 2);
}
},
breaksProtect: true
@ -293,7 +293,7 @@ exports.BattleMovedex = {
duration: 2,
onLockMove: 'skullbash',
onStart: function(pokemon) {
this.boost({def:1,spd:1,accuracy:1}, pokemon, pokemon, this.getMove('skullbash'));
this.boost({def:1, spd:1, accuracy:1}, pokemon, pokemon, this.getMove('skullbash'));
}
},
breaksProtect: true
@ -539,7 +539,7 @@ exports.BattleMovedex = {
if (!effect || effect.effectType !== 'Move') return;
if (!source || source.side === target.side) return;
if (effect && effect.effectType === 'Move' && damage >= target.hp) {
damage = target.hp-1;
damage = target.hp - 1;
}
this.effectData.totalDamage += damage;
this.effectData.sourcePosition = source.position;
@ -561,7 +561,7 @@ exports.BattleMovedex = {
}
this.add('-end', pokemon, 'Bide');
var target = this.effectData.sourceSide.active[this.effectData.sourcePosition];
this.moveHit(target, pokemon, 'bide', {damage: this.effectData.totalDamage*2});
this.moveHit(target, pokemon, 'bide', {damage: this.effectData.totalDamage * 2});
return false;
}
this.add('-activate', pokemon, 'Bide');
@ -648,13 +648,13 @@ exports.BattleMovedex = {
'Timid': 'Jolly',
'Jolly': 'Timid'
};
if (pokemon.template.speciesid==='meloettapirouette' && pokemon.formeChange('Meloetta')) {
if (pokemon.template.speciesid === 'meloettapirouette' && pokemon.formeChange('Meloetta')) {
this.add('-formechange', pokemon, 'Meloetta');
var 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);
var Atk2SpA = (pokemon.boosts.spa || 0) - (pokemon.boosts.atk || 0);
this.boost({
atk: Atk2SpA,
spa: -Atk2SpA
@ -665,7 +665,7 @@ exports.BattleMovedex = {
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);
var Atk2SpA = (pokemon.boosts.spa || 0) - (pokemon.boosts.atk || 0);
this.boost({
atk: Atk2SpA,
spa: -Atk2SpA
@ -697,12 +697,12 @@ exports.BattleMovedex = {
effect: {
// this is a side condition
onStart: function(side) {
this.add('-sidestart',side,'move: Stealth Rock');
this.add('-sidestart', side, 'move: Stealth Rock');
},
onSwitchIn: function(pokemon) {
var factor = 2;
if (pokemon.hasType('Flying')) factor = 4;
var damage = this.damage(pokemon.maxhp*factor/16);
var damage = this.damage(pokemon.maxhp * factor / 16);
}
}
},
@ -756,7 +756,7 @@ exports.BattleMovedex = {
onHit: function(target, source) {
var stats = [];
for (var i in target.boosts) {
if (i!=='accuracy' && i!=='evasion' && i!=='atk' && target.boosts[i] < 6) {
if (i !== 'accuracy' && i !== 'evasion' && i !== 'atk' && target.boosts[i] < 6) {
stats.push(i);
}
}
@ -786,7 +786,7 @@ exports.BattleMovedex = {
onHit: function(target, source) {
var stats = [];
for (var i in target.boosts) {
if (i!=='accuracy' && i!=='evasion' && i!=='atk' && target.boosts[i] < 6) {
if (i !== 'accuracy' && i !== 'evasion' && i !== 'atk' && target.boosts[i] < 6) {
stats.push(i);
}
}
@ -810,7 +810,7 @@ exports.BattleMovedex = {
onHit: function(target, source) {
var stats = [];
for (var i in target.boosts) {
if (i!=='accuracy' && i!=='evasion' && i!=='atk' && target.boosts[i] < 6) {
if (i !== 'accuracy' && i !== 'evasion' && i !== 'atk' && target.boosts[i] < 6) {
stats.push(i);
}
}
@ -837,10 +837,10 @@ exports.BattleMovedex = {
inherit: true,
basePowerCallback: function(pokemon, source) {
if ((source.lastDamage > 0 && pokemon.lastAttackedBy && pokemon.lastAttackedBy.thisTurn)) {
this.debug('Boosted for getting hit by '+pokemon.lastAttackedBy.move);
return this.isWeather('hail')?180:120;
this.debug('Boosted for getting hit by ' + pokemon.lastAttackedBy.move);
return this.isWeather('hail') ? 180 : 120;
}
return this.isWeather('hail')?90:60;
return this.isWeather('hail') ? 90 : 60;
}
},
/******************************************************************
@ -981,7 +981,7 @@ exports.BattleMovedex = {
inherit: true,
basePower: 40,
accuracy: true,
multihit: [2,2]
multihit: [2, 2]
},
/******************************************************************
Moves with not enough drawbacks:
@ -1143,18 +1143,18 @@ exports.BattleMovedex = {
onBasePower: function(power, user) {
var doubled = false;
if (user.removeVolatile('leechseed')) {
this.add('-end', user, 'Leech Seed', '[from] move: Rapid Spin', '[of] '+user);
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) {
if (user.side.removeSideCondition(i)) {
this.add('-sideend', user.side, this.getEffect(i).name, '[from] move: Rapid Spin', '[of] '+user);
this.add('-sideend', user.side, this.getEffect(i).name, '[from] move: Rapid Spin', '[of] ' + user);
doubled = true;
}
}
if (user.volatiles['partiallytrapped']) {
this.add('-remove', user, user.volatiles['partiallytrapped'].sourceEffect.name, '[from] move: Rapid Spin', '[of] '+user, '[partiallytrapped]');
this.add('-remove', user, user.volatiles['partiallytrapped'].sourceEffect.name, '[from] move: Rapid Spin', '[of] ' + user, '[partiallytrapped]');
doubled = true;
delete user.volatiles['partiallytrapped'];
}
@ -1167,7 +1167,7 @@ exports.BattleMovedex = {
accuracy: 100,
onBasePower: function(power, user) {
if (user.side.removeSideCondition('stealthrock')) {
this.add('-sideend', user.side, "Stealth Rock", '[from] move: Rapid Spin', '[of] '+user);
this.add('-sideend', user.side, "Stealth Rock", '[from] move: Rapid Spin', '[of] ' + user);
return power * 2;
}
}
@ -1680,7 +1680,7 @@ exports.BattleMovedex = {
inherit: true,
basePower: 40,
accuracy: true,
multihit: [2,2]
multihit: [2, 2]
},
acid: {
inherit: true,
@ -1712,14 +1712,14 @@ exports.BattleMovedex = {
pp: 10,
isViable: true,
priority: 0,
multihit: [3,3],
multihit: [3, 3],
secondary: {
chance: 10,
onHit: function(target, source) {
var result = this.random(3);
if (result===0) {
if (result === 0) {
target.trySetStatus('brn', source);
} else if (result===1) {
} else if (result === 1) {
target.trySetStatus('par', source);
} else {
target.trySetStatus('frz', source);

View File

@ -26,7 +26,7 @@ exports.BattleStatuses = {
lockedmove: {
// Outrage, Thrash, Petal Dance...
durationCallback: function() {
return this.random(2,4);
return this.random(2, 4);
},
onResidual: function(target) {
var move = this.getMove(target.lastMove);
@ -52,7 +52,7 @@ exports.BattleStatuses = {
var result = this.runEvent('TryConfusion', target, source, sourceEffect);
if (!result) return result;
this.add('-start', target, 'confusion');
this.effectData.time = this.random(3,4);
this.effectData.time = this.random(3, 4);
},
onEnd: function(target) {
this.add('-end', target, 'confusion');
@ -63,7 +63,7 @@ exports.BattleStatuses = {
pokemon.removeVolatile('confusion');
return;
}
this.directDamage(this.getDamage(pokemon,pokemon,30));
this.directDamage(this.getDamage(pokemon, pokemon, 30));
}
},

View File

@ -16,8 +16,8 @@ exports.BattleMovedex = {
var side = pokemon.side;
if (!pokemon.runImmunity('Ground')) return;
if (pokemon.hasType('Flying') && pokemon.item !== 'ironball' && !this.pseudoWeather.gravity && !pokemon.volatiles['ingrain']) return;
var damageAmounts = [0,3,4,6]; // 1/8, 1/6, 1/4
var damage = this.damage(damageAmounts[this.effectData.layers]*pokemon.maxhp/24);
var damageAmounts = [0, 3, 4, 6]; // 1/8, 1/6, 1/4
var damage = this.damage(damageAmounts[this.effectData.layers] * pokemon.maxhp / 24);
}
}
},
@ -52,7 +52,7 @@ exports.BattleMovedex = {
if (!pokemon.runImmunity('Poison')) return;
if (pokemon.hasType('Flying') && pokemon.item !== 'ironball' && !this.pseudoWeather.gravity && !pokemon.volatiles['ingrain']) return;
if (pokemon.hasType('Poison')) {
this.add('-sideend', pokemon.side, 'move: Toxic Spikes', '[of] '+pokemon);
this.add('-sideend', pokemon.side, 'move: Toxic Spikes', '[of] ' + pokemon);
pokemon.side.removeSideCondition('toxicspikes');
} else if (this.effectData.layers >= 2) {
pokemon.trySetStatus('tox');

196
rooms.js
View File

@ -9,9 +9,9 @@
* @license MIT license
*/
const TIMEOUT_EMPTY_DEALLOCATE = 10*60*1000;
const TIMEOUT_INACTIVE_DEALLOCATE = 40*60*1000;
const REPORT_USER_STATS_INTERVAL = 1000*60*10;
const TIMEOUT_EMPTY_DEALLOCATE = 10 * 60 * 1000;
const TIMEOUT_INACTIVE_DEALLOCATE = 40 * 60 * 1000;
const REPORT_USER_STATS_INTERVAL = 1000 * 60 * 10;
var fs = require('fs');
@ -54,13 +54,13 @@ 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 (var 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);
console.log("NEW CHATROOM: "+id);
console.log("NEW CHATROOM: " + id);
var room = rooms[id] = new ChatRoom(id, this.chatRoomData[i].title, this.chatRoomData[i]);
this.chatRooms.push(room);
if (room.autojoin) this.autojoin.push(id);
@ -116,7 +116,7 @@ var GlobalRoom = (function() {
return;
}
writing = true;
var data = JSON.stringify(self.chatRoomData).replace(/\{"title"\:/g, '\n{"title":').replace(/\]$/,'\n]');
var 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) {
@ -172,9 +172,9 @@ var GlobalRoom = (function() {
if (!section) section = '';
if (section !== curSection) {
curSection = section;
formatListText += '|,' + (format.column || 1) + '|'+section;
formatListText += '|,' + (format.column || 1) + '|' + section;
}
formatListText += '|'+format.name;
formatListText += '|' + format.name;
if (!format.challengeShow) formatListText += ',,';
else if (!format.searchShow) formatListText += ',';
if (format.team) formatListText += ',#';
@ -185,7 +185,7 @@ var GlobalRoom = (function() {
GlobalRoom.prototype.getRoomList = function(filter) {
var roomList = {};
var total = 0;
for (var i=this.rooms.length-1; i>=0; i--) {
for (var i = this.rooms.length - 1; i >= 0; i--) {
var room = this.rooms[i];
if (!room || !room.active) continue;
if (filter && filter !== room.format && filter !== true) continue;
@ -204,7 +204,7 @@ var GlobalRoom = (function() {
};
GlobalRoom.prototype.getRooms = function() {
var rooms = {official:[], chat:[], userCount: this.userCount, battleCount: this.battleCount};
for (var i=0; i<this.chatRooms.length; i++) {
for (var i = 0; i < this.chatRooms.length; i++) {
var room = this.chatRooms[i];
if (!room) continue;
if (room.isPrivate) continue;
@ -219,19 +219,19 @@ var GlobalRoom = (function() {
GlobalRoom.prototype.cancelSearch = function(user) {
var success = false;
user.cancelChallengeTo();
for (var i=0; i<this.searchers.length; i++) {
for (var i = 0; i < this.searchers.length; i++) {
var search = this.searchers[i];
var searchUser = Users.get(search.userid);
if (!searchUser.connected) {
this.searchers.splice(i,1);
this.searchers.splice(i, 1);
i--;
continue;
}
if (searchUser === user) {
this.searchers.splice(i,1);
this.searchers.splice(i, 1);
i--;
if (!success) {
searchUser.send('|updatesearch|'+JSON.stringify({searching: false}));
searchUser.send('|updatesearch|' + JSON.stringify({searching: false}));
success = true;
}
continue;
@ -253,7 +253,7 @@ var GlobalRoom = (function() {
var newSearchData = {
format: formatid
};
user.send('|updatesearch|'+JSON.stringify({searching: newSearchData}));
user.send('|updatesearch|' + JSON.stringify({searching: newSearchData}));
// get the user's rating before actually starting to search
var newSearch = {
@ -266,7 +266,7 @@ var GlobalRoom = (function() {
var self = this;
user.doWithMMR(formatid, function(mmr, error) {
if (error) {
user.popup("Connection to ladder server failed with error: "+error+"; please try again later");
user.popup("Connection to ladder server failed with error: " + error + "; please try again later");
return;
}
newSearch.rating = mmr;
@ -281,9 +281,9 @@ var GlobalRoom = (function() {
if (user1.lastMatch === user2.userid || user2.lastMatch === user1.userid) return false;
// search must be within range
var searchRange = 100, formatid = search1.formatid, elapsed = Math.abs(search1.time-search2.time);
var searchRange = 100, formatid = search1.formatid, elapsed = Math.abs(search1.time - search2.time);
if (formatid === 'ou' || formatid === 'oucurrent' || formatid === 'randombattle') searchRange = 50;
searchRange += elapsed/300; // +1 every .3 seconds
searchRange += elapsed / 300; // +1 every .3 seconds
if (searchRange > 300) searchRange = 300;
if (Math.abs(search1.rating - search2.rating) > searchRange) return false;
@ -293,11 +293,11 @@ var GlobalRoom = (function() {
};
GlobalRoom.prototype.addSearch = function(newSearch, user) {
if (!user.connected) return;
for (var i=0; i<this.searchers.length; i++) {
for (var i = 0; i < this.searchers.length; i++) {
var search = this.searchers[i];
var searchUser = Users.get(search.userid);
if (!searchUser || !searchUser.connected) {
this.searchers.splice(i,1);
this.searchers.splice(i, 1);
i--;
continue;
}
@ -305,7 +305,7 @@ var GlobalRoom = (function() {
if (newSearch.formatid === search.formatid && this.matchmakingOK(search, newSearch, searchUser, user)) {
this.cancelSearch(user, true);
this.cancelSearch(searchUser, true);
user.send('|updatesearch|'+JSON.stringify({searching: false}));
user.send('|updatesearch|' + JSON.stringify({searching: false}));
this.startBattle(searchUser, user, search.formatid, true, search.team, newSearch.team);
return;
}
@ -358,7 +358,7 @@ var GlobalRoom = (function() {
// 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 (var i = this.chatRoomData.length - 1; i >= 0; i--) {
if (id === toId(this.chatRoomData[i].title)) {
this.chatRoomData.splice(i, 1);
this.writeChatRoomData();
@ -371,7 +371,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 (var i = this.chatRooms.length - 1; i >= 0; i--) {
if (id === this.chatRooms[i].id) {
this.chatRooms.splice(i, 1);
break;
@ -388,20 +388,20 @@ 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 (var i = 0; i < this.autojoin.length; i++) {
user.joinRoom(this.autojoin[i], connection);
}
};
GlobalRoom.prototype.checkAutojoin = function(user, connection) {
if (user.isStaff) {
for (var i=0; i<this.staffAutojoin.length; i++) {
for (var i = 0; i < this.staffAutojoin.length; i++) {
user.joinRoom(this.staffAutojoin[i], connection);
}
}
};
GlobalRoom.prototype.onJoinConnection = function(user, connection) {
var initdata = '|updateuser|'+user.name+'|'+(user.named?'1':'0')+'|'+user.avatar+'\n';
connection.send(initdata+this.formatListText);
var 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
};
GlobalRoom.prototype.onJoin = function(user, connection, merging) {
@ -415,8 +415,8 @@ var GlobalRoom = (function() {
}
if (!merging) {
var initdata = '|updateuser|'+user.name+'|'+(user.named?'1':'0')+'|'+user.avatar+'\n';
connection.send(initdata+this.formatListText);
var 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
}
@ -460,15 +460,15 @@ var GlobalRoom = (function() {
return;
}
//console.log('BATTLE START BETWEEN: '+p1.userid+' '+p2.userid);
var i = this.lastBattle+1;
var formaturlid = format.toLowerCase().replace(/[^a-z0-9]+/g,'');
while(rooms['battle-'+formaturlid+i]) {
//console.log('BATTLE START BETWEEN: ' + p1.userid + ' ' + p2.userid);
var i = this.lastBattle + 1;
var formaturlid = format.toLowerCase().replace(/[^a-z0-9] + /g, '');
while(rooms['battle-' + formaturlid + i]) {
i++;
}
this.lastBattle = i;
rooms.global.writeNumRooms();
newRoom = this.addRoom('battle-'+formaturlid+'-'+i, format, p1, p2, this.id, rated);
newRoom = this.addRoom('battle-' + formaturlid + '-' + i, format, p1, p2, this.id, rated);
p1.joinRoom(newRoom);
p2.joinRoom(newRoom);
newRoom.joinBattle(p1, p1team);
@ -476,7 +476,7 @@ var GlobalRoom = (function() {
this.cancelSearch(p1, true);
this.cancelSearch(p2, true);
if (Config.reportbattles && rooms.lobby) {
rooms.lobby.add('|b|'+newRoom.id+'|'+p1.getIdentity()+'|'+p2.getIdentity());
rooms.lobby.add('|b|' + newRoom.id + '|' + p1.getIdentity() + '|' + p2.getIdentity());
}
return newRoom;
};
@ -491,9 +491,9 @@ var GlobalRoom = (function() {
room = getRoom(room);
if (!room) return;
if (this.id in room.i) {
this.rooms.splice(room.i[this.id],1);
this.rooms.splice(room.i[this.id], 1);
delete room.i[this.id];
for (var i=0; i<this.rooms.length; i++) {
for (var i = 0; i < this.rooms.length; i++) {
this.rooms[i].i[this.id] = i;
}
}
@ -511,11 +511,11 @@ var GlobalRoom = (function() {
var BattleRoom = (function() {
function BattleRoom(roomid, format, p1, p2, parentid, rated) {
this.id = roomid;
this.title = ""+p1.name+" vs. "+p2.name;
this.title = "" + p1.name + " vs. " + p2.name;
this.i = {};
this.modchat = (Config.battlemodchat || false);
format = ''+(format||'');
format = '' + (format || '');
this.users = {};
this.format = format;
@ -537,12 +537,12 @@ var BattleRoom = (function() {
this.rated = rated;
this.battle = Simulator.create(this.id, format, rated, this);
this.parentid = parentid||'';
this.parentid = parentid || '';
this.p1 = p1 || '';
this.p2 = p2 || '';
this.sideTicksLeft = [21, 21];
if (!rated) this.sideTicksLeft = [28,28];
if (!rated) this.sideTicksLeft = [28, 28];
this.sideTurnTicks = [0, 0];
this.disconnectTickDiff = [0, 0];
@ -583,7 +583,7 @@ var BattleRoom = (function() {
var p2 = rated.p2;
if (Users.getExact(rated.p2)) p2 = Users.getExact(rated.p2).name;
//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]');
//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]');
if (!rated.p1 || !rated.p2) {
this.push('|raw|ERROR: Ladder not updated: a player does not exist');
@ -607,7 +607,7 @@ var BattleRoom = (function() {
return;
}
if (!data) {
self.addRaw('Ladder (probably) updated, but score could not be retrieved ('+error+').');
self.addRaw('Ladder (probably) updated, but score could not be retrieved (' + error + ').');
self.update();
// log the battle anyway
if (!Tools.getFormat(self.format).noLog) {
@ -615,7 +615,7 @@ var BattleRoom = (function() {
}
return;
} else if (data.errorip) {
self.addRaw("This server's request IP "+data.errorip+" is not a registered server.");
self.addRaw("This server's request IP " + data.errorip + " is not a registered server.");
return;
} else {
try {
@ -626,15 +626,15 @@ var BattleRoom = (function() {
var oldacre = Math.round(data.p1rating.oldacre);
var acre = Math.round(data.p1rating.acre);
var reasons = ''+(acre-oldacre)+' for '+(p1score>0.99?'winning':(p1score<0.01?'losing':'tying'));
if (reasons.substr(0,1) !== '-') reasons = '+'+reasons;
self.addRaw(sanitize(p1)+'\'s rating: '+oldacre+' &rarr; <strong>'+acre+'</strong><br />('+reasons+')');
var reasons = '' + (acre - oldacre) + ' for ' + (p1score > 0.99 ? 'winning' : (p1score < 0.01 ? 'losing' : 'tying'));
if (reasons.substr(0, 1) !== '-') reasons = '+' + reasons;
self.addRaw(sanitize(p1) + '\'s rating: ' + oldacre + ' &rarr; <strong>' + acre + '</strong><br />(' + reasons + ')');
oldacre = Math.round(data.p2rating.oldacre);
acre = Math.round(data.p2rating.acre);
reasons = ''+(acre-oldacre)+' for '+(p1score>0.99?'losing':(p1score<0.01?'winning':'tying'));
if (reasons.substr(0,1) !== '-') reasons = '+'+reasons;
self.addRaw(sanitize(p2)+'\'s rating: '+oldacre+' &rarr; <strong>'+acre+'</strong><br />('+reasons+')');
reasons = '' + (acre - oldacre) + ' for ' + (p1score > 0.99 ? 'losing':(p1score < 0.01 ? 'winning' : 'tying'));
if (reasons.substr(0, 1) !== '-') reasons = '+' + reasons;
self.addRaw(sanitize(p2) + '\'s rating: ' + oldacre + ' &rarr; <strong>' + acre + '</strong><br />(' + reasons + ')');
Users.get(p1).cacheMMR(rated.format, data.p1rating);
Users.get(p2).cacheMMR(rated.format, data.p2rating);
@ -651,7 +651,7 @@ var BattleRoom = (function() {
});
}
}
rooms.global.battleCount += 0 - (this.active?1:0);
rooms.global.battleCount += 0 - (this.active ? 1 : 0);
this.active = false;
this.update();
};
@ -730,15 +730,15 @@ var BattleRoom = (function() {
var date = new Date();
var logfolder = date.format('{yyyy}-{MM}');
var logsubfolder = date.format('{yyyy}-{MM}-{dd}');
var curpath = 'logs/'+logfolder;
var curpath = 'logs/' + logfolder;
var self = this;
fs.mkdir(curpath, '0755', function() {
var tier = self.format.toLowerCase().replace(/[^a-z0-9]+/g,'');
curpath += '/'+tier;
var tier = self.format.toLowerCase().replace(/[^a-z0-9]+/g, '');
curpath += '/' + tier;
fs.mkdir(curpath, '0755', function() {
curpath += '/'+logsubfolder;
curpath += '/' + logsubfolder;
fs.mkdir(curpath, '0755', function() {
fs.writeFile(curpath+'/'+self.id+'.log.json', JSON.stringify(logData));
fs.writeFile(curpath + '/' + self.id + '.log.json', JSON.stringify(logData));
});
});
}); // asychronicity
@ -748,7 +748,7 @@ var BattleRoom = (function() {
if (user) {
user.sendTo(this, message);
} else {
Sockets.channelBroadcast(this.id, '>'+this.id+'\n'+message);
Sockets.channelBroadcast(this.id, '>' + this.id + '\n' + message);
}
};
BattleRoom.prototype.tryExpire = function() {
@ -767,7 +767,7 @@ var BattleRoom = (function() {
this.add('RESET');
this.update();
rooms.global.battleCount += 0 - (this.active?1:0);
rooms.global.battleCount += 0 - (this.active ? 1 : 0);
this.active = false;
if (this.parentid) {
getRoom(this.parentid).updateRooms();
@ -792,17 +792,17 @@ var BattleRoom = (function() {
var ids = ['p1', 'p2'];
var otherids = ['p2', 'p1'];
var name = 'Player '+(side+1);
var name = 'Player ' + (side + 1);
if (user) {
name = user.name;
} else if (this.rated) {
name = this.rated[ids[side]];
}
this.addCmd('-message', name+message);
this.addCmd('-message', name + message);
this.battle.endType = 'forfeit';
this.battle.send('win', otherids[side]);
rooms.global.battleCount += (this.battle.active?1:0) - (this.active?1:0);
rooms.global.battleCount += (this.battle.active ? 1 : 0) - (this.active ? 1 : 0);
this.active = this.battle.active;
this.update();
return true;
@ -830,26 +830,26 @@ var BattleRoom = (function() {
ticksLeft[1] = Math.min(this.sideTurnTicks[1], this.sideTicksLeft[1]);
if (ticksLeft[0] && ticksLeft[1]) {
if (inactiveSide == 0 || inactiveSide == 1) {
if (inactiveSide === 0 || inactiveSide === 1) {
// one side is inactive
var inactiveTicksLeft = ticksLeft[inactiveSide];
var 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.');
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);
if (ticksLeft[0] % 3 == 0 || ticksLeft[0] <= 4) {
this.send('|inactive|'+(inactiveUser0?inactiveUser0.name:'Player 1')+' has '+(ticksLeft[0]*10)+' seconds left.', inactiveUser0);
if (ticksLeft[0] % 3 === 0 || ticksLeft[0] <= 4) {
this.send('|inactive|' + (inactiveUser0 ? inactiveUser0.name : 'Player 1') + ' has ' + (ticksLeft[0] * 10) + ' seconds left.', inactiveUser0);
}
var inactiveUser1 = this.battle.getPlayer(1);
if (ticksLeft[1] % 3 == 0 || ticksLeft[1] <= 4) {
this.send('|inactive|'+(inactiveUser1?inactiveUser1.name:'Player 2')+' has '+(ticksLeft[1]*10)+' seconds left.', inactiveUser1);
if (ticksLeft[1] % 3 === 0 || ticksLeft[1] <= 4) {
this.send('|inactive|' + (inactiveUser1 ? inactiveUser1.name : 'Player 2') + ' has ' + (ticksLeft[1] * 10) + ' seconds left.', inactiveUser1);
}
}
this.resetTimer = setTimeout(this.kickInactive.bind(this), 10*1000);
this.resetTimer = setTimeout(this.kickInactive.bind(this), 10 * 1000);
return;
}
@ -858,7 +858,7 @@ var BattleRoom = (function() {
else if (ticksLeft[1]) inactiveSide = 0;
}
this.forfeit(this.battle.getPlayer(inactiveSide),' lost due to inactivity.', inactiveSide);
this.forfeit(this.battle.getPlayer(inactiveSide), ' lost due to inactivity.', inactiveSide);
this.resetUser = '';
if (this.parentid) {
@ -873,7 +873,7 @@ var BattleRoom = (function() {
if (user) {
if (!force && this.battle.getSlot(user) < 0) return false;
this.resetUser = user.userid;
this.send('|inactive|Battle timer is now ON: inactive players will automatically lose when time\'s up. (requested by '+user.name+')');
this.send('|inactive|Battle timer is now ON: inactive players will automatically lose when time\'s up. (requested by ' + user.name + ')');
} else if (user === false) {
this.resetUser = '~';
this.add('|inactive|Battle timer is ON: inactive players will automatically lose when time\'s up.');
@ -901,15 +901,15 @@ var BattleRoom = (function() {
if (inactiveSide != 1) {
// side 0 is inactive
var ticksLeft0 = Math.min(this.sideTicksLeft[0] + 1, maxTicksLeft);
this.send('|inactive|You have '+(ticksLeft0*10)+' seconds to make your decision.', this.battle.getPlayer(0));
this.send('|inactive|You have ' + (ticksLeft0 * 10) + ' seconds to make your decision.', this.battle.getPlayer(0));
}
if (inactiveSide != 0) {
// side 1 is inactive
var ticksLeft1 = Math.min(this.sideTicksLeft[1] + 1, maxTicksLeft);
this.send('|inactive|You have '+(ticksLeft1*10)+' seconds to make your decision.', this.battle.getPlayer(1));
this.send('|inactive|You have ' + (ticksLeft1 * 10) + ' seconds to make your decision.', this.battle.getPlayer(1));
}
this.resetTimer = setTimeout(this.kickInactive.bind(this), 10*1000);
this.resetTimer = setTimeout(this.kickInactive.bind(this), 10 * 1000);
return true;
};
BattleRoom.prototype.nextInactive = function() {
@ -983,7 +983,7 @@ var BattleRoom = (function() {
BattleRoom.prototype.decision = function(user, choice, data) {
this.battle.sendFor(user, choice, data);
if (this.active !== this.battle.active) {
rooms.global.battleCount += (this.battle.active?1:0) - (this.active?1:0);
rooms.global.battleCount += (this.battle.active ? 1 : 0) - (this.active ? 1 : 0);
this.active = this.battle.active;
if (this.parentid) {
getRoom(this.parentid).updateRooms();
@ -994,7 +994,7 @@ var BattleRoom = (function() {
// This function is only called when the room is not empty.
// Joining an empty room calls this.join() below instead.
BattleRoom.prototype.onJoinConnection = function(user, connection) {
this.send('|init|battle\n|title|'+this.title+'\n'+this.getLogForUser(user).join('\n'), connection);
this.send('|init|battle\n|title|' + this.title + '\n' + this.getLogForUser(user).join('\n'), connection);
// this handles joining a battle in which a user is a participant,
// where the user has already identified before attempting to join
// the battle
@ -1011,7 +1011,7 @@ var BattleRoom = (function() {
this.update(user);
}
this.send('|init|battle\n|title|'+this.title+'\n'+this.getLogForUser(user).join('\n'), connection);
this.send('|init|battle\n|title|' + this.title + '\n' + this.getLogForUser(user).join('\n'), connection);
return user;
};
BattleRoom.prototype.onRename = function(user, oldid, joining) {
@ -1021,7 +1021,7 @@ var BattleRoom = (function() {
var resend = joining || !this.battle.playerTable[oldid];
if (this.battle.playerTable[oldid]) {
if (this.rated) {
this.add('|message|'+user.name+' forfeited by changing their name.');
this.add('|message|' + user.name + ' forfeited by changing their name.');
this.battle.lose(oldid);
this.battle.leave(oldid);
resend = false;
@ -1044,7 +1044,7 @@ var BattleRoom = (function() {
if (!user) return; // ...
if (user.battles[this.id]) {
this.battle.leave(user);
rooms.global.battleCount += (this.battle.active?1:0) - (this.active?1:0);
rooms.global.battleCount += (this.battle.active ? 1 : 0) - (this.active ? 1 : 0);
this.active = this.battle.active;
if (this.parentid) {
getRoom(this.parentid).updateRooms();
@ -1057,7 +1057,7 @@ var BattleRoom = (function() {
this.addCmd('leave', user.name);
if (Object.isEmpty(this.users)) {
rooms.global.battleCount += 0 - (this.active?1:0);
rooms.global.battleCount += 0 - (this.active ? 1 : 0);
this.active = false;
}
@ -1072,18 +1072,18 @@ var BattleRoom = (function() {
} else if (this.rated.p2 === user.userid) {
slot = 1;
} else {
user.popup("This is a rated battle; your username must be "+this.rated.p1+" or "+this.rated.p2+" to join.");
user.popup("This is a rated battle; your username must be " + this.rated.p1 + " or " + this.rated.p2 + " to join.");
return false;
}
}
this.auth[user.userid] = '\u2605';
this.battle.join(user, slot, team);
rooms.global.battleCount += (this.battle.active?1:0) - (this.active?1:0);
rooms.global.battleCount += (this.battle.active ? 1 : 0) - (this.active ? 1 : 0);
this.active = this.battle.active;
if (this.active) {
this.title = ""+this.battle.p1+" vs. "+this.battle.p2;
this.send('|title|'+this.title);
this.title = "" + this.battle.p1 + " vs. " + this.battle.p2;
this.send('|title|' + this.title);
}
this.update();
this.kickInactiveUpdate();
@ -1100,7 +1100,7 @@ var BattleRoom = (function() {
return false;
}
this.auth[user.userid] = '+';
rooms.global.battleCount += (this.battle.active?1:0) - (this.active?1:0);
rooms.global.battleCount += (this.battle.active ? 1 : 0) - (this.active ? 1 : 0);
this.active = this.battle.active;
this.update();
this.kickInactiveUpdate();
@ -1111,7 +1111,7 @@ var BattleRoom = (function() {
return true;
};
BattleRoom.prototype.addCmd = function() {
this.log.push('|'+Array.prototype.slice.call(arguments).join('|'));
this.log.push('|' + Array.prototype.slice.call(arguments).join('|'));
};
BattleRoom.prototype.add = function(message) {
if (message.rawMessage) {
@ -1179,7 +1179,7 @@ var ChatRoom = (function() {
Object.merge(this, options);
}
this.id = roomid;
this.title = title||roomid;
this.title = title || roomid;
this.i = {};
this.log = [];
@ -1308,9 +1308,9 @@ var ChatRoom = (function() {
continue;
}
counter++;
buffer += ','+this.users[i].getIdentity(this.id);
buffer += ',' + this.users[i].getIdentity(this.id);
}
var msg = '|users|'+counter+buffer;
var msg = '|users|' + counter + buffer;
return msg;
};
ChatRoom.prototype.update = function() {
@ -1329,7 +1329,7 @@ var ChatRoom = (function() {
if (user) {
user.sendTo(this, message);
} else {
if (this.id !== 'lobby') message = '>'+this.id+'\n'+message;
if (this.id !== 'lobby') message = '>' + this.id + '\n' + message;
Sockets.channelBroadcast(this.id, message);
}
};
@ -1350,7 +1350,7 @@ var ChatRoom = (function() {
}
};
ChatRoom.prototype.addRaw = function(message) {
this.add('|raw|'+message);
this.add('|raw|' + message);
};
ChatRoom.prototype.logGetLast = function (amount, noTime) {
if (!amount) {
@ -1402,7 +1402,7 @@ var ChatRoom = (function() {
ChatRoom.prototype.onJoinConnection = function(user, connection) {
var userList = this.userList ? this.userList : this.getUserList();
var modchat = this.getModchatNote();
this.send('|init|chat\n|title|'+this.title+'\n'+userList+'\n'+this.logGetLast(25).join('\n')+modchat, connection);
this.send('|init|chat\n|title|' + this.title + '\n' + userList + '\n' + this.logGetLast(25).join('\n') + modchat, connection);
if (global.Tournaments && Tournaments.get(this.id))
Tournaments.get(this.id).update(user);
};
@ -1412,10 +1412,10 @@ var ChatRoom = (function() {
this.users[user.userid] = user;
if (user.named && Config.reportjoins) {
this.add('|j|'+user.getIdentity(this.id), true);
this.add('|j|' + user.getIdentity(this.id), true);
this.update(user);
} else if (user.named) {
var entry = '|J|'+user.getIdentity(this.id);
var entry = '|J|' + user.getIdentity(this.id);
if (Config.reportjoinsperiod) {
this.reportJoinsQueue.push(entry);
} else {
@ -1427,7 +1427,7 @@ var ChatRoom = (function() {
if (!merging) {
var userList = this.userList ? this.userList : this.getUserList();
var modchat = this.getModchatNote();
this.send('|init|chat\n|title|'+this.title+'\n'+userList+'\n'+this.logGetLast(100).join('\n')+modchat, connection);
this.send('|init|chat\n|title|' + this.title + '\n' + userList + '\n' + this.logGetLast(100).join('\n') + modchat, connection);
}
if (global.Tournaments && Tournaments.get(this.id))
Tournaments.get(this.id).update(user);
@ -1480,7 +1480,7 @@ var ChatRoom = (function() {
if (!user) return; // ...
delete this.users[user.userid];
if (user.named && Config.reportjoins) {
this.add('|l|'+user.getIdentity(this.id));
this.add('|l|' + user.getIdentity(this.id));
} else if (user.named) {
var entry = '|L|' + user.getIdentity(this.id);
if (Config.reportjoinsperiod) {
@ -1495,7 +1495,7 @@ var ChatRoom = (function() {
message = CommandParser.parse(message, this, user, connection);
if (message) {
this.add('|c|'+user.getIdentity(this.id)+'|'+message, true);
this.add('|c|' + user.getIdentity(this.id) + '|' + message, true);
}
this.update();
};
@ -1533,7 +1533,7 @@ var newRoom = function(roomid, format, p1, p2, parent, rated) {
if (!p1 || !p2) return false;
if (!roomid) roomid = 'default';
if (!rooms[roomid]) {
// console.log("NEW BATTLE ROOM: "+roomid);
// console.log("NEW BATTLE ROOM: " + roomid);
ResourceMonitor.countBattle(p1.latestIp, p1.name);
ResourceMonitor.countBattle(p2.latestIp, p2.name);
rooms[roomid] = new BattleRoom(roomid, format, p1, p2, parent, rated);

View File

@ -89,7 +89,7 @@ var Simulator = (function(){
simulators[id] = this;
this.send('init', this.format, rated?'1':'');
this.send('init', this.format, rated ? '1' : '');
}
Simulator.prototype.id = '';
@ -115,12 +115,12 @@ var Simulator = (function(){
Simulator.prototype.lastIp = null;
Simulator.prototype.send = function() {
this.activeIp = ResourceMonitor.activeIp;
this.process.send(''+this.id+'|'+slice.call(arguments).join('|'));
this.process.send('' + this.id + '|' + slice.call(arguments).join('|'));
};
Simulator.prototype.sendFor = function(user, action) {
var player = this.playerTable[toId(user)];
if (!player) {
console.log('SENDFOR FAILED: Player doesn\'t exist: '+user.name);
console.log('SENDFOR FAILED: Player doesn\'t exist: ' + user.name);
return;
}
@ -171,7 +171,7 @@ var Simulator = (function(){
var rqid = lines[3];
if (player) {
this.requests[player.userid] = lines[4];
player.sendTo(this.id, '|request|'+lines[4]);
player.sendTo(this.id, '|request|' + lines[4]);
}
if (rqid !== this.rqid) {
this.rqid = rqid;
@ -196,7 +196,7 @@ var Simulator = (function(){
Simulator.prototype.resendRequest = function(user) {
if (this.requests[user.userid]) {
user.sendTo(this.id, '|request|'+this.requests[user.userid]);
user.sendTo(this.id, '|request|' + this.requests[user.userid]);
}
};
Simulator.prototype.win = function(user) {
@ -213,7 +213,7 @@ var Simulator = (function(){
this.send('tie');
};
Simulator.prototype.chat = function(user, message) {
this.send('chat', user.name+"\n"+message);
this.send('chat', user.name + "\n" + message);
};
Simulator.prototype.isEmpty = function() {
@ -245,20 +245,20 @@ var Simulator = (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++) {
for (var i = 0, len = this.players.length; i < len; i++) {
var player = this.players[i];
this['p'+(i+1)] = player?player.name:'';
this['p' + (i + 1)] = player ? player.name : '';
if (!player) {
this.active = false;
continue;
}
this.playerTable[player.userid] = 'p'+(i+1);
this.playerTable[player.userid] = 'p' + (i + 1);
}
};
Simulator.prototype.getPlayer = function(slot) {
if (typeof slot === 'string') {
if (slot.substr(0,1) === 'p') {
slot = parseInt(slot.substr(1),10)-1;
if (slot.substr(0, 1) === 'p') {
slot = parseInt(slot.substr(1), 10) - 1;
} else {
slot = parseInt(slot, 10);
}
@ -274,14 +274,14 @@ var Simulator = (function(){
slot = 0;
while (this.players[slot]) slot++;
}
// console.log('joining: '+user.name+' '+slot);
// console.log('joining: ' + user.name + ' ' + slot);
if (this.players[slot] || slot >= this.players.length) return false;
this.setPlayer(user, slot);
var message = ''+user.avatar;
var message = '' + user.avatar;
if (!this.started) {
message += "\n"+team;
message += "\n" + team;
}
if (this.p1 && this.p2) this.started = true;
this.sendFor(user, 'join', user.name, message);
@ -289,7 +289,7 @@ var Simulator = (function(){
};
Simulator.prototype.rename = function() {
for (var i=0, len=this.players.length; i<len; i++) {
for (var i = 0, len = this.players.length; i < len; i++) {
var player = this.players[i];
var playerid = this.playerids[i];
if (!player) continue;
@ -301,7 +301,7 @@ var Simulator = (function(){
};
Simulator.prototype.leave = function(user) {
for (var i=0, len=this.players.length; i<len; i++) {
for (var i = 0, len = this.players.length; i < len; i++) {
var player = this.players[i];
if (player === user) {
this.sendFor(user, 'leave');

View File

@ -27,12 +27,12 @@ if (cluster.isMaster) {
var id = worker.id;
workers[id] = worker;
worker.on('message', function(data) {
// console.log('master received: '+data);
// console.log('master received: ' + data);
switch (data.charAt(0)) {
case '*': // *socketid, ip
// connect
var nlPos = data.indexOf('\n');
Users.socketConnect(worker, id, data.substr(1, nlPos-1), data.substr(nlPos+1));
Users.socketConnect(worker, id, data.substr(1, nlPos - 1), data.substr(nlPos + 1));
break;
case '!': // !socketid
@ -43,19 +43,19 @@ if (cluster.isMaster) {
case '<': // <socketid, message
// message
var nlPos = data.indexOf('\n');
Users.socketReceive(worker, id, data.substr(1, nlPos-1), data.substr(nlPos+1));
Users.socketReceive(worker, id, data.substr(1, nlPos - 1), data.substr(nlPos + 1));
break;
}
});
};
var workerCount = Config.workers || 1;
for (var i=0; i<workerCount; i++) {
for (var i = 0; i < workerCount; i++) {
spawnWorker();
}
var killWorker = exports.killWorker = function(worker) {
var idd = worker.id+'-';
var idd = worker.id + '-';
var count = 0;
for (var connectionid in Users.connections) {
if (connectionid.substr(idd.length) === idd) {
@ -72,10 +72,10 @@ if (cluster.isMaster) {
};
var killPid = exports.killPid = function(pid) {
pid = ''+pid;
pid = '' + pid;
for (var id in workers) {
var worker = workers[id];
if (pid === ''+worker.process.pid) {
if (pid === '' + worker.process.pid) {
return killWorker(worker);
}
}
@ -83,25 +83,25 @@ if (cluster.isMaster) {
};
exports.socketSend = function(worker, socketid, message) {
worker.send('>'+socketid+'\n'+message);
worker.send('>' + socketid + '\n' + message);
};
exports.socketDisconnect = function(worker, socketid) {
worker.send('!'+socketid);
worker.send('!' + socketid);
};
exports.channelBroadcast = function(channelid, message) {
for (var workerid in workers) {
workers[workerid].send('#'+channelid+'\n'+message);
workers[workerid].send('#' + channelid + '\n' + message);
}
};
exports.channelSend = function(worker, channelid, message) {
worker.send('#'+channelid+'\n'+message);
worker.send('#' + channelid + '\n' + message);
};
exports.channelAdd = function(worker, channelid, socketid) {
worker.send('+'+channelid+'\n'+socketid);
worker.send('+'+channelid + '\n' + socketid);
};
exports.channelRemove = function(worker, channelid, socketid) {
worker.send('-'+channelid+'\n'+socketid);
worker.send('-' + channelid + '\n' + socketid);
};
} else {
@ -127,7 +127,7 @@ if (cluster.isMaster) {
if (Config.crashguard) {
// graceful crash
process.on('uncaughtException', function(err) {
require('./crashlogger.js')(err, 'Socket process '+cluster.worker.id+' ('+process.pid+')');
require('./crashlogger.js')(err, 'Socket process ' + cluster.worker.id + ' (' + process.pid + ')');
});
}
@ -187,7 +187,7 @@ if (cluster.isMaster) {
var 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);
if (severity === 'error') console.log('ERROR: ' + message);
},
prefix: '/showdown',
websocket: !Config.disablewebsocket
@ -220,11 +220,11 @@ if (cluster.isMaster) {
};
var interval;
if (!Config.herokuhack) {
interval = setInterval(sweepClosedSockets, 1000*60*10);
interval = setInterval(sweepClosedSockets, 1000 * 60 * 10);
}
process.on('message', function(data) {
// console.log('worker received: '+data);
// console.log('worker received: ' + data);
var socket = null;
var socketid = null;
var channelid = null;
@ -246,16 +246,16 @@ if (cluster.isMaster) {
case '>': // >socketid, message
// message
var nlLoc = data.indexOf('\n');
socket = sockets[data.substr(1, nlLoc-1)];
socket = sockets[data.substr(1, nlLoc - 1)];
if (!socket) return;
socket.write(data.substr(nlLoc+1));
socket.write(data.substr(nlLoc + 1));
break;
case '#': // #channelid, message
// message to channel
var nlLoc = data.indexOf('\n');
channel = channels[data.substr(1, nlLoc-1)];
var message = data.substr(nlLoc+1);
channel = channels[data.substr(1, nlLoc - 1)];
var message = data.substr(nlLoc + 1);
for (socketid in channel) {
channel[socketid].write(message);
}
@ -264,10 +264,10 @@ if (cluster.isMaster) {
case '+': // +channelid, socketid
// add to channel
var nlLoc = data.indexOf('\n');
socketid = data.substr(nlLoc+1);
socketid = data.substr(nlLoc + 1);
socket = sockets[socketid];
if (!socket) return;
channelid = data.substr(1, nlLoc-1);
channelid = data.substr(1, nlLoc - 1);
var channel = channels[channelid];
if (!channel) channel = channels[channelid] = {};
channel[socketid] = socket;
@ -276,10 +276,10 @@ if (cluster.isMaster) {
case '-': // -channelid, socketid
// remove from channel
var nlLoc = data.indexOf('\n');
var channelid = data.substr(1, nlLoc-1);
var channelid = data.substr(1, nlLoc - 1);
var channel = channels[channelid];
if (!channel) return;
delete channel[data.substr(nlLoc+1)];
delete channel[data.substr(nlLoc + 1)];
var isEmpty = true;
for (var socketid in channel) {
isEmpty = false;
@ -321,9 +321,9 @@ if (cluster.isMaster) {
}
}
process.send('*'+socketid+'\n'+socket.remoteAddress);
process.send('*' + socketid + '\n' + socket.remoteAddress);
// console.log('CONNECT: '+socket.remoteAddress+' ['+socket.id+']');
// console.log('CONNECT: ' + socket.remoteAddress + ' [' + socket.id + ']');
var interval;
if (Config.herokuhack) {
// see https://github.com/sockjs/sockjs-node/issues/57#issuecomment-5242187
@ -339,17 +339,17 @@ if (cluster.isMaster) {
if (!message) return;
// drop blank messages (DDoS?)
var pipeIndex = message.indexOf('|');
if (pipeIndex < 0 || pipeIndex === message.length-1) return;
if (pipeIndex < 0 || pipeIndex === message.length - 1) return;
// drop legacy JSON messages
if (message.charAt(0) === '{') return;
process.send('<'+socketid+'\n'+message);
process.send('<' + socketid + '\n' + message);
});
socket.on('close', function() {
if (interval) {
clearInterval(interval);
}
process.send('!'+socketid);
process.send('!' + socketid);
delete sockets[socketid];
for (var channelid in channels) {
@ -359,12 +359,12 @@ if (cluster.isMaster) {
});
server.installHandlers(app, {});
app.listen(Config.port);
console.log('Worker '+cluster.worker.id+' now listening on port ' + Config.port);
console.log('Worker ' + cluster.worker.id + ' now listening on port ' + Config.port);
if (appssl) {
server.installHandlers(appssl, {});
appssl.listen(Config.ssl.port);
console.log('Worker '+cluster.worker.id+' now listening for SSL on port ' + Config.ssl.port);
console.log('Worker ' + cluster.worker.id + ' now listening for SSL on port ' + Config.ssl.port);
}
console.log('Test your server at http://localhost:' + Config.port);

View File

@ -20,12 +20,12 @@ if (!process.send) {
// 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');
var id = message.substr(0, pipeIndex);
var success = (message.charAt(pipeIndex + 1) === '1');
if (pendingValidations[id]) {
ValidatorProcess.release(self);
pendingValidations[id](success, message.substr(pipeIndex+2));
pendingValidations[id](success, message.substr(pipeIndex + 2));
delete pendingValidations[id];
}
});
@ -66,7 +66,7 @@ if (!process.send) {
var process = this.acquire();
pendingValidations[validationCount] = callback;
try {
process.process.send(''+validationCount+'|'+format+'|'+team);
process.process.send('' + validationCount + '|' + format + '|' + team);
} catch (e) {}
++validationCount;
};
@ -131,7 +131,7 @@ if (!process.send) {
while (bannedNameStartChars[name.charAt(0)]) {
name = name.substr(1);
}
if (name.length > 18) name = name.substr(0,18);
if (name.length > 18) name = name.substr(0, 18);
if (Config.namefilter) {
name = Config.namefilter(name);
}
@ -140,12 +140,12 @@ if (!process.send) {
/**
* Safely ensures the passed variable is a string
* Simply doing ''+str can crash if str.toString crashes or isn't a function
* Simply doing '' + str can crash if str.toString crashes or isn't a function
* If we're expecting a string and being given anything that isn't a string
* or a number, it's safe to assume it's an error, and return ''
*/
global.string = function(str) {
if (typeof str === 'string' || typeof str === 'number') return ''+str;
if (typeof str === 'string' || typeof str === 'number') return '' + str;
return '';
};
@ -154,7 +154,7 @@ if (!process.send) {
var validators = {};
function respond(id, success, details) {
process.send(id+(success?'|1':'|0')+details);
process.send(id + (success ? '|1' : '|0') + details);
}
process.on('message', function(message) {
@ -174,8 +174,8 @@ if (!process.send) {
} else {
var packedTeam = Tools.packTeam(parsedTeam);
if (packedTeam === message.substr(pipeIndex2 + 1)) packedTeam = '';
// console.log('FROM: '+message.substr(pipeIndex2 + 1));
// console.log('TO: '+packedTeam);
// console.log('FROM: ' + message.substr(pipeIndex2 + 1));
// console.log('TO: ' + packedTeam);
respond(id, true, packedTeam);
}
});
@ -205,11 +205,11 @@ var Validator = (function() {
if (!team.length) {
return ["Your team has no pokemon."];
}
if (team.length>6) {
if (team.length > 6) {
return ["Your team has more than 6 pokemon."];
}
var teamHas = {};
for (var i=0; i<team.length; i++) {
for (var 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 = this.validateSet(team[i], teamHas);
if (setProblems) {
@ -217,30 +217,30 @@ var Validator = (function() {
}
}
for (var i=0; i<format.teamBanTable.length; i++) {
for (var i = 0; i < format.teamBanTable.length; i++) {
var bannedCombo = true;
for (var j=0; j<format.teamBanTable[i].length; j++) {
for (var 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 : '';
problems.push("Your team has the combination of "+format.teamBanTable[i].join('+')+", which is banned"+clause+".");
var 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++) {
for (var i = 0; i < format.ruleset.length; i++) {
var subformat = tools.getFormat(format.ruleset[i]);
if (subformat.validateTeam) {
problems = problems.concat(subformat.validateTeam.call(tools, team, format)||[]);
problems = problems.concat(subformat.validateTeam.call(tools, team, format) || []);
}
}
}
if (format.validateTeam) {
problems = problems.concat(format.validateTeam.call(tools, team, format)||[]);
problems = problems.concat(format.validateTeam.call(tools, team, format) || []);
}
if (!problems.length) return false;
@ -258,7 +258,7 @@ var Validator = (function() {
var template = tools.getTemplate(string(set.species));
if (!template.exists) {
return ["The Pokemon '"+set.species+"' does not exist."];
return ["The Pokemon '" + set.species + "' does not exist."];
}
set.species = template.species;
@ -279,7 +279,7 @@ var Validator = (function() {
} else if (set.level >= maxForcedLevel) {
set.forcedLevel = maxForcedLevel;
}
if (set.level > maxLevel || set.level == set.forcedLevel || set.level == set.maxForcedLevel) {
if (set.level > maxLevel || set.level === set.forcedLevel || set.level === set.maxForcedLevel) {
set.level = maxLevel;
}
@ -288,7 +288,7 @@ var Validator = (function() {
set.species = set.species;
set.name = set.name || set.species;
var name = set.species;
if (set.species !== set.name) name = set.name + " ("+set.species+")";
if (set.species !== set.name) name = set.name + " (" + set.species + ")";
var isHidden = false;
var lsetData = {set:set, format:format};
@ -300,17 +300,17 @@ var Validator = (function() {
}
if (format.ruleset) {
for (var i=0; i<format.ruleset.length; i++) {
for (var i = 0; i < format.ruleset.length; i++) {
var subformat = tools.getFormat(format.ruleset[i]);
if (subformat.validateSet) {
problems = problems.concat(subformat.validateSet.call(tools, set, format)||[]);
problems = problems.concat(subformat.validateSet.call(tools, set, format) || []);
}
}
}
template = tools.getTemplate(set.species);
item = tools.getItem(set.item);
if (item.id && !item.exists) {
return ['"'+set.item+"' is an invalid item."];
return ['"' + set.item + "' is an invalid item."];
}
ability = tools.getAbility(set.ability);
@ -321,12 +321,12 @@ var Validator = (function() {
setHas[check] = true;
if (banlistTable[check]) {
clause = typeof banlistTable[check] === 'string' ? " by "+ banlistTable[check] : '';
problems.push(set.species+' is banned'+clause+'.');
problems.push(set.species + ' is banned' + clause + '.');
} else if (!tools.data.FormatsData[check] || !tools.data.FormatsData[check].tier) {
check = toId(template.baseSpecies);
if (banlistTable[check]) {
clause = typeof banlistTable[check] === 'string' ? " by "+ banlistTable[check] : '';
problems.push(template.baseSpecies+' is banned'+clause+'.');
problems.push(template.baseSpecies + ' is banned' + clause + '.');
}
}
@ -334,20 +334,20 @@ var Validator = (function() {
setHas[check] = true;
if (banlistTable[check]) {
clause = typeof banlistTable[check] === 'string' ? " by "+ banlistTable[check] : '';
problems.push(name+"'s ability "+set.ability+" is banned"+clause+".");
problems.push(name + "'s ability " + set.ability + " is banned" + clause + ".");
}
check = toId(set.item);
setHas[check] = true;
if (banlistTable[check]) {
clause = typeof banlistTable[check] === 'string' ? " by "+ banlistTable[check] : '';
problems.push(name+"'s item "+set.item+" is banned"+clause+".");
problems.push(name + "'s item " + set.item + " is banned" + clause + ".");
}
if (banlistTable['illegal'] && item.isUnreleased) {
problems.push(name+"'s item "+set.item+" is unreleased.");
problems.push(name + "'s item " + set.item + " is unreleased.");
}
if (banlistTable['Unreleased'] && template.isUnreleased) {
if (!format.requirePentagon || (template.eggGroups[0] === 'Undiscovered' && !template.evos)) {
problems.push(name+" ("+template.species+") is unreleased.");
problems.push(name + " (" + template.species + ") is unreleased.");
}
}
setHas[toId(set.ability)] = true;
@ -361,7 +361,7 @@ var Validator = (function() {
}
// In gen 1 and 2, it was possible to max out all EVs
if (tools.gen >= 3 && totalEV > 510) {
problems.push(name+" has more than 510 total EVs.");
problems.push(name + " has more than 510 total EVs.");
}
// Don't check abilities for metagames with All Abilities
@ -369,19 +369,19 @@ var Validator = (function() {
set.ability = 'None';
} else if (!banlistTable['ignoreillegalabilities']) {
if (!ability.name) {
problems.push(name+" needs to have an ability.");
problems.push(name + " needs to have an ability.");
} else if (ability.name !== template.abilities['0'] &&
ability.name !== template.abilities['1'] &&
ability.name !== template.abilities['H']) {
problems.push(name+" can't have "+set.ability+".");
problems.push(name + " can't have " + set.ability + ".");
}
if (ability.name === template.abilities['H']) {
isHidden = true;
if (template.unreleasedHidden && banlistTable['illegal']) {
problems.push(name+"'s hidden ability is unreleased.");
problems.push(name + "'s hidden ability is unreleased.");
} else if (tools.gen === 5 && set.level < 10 && (template.maleOnlyHidden || template.gender === 'N')) {
problems.push(name+" must be at least level 10 with its hidden ability.");
problems.push(name + " must be at least level 10 with its hidden ability.");
}
if (template.maleOnlyHidden) {
set.gender = 'M';
@ -394,16 +394,16 @@ var Validator = (function() {
set.moves = set.moves.filter(function(val){ return val; });
}
if (!set.moves || !set.moves.length) {
problems.push(name+" has no moves.");
problems.push(name + " has no moves.");
} else {
// A limit is imposed here to prevent too much engine strain or
// too much layout deformation - to be exact, this is the Debug
// Mode limitation.
// The usual limit of 4 moves is handled elsewhere - currently
// in the cartridge-compliant set validator: rulesets.js:pokemon
set.moves = set.moves.slice(0,24);
set.moves = set.moves.slice(0, 24);
for (var i=0; i<set.moves.length; i++) {
for (var i = 0; i < set.moves.length; i++) {
if (!set.moves[i]) continue;
var move = tools.getMove(string(set.moves[i]));
set.moves[i] = move.name;
@ -411,13 +411,13 @@ var Validator = (function() {
setHas[check] = true;
if (banlistTable[check]) {
clause = typeof banlistTable[check] === 'string' ? " by "+ banlistTable[check] : '';
problems.push(name+"'s move "+set.moves[i]+" is banned"+clause+".");
problems.push(name + "'s move " + set.moves[i] + " is banned" + clause + ".");
}
if (banlistTable['illegal']) {
var problem = this.checkLearnset(move, template, lsetData);
if (problem) {
var problemString = name+" can't learn "+move.name;
var 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.");
@ -425,7 +425,7 @@ var Validator = (function() {
problemString = problemString.concat(" because it's incompatible with another move.");
}
} else if (problem.type === 'oversketched') {
problemString = problemString.concat(" because it can only sketch "+problem.maxSketches+" move"+(problem.maxSketches>1?"s":"")+".");
problemString = problemString.concat(" because it can only sketch " + problem.maxSketches + " move" + (problem.maxSketches > 1 ? "s" : "") + ".");
} else if (problem.type === 'pokebank') {
problemString = problemString.concat(" because it's only obtainable from a previous generation.");
} else {
@ -439,31 +439,31 @@ var Validator = (function() {
if (lsetData.sources && lsetData.sources.length === 1 && !lsetData.sourcesBefore) {
// we're restricted to a single source
var source = lsetData.sources[0];
if (source.substr(1,1) === 'S') {
if (source.substr(1, 1) === 'S') {
// it's an event
var eventData = null;
var splitSource = source.substr(2).split(' ');
var eventTemplate = tools.getTemplate(splitSource[1]);
if (eventTemplate.eventPokemon) eventData = eventTemplate.eventPokemon[parseInt(splitSource[0],10)];
if (eventTemplate.eventPokemon) eventData = eventTemplate.eventPokemon[parseInt(splitSource[0], 10)];
if (eventData) {
if (eventData.nature && eventData.nature !== set.nature) {
problems.push(name+" must have a "+eventData.nature+" nature because it comes from a specific event.");
problems.push(name + " must have a " + eventData.nature + " nature because it comes from a specific event.");
}
if (eventData.shiny) {
set.shiny = true;
}
if (eventData.generation < 5) eventData.isHidden = false;
if (eventData.isHidden !== undefined && eventData.isHidden !== isHidden) {
problems.push(name+(isHidden?" can't have":" must have")+" its hidden ability because it comes from a specific event.");
problems.push(name + (isHidden ? " can't have" : " must have") + " its hidden ability because it comes from a specific event.");
}
if (tools.gen <= 5 && eventData.abilities && eventData.abilities.indexOf(ability.id) < 0) {
problems.push(name+" must have "+eventData.abilities.join(" or ")+" because it comes from a specific event.");
problems.push(name + " must have " + eventData.abilities.join(" or ") + " because it comes from a specific event.");
}
if (eventData.gender) {
set.gender = eventData.gender;
}
if (eventData.level && set.level < eventData.level) {
problems.push(name+" must be at least level "+eventData.level+" because it comes from a specific event.");
problems.push(name + " must be at least level " + eventData.level + " because it comes from a specific event.");
}
}
isHidden = false;
@ -471,37 +471,37 @@ var Validator = (function() {
}
if (isHidden && lsetData.sourcesBefore < 5) {
if (!lsetData.sources) {
problems.push(name+" has a hidden ability - it can't have moves only learned before gen 5.");
problems.push(name + " has a hidden ability - it can't have moves only learned before gen 5.");
} else if (template.gender) {
var compatibleSource = false;
for (var 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)) {
for (var 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;
}
}
if (!compatibleSource) {
problems.push(name+" has moves incompatible with its hidden ability.");
problems.push(name + " has moves incompatible with its hidden ability.");
}
}
}
if (banlistTable['illegal'] && set.level < template.evoLevel) {
// FIXME: Event pokemon given at a level under what it normally can be attained at gives a false positive
problems.push(name+" must be at least level "+template.evoLevel+".");
problems.push(name + " must be at least level " + template.evoLevel + ".");
}
if (!lsetData.sources && lsetData.sourcesBefore <= 3 && tools.getAbility(set.ability).gen === 4 && !template.prevo && tools.gen <= 5) {
problems.push(name+" has a gen 4 ability and isn't evolved - it can't use anything from gen 3.");
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;
var 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.");
problems.push(name + " has moves incompatible with its ability.");
}
}
}
setHas[toId(template.tier)] = true;
if (banlistTable[template.tier]) {
problems.push(name+" is in "+template.tier+", which is banned.");
problems.push(name + " is in " + template.tier + ", which is banned.");
}
if (teamHas) {
@ -509,22 +509,22 @@ var Validator = (function() {
teamHas[i] = true;
}
}
for (var i=0; i<format.setBanTable.length; i++) {
for (var i = 0; i < format.setBanTable.length; i++) {
var bannedCombo = true;
for (var j=0; j<format.setBanTable[i].length; j++) {
for (var j = 0; j < format.setBanTable[i].length; j++) {
if (!setHas[format.setBanTable[i][j]]) {
bannedCombo = false;
break;
}
}
if (bannedCombo) {
clause = format.name ? " by "+format.name : '';
problems.push(name+" has the combination of "+format.setBanTable[i].join('+')+", which is banned"+clause+".");
clause = format.name ? " by " + format.name : '';
problems.push(name + " has the combination of " + format.setBanTable[i].join(' + ') + ", which is banned" + clause + ".");
}
}
if (format.validateSet) {
problems = problems.concat(format.validateSet.call(tools, set, format)||[]);
problems = problems.concat(format.validateSet.call(tools, set, format) || []);
}
if (!problems.length) {
@ -541,8 +541,8 @@ var Validator = (function() {
template = tools.getTemplate(template);
lsetData = lsetData || {};
var set = (lsetData.set || (lsetData.set={}));
var format = (lsetData.format || (lsetData.format={}));
var set = (lsetData.set || (lsetData.set = {}));
var format = (lsetData.format || (lsetData.format = {}));
var alreadyChecked = {};
var level = set.level || 100;
if (format.id === 'alphabetcup') var alphabetCupLetter = template.speciesid.charAt(0);
@ -581,7 +581,7 @@ var Validator = (function() {
// Stabmons hack to avoid copying all of validateSet to formats.
if (format.id === 'stabmons' && template.types.indexOf(tools.getMove(move).type) > -1) return false;
// Alphabet Cup hack to do the same
if (alphabetCupLetter && alphabetCupLetter === Tools.getMove(move).id.slice(0,1) && Tools.getMove(move).id !== 'sketch') return false;
if (alphabetCupLetter && alphabetCupLetter === Tools.getMove(move).id.slice(0, 1) && Tools.getMove(move).id !== 'sketch') return false;
if (template.learnset) {
if (template.learnset[move] || template.learnset['sketch']) {
sometimesPossible = true;
@ -594,11 +594,11 @@ var Validator = (function() {
}
if (typeof lset === 'string') lset = [lset];
for (var i=0, len=lset.length; i<len; i++) {
for (var i = 0, len = lset.length; i < len; i++) {
var learned = lset[i];
if (noPastGen && learned.charAt(0) !== '6') continue;
if (parseInt(learned.charAt(0),10) > tools.gen) continue;
if (isHidden && !tools.mod('gen'+learned.charAt(0)).getTemplate(template.species).abilities['H']) {
if (parseInt(learned.charAt(0), 10) > tools.gen) continue;
if (isHidden && !tools.mod('gen' + learned.charAt(0)).getTemplate(template.species).abilities['H']) {
// check if the Pokemon's hidden ability was available
incompatibleHidden = true;
continue;
@ -608,21 +608,21 @@ var Validator = (function() {
if (tools.gen >= 4 && learned.charAt(0) <= 3 && move in {'cut':1, 'fly':1, 'surf':1, 'strength':1, 'flash':1, 'rocksmash':1, 'waterfall':1, 'dive':1}) continue;
if (tools.gen >= 5 && learned.charAt(0) <= 4 && move in {'cut':1, 'fly':1, 'surf':1, 'strength':1, 'rocksmash':1, 'waterfall':1, 'rockclimb':1}) continue;
}
if (learned.substr(0,2) in {'4L':1,'5L':1,'6L':1}) {
if (learned.substr(0, 2) in {'4L':1, '5L':1, '6L':1}) {
// gen 4-6 level-up moves
if (level >= parseInt(learned.substr(2),10)) {
if (level >= parseInt(learned.substr(2), 10)) {
// we're past the required level to learn it
return false;
}
if (!template.gender || template.gender === 'F') {
// available as egg move
learned = learned.charAt(0)+'Eany';
learned = learned.charAt(0) + 'Eany';
} else {
// this move is unavailable, skip it
continue;
}
}
if (learned.charAt(1) in {L:1,M:1,T:1}) {
if (learned.charAt(1) in {L:1, M:1, T:1}) {
if (learned.charAt(0) === '6') {
// current-gen TM or tutor moves:
// always available
@ -631,8 +631,8 @@ var Validator = (function() {
// past-gen level-up, TM, or tutor moves:
// available as long as the source gen was or was before this gen
limit1 = false;
sourcesBefore = Math.max(sourcesBefore, parseInt(learned.charAt(0),10));
} else if (learned.charAt(1) in {E:1,S:1,D:1}) {
sourcesBefore = Math.max(sourcesBefore, parseInt(learned.charAt(0), 10));
} else if (learned.charAt(1) in {E:1, S:1, D:1}) {
// egg, event, or DW moves:
// only if that was the source
if (learned.charAt(1) === 'E') {
@ -647,33 +647,33 @@ var Validator = (function() {
if (eggGroups[0] === 'Undiscovered') eggGroups = tools.getTemplate(template.evos[0]).eggGroups;
var atLeastOne = false;
var fromSelf = (learned.substr(1) === 'Eany');
learned = learned.substr(0,2);
learned = learned.substr(0, 2);
for (var templateid in tools.data.Pokedex) {
var dexEntry = tools.getTemplate(templateid);
if (
// CAP pokemon can't breed
!dexEntry.isNonstandard &&
// can't breed mons from future gens
dexEntry.gen <= parseInt(learned.charAt(0),10) &&
dexEntry.gen <= parseInt(learned.charAt(0), 10) &&
// genderless pokemon can't pass egg moves
dexEntry.gender !== 'N') {
if (
// chainbreeding
fromSelf ||
// otherwise parent must be able to learn the move
!alreadyChecked[dexEntry.speciesid] && dexEntry.learnset && (dexEntry.learnset[move]||dexEntry.learnset['sketch'])) {
!alreadyChecked[dexEntry.speciesid] && dexEntry.learnset && (dexEntry.learnset[move] || dexEntry.learnset['sketch'])) {
if (dexEntry.eggGroups.intersect(eggGroups).length) {
// we can breed with it
atLeastOne = true;
sources.push(learned+dexEntry.id);
sources.push(learned + dexEntry.id);
}
}
}
}
// chainbreeding with itself from earlier gen
if (!atLeastOne) sources.push(learned+template.id);
if (!atLeastOne) sources.push(learned + template.id);
} else if (learned.charAt(1) === 'S') {
sources.push(learned+' '+template.id);
sources.push(learned + ' ' + template.id);
} else {
sources.push(learned);
}
@ -686,7 +686,7 @@ var Validator = (function() {
var getGlitch = false;
for (var i in glitchMoves) {
if (template.learnset[i]) {
if (i === 'mimic' && tools.getAbility(set.ability).gen == 4 && !template.prevo) {
if (i === 'mimic' && tools.getAbility(set.ability).gen === 4 && !template.prevo) {
// doesn't get the glitch
} else {
getGlitch = true;
@ -738,9 +738,9 @@ var Validator = (function() {
var learned;
if (sourcesBefore && lsetData.sources) {
if (!sources) sources = [];
for (var i=0, len=lsetData.sources.length; i<len; i++) {
for (var i = 0, len = lsetData.sources.length; i < len; i++) {
learned = lsetData.sources[i];
if (parseInt(learned.substr(0,1),10) <= sourcesBefore) {
if (parseInt(learned.substr(0, 1), 10) <= sourcesBefore) {
sources.push(learned);
}
}
@ -748,9 +748,9 @@ var Validator = (function() {
}
if (lsetData.sourcesBefore && sources) {
if (!lsetData.sources) lsetData.sources = [];
for (var i=0, len=sources.length; i<len; i++) {
for (var i = 0, len = sources.length; i < len; i++) {
learned = sources[i];
if (parseInt(learned.substr(0,1),10) <= lsetData.sourcesBefore) {
if (parseInt(learned.substr(0, 1), 10) <= lsetData.sourcesBefore) {
lsetData.sources.push(learned);
}
}
@ -770,7 +770,7 @@ var Validator = (function() {
}
if (sourcesBefore) {
lsetData.sourcesBefore = Math.min(sourcesBefore, lsetData.sourcesBefore||6);
lsetData.sourcesBefore = Math.min(sourcesBefore, lsetData.sourcesBefore || 6);
}
return false;

142
tools.js
View File

@ -50,7 +50,7 @@ module.exports = (function () {
data[dataType] = require(path)['Battle' + dataType];
}
} catch (e) {
console.log('CRASH LOADING DATA: '+e.stack);
console.log('CRASH LOADING DATA: ' + e.stack);
}
if (!data[dataType]) data[dataType] = {};
}, this);
@ -58,7 +58,7 @@ module.exports = (function () {
var path = './config/formats.js';
if (fs.existsSync(path)) {
var configFormats = require(path).Formats;
for (var i=0; i<configFormats.length; i++) {
for (var i = 0; i < configFormats.length; i++) {
var format = configFormats[i];
var id = toId(format.name);
format.effectType = 'Format';
@ -68,7 +68,7 @@ module.exports = (function () {
}
}
} catch (e) {
console.log('CRASH LOADING FORMATS: '+e.stack);
console.log('CRASH LOADING FORMATS: ' + e.stack);
}
} else {
var parentData = moddedTools[parentMod].data;
@ -79,7 +79,7 @@ module.exports = (function () {
data[dataType] = require(path)['Battle' + dataType];
}
} catch (e) {
console.log('CRASH LOADING MOD DATA: '+e.stack);
console.log('CRASH LOADING MOD DATA: ' + e.stack);
}
if (!data[dataType]) data[dataType] = {};
for (var i in parentData[dataType]) {
@ -125,7 +125,7 @@ module.exports = (function () {
};
Tools.prototype.getImmunity = function(type, target) {
var types = target.getTypes && target.getTypes() || target.types;
for (var i=0; i<types.length; i++) {
for (var i = 0; i < types.length; i++) {
if (this.data.TypeChart[types[i]] && this.data.TypeChart[types[i]].damageTaken && this.data.TypeChart[types[i]].damageTaken[type] === 3) {
return false;
}
@ -139,7 +139,7 @@ module.exports = (function () {
var type = source.type || source;
var totalTypeMod = 0;
var targetTypes = target.getTypes && target.getTypes() || target.types;
for (var i=0; i<targetTypes.length; i++) {
for (var i = 0; i < targetTypes.length; i++) {
if (!this.data.TypeChart[targetTypes[i]]) continue;
var typeMod = this.data.TypeChart[targetTypes[i]].damageTaken[type];
if (typeMod === 1) { // super-effective
@ -155,7 +155,7 @@ module.exports = (function () {
};
Tools.prototype.getTemplate = function(template) {
if (!template || typeof template === 'string') {
var name = (template||'').trim();
var name = (template || '').trim();
var id = toId(name);
if (this.data.Aliases[id]) {
name = this.data.Aliases[id];
@ -182,19 +182,19 @@ module.exports = (function () {
if (!template.baseSpecies) template.baseSpecies = name;
if (!template.forme) template.forme = '';
if (!template.formeLetter) template.formeLetter = '';
if (!template.spriteid) template.spriteid = toId(template.baseSpecies)+(template.baseSpecies!==name?'-'+toId(template.forme):'');
if (!template.spriteid) template.spriteid = toId(template.baseSpecies) + (template.baseSpecies !== name ? '-' + toId(template.forme) : '');
if (!template.prevo) template.prevo = '';
if (!template.evos) template.evos = [];
if (!template.nfe) template.nfe = !!template.evos.length;
if (!template.gender) template.gender = '';
if (!template.genderRatio && template.gender === 'M') template.genderRatio = {M:1,F:0};
if (!template.genderRatio && template.gender === 'F') template.genderRatio = {M:0,F:1};
if (!template.genderRatio && template.gender === 'N') template.genderRatio = {M:0,F:0};
if (!template.genderRatio) template.genderRatio = {M:0.5,F:0.5};
if (!template.genderRatio && template.gender === 'M') template.genderRatio = {M:1, F:0};
if (!template.genderRatio && template.gender === 'F') template.genderRatio = {M:0, F:1};
if (!template.genderRatio && template.gender === 'N') template.genderRatio = {M:0, F:0};
if (!template.genderRatio) template.genderRatio = {M:0.5, F:0.5};
if (!template.tier && template.baseSpecies !== template.species) template.tier = this.data.FormatsData[toId(template.baseSpecies)].tier;
if (!template.tier) template.tier = 'Illegal';
if (!template.gen) {
if (template.forme && template.forme in {'Mega':1,'Mega-X':1,'Mega-Y':1}) {
if (template.forme && template.forme in {'Mega':1, 'Mega-X':1, 'Mega-Y':1}) {
template.gen = 6;
template.isMega = true;
} else if (template.num >= 650) template.gen = 6;
@ -210,14 +210,14 @@ module.exports = (function () {
};
Tools.prototype.getMove = function(move) {
if (!move || typeof move === 'string') {
var name = (move||'').trim();
var name = (move || '').trim();
var id = toId(name);
if (this.data.Aliases[id]) {
name = this.data.Aliases[id];
id = toId(name);
}
move = {};
if (id.substr(0,11) === 'hiddenpower') {
if (id.substr(0, 11) === 'hiddenpower') {
var matches = /([a-z]*)([0-9]*)/.exec(id);
id = matches[1];
}
@ -229,7 +229,7 @@ module.exports = (function () {
}
if (!move.id) move.id = id;
if (!move.name) move.name = name;
if (!move.fullname) move.fullname = 'move: '+move.name;
if (!move.fullname) move.fullname = 'move: ' + move.name;
move.toString = this.effectToString;
if (!move.critRatio) move.critRatio = 1;
if (!move.baseType) move.baseType = move.type;
@ -269,7 +269,7 @@ module.exports = (function () {
};
Tools.prototype.getEffect = function(effect) {
if (!effect || typeof effect === 'string') {
var name = (effect||'').trim();
var name = (effect || '').trim();
var id = toId(name);
effect = {};
if (id && this.data.Statuses[id]) {
@ -309,7 +309,7 @@ module.exports = (function () {
};
Tools.prototype.getFormat = function(effect) {
if (!effect || typeof effect === 'string') {
var name = (effect||'').trim();
var name = (effect || '').trim();
var id = toId(name);
if (this.data.Aliases[id]) {
name = this.data.Aliases[id];
@ -336,7 +336,7 @@ module.exports = (function () {
};
Tools.prototype.getItem = function(item) {
if (!item || typeof item === 'string') {
var name = (item||'').trim();
var name = (item || '').trim();
var id = toId(name);
if (this.data.Aliases[id]) {
name = this.data.Aliases[id];
@ -351,7 +351,7 @@ module.exports = (function () {
}
if (!item.id) item.id = id;
if (!item.name) item.name = name;
if (!item.fullname) item.fullname = 'item: '+item.name;
if (!item.fullname) item.fullname = 'item: ' + item.name;
item.toString = this.effectToString;
if (!item.category) item.category = 'Effect';
if (!item.effectType) item.effectType = 'Item';
@ -368,7 +368,7 @@ module.exports = (function () {
};
Tools.prototype.getAbility = function(ability) {
if (!ability || typeof ability === 'string') {
var name = (ability||'').trim();
var name = (ability || '').trim();
var id = toId(name);
ability = {};
if (id && this.data.Abilities[id]) {
@ -379,7 +379,7 @@ module.exports = (function () {
}
if (!ability.id) ability.id = id;
if (!ability.name) ability.name = name;
if (!ability.fullname) ability.fullname = 'ability: '+ability.name;
if (!ability.fullname) ability.fullname = 'ability: ' + ability.name;
ability.toString = this.effectToString;
if (!ability.category) ability.category = 'Effect';
if (!ability.effectType) ability.effectType = 'Ability';
@ -396,7 +396,7 @@ module.exports = (function () {
Tools.prototype.getType = function(type) {
if (!type || typeof type === 'string') {
var id = toId(type);
id = id.substr(0,1).toUpperCase() + id.substr(1);
id = id.substr(0, 1).toUpperCase() + id.substr(1);
type = {};
if (id && this.data.TypeChart[id]) {
type = this.data.TypeChart[id];
@ -457,7 +457,7 @@ module.exports = (function () {
Tools.prototype.getBanlistTable = function(format, subformat, depth) {
var banlistTable;
if (!depth) depth = 0;
if (depth>8) return; // avoid infinite recursion
if (depth > 8) return; // avoid infinite recursion
if (format.banlistTable && !subformat) {
banlistTable = format.banlistTable;
} else {
@ -468,7 +468,7 @@ module.exports = (function () {
banlistTable = format.banlistTable;
if (!subformat) subformat = format;
if (subformat.banlist) {
for (var i=0; i<subformat.banlist.length; i++) {
for (var i = 0; i < subformat.banlist.length; i++) {
// don't revalidate what we already validate
if (banlistTable[toId(subformat.banlist[i])]) continue;
@ -481,13 +481,13 @@ module.exports = (function () {
var plusPlusPos = subformat.banlist[i].indexOf('++');
if (plusPlusPos && plusPlusPos > 0) {
complexList = subformat.banlist[i].split('++');
for (var j=0; j<complexList.length; j++) {
for (var 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 (var j = 0; j < complexList.length; j++) {
complexList[j] = toId(complexList[j]);
}
format.setBanTable.push(complexList);
@ -496,16 +496,16 @@ module.exports = (function () {
}
}
if (subformat.ruleset) {
for (var i=0; i<subformat.ruleset.length; i++) {
for (var i = 0; i < subformat.ruleset.length; i++) {
// don't revalidate what we already validate
if (banlistTable['Rule:'+toId(subformat.ruleset[i])]) continue;
if (banlistTable['Rule:' + toId(subformat.ruleset[i])]) continue;
banlistTable['Rule:'+toId(subformat.ruleset[i])] = subformat.ruleset[i];
banlistTable['Rule:' + toId(subformat.ruleset[i])] = subformat.ruleset[i];
if (format.ruleset.indexOf(subformat.ruleset[i]) === -1) format.ruleset.push(subformat.ruleset[i]);
var subsubformat = this.getFormat(subformat.ruleset[i]);
if (subsubformat.ruleset || subsubformat.banlist) {
this.getBanlistTable(format, subsubformat, depth+1);
this.getBanlistTable(format, subsubformat, depth + 1);
}
}
}
@ -521,8 +521,8 @@ module.exports = (function () {
var n = s.length;
var m = t.length;
if (n == 0) return m;
if (m == 0) return n;
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)
@ -539,10 +539,10 @@ module.exports = (function () {
// Step 4
for (var j = 1; j <= m; j++) {
// Check the jagged ld total so far
if (i == j && d[i][j] > 4) return n;
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
var cost = (s_i === t_j) ? 0 : 1; // Step 5
// Calculate the minimum
var mi = d[i - 1][j] + 1;
@ -646,7 +646,7 @@ module.exports = (function () {
var buf = '';
for (var i=0; i<team.length; i++) {
for (var i = 0; i < team.length; i++) {
var set = team[i];
if (buf) buf += ']';
@ -665,7 +665,7 @@ module.exports = (function () {
var abilities = template.abilities;
id = toId(set.ability);
if (abilities) {
if (id == toId(abilities['0'])) {
if (id === toId(abilities['0'])) {
buf += '|';
} else if (id === toId(abilities['1'])) {
buf += '|1';
@ -687,7 +687,7 @@ module.exports = (function () {
// evs
var evs = '|';
if (set.evs) {
evs = '|' + (set.evs['hp']||'') + ',' + (set.evs['atk']||'') + ',' + (set.evs['def']||'') + ',' + (set.evs['spa']||'') + ',' + (set.evs['spd']||'') + ',' + (set.evs['spe']||'');
evs = '|' + (set.evs['hp'] || '') + ',' + (set.evs['atk'] || '') + ',' + (set.evs['def'] || '') + ',' + (set.evs['spa'] || '') + ',' + (set.evs['spd'] || '') + ',' + (set.evs['spe'] || '');
}
if (evs === '|,,,,,') {
buf += '|';
@ -697,7 +697,7 @@ module.exports = (function () {
// gender
if (set.gender && set.gender !== template.gender) {
buf += '|'+set.gender;
buf += '|' + set.gender;
} else {
buf += '|';
}
@ -705,7 +705,7 @@ module.exports = (function () {
// ivs
var 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']);
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']);
}
if (ivs === '|,,,,,') {
buf += '|';
@ -722,14 +722,14 @@ module.exports = (function () {
// level
if (set.level && set.level != 100) {
buf += '|'+set.level;
buf += '|' + set.level;
} else {
buf += '|';
}
// happiness
if (set.happiness !== undefined && set.happiness !== 255) {
buf += '|'+set.happiness;
buf += '|' + set.happiness;
} else {
buf += '|';
}
@ -745,7 +745,7 @@ module.exports = (function () {
var i = 0, j = 0;
// limit to 24
for (var count=0; count<24; count++) {
for (var count = 0; count < 24; count++) {
var set = {};
team.push(set);
@ -753,39 +753,39 @@ module.exports = (function () {
j = buf.indexOf('|', i);
if (j < 0) return;
set.name = buf.substring(i, j);
i = j+1;
i = j + 1;
// species
j = buf.indexOf('|', i);
if (j < 0) return;
set.species = buf.substring(i, j) || set.name;
i = j+1;
i = j + 1;
// item
j = buf.indexOf('|', i);
if (j < 0) return;
set.item = buf.substring(i, j);
i = j+1;
i = j + 1;
// ability
j = buf.indexOf('|', i);
if (j < 0) return;
var ability = buf.substring(i, j);
var 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;
set.ability = (template.abilities && ability in {'':1, 0:1, 1:1, H:1} ? template.abilities[ability || '0'] : ability);
i = j + 1;
// moves
j = buf.indexOf('|', i);
if (j < 0) return;
set.moves = buf.substring(i, j).split(',');
i = j+1;
i = j + 1;
// nature
j = buf.indexOf('|', i);
if (j < 0) return;
set.nature = buf.substring(i, j);
i = j+1;
i = j + 1;
// evs
j = buf.indexOf('|', i);
@ -793,21 +793,21 @@ module.exports = (function () {
if (j !== i) {
var evs = buf.substring(i, j).split(',');
set.evs = {
hp: Number(evs[0])||0,
atk: Number(evs[1])||0,
def: Number(evs[2])||0,
spa: Number(evs[3])||0,
spd: Number(evs[4])||0,
spe: Number(evs[5])||0
hp: Number(evs[0]) || 0,
atk: Number(evs[1]) || 0,
def: Number(evs[2]) || 0,
spa: Number(evs[3]) || 0,
spd: Number(evs[4]) || 0,
spe: Number(evs[5]) || 0
};
}
i = j+1;
i = j + 1;
// gender
j = buf.indexOf('|', i);
if (j < 0) return;
if (i !== j) set.gender = buf.substring(i, j);
i = j+1;
i = j + 1;
// ivs
j = buf.indexOf('|', i);
@ -815,27 +815,27 @@ module.exports = (function () {
if (j !== i) {
var ivs = buf.substring(i, j).split(',');
set.ivs = {
hp: ivs[0]==='' ? 31 : Number(ivs[0]) || 0,
atk: ivs[1]==='' ? 31 : Number(ivs[1]) || 0,
def: ivs[2]==='' ? 31 : Number(ivs[2]) || 0,
spa: ivs[3]==='' ? 31 : Number(ivs[3]) || 0,
spd: ivs[4]==='' ? 31 : Number(ivs[4]) || 0,
spe: ivs[5]==='' ? 31 : Number(ivs[5]) || 0
hp: ivs[0] === '' ? 31 : Number(ivs[0]) || 0,
atk: ivs[1] === '' ? 31 : Number(ivs[1]) || 0,
def: ivs[2] === '' ? 31 : Number(ivs[2]) || 0,
spa: ivs[3] === '' ? 31 : Number(ivs[3]) || 0,
spd: ivs[4] === '' ? 31 : Number(ivs[4]) || 0,
spe: ivs[5] === '' ? 31 : Number(ivs[5]) || 0
};
}
i = j+1;
i = j + 1;
// shiny
j = buf.indexOf('|', i);
if (j < 0) return;
if (i !== j) set.shiny = true;
i = j+1;
i = j + 1;
// level
j = buf.indexOf('|', i);
if (j < 0) return;
if (i !== j) set.level = parseInt(buf.substring(i, j), 10);
i = j+1;
i = j + 1;
// happiness
j = buf.indexOf(']', i);
@ -846,7 +846,7 @@ module.exports = (function () {
break;
}
if (i !== j) set.happiness = Number(buf.substring(i, j));
i = j+1;
i = j + 1;
}
return team;
@ -888,8 +888,8 @@ module.exports = (function () {
var mods = fs.readdirSync('./mods/');
mods.forEach(function(mod) {
if (fs.existsSync('./mods/'+mod+'/scripts.js')) {
parentMods[mod] = require('./mods/'+mod+'/scripts.js').BattleScripts.inherit || 'base';
if (fs.existsSync('./mods/' + mod + '/scripts.js')) {
parentMods[mod] = require('./mods/' + mod + '/scripts.js').BattleScripts.inherit || 'base';
} else {
parentMods[mod] = 'base';
}
@ -906,7 +906,7 @@ module.exports = (function () {
}
} while (didSomething);
} catch (e) {
console.log("Error while loading mods: "+e);
console.log("Error while loading mods: " + e);
}
moddedTools.base.__proto__.moddedTools = moddedTools;

196
users.js
View File

@ -96,7 +96,7 @@ function searchUser(name) {
var connections = exports.connections = {};
function socketConnect(worker, workerid, socketid, ip) {
var id = ''+workerid+'-'+socketid;
var id = '' + workerid + '-' + socketid;
var connection = connections[id] = new Connection(id, worker, socketid, null, ip);
if (ResourceMonitor.countConnection(ip)) {
@ -107,11 +107,11 @@ function socketConnect(worker, workerid, socketid, ip) {
checkResult = '#ipban';
}
if (checkResult) {
console.log('CONNECT BLOCKED - IP BANNED: '+ip+' ('+checkResult+')');
console.log('CONNECT BLOCKED - IP BANNED: ' + ip + ' (' + checkResult + ')');
if (checkResult === '#ipban') {
connection.send("|popup|Your IP ("+ip+") is on our abuse list and is permanently banned. If you are using a proxy, stop.");
connection.send("|popup|Your IP (" + ip + ") is on our abuse list and is permanently banned. If you are using a proxy, stop.");
} else {
connection.send("|popup|Your IP ("+ip+") used is banned under the username '"+checkResult+"''. Your ban will expire in a few days."+(Config.appealurl ? " Or you can appeal at:\n" + Config.appealurl:""));
connection.send("|popup|Your IP (" + ip + ") used is banned under the username '" + checkResult + "''. Your ban will expire in a few days." + (Config.appealurl ? " Or you can appeal at:\n" + Config.appealurl:""));
}
return connection.destroy();
}
@ -154,7 +154,7 @@ function socketConnect(worker, workerid, socketid, ip) {
}
function socketDisconnect(worker, workerid, socketid) {
var id = ''+workerid+'-'+socketid;
var id = '' + workerid + '-' + socketid;
var connection = connections[id];
if (!connection) return;
@ -162,7 +162,7 @@ function socketDisconnect(worker, workerid, socketid) {
}
function socketReceive(worker, workerid, socketid, message) {
var id = ''+workerid+'-'+socketid;
var id = '' + workerid + '-' + socketid;
var connection = connections[id];
if (!connection) return;
@ -173,7 +173,7 @@ function socketReceive(worker, workerid, socketid, message) {
// from propagating out of this function.
// drop legacy JSON messages
if (message.substr(0,1) === '{') return;
if (message.substr(0, 1) === '{') return;
// drop invalid messages without a pipe character
var pipeIndex = message.indexOf('|');
@ -185,7 +185,7 @@ function socketReceive(worker, workerid, socketid, message) {
if (!room) room = Rooms.lobby || Rooms.global;
var user = connection.user;
if (!user) return;
if (lines.substr(0,3) === '>> ' || lines.substr(0,4) === '>>> ') {
if (lines.substr(0, 3) === '>> ' || lines.substr(0, 4) === '>>> ') {
user.chat(lines, room, connection);
return;
}
@ -203,7 +203,7 @@ function socketReceive(worker, workerid, socketid, message) {
}
});
}
for (var i=0; i<lines.length; i++) {
for (var i = 0; i < lines.length; i++) {
if (user.chat(lines[i], room, connection) === false) break;
}
}
@ -219,18 +219,18 @@ function importUsergroups() {
fs.readFile('config/usergroups.csv', function(err, data) {
if (err) return;
data = (''+data).split("\n");
data = ('' + data).split("\n");
for (var i = 0; i < data.length; i++) {
if (!data[i]) continue;
var row = data[i].split(",");
usergroups[toId(row[0])] = (row[1]||Config.groupsranking[0])+row[0];
usergroups[toId(row[0])] = (row[1] || Config.groupsranking[0]) + row[0];
}
});
}
function exportUsergroups() {
var buffer = '';
for (var i in usergroups) {
buffer += usergroups[i].substr(1).replace(/,/g,'') + ',' + usergroups[i].substr(0,1) + "\n";
buffer += usergroups[i].substr(1).replace(/,/g, '') + ',' + usergroups[i].substr(0, 1) + "\n";
}
fs.writeFile('config/usergroups.csv', buffer);
}
@ -240,7 +240,7 @@ var bannedWords = {};
function importBannedWords() {
fs.readFile('config/bannedwords.txt', function(err, data) {
if (err) return;
data = (''+data).split("\n");
data = ('' + data).split("\n");
bannedWords = {};
for (var i = 0; i < data.length; i++) {
if (!data[i]) continue;
@ -267,7 +267,7 @@ var User = (function () {
numUsers++;
this.mmrCache = {};
this.guestNum = numUsers;
this.name = 'Guest '+numUsers;
this.name = 'Guest ' + numUsers;
this.named = false;
this.renamePending = false;
this.authenticated = false;
@ -275,7 +275,7 @@ var User = (function () {
this.group = Config.groupsranking[0];
var trainersprites = [1, 2, 101, 102, 169, 170, 265, 266];
this.avatar = trainersprites[Math.floor(Math.random()*trainersprites.length)];
this.avatar = trainersprites[Math.floor(Math.random() * trainersprites.length)];
this.connected = true;
@ -317,38 +317,38 @@ var 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++) {
if (roomid && roomid !== 'global' && roomid !== 'lobby') data = '>' + roomid + '\n' + data;
for (var i = 0; i < this.connections.length; i++) {
if (roomid && !this.connections[i].rooms[roomid]) continue;
this.connections[i].send(data);
ResourceMonitor.countNetworkUse(data.length);
}
};
User.prototype.send = function(data) {
for (var i=0; i<this.connections.length; i++) {
for (var i = 0; i < this.connections.length; i++) {
this.connections[i].send(data);
ResourceMonitor.countNetworkUse(data.length);
}
};
User.prototype.popup = function(message) {
this.send('|popup|'+message.replace(/\n/g,'||'));
this.send('|popup|' + message.replace(/\n/g, '||'));
};
User.prototype.getIdentity = function(roomid) {
if (!roomid) roomid = 'lobby';
if (this.locked) {
return '‽'+this.name;
return '‽' + this.name;
}
if (this.mutedRooms[roomid]) {
return '!'+this.name;
return '!' + this.name;
}
var room = Rooms.rooms[roomid];
if (room.auth) {
if (room.auth[this.userid]) {
return room.auth[this.userid] + this.name;
}
if (room.isPrivate) return ' '+this.name;
if (room.isPrivate) return ' ' + this.name;
}
return this.group+this.name;
return this.group + this.name;
};
User.prototype.isStaff = false;
User.prototype.can = function(permission, target, room) {
@ -498,38 +498,38 @@ var User = (function () {
if (authenticated && userid in bannedUsers) {
var bannedUnder = '';
if (bannedUsers[userid] !== userid) bannedUnder = ' under the username '+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:""));
if (bannedUsers[userid] !== userid) bannedUnder = ' under the username ' + 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);
}
if (authenticated && userid in lockedUsers) {
var bannedUnder = '';
if (lockedUsers[userid] !== userid) bannedUnder = ' under the username '+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:""));
if (lockedUsers[userid] !== userid) bannedUnder = ' under the username ' + 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);
}
for (var 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;
for (var 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;
this.connections[i].send(initdata);
}
var joining = !this.named;
this.named = (this.userid.substr(0,5) !== 'guest');
this.named = (this.userid.substr(0, 5) !== 'guest');
for (var i in this.roomCount) {
Rooms.get(i,'lobby').onRename(this, oldid, joining);
Rooms.get(i, 'lobby').onRename(this, oldid, joining);
}
return true;
};
User.prototype.resetName = function() {
var name = 'Guest '+this.guestNum;
var name = 'Guest ' + this.guestNum;
var userid = toId(name);
if (this.userid === userid) return;
var i = 0;
while (users[userid] && users[userid] !== this) {
this.guestNum++;
name = 'Guest '+this.guestNum;
name = 'Guest ' + this.guestNum;
userid = toId(name);
if (i > 1000) return false;
}
@ -548,23 +548,23 @@ var User = (function () {
this.isStaff = false;
this.isSysop = false;
for (var 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;
for (var 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;
this.connections[i].send(initdata);
}
this.named = false;
for (var i in this.roomCount) {
Rooms.get(i,'lobby').onRename(this, oldid, false);
Rooms.get(i, 'lobby').onRename(this, oldid, false);
}
return true;
};
User.prototype.updateIdentity = function(roomid) {
if (roomid) {
return Rooms.get(roomid,'lobby').onUpdateIdentity(this);
return Rooms.get(roomid, 'lobby').onUpdateIdentity(this);
}
for (var i in this.roomCount) {
Rooms.get(i,'lobby').onUpdateIdentity(this);
Rooms.get(i, 'lobby').onUpdateIdentity(this);
}
};
var bannedNameStartChars = {'~':1, '&':1, '@':1, '%':1, '+':1, '-':1, '!':1, '?':1, '#':1, ' ':1};
@ -608,12 +608,12 @@ var User = (function () {
// technically it's not "taken", but if your client doesn't warn you
// before it gets to this stage it's your own fault for getting a
// bad error message
this.send('|nametaken|'+"|You did not specify a name.");
this.send('|nametaken|' + "|You did not specify a name.");
return false;
} else {
for (var w in bannedWords) {
if (userid.indexOf(w) >= 0) {
this.send('|nametaken|'+"|That name contains a banned word or phrase.");
this.send('|nametaken|' + "|That name contains a banned word or phrase.");
return false;
}
}
@ -622,14 +622,14 @@ var User = (function () {
}
}
if (users[userid] && !users[userid].authenticated && users[userid].connected && !auth) {
this.send('|nametaken|'+name+"|Someone is already using the name \""+users[userid].name+"\".");
this.send('|nametaken|' + name + "|Someone is already using the name \"" + users[userid].name + "\".");
return false;
}
if (token && token.substr(0,1) !== ';') {
if (token && token.substr(0, 1) !== ';') {
var tokenSemicolonPos = token.indexOf(';');
var tokenData = token.substr(0, tokenSemicolonPos);
var tokenSig = token.substr(tokenSemicolonPos+1);
var tokenSig = token.substr(tokenSemicolonPos + 1);
this.renamePending = name;
var self = this;
@ -637,7 +637,7 @@ var User = (function () {
self.finishRename(success, tokenData, token, auth, challenge);
});
} else {
this.send('|nametaken|'+name+"|Your authentication token was invalid.");
this.send('|nametaken|' + name + "|Your authentication token was invalid.");
}
return false;
@ -655,8 +655,8 @@ var User = (function () {
expired = true;
} else if ((tokenDataSplit[0] === challenge) && (tokenDataSplit[1] === userid)) {
body = tokenDataSplit[2];
var expiry = Config.tokenexpiry || 25*60*60;
if (Math.abs(parseInt(tokenDataSplit[3],10) - Date.now()/1000) > expiry) {
var expiry = Config.tokenexpiry || 25 * 60 * 60;
if (Math.abs(parseInt(tokenDataSplit[3], 10) - Date.now() / 1000) > expiry) {
expired = true;
}
if (Config.tokenhosts) {
@ -681,35 +681,35 @@ var User = (function () {
} else {
// a user sent an invalid token
if (tokenDataSplit[0] !== challenge) {
console.log('verify token challenge mismatch: '+tokenDataSplit[0]+' <=> '+challenge);
console.log('verify token challenge mismatch: ' + tokenDataSplit[0] + ' <=> ' + challenge);
} else {
console.log('verify token mismatch: '+tokenData);
console.log('verify token mismatch: ' + tokenData);
}
}
} else {
if (!challenge) {
console.log('verification failed; no challenge');
} else {
console.log('verify failed: '+token);
console.log('verify failed: ' + token);
}
}
if (invalidHost) {
console.log('invalid hostname in token: ' + tokenData);
body = '';
this.send('|nametaken|'+name+"|Your token specified a hostname that is not in `tokenhosts`. If this is your server, please read the documentation in config/config.js for help. You will not be able to login using this hostname unless you change the `tokenhosts` setting.");
this.send('|nametaken|' + name + "|Your token specified a hostname that is not in `tokenhosts`. If this is your server, please read the documentation in config/config.js for help. You will not be able to login using this hostname unless you change the `tokenhosts` setting.");
} else if (expired) {
console.log('verify failed: '+tokenData);
console.log('verify failed: ' + tokenData);
body = '';
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.");
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.");
} else if (body) {
//console.log('BODY: "'+body+'"');
//console.log('BODY: "' + body + '"');
if (users[userid] && !users[userid].authenticated && users[userid].connected) {
if (auth) {
if (users[userid] !== this) users[userid].resetName();
} else {
this.send('|nametaken|'+name+"|Someone is already using the name \""+users[userid].name+"\".");
this.send('|nametaken|' + name + "|Someone is already using the name \"" + users[userid].name + "\".");
return this;
}
}
@ -734,7 +734,7 @@ var User = (function () {
}
if (usergroups[userid]) {
group = usergroups[userid].substr(0,1);
group = usergroups[userid].substr(0, 1);
}
if (body === '3') {
@ -752,7 +752,7 @@ var User = (function () {
return false;
}
for (var i in this.roomCount) {
Rooms.get(i,'lobby').onLeave(this);
Rooms.get(i, 'lobby').onLeave(this);
}
if (!user.authenticated) {
if (Object.isEmpty(Object.select(this.ips, user.ips))) {
@ -763,8 +763,8 @@ var User = (function () {
this.locked = false;
}
}
for (var i=0; i<this.connections.length; i++) {
//console.log(''+this.name+' preparing to merge: connection '+i+' of '+this.connections.length);
for (var i = 0; i < this.connections.length; i++) {
//console.log('' + this.name + ' preparing to merge: connection ' + i + ' of ' + this.connections.length);
user.merge(this.connections[i]);
}
this.roomCount = {};
@ -820,19 +820,19 @@ var User = (function () {
} else if (tokenData) {
console.log('BODY: "" authInvalid');
// rename failed, but shouldn't
this.send('|nametaken|'+name+"|Your authentication token was invalid.");
this.send('|nametaken|' + name + "|Your authentication token was invalid.");
} else {
console.log('BODY: "" nameRegistered');
// rename failed
this.send('|nametaken|'+name+"|The name you chose is registered");
this.send('|nametaken|' + name + "|The name you chose is registered");
}
this.renamePending = false;
};
User.prototype.merge = function(connection) {
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;
//console.log('' + this.name + ' merging: connection ' + connection.socket.id);
var initdata = '|updateuser|' + this.name + '|' + (true ? '1' : '0') + '|' + this.avatar;
connection.send(initdata);
connection.user = this;
for (var i in connection.rooms) {
@ -848,14 +848,14 @@ var User = (function () {
}
};
User.prototype.debugData = function() {
var str = ''+this.group+this.name+' ('+this.userid+')';
for (var i=0; i<this.connections.length; i++) {
var str = '' + this.group + this.name + ' (' + this.userid + ')';
for (var i = 0; i < this.connections.length; i++) {
var connection = this.connections[i];
str += ' socket'+i+'[';
str += ' socket' + i + '[';
var first = true;
for (var j in connection.rooms) {
if (first) first=false;
else str+=',';
if (first) first = false;
else str += ', ';
str += j;
}
str += ']';
@ -864,12 +864,12 @@ var User = (function () {
return str;
};
User.prototype.setGroup = function(group) {
this.group = group.substr(0,1);
this.group = group.substr(0, 1);
this.isStaff = (this.group in {'%':1, '@':1, '&':1, '~':1});
if (!this.group || this.group === Config.groupsranking[0]) {
delete usergroups[this.userid];
} else {
usergroups[this.userid] = this.group+this.name;
usergroups[this.userid] = this.group + this.name;
}
exportUsergroups();
Rooms.global.checkAutojoin(this);
@ -879,9 +879,9 @@ var User = (function () {
this.lastConnected = Date.now();
};
User.prototype.onDisconnect = function(connection) {
for (var i=0; i<this.connections.length; i++) {
for (var i = 0; i < this.connections.length; i++) {
if (this.connections[i] === connection) {
// console.log('DISCONNECT: '+this.userid);
// console.log('DISCONNECT: ' + this.userid);
if (this.connections.length <= 1) {
this.markInactive();
if (!this.authenticated) {
@ -894,7 +894,7 @@ var User = (function () {
}
connection.user = null;
--this.ips[connection.ip];
this.connections.splice(i,1);
this.connections.splice(i, 1);
break;
}
}
@ -903,8 +903,8 @@ var User = (function () {
for (var i in this.roomCount) {
if (this.roomCount[i] > 0) {
// should never happen.
console.log('!! room miscount: '+i+' not left');
Rooms.get(i,'lobby').onLeave(this);
console.log('!! room miscount: ' + i + ' not left');
Rooms.get(i, 'lobby').onLeave(this);
}
}
this.roomCount = {};
@ -925,8 +925,8 @@ var User = (function () {
this.clearChatQueue();
var connection = null;
this.markInactive();
for (var i=0; i<this.connections.length; i++) {
// console.log('DESTROY: '+this.userid);
for (var i = 0; i < this.connections.length; i++) {
// console.log('DESTROY: ' + this.userid);
connection = this.connections[i];
connection.user = null;
for (var j in connection.rooms) {
@ -966,10 +966,10 @@ var User = (function () {
var mmr = 1000, error = (error || true);
if (data) {
if (data.errorip) {
self.popup("This server's request IP "+data.errorip+" is not a registered server.");
self.popup("This server's request IP " + data.errorip + " is not a registered server.");
return;
}
mmr = parseInt(data,10);
mmr = parseInt(data, 10);
if (!isNaN(mmr)) {
error = false;
self.mmrCache[formatid] = mmr;
@ -990,9 +990,9 @@ var User = (function () {
User.prototype.mute = function(roomid, time, force, noRecurse) {
if (!roomid) roomid = 'lobby';
if (this.mutedRooms[roomid] && !force) return;
if (!time) time = 7*60000; // default time: 7 minutes
if (!time) time = 7 * 60000; // default time: 7 minutes
if (time < 1) time = 1; // mostly to prevent bugs
if (time > 90*60000) time = 90*60000; // limit 90 minutes
if (time > 90 * 60000) time = 90 * 60000; // limit 90 minutes
// recurse only once; the root for-loop already mutes everything with your IP
if (!noRecurse) for (var i in users) {
if (users[i] === this) continue;
@ -1067,7 +1067,7 @@ var User = (function () {
}
}
if (!connection) {
for (var i=0; i<this.connections.length;i++) {
for (var i = 0; i < this.connections.length;i++) {
// only join full clients, not pop-out single-room
// clients
if (this.connections[i].rooms['global']) {
@ -1079,7 +1079,7 @@ var User = (function () {
if (!connection.rooms[room.id]) {
connection.joinRoom(room);
if (!this.roomCount[room.id]) {
this.roomCount[room.id]=1;
this.roomCount[room.id] = 1;
room.onJoin(this, connection);
} else {
this.roomCount[room.id]++;
@ -1094,7 +1094,7 @@ var User = (function () {
// you can't leave the global room except while disconnecting
return false;
}
for (var i=0; i<this.connections.length; i++) {
for (var 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]) {
@ -1107,7 +1107,7 @@ var User = (function () {
if (!this.connections[i]) {
// race condition? This should never happen, but it does.
fs.createWriteStream('logs/errors.txt', {'flags': 'a'}).on("open", function(fd) {
this.write("\nconnections="+JSON.stringify(this.connections)+"\ni="+i+"\n\n");
this.write("\nconnections = " + JSON.stringify(this.connections) + "\ni = " + i + "\n\n");
this.end();
});
} else {
@ -1146,7 +1146,7 @@ var User = (function () {
}
var format = Tools.getFormat(formatid);
if (!format[''+type+'Show']) {
if (!format['' + type + 'Show']) {
connection.popup("That format is not available.");
setImmediate(callback.bind(null, false));
return;
@ -1155,7 +1155,7 @@ var User = (function () {
};
User.prototype.finishPrepBattle = function(connection, callback, success, details) {
if (!success) {
connection.popup("Your team was rejected for the following reasons:\n\n- "+details.replace(/\n/g, '\n- '));
connection.popup("Your team was rejected for the following reasons:\n\n- " + details.replace(/\n/g, '\n- '));
callback(false);
} else {
if (details) {
@ -1175,7 +1175,7 @@ var User = (function () {
format: challengeTo.format
};
}
this.send('|updatechallenges|'+JSON.stringify({
this.send('|updatechallenges|' + JSON.stringify({
challengesFrom: Object.map(this.challengesFrom, 'format'),
challengeTo: challengeTo
}));
@ -1197,7 +1197,7 @@ var User = (function () {
time: time,
from: this.userid,
to: user.userid,
format: ''+(format||''),
format: '' + (format || ''),
//isPrivate: !!isPrivate, // currently unused
team: this.team
};
@ -1259,7 +1259,7 @@ var User = (function () {
User.prototype.chat = function(message, room, connection) {
var now = new Date().getTime();
if (message.substr(0,16) === '/cmd userdetails') {
if (message.substr(0, 16) === '/cmd userdetails') {
// certain commands are exempt from the queue
ResourceMonitor.activeIp = connection.ip;
room.chat(this, message, connection);
@ -1351,7 +1351,7 @@ var Connection = (function () {
Connection.prototype.sendTo = function(roomid, data) {
if (roomid && roomid.id) roomid = roomid.id;
if (roomid && roomid !== 'lobby') data = '>'+roomid+'\n'+data;
if (roomid && roomid !== 'lobby') data = '>' + roomid + '\n' + data;
Sockets.socketSend(this.worker, this.socketid, data);
ResourceMonitor.countNetworkUse(data.length);
};
@ -1371,7 +1371,7 @@ var Connection = (function () {
};
Connection.prototype.popup = function(message) {
this.send('|popup|'+message.replace(/\n/g,'||'));
this.send('|popup|' + message.replace(/\n/g, '||'));
};
Connection.prototype.joinRoom = function(room) {
@ -1394,9 +1394,9 @@ var Connection = (function () {
function ipSearch(ip, table) {
if (table[ip]) return table[ip];
var dotIndex = ip.lastIndexOf('.');
for (var i=0; i<4 && dotIndex > 0; i++) {
for (var i = 0; i < 4 && dotIndex > 0; i++) {
ip = ip.substr(0, dotIndex);
if (table[ip+'.*']) return table[ip+'.*'];
if (table[ip + '.*']) return table[ip + '.*'];
dotIndex = ip.lastIndexOf('.');
}
return false;
@ -1490,8 +1490,8 @@ exports.usergroups = usergroups;
exports.pruneInactive = User.pruneInactive;
exports.pruneInactiveTimer = setInterval(
User.pruneInactive,
1000*60*30,
Config.inactiveuserthreshold || 1000*60*60
1000 * 60 * 30,
Config.inactiveuserthreshold || 1000 * 60 * 60
);
exports.getNextGroupSymbol = function(group, isDown, excludeRooms) {
@ -1527,7 +1527,7 @@ exports.setOfflineGroup = function(name, group, force) {
var usergroup = usergroups[userid];
if (!usergroup && !force) return false;
name = usergroup ? usergroup.substr(1) : name;
usergroups[userid] = group+name;
usergroups[userid] = group + name;
}
exportUsergroups();
return true;