SlideShare a Scribd company logo
var buffer = document.createElement('canvas');
var bufferCtx = buffer.getContext('2d');
var bIsIPhone = false;
var bIsIPad = false;
var bWildBattleIsReady = false;
var bIsLoadingWildDialog = false;
var inventory = [];
var eggs = [];
if( navigator.userAgent.match(/iPhone/i) || navigator.userAgent.match(/iPod/i) ) {
bIsIPhone = true;
rebindClicks();
} else if( navigator.userAgent.match(/iPad/i) ) {
bIsIPad = true;
rebindClicks();
}
var bMagnify = false;
//User Variables
var userID = '';
var userName = '';
var userSprite = '';
var userMoney = 0;
var userEvent = null;
var serverToken = '';
var userX = 0;
var userY = 0;
var userDirection = 0;
var userStepPart = 0;
var userStepX = 0;
var userStepY = 0;
//Rendering Variables
var bLoading = true;
var loadAction = "";
var tick = 0;
var ctx = null;
var cvsWidth = 0;
var cvsHeight = 0;
var tagAlong = "";
var tagAlongName = "";
var follower = null;
var captchaKeypress = new Array(false,false,false,false,false,false);
//Drawing Resources
var screenResources = new Array();
var ImageResourceLoadedCount = 0;
var ImageResourceTotalCount = 0;
function ResourceImage(src,key) {
this.img = new Image();
this.img.src = src;
this.url = src;
this.img.onload = loadedResource;
this.key = key;
ImageResourceTotalCount++;
return this;
}
//Audio Resources
var musicResources = new Array();
var MusicResourceLoadedCount = 0;
var MusicResourceTotalCount = 0;
function ResourceMusic(src,key) {
this.audio = null;
MusicResourceTotalCount++;
this.key = key;
this.src = src;
if(navigator.userAgent.toLowerCase().indexOf('firefox') > -1)
{
this.audio = new Audio();
this.audio.src = src;
this.audio.load();
}
return this;
}
var prevPlaying = "";
var prevPlayingSong = null;
var playOnceSong = null;
var soundEnabled = 0;
var musicEnabled = 0;
var effectResources = new Array();
var EffectResourceLoadedCount = 0;
var EffectResourceTotalCount = 0;
function ResourceEffect(src,key) {
this.audio = new Audio();
this.audio.src = src;
//this.audio.onload = loadedEffectResource;
this.audio.oncanplaythrough = loadedEffectResource;
//this.audio.load();
if(navigator.userAgent.toLowerCase().indexOf('firefox') > -1)
{
this.audio.load();
}
//this.audio.play();
//this.audio.pause();
this.audio.volume = 0.5;
this.key = key;
EffectResourceTotalCount++;
return this;
}
//Map Variables
var currentMap = null;
var mapName = '';
var mapCode = '';
var mapID = '';
var mapWidth = 0;
var mapHeight = 0;
var mapData = null;
var mapEvents = null;
var bMapDataLoaded = false;
var bMapEventsLoaded = false;
var mapLoadedCount = 0;
var rawMapData = null;
var mapAbove = new Image();
var mapBase = new Image();
mapAbove.onload = loadedMapImage;
mapBase.onload = loadedMapImage;
var stepsInGrass = 0;
var mapEventObjects = new Array();
//Map - runtime draw,centerMap functions
var mapLeft = 0;
var mapTop = 0;
//Charset Variables
var charsets = new Array();
var charsetLoadedCount = 0;
//Scripting Variables
var events = new Array();
var lastTriggeredEventName = "";
//User Interaction
var keyState = new Object;
keyState.up = false;
keyState.down = false;
keyState.left = false;
keyState.right = false;
keyState.btn1 = false;
keyState.btn2 = false;
keyState.btn3 = false;
var bMouseDown = false;
//###########################################################
//### SOCKET FUNCTIONS ############## Chat, Support Dialog
//###########################################################
//Sockets Variables
var foregnusers = new Array();
var ws = null;
var bConnected = false;
var updateTick = 0;
var messages = new Array();
function ChatMessage(isadmin,userid,username,message) {
this.isadmin = isadmin;
this.userid = userid;
this.username = username;
this.message = message;
return this;
}
function chatKeyPress(e){
e = e || event;
var unicode=e.keyCode? e.keyCode : e.charCode
if( unicode == 13 ) {
e.preventDefault();
if( document.getElementById("txtUpdate").value != "" ) {
ws.send("/msg^" + document.getElementById("txtUpdate").value +
"rnrn");
document.getElementById("txtUpdate").value = "";
return true;
}
}
return false;
}
function chatBoxIsActive() {
var curElement = document.activeElement;
if( document.getElementById("txtUpdate") == curElement ) {
return true;
}
return false;
}
function selectChatBox() {
if( bConnected ) {
var curElement = document.activeElement;
if( document.getElementById("txtUpdate") != curElement ) {
document.getElementById("txtUpdate").focus();
} /* else {
document.getElementById("txtUpdate").blur();
return true;
}*/
}
}
function showChatBox() {
if( bConnected ) {
document.getElementById("txtUpdate").value = "";
$("#mws-jui-dialog-post").dialog({
autoOpen: false,
title: "Chat Window",
modal: true,
width: "480",
buttons: []
});
$("#mws-jui-dialog-post").dialog("option", {modal:
false}).dialog("open");
document.getElementById("txtUpdate").focus();
}
}
function showUnsupportedMessage() {
var html = "<p>Some of the functionality needed to dsplay this page correctly
is missing from the browser you are using. You can continue to play but you will not
be able to see or chat to other players of the game.</p>";
document.getElementById("mws-jui-dialog-data").innerHTML = html;
$("#mws-jui-dialog-data").dialog({
autoOpen: false,
title: "Partial Functionality Support Notification",
modal: true,
width: "480",
buttons: []
});
$("#mws-jui-dialog-data").dialog("option", {modal: true}).dialog("open");
}
function rebindClicks(){
var userAgent = navigator.userAgent.toLowerCase();
var isIphone = (userAgent.indexOf('iphone') != -1) ? true : false;
if (isIphone) {
// For each event with an inline onclick
$('[onclick]').each(function() {
var onclick = $(this).attr('onclick');
$(this).removeAttr('onclick'); // Remove the onclick attribute
$(this).bind("click", preventClickEvent); // See to it that clicks never
happen
$(this).bind('tap', onclick); // Point taps to the onclick
});
}
}
function preventClickEvent(event) {
event.preventDefault();
}
//###########################################################
//### GAME FUNCTIONS ############## update, draw, centerMap
//###########################################################
function update() {
if( bLoading ) {
if( ImageResourceLoadedCount == screenResources.length )
if( charsetLoadedCount == charsets.length )
if( mapLoadedCount == 2 )
if( bMapEventsLoaded && bMapDataLoaded ) {
bLoading = false;
mapWidth = mapAbove.width;
mapHeight = mapAbove.height;
clearInterval(gameInterval);
gameInterval = setInterval(function() {
update();
draw();
}, 50);
}
} else {
if( bConnected ) {
updateTick++;
if( updateTick > 10 ) {
var sendStr = "";
var running = "0";
if( keyState.btn2 )
running = "1";
if( tagAlong != "" && follower != null ) {
sendStr = "/update^" + mapID +"^" +
userEvent.mapPosition.X +"^" + userEvent.mapPosition.Y +"^" +
userEvent.direction +"^" + userEvent.stepAnimation + "^" + running + "^" +
(bInBattle ? "1" : "0") + "^" + tagAlong +"^" + follower.mapPosition.X +"^" +
(follower.mapPosition.Y-2) +"^" + follower.direction +"^" + follower.stepAnimation
+ "^" + running +"^rnrn";
} else {
sendStr = "/update^" + mapID +"^" +
userEvent.mapPosition.X +"^" + userEvent.mapPosition.Y +"^" +
userEvent.direction +"^" + userEvent.stepAnimation + "^" + running + "^" +
(bInBattle ? "1" : "0") + "rnrn";
}
ws.send(sendStr);
updateTick = 0;
}
}
if( activeScript.length > 0 ) {
scriptUpdate();
} else if( bInBattle ) {
battleUpdate();
} else {
//Process input and movement.
if( activeScript.length == 0 ) {
if( userEvent.moveQueue.length == 0 ) {
if( keyState.up ) {
userEvent.addMoveQueue("Up");
} else if( keyState.down ) {
userEvent.addMoveQueue("Down");
} else if( keyState.left ) {
userEvent.addMoveQueue("Left");
} else if( keyState.right ) {
userEvent.addMoveQueue("Right");
}
}
}
if( keyState.btn1 ) {
for(var k=0;k<currentMap.events.length;k++)
{
var evnt = currentMap.events[k];
if (evnt.bEventEnabled && (evnt.type == "Action Button" ||
evnt.type == "X1" || evnt.type == "X2" || evnt.type == "X3" || evnt.type == "X10" ||
evnt.type == "X15") && activeScript.length == 0 && evnt.eventData.length > 0)
{
var checkX = 0;
var checkY = 0;
if (userEvent.direction == 0)
checkY = -1;
if (userEvent.direction == 1)
checkY = 1;
if (userEvent.direction == 2)
checkX = -1;
if (userEvent.direction == 3)
checkX = 1;
if (evnt.mapPosition.X == userEvent.mapPosition.X +
checkX && evnt.mapPosition.Y == userEvent.mapPosition.Y + checkY + 2 )
{
//sfx(SOUND_CONFIRM);
if (triggerEvent(evnt, false))
{
keyState.btn1 = false;
return;
}
}
}
}
}
}
//Evaluate our hero
userEvent.evaluate();
centerMap();
currentMap.evaluateEvents(ctx);
if( bWildBattleIsReady ) {
if( keyState.btn1 == true ) {
wipeWildMonsterBox();
battleWildSelected();
keyState.btn1 = false;
}
}
}
}
function draw() {
ctx.fillStyle="#000000";
ctx.fillRect(0,0,cvsWidth,cvsHeight);
if( bLoading ) {
var status = "Loading";
if( tick > 2 )
status = status + ".";
if( tick > 5 )
status = status + ".";
if( tick > 7 )
status = status + ".";
if( tick > 10 )
tick = 0;
ctx.font = "bold 14px sans-serif";
ctx.textAlign = "center";
drawShadowText(ctx,status, cvsWidth/2, 40);
if( ImageResourceLoadedCount > ImageResourceTotalCount)
ImageResourceLoadedCount = ImageResourceTotalCount;
if( EffectResourceLoadedCount > EffectResourceTotalCount)
EffectResourceLoadedCount = EffectResourceTotalCount;
status = ImageResourceLoadedCount + " of " +
ImageResourceTotalCount + " images loaded";
drawShadowText(ctx,status, cvsWidth/2, 65);
status = EffectResourceLoadedCount + " of " +
EffectResourceTotalCount + " sound effects loaded";
drawShadowText(ctx,status, cvsWidth/2, 85);
} else {
//context.drawImage(img,sx,sy,swidth,sheight,dx,dy,dwidth,dheight);
var drawWidth = mapWidth > cvsWidth ? cvsWidth : mapWidth;
var drawHeight = mapHeight > cvsHeight ? cvsHeight : mapHeight;
if( drawHeight > mapHeight +(-mapTop-cvsHeight)-130 )
drawHeight = mapHeight +(-mapTop-cvsHeight)-130;
if( drawWidth > mapWidth + mapLeft )
drawWidth = mapWidth + mapLeft;
//Draw Base Layer
ctx.drawImage(mapBase, -mapLeft, -(-mapTop-cvsHeight)+130,
drawWidth, drawHeight, 0, 0, drawWidth, drawHeight );
currentMap.drawEvents(ctx,"below");
userEvent.drawImage(ctx);
currentMap.drawEvents(ctx,"above");
//Draw Above Layer
ctx.drawImage(mapAbove, -mapLeft, -(-mapTop-cvsHeight)+130,
drawWidth, drawHeight,0, 0, drawWidth, drawHeight);
currentMap.drawNames(ctx);
if( bMagnify ) {
bufferCtx.fillStyle="#000000";
bufferCtx.fillRect(0,0,cvsWidth,cvsHeight);
bufferCtx.drawImage(ctx.canvas,
ctx.canvas.width/4+userEvent.offsetX, ctx.canvas.height/4+userEvent.offsetY,
ctx.canvas.width/2, ctx.canvas.height/2,0, 0, drawWidth, drawHeight);
ctx.fillStyle="#000000";
ctx.fillRect(0,0,cvsWidth,cvsHeight);
ctx.drawImage(bufferCtx.canvas,0,0,drawWidth, drawHeight);
//ctx.drawImage(ctx.canvas, ctx.canvas.width/4, ctx.canvas.height/4,
ctx.canvas.width/4*3, ctx.canvas.height/4*3,0, 0, drawWidth, drawHeight);
}
ctx.font = "bold 12px sans-serif";
ctx.textAlign = "left";
drawShadowText(ctx,mapName,10, cvsHeight-15);
//ctx.textAlign = "left";
//drawShadowText(ctx,"Use Arrow Keys to move and Battle. Confirm
with X, Cancel with Z.",10, cvsHeight-25);
ctx.textAlign = "right";
drawShadowText(ctx,"Username: " + userName,cvsWidth-27, cvsHeight-
45);
ctx.textAlign = "right";
if( bConnected )
drawShadowText(ctx,"Connected: True" ,cvsWidth-27, cvsHeight-
30);
else
drawShadowText(ctx,"Connected: False" ,cvsWidth-27, cvsHeight-
30);
drawShadowText(ctx,userCount + " Trainers Online" ,cvsWidth-27,
cvsHeight-15);
ctx.textAlign = "right";
drawShadowText(ctx,"Currency: " + userMoney + "¢",cvsWidth-27, 20);
if( bInBattle ) {
battleDraw();
}
if( activeScript.length > 0 ) {
scriptDraw();
}
if( eggs.length > 0 ) {
var egg = resourceByKey("pokemonegg");
for(var i=0;i<eggs.length;i++) {
ctx.drawImage(egg, -25 + (i*30), cvsHeight-100);
}
}
}
tick++;
}
function centerMap()
{
var MyX = userEvent.mapPosition.X * 16;
var MyY = userEvent.mapPosition.Y * 16;
var winSize = new Object;
winSize.Width = cvsWidth;
winSize.Height = cvsHeight;
var xTmp = Math.max(MyX, cvsWidth / 2);
var yTmp = Math.max(MyY, cvsHeight / 2);
xTmp = Math.min(xTmp, mapWidth - winSize.Width / 2);
yTmp = Math.min(yTmp, mapHeight - winSize.Height / 2);
var actualPosition = new Object;
actualPosition.X = xTmp;
actualPosition.Y = yTmp;
var centerOfView = new Object;
centerOfView.X = cvsWidth / 2;
centerOfView.Y = cvsHeight / 2;
var viewPoint = new Object;
viewPoint.X = centerOfView.X - actualPosition.X;
viewPoint.Y = centerOfView.Y - actualPosition.Y;
if( userEvent.direction == 0 ) {
userStepY = userEvent.stepPart;
} else if( userEvent.direction == 1 ) {
userStepY = -userEvent.stepPart;
} else if( userEvent.direction == 2 ) {
userStepX = userEvent.stepPart;
} else if( userEvent.direction == 3 ) {
userStepX = -userEvent.stepPart;
}
//TODO: Check mapSize Worked
if( MyX-userStepX > mapWidth - cvsWidth/2) {
userStepX = 0;
}
if( MyX-userStepX < cvsWidth/2 ) {
userStepX = 0;
}
if( MyY-userStepY > mapHeight - cvsHeight/2 ) {
userStepY = 0;
}
if( MyY-userStepY < cvsHeight/2 ) {
userStepY = 0;
}
var additionalDown = -cvsHeight-mapHeight/8;
mapLeft = viewPoint.X + userStepX;
mapTop = (viewPoint.Y + userStepY) * -1 + additionalDown;
//User position should update as if it was an event, theirfore it should not be
done in this function but rather in the gameEvent Class.
}
//###########################################################
//### RENDERING FUNCTIONS ##############
//###########################################################
//drawShadowText(context,text,postionX,positionY)
function drawShadowText(ctx,text,posX,posY,color) {
ctx.fillStyle = 'black';
ctx.fillText(text, posX+1, posY-1);
ctx.fillText(text, posX-1, posY-1);
ctx.fillText(text, posX+1, posY+1);
ctx.fillText(text, posX-1, posY+1);
if(!color)
color = 'white';
ctx.fillStyle = color;
ctx.fillText(text, posX, posY);
}
//###########################################################
//### AJAX FUNCTIONS ##############
//###########################################################
function requestObject() {
var xmlHttpReq = false;
// Mozilla/Safari
if (window.XMLHttpRequest) {
self.xmlHttpReq = new XMLHttpRequest();
}
// IE
else if (window.ActiveXObject) {
self.xmlHttpReq = new ActiveXObject("Microsoft.XMLHTTP");
}
return xmlHttpReq;
}
function loadMapData() {
wipeWildMonsterBox();
var xmlHttpReq = requestObject();
self.xmlHttpReq.open("GET", "/maps/" + mapCode + ".xml", true);
self.xmlHttpReq.onreadystatechange = loadMapDataCallback;
self.xmlHttpReq.send();
}
function loadMapDataCallback() {
if (self.xmlHttpReq.readyState == 4) {
if (self.xmlHttpReq.responseXML) {
var resultsNode = self.xmlHttpReq.responseXML.childNodes[1];
if (!resultsNode) {
resultsNode = self.xmlHttpReq.responseXML.childNodes[0];
}
if (resultsNode == null) {
loadMapData();
return;
}
mapData = resultsNode;
bMapDataLoaded = true;
currentMap.load(mapData);
if( loadAction != "" ) {
if( loadAction.substr(0,4) == "wrap" ) {
var direction = loadAction.substr(5,1);
if( direction == 0 ) {
userEvent.mapPosition.Y = Math.floor(mapHeight/16)-
3;
} else if( direction == 1 ) {
userEvent.mapPosition.Y = 0;
} else if( direction == 2 ) {
userEvent.mapPosition.X = Math.floor(mapWidth/16)-
3;
} else if( direction == 3 ) {
userEvent.mapPosition.X = 0;
}
}
}
loadMapEvents();
}
}
}
function loadMapEvents() {
var xmlHttpReq = requestObject();
var finalPostString = "mapid="+encodeURIComponent(mapCode)
+"&x="+userEvent.mapPosition.X+"&y="+userEvent.mapPosition.Y;
self.xmlHttpReq.open("POST", "/xml/explore.xml.php?rand=" +
(Math.random() * 1000000), true);
self.xmlHttpReq.setRequestHeader("Content-type", "application/x-www-
form-urlencoded");
self.xmlHttpReq.onreadystatechange = loadMapEventsCallback;
self.xmlHttpReq.send(finalPostString);
}
function loadMapEventsCallback() {
if (self.xmlHttpReq.readyState == 4) {
if (self.xmlHttpReq.responseXML) {
var resultsNode = self.xmlHttpReq.responseXML.childNodes[1];
if (!resultsNode) {
resultsNode = self.xmlHttpReq.responseXML.childNodes[0];
}
if (resultsNode == null) {
loadMapEvents();
return;
}
mapEvents = resultsNode;
mapName = nodeValue(firstChildNodeNamed("name", mapEvents));
mapID = nodeValue(firstChildNodeNamed("id", mapEvents));
//Load the map's events
currentMap.loadEvents(mapEvents);
currentMap.mapMusic = nodeValue(firstChildNodeNamed("music",
mapEvents));
if( currentMap.mapMusic != "" && currentMap.mapMusic !=
prevPlaying ) {
playMusic(currentMap.mapMusic);
}
if( currentMap.mapMusic != "" ) {
playMusic(currentMap.mapMusic);
}
bMapEventsLoaded = true;
} else {
alert("Error loading events.");
bMapEventsLoaded = true;
}
}
}
function firstChildNodeNamed(name, node) {
for (var i = 0; i < node.childNodes.length; i++) {
if (node.childNodes[i].nodeName == name)
return node.childNodes[i];
}
return null;
}
function nodeValue(node) {
var str = node.nodeValue;
if (str == null)
if (node.childNodes.length > 0)
str = node.childNodes[0].nodeValue;
return str;
}
function getDataOfImmediateChild(parentNode)
{
var val = "";
for (n=0; n < parentNode.childNodes.length; n++)
{
val = val + nodeValue(parentNode.childNodes[n]);
}
return val;
}
//###########################################################
//### LOADING & SETUP ##############
//###########################################################
$(document).ready(function() {
curMonImage = document.getElementById("curMonImage");
curOppImage = document.getElementById("curOppImage");
var c=document.getElementById("cvsGame");
ctx = c.getContext("2d");
ctx.canvas.width = $("#mws-explore-area").innerWidth();
ctx.canvas.height = $("#mws-explore-area").innerHeight();
cvsWidth = Math.floor(ctx.canvas.width/16+1)*16;
cvsHeight = Math.floor(ctx.canvas.height/16+1)*16;
if( cvsWidth > 1024 ) {
cvsWidth = 1024;
}
loadUserData(); //Instant / Async
loadCharacterSets(); //Async
loadImages();
loadMapData(); //Async
//CALLS: loadMapEvents(); UPON COMPLETION. //Async
userEvent = new gameEvent();
userEvent.initAsPlayer(Point(userX,userY));
currentMap = gameMap();
//KEY DOWN
$(document).bind('keydown', 'up', function (evt){ keyState.up = true; return
false; } );
$(document).bind('keydown', 'down', function (evt){ keyState.down = true;
return false; });
$(document).bind('keydown', 'left', function (evt){ keyState.left = true; return
false; });
$(document).bind('keydown', 'right', function (evt){ keyState.right = true;
return false; });
$(document).bind('keydown', 'x', function (evt){ if( !chatBoxIsActive() )
{keyState.btn1 = true;} return true; });
$(document).bind('keydown', 'z', function (evt){ if( !chatBoxIsActive() )
{keyState.btn2 = true;} return true; });
$(document).bind('keydown', 'c', function (evt){ if( !chatBoxIsActive() )
{keyState.btn3 = true;} return true; });
$(document).bind('keydown', 'esc', function (evt){ menuOpen(); return
true; });
$(document).bind('keydown', 'w', function (evt){ if( !chatBoxIsActive() )
{keyState.up = true;} return true; } );
$(document).bind('keydown', 's', function (evt){ if( !chatBoxIsActive() )
{keyState.down = true;} return true; });
$(document).bind('keydown', 'a', function (evt){ if( !chatBoxIsActive() )
{keyState.left = true;} return true; });
$(document).bind('keydown', 'd', function (evt){ if( !chatBoxIsActive() )
{keyState.right = true;} return true; });
$(document).bind('keydown', '1', function (evt){ captchaKeypress[0] = false;
return true; });
$(document).bind('keydown', '2', function (evt){ captchaKeypress[1] = false;
return true; });
$(document).bind('keydown', '3', function (evt){ captchaKeypress[2] = false;
return true; });
$(document).bind('keydown', '4', function (evt){ captchaKeypress[3] = false;
return true; });
$(document).bind('keydown', '5', function (evt){ captchaKeypress[4] = false;
return true; });
$(document).bind('keydown', '6', function (evt){ captchaKeypress[5] = false;
return true; });
$(document).bind('keyup', '1', function (evt){ addToCaptcha("1"); return
true; });
$(document).bind('keyup', '2', function (evt){ addToCaptcha("2"); return
true; });
$(document).bind('keyup', '3', function (evt){ addToCaptcha("3"); return
true; });
$(document).bind('keyup', '4', function (evt){ addToCaptcha("4"); return
true; });
$(document).bind('keyup', '5', function (evt){ addToCaptcha("5"); return
true; });
$(document).bind('keyup', '6', function (evt){ addToCaptcha("6"); return
true; });
//KEY UP/RELEASE
$(document).bind('keyup', 'up', function (evt){ keyState.up = false; return
false; } );
$(document).bind('keyup', 'down', function (evt){ keyState.down = false;
return false; });
$(document).bind('keyup', 'left', function (evt){ keyState.left = false; return
false; });
$(document).bind('keyup', 'right', function (evt){ keyState.right = false; return
false; });
$(document).bind('keyup', 'x', function (evt){ if( !chatBoxIsActive() )
{keyState.btn1 = false;} return true; });
$(document).bind('keyup', 'z', function (evt){ if( !chatBoxIsActive() )
{keyState.btn2 = false;} return true; });
$(document).bind('keyup', 'c', function (evt){ if( !chatBoxIsActive() )
{keyState.btn3 = false;} return true; });
$(document).bind('keyup', 'w', function (evt){ if( !chatBoxIsActive() )
{keyState.up = false;} return true; } );
$(document).bind('keyup', 's', function (evt){ if( !chatBoxIsActive() )
{keyState.down = false;} return true; });
$(document).bind('keyup', 'a', function (evt){ if( !chatBoxIsActive() )
{keyState.left = false;} return true; });
$(document).bind('keyup', 'd', function (evt){ if( !chatBoxIsActive() )
{keyState.right = false;} return true; });
$(document).bind('keyup', 'return', function (evt){ selectChatBox(); return
false; });
$(document).bind('keyup', '/', function (evt){ selectChatBox(); return true; });
$(document).bind('keydown', 'm', function (evt){
if( document.getElementById("txtUpdate") == document.activeElement )
{
return true;
}
bMagnify=!bMagnify;
return false;
});
$("#cvsGame").mousedown(function(e) {
if (!e) var e = window.event;
canvasMouseDown(e);
});
$("#cvsGame").mouseup(function(e) {
if (!e) var e = window.event;
canvasMouseUp(e);
});
$("#cvsGame").mousemove(function(e) {
if (!e) var e = window.event;
canvasMouseMove(e);
});
if( bIsIPhone || bIsIPad ) {
c.addEventListener('touchstart', canvasMouseDown, true);
c.addEventListener('touchend', canvasMouseUp, true);
c.addEventListener('touchmove', canvasMouseMove, true);
c.addEventListener("mousedown", canvasMouseDown, true);
c.addEventListener("mouseup", canvasMouseUp, true);
c.addEventListener("mousemove", canvasMouseMove, true);
}
// test if the browser supports web sockets
if ("WebSocket" in window) {
//connect("ws://www.pokemonlegends.com:8082/game");
connect("ws://www.pokemonlegends.com:8082/game");
} else {
showUnsupportedMessage();
};
if( bIsIPhone || bIsIPad ) {
rebindClicks();
}
timeoutInterval = setInterval(keepSession, 120000);
//
gameInterval = setInterval(function() {
update();
draw();
}, 500);
reszeWindow();
});
var timeoutInterval = null;
var gameInterval = null;
// connect to the specified host
function connect(host) {
$.jGrowl("Note: Connecting to Pokemon Legends Server.", {life: 5000,
header: "Connectivity Notification.", position: "bottom-right"});
try {
ws = new WebSocket(host); // create the web socket
} catch (err) {
$.jGrowl("Note: Connection Error"+err, {life: 5000, header:
"Connectivity Notification.", position: "bottom-right"});
}
ws.onopen = function () {
ws.send("/auth^" + serverToken + "rnrn");
$.jGrowl("Note: Connection Established.", {life: 5000, header:
"Connectivity Notification.", position: "bottom-right"});
bConnected = true;
};
ws.onmessage = function (evt) {
if (typeof evt.data == "string") {
if( evt.data.indexOf("/update") > -1 ) {
updateMMOEvents(evt.data);
} else if( evt.data.indexOf("/msg") > -1 ) {
updateChat(evt.data);
} else if( evt.data.indexOf("/pvprequest") > -1 ) {
pvpRequested(evt.data);
} else if( evt.data.indexOf("/pvpaccepted") > -1 ) {
pvpLoadBattle(evt.data);
} else if( evt.data.indexOf("/ping") > -1 ) {
serverPing(evt.data);
}
}
};
ws.onclose = function () {
$.jGrowl("Note: Connection Closed. Will retry in 2 minutes.", {life:
5000, header: "Connectivity Notification.", position: "bottom-right"});
bConnected = false;
mmoUsers = new Array();
};
};
function rebindClicks(){
var userAgent = navigator.userAgent.toLowerCase();
var isIphone = (userAgent.indexOf('iphone') != -1) ? true : false;
if (isIphone) {
// For each event with an inline onclick
$('[onclick]').each(function() {
var onclick = $(this).attr('onclick');
$(this).removeAttr('onclick'); // Remove the onclick attribute
$(this).bind("click", preventClickEvent); // See to it that clicks never
happen
$(this).bind('tap', onclick); // Point taps to the onclick
});
}
}
function preventClickEvent(event) {
event.preventDefault();
}
function keepSession() {
if( bConnected == false ) {
connect("ws://www.pokemonlegends.com:8082/game");
}
loadUtility("keepAlive=true");
}
function loadMap(newMapCode, arrivalMethod, arrivalDirection) {
mapLoadedCount = 0;
bMapEventsLoaded = false;
bMapDataLoaded = false;
bLoading = true;
clearInterval(gameInterval);
gameInterval = setInterval(function() {
update();
draw();
}, 500);
mapCode = newMapCode;
loadMapData();
currentMap = gameMap();
mapWidth = mapAbove.width;
mapHeight = mapAbove.height;
mapAbove = new Image();
mapBase = new Image();
mapAbove.onload = loadedMapImage;
mapBase.onload = loadedMapImage;
mapAbove.src='http://cache.pokemonlegends.com/maps/' +mapCode+ '
above.png';
mapBase.src='http://cache.pokemonlegends.com/maps/' +mapCode+ '
base.png';
if( arrivalDirection != null ) {
loadAction = "wrap:" + arrivalDirection;
} else {
loadAction = "";
}
mmoUsers = new Array();
}
$(window).resize(function() {
if( ctx == null )
return;
reszeWindow();
});
function reszeWindow() {
var heightPotential = $( window ).height();
var usableHeight = heightPotential-175;
if( $(".adDiv").length > 0 ) {
usableHeight-=$(".adDiv").innerHeight();
}
$("#mws-explore-area").css("height",usableHeight+"px");
$("#cvsGame").css("height",usableHeight+"px");
$(".mws-panel-content").css("height",(usableHeight-33)+"px");
if( $("#mws-explore-area").innerWidth() > 502 ) {
usableHeight-=19;
}
$("#mws-explore-encounter").css("top",-(usableHeight+30)+"px");
$("#mws-explore-trade-or-battle").css("top",-(usableHeight+30)+"px");
$("#mws-explore-requests").css("top",-(usableHeight+30)+"px");
ctx.canvas.width = $("#mws-explore-area").innerWidth();
ctx.canvas.height = $("#mws-explore-area").innerHeight();
cvsWidth = Math.floor(ctx.canvas.width/16+1)*16;
cvsHeight = Math.floor(ctx.canvas.height/16+1)*16;
buffer.width = ctx.canvas.width;
buffer.height = ctx.canvas.height;
if( cvsWidth > 1024 ) {
cvsWidth = 1024;
}
repositionMonsters();
}
function repositionMonsters() {
cvsWidth = Math.floor(ctx.canvas.width/16+1)*16;
cvsHeight = Math.floor(ctx.canvas.height/16+1)*16;
var left = $("#cvsGame").offset().left + $("#cvsGame").position().left;
var top = $("#cvsGame").offset().top + $("#cvsGame").position().top;
var centerX = cvsWidth/2;
var centerY = cvsHeight/2;
//if( top > 158 ) {
//centerY += top-158;
//}
curMonImage.style.left = (centerX-120-curMonImage.width/2) + 'px';
curMonImage.style.top = (centerY-curMonImage.height/2+70) + 'px';
curOppImage.style.left = (centerX+120-curOppImage.width/2) + 'px';
curOppImage.style.top = (centerY-curOppImage.height/2) + 'px';
}
function loadedMapImage() {
mapLoadedCount++;
}
function resourceByKey(key) {
for(var i=0;i<screenResources.length;i++) {
if( screenResources[i].key == key)
return screenResources[i].img;
}
return null;
}
function musicResourceByKey(key) {
for(var i=0;i<musicResources.length;i++) {
if( musicResources[i].key == key)
return musicResources[i];
}
return null;
}
function effectResourceByKey(key) {
for(var i=0;i<effectResources.length;i++) {
if( effectResources[i].key == key)
return effectResources[i].audio;
}
return null;
}
function loadedMusicResource() {
MusicResourceLoadedCount++;
}
function loadedEffectResource() {
EffectResourceLoadedCount++;
}
function loadedResource() {
ImageResourceLoadedCount++;
for(var k=0;k<screenResources.length;k++) {
if( this.src.indexOf(screenResources[k].url) > -1 ) {
screenResources[k].width = this.width;
screenResources[k].height = this.height;
}
}
}
function loadImages() {
//Images
screenResources.push(new
ResourceImage("http://cache.pokemonlegends.com/images/battlescreen.png","battlesc
reen"));
screenResources.push(new
ResourceImage("http://cache.pokemonlegends.com/images/BattleIcon.png","battleico
n"));
screenResources.push(new
ResourceImage("http://cache.pokemonlegends.com/images/pokeball_bubble.png","po
keballicon"));
screenResources.push(new
ResourceImage("http://cache.pokemonlegends.com/images/pokemonEgg.png","poke
monegg"));
screenResources.push(new
ResourceImage("http://cache.pokemonlegends.com/images/btnHighlightAttack.png","
btnHighlightAttack"));
screenResources.push(new
ResourceImage("http://cache.pokemonlegends.com/images/btnHighlightOption.png","
btnHighlightOption"));
screenResources.push(new
ResourceImage("http://cache.pokemonlegends.com/images/btnHighlightSwap.png","b
tnHighlightSwap"));
var elements = new Array("ani-air","ani-ancient","ani-basic","ani-
demonic","ani-divine","ani-earth","ani-electric","ani-fire","ani-ghost","ani-
psychic","ani-steel","ani-water", "ani-berserk","ani-confusion","ani-heal","ani-
paralyze","ani-poison","ani-seed","ani-sleep");
for(var k=0;k<elements.length;k++)
screenResources.push(new
ResourceImage("http://cache.pokemonlegends.com/images/typeanimations/"+element
s[k]+".png",elements[k]));
//sfx
effectResources.push(new
ResourceEffect("http://cache.pokemonlegends.com/audio/MonAppear.wav","MonApp
ear"));
effectResources.push(new
ResourceEffect("http://cache.pokemonlegends.com/audio/beep.wav","beep"));
effectResources.push(new
ResourceEffect("http://cache.pokemonlegends.com/audio/door.wav","door"));
effectResources.push(new
ResourceEffect("http://cache.pokemonlegends.com/audio/hit.mp3","hit"));
effectResources.push(new
ResourceEffect("http://cache.pokemonlegends.com/audio/intro.mp3","intro"));
effectResources.push(new
ResourceEffect("http://cache.pokemonlegends.com/audio/levelup.mp3","levelup"));
effectResources.push(new
ResourceEffect("http://cache.pokemonlegends.com/audio/coinchange.mp3","coinchan
ge"));
effectResources.push(new
ResourceEffect("http://cache.pokemonlegends.com/audio/battle.wav","battle"));
//music
musicResources.push(new
ResourceMusic("http://cache.pokemonlegends.com/audio/Vaniville
Town.mp3","vanivilletown"));
musicResources.push(new
ResourceMusic("http://cache.pokemonlegends.com/audio/Route 8.mp3","route8"));
musicResources.push(new
ResourceMusic("http://cache.pokemonlegends.com/audio/victory.mp3","victory"));
musicResources.push(new
ResourceMusic("http://cache.pokemonlegends.com/audio/Scary House.mp3","cave"));
musicResources.push(new
ResourceMusic("http://cache.pokemonlegends.com/audio/fail.mp3","fail"));
musicResources.push(new
ResourceMusic("http://cache.pokemonlegends.com/audio/healing.mp3","healing"));
musicResources.push(new
ResourceMusic("http://cache.pokemonlegends.com/audio/Pokemon
Center.mp3","pokecenter"));
musicResources.push(new
ResourceMusic("http://cache.pokemonlegends.com/audio/overworld1.mp3","overworl
d1"));
musicResources.push(new
ResourceMusic("http://cache.pokemonlegends.com/audio/overworld2.mp3","overworl
d2"));
musicResources.push(new
ResourceMusic("http://cache.pokemonlegends.com/audio/Magic Forest.mp3","Magic
Forest"));
musicResources.push(new
ResourceMusic("http://cache.pokemonlegends.com/audio/battle1.mp3","battle1"));
musicResources.push(new
ResourceMusic("http://cache.pokemonlegends.com/audio/tournament.mp3","tourname
nt"));
musicResources.push(new
ResourceMusic("http://cache.pokemonlegends.com/audio/Sharks.mp3","Sharks"));
musicResources.push(new
ResourceMusic("http://cache.pokemonlegends.com/audio/Dark Intentions.mp3","Dark
Intentions"));
}
//Loads all NPC and main character sprites into an array
function loadCharacterSets() {
//no longer used. All are loaded from explore.php.
}
function loadedSprite() {
charsetLoadedCount++;
}
//Adds a sprite to the charsets array
function addCharset(imgURL) {
var newImage = new Image();
newImage.src = imgURL;
newImage.onload = loadedSprite;
charsets.push(newImage);
}
//### SCRIPTING FUNCTIONS ##############
function triggerEvent( Event, fromCollision)
{
if( Event.bEventEnabled ) {
lastTriggeredEventName = Event.name;
//face the user
if( Event.mapPosition.X > userEvent.mapPosition.X ) {
scriptAddLine("move event",Event.id + "^Face Left^1");
} else if( Event.mapPosition.X < userEvent.mapPosition.X ) {
scriptAddLine("move event",Event.id + "^Face Right^1");
} else if( Event.mapPosition.Y > userEvent.mapPosition.Y+2 ) {
scriptAddLine("move event",Event.id + "^Face Up^1");
} else if( Event.mapPosition.Y < userEvent.mapPosition.Y+2 ) {
scriptAddLine("move event",Event.id + "^Face Down^1");
}
for(var i=0;i<Event.eventData.length;i++) {
activeScript.push(Event.eventData[i]);
}
if( activeScript.length > 0 ) {
scriptProgress();
return true;
} else {
return false;
}
}
return false;
}
//### KEY PRESS / MOUSE FUNCTIONS ##############
function getPosition(e) {
e = e || window.event;
var cursor = {x:0, y:0};
if (e.pageX || e.pageY) {
cursor.x = e.pageX;
cursor.y = e.pageY;
}
else {
var de = document.documentElement;
var b = document.body;
cursor.x = e.clientX +
(de.scrollLeft || b.scrollLeft) - (de.clientLeft || 0);
cursor.y = e.clientY +
(de.scrollTop || b.scrollTop) - (de.clientTop || 0);
}
return cursor;
}
function hitTest(x,y,boxX1,boxY1,boxX2,boxY2) {
if( x >= boxX1 && x <= boxX2 ) {
if( y >= boxY1 && y <= boxY2 ) {
return true;
}
}
return false;
}
function checkMousePosition(posX,posY) {
var boxWidth = 160;
var boxHeight = 40;
var centerX = cvsWidth/2;
var centerY = cvsHeight/2;
var boxX = centerX+46;
var boxY = centerY+110-50;
if( hitTest(posX,posY,boxX-boxWidth/2,boxY-
boxHeight/2,boxX+boxWidth/2,boxY+boxHeight/2) ) {
return "atk1";
}
boxX = centerX+174;
boxY = centerY+110-50;
if( hitTest(posX,posY,boxX-boxWidth/2,boxY-
boxHeight/2,boxX+boxWidth/2,boxY+boxHeight/2) ) {
return "atk2";
}
boxX = centerX+46;
boxY = centerY+145-50;
if( hitTest(posX,posY,boxX-boxWidth/2,boxY-
boxHeight/2,boxX+boxWidth/2,boxY+boxHeight/2) ) {
return "atk3";
}
boxX = centerX+174;
boxY = centerY+145-50;
if( hitTest(posX,posY,boxX-boxWidth/2,boxY-
boxHeight/2,boxX+boxWidth/2,boxY+boxHeight/2) ) {
return "atk4";
}
boxWidth = 100;
boxX = centerX-232+45;
boxY = centerY+125-40;
if( hitTest(posX,posY,boxX-boxWidth/2,boxY-
boxHeight/2,boxX+boxWidth/2,boxY+boxHeight/2) ) {
return "run";
}
boxX = centerX-138+45;
boxY = centerY+125-40;
if( hitTest(posX,posY,boxX-boxWidth/2,boxY-
boxHeight/2,boxX+boxWidth/2,boxY+boxHeight/2) ) {
return "item";
}
boxWidth = 50;
boxHeight = 50;
boxX = centerX-220;
boxY = centerY-111-80;
if( hitTest(posX,posY,boxX-boxWidth/2,boxY-
boxHeight/2,boxX+boxWidth/2,boxY+boxHeight/2) ) {
return "swap";
}
if( battleSelectedMenu > 6 && battleSelectedMenu <= 12 ) {
for(var k=0;k< teamMonsters.length;k++) {
var pos = k+1;
var x = centerX;
var y = centerY-75-60;
if( pos < 4 ) {
x = x - 110;
y = y + pos * 30;
} else {
x = x + 110;
y = y + (pos-3) * 30;
}
boxWidth = 200;
boxHeight = 40;
boxX = x;
boxY = y;
if( hitTest(posX,posY,boxX-boxWidth/2,boxY-
boxHeight/2,boxX+boxWidth/2,boxY+boxHeight/2) ) {
return "swap" + pos;
}
}
} if( battleSelectedMenu == 13 ) {
for(var k=0;k< battleItems.length;k++) {
var pos = k+1;
var x = centerX;
var y = centerY-75-60;
if( pos < 5 ) {
x = x - 110;
y = y + pos * 30;
} else {
x = x + 110;
y = y + (pos-4) * 30;
}
boxWidth = 200;
boxHeight = 40;
boxX = x;
boxY = y;
if( hitTest(posX,posY,boxX-boxWidth/2,boxY-
boxHeight/2,boxX+boxWidth/2,boxY+boxHeight/2) ) {
return "item" + pos;
}
}
}
return "";
}
function canvasMouseDown(e) {
var pos = getPosition(e);
var centerX = cvsWidth/2;
var centerY = cvsHeight/2;
bMouseDown = true;
var left = $("#cvsGame").offset().left + $("#cvsGame").position().left;
var top = $("#cvsGame").offset().top + $("#cvsGame").position().top;
var posX = pos.x-left;
var posY = pos.y-top;
/*
var pos = getPosition(e);
if( pos.x - left < 64 ) {
keyState.left = true;
} else if( pos.x - left > cvsWidth - 64 ) {
keyState.right = true;
} else if( pos.y - top < 64 ) {
keyState.up = true;
} else if( pos.y - top > cvsHeight - 64 ) {
keyState.down = true;
} else {
keyState.btn1 = true;
}
*/
if( bInBattle ) {
if( battleScript.length > 0 ) {
keyState.btn1 = true;
} else {
var activeMenu = checkMousePosition(posX,posY);
if( activeMenu != "") {
if( activeMenu != "item" && activeMenu != "swap" ) {
keyState.btn1 = true;
}
}
}
} else {
document.getElementById('mws-explore-trade-or-battle').innerHTML =
"";
for(var i=0;i< mmoUsers.length;i++) {
var user = mmoUsers[i];
if( pos.x-left > user.drawPosX && pos.x-left < user.drawPosX +32 )
{
if( pos.y-top < user.drawPosY && pos.y-top > user.drawPosY
-48 ) {
if( user.name.indexOf("'s Pet") == -1 ) {
displayMMOUser(user);
}
}
}
}
}
return false;
}
function canvasMouseUp(e) {
var pos = getPosition(e);
var centerX = cvsWidth/2;
var centerY = cvsHeight/2;
bMouseDown = false;
//var pos = getPosition(e);
/*
keyState.up = false;
keyState.down = false;
keyState.left = false;
keyState.right = false;
keyState.btn1 = false;
keyState.btn2 = false;
keyState.btn3 = false;
*/
return false;
}
function canvasMouseMove(e) {
var pos = getPosition(e);
var centerX = cvsWidth/2;
var centerY = cvsHeight/2;
var left = $("#cvsGame").offset().left + $("#cvsGame").position().left;
var top = $("#cvsGame").offset().top + $("#cvsGame").position().top;
var posX = pos.x-left;
var posY = pos.y-top;
if( bInBattle ) {
if( battleScript.length == 0 ) {
var activeMenu = checkMousePosition(posX,posY);
if( activeMenu == "atk1" && parseInt(battleStage) != 1) {
battleSelectedMenu = 2;
} else if( activeMenu == "atk2" && parseInt(battleStage) != 1) {
battleSelectedMenu = 3;
} else if( activeMenu == "atk3" && parseInt(battleStage) != 1) {
battleSelectedMenu = 4;
} else if( activeMenu == "atk4" && parseInt(battleStage) != 1) {
battleSelectedMenu = 5;
} else if( activeMenu == "run" && parseInt(battleStage) != 1) {
battleSelectedMenu = 0;
} else if( activeMenu == "item" && battleSelectedMenu != 13 &&
parseInt(battleStage) != 1) {
battleSelectedMenu = 13;
} else if( activeMenu == "swap" && parseInt(battleStage) != 1 ) {
battleSelectedMenu = 7;
} else if( activeMenu.indexOf('swap') > -1 && activeMenu !=
"swap" ) {
var pos = parseInt(activeMenu.replace(/swap/gi,''));
battleSelectedMenu = pos+6;
} else if( activeMenu.indexOf('item') > -1 && battleSelectedMenu
== 13 && parseInt(battleStage) != 1 ) {
var pos = parseInt(activeMenu.replace(/item/gi,''));
battleItemSelectedMenu = pos-1;
}
if( activeMenu != "" )
battleUpdatedMenu();
}
}
/*
keyState.up = false;
keyState.down = false;
keyState.left = false;
keyState.right = false;
keyState.btn1 = false;
keyState.btn2 = false;
keyState.btn3 = false;
var left = $("#cvsGame").offset().left + $("#cvsGame").position().left;
var top = $("#cvsGame").offset().top + $("#cvsGame").position().top;
if( pos.x - left < 64 ) {
keyState.left = true;
} else if( pos.x - left > cvsWidth - 64 ) {
keyState.right = true;
} else if( pos.y - top < 64 ) {
keyState.up = true;
} else if( pos.y - top > cvsHeight - 64 ) {
keyState.down = true;
}
*/
}
//### MMO FUNCTIONS ###############
function displayMMOUser(user) {
var div = document.getElementById('mws-explore-trade-or-battle');
var html = "<center><b>" + user.name + "</b><br/>";
//html += '<input type="button" style="width:120px;" class="mws-tooltip-s
mws-button blue" value="Trade" title="Offer to Trade with this Player."><br/>';
html += '<input type="button" style="width:120px;" class="mws-tooltip-s
mws-button red" value="Battle" onclick="pvpRequest('' + user.name + '');"
title="Request a Battle with this Player."><br/>';
html += '<input type="button" style="width:120px;" class="mws-tooltip-s
mws-button green" value="PM" onclick="pmUser('' + user.name + '')" title="Send a
Private Message to this Player."><br/>';
html += "</center>";
div.innerHTML = html;
}
function pmUser(name) {
document.getElementById("txtUpdate").value = "/pm " + name + " ";
document.getElementById("txtUpdate").focus();
}
function pvpRequest(name) {
ws.send("/msg^/pvprequest " + name + "rnrn");
document.getElementById('mws-explore-trade-or-battle').innerHTML = "";
}
function pvpAccept(name) {
ws.send("/msg^/pvpaccept " + name + "rnrn");
document.getElementById("mws-explore-requests").innerHTML = "";
}
function pvpRequested(data) {
var dataRow = data.split("^");
document.getElementById("mws-explore-requests").innerHTML = '<div
style="padding:8px;"><b>'+dataRow[1]+'</b> wants to battle: <br/><center><input
type="button" style="width:120px;" class="mws-tooltip-s mws-button green"
value="Accept PvP" onclick="pvpAccept('' +dataRow[1]+ '')"
title="Accept"></center></div>';
}
var userCount = "?";
function serverPing(data) {
var dataRow = data.split("^");
userCount = parseInt(dataRow[1]);
}
function pvpLoadBattle(data) {
var dataRow = data.split("^");
battleRoundTacker = 0;
curOpp = null;
nextOpp = null;
curMon = null;
nextMon = null;
curMonImage.src = 'http://cache.pokemonlegends.com/images/blank.png';
curOppImage.src = 'http://cache.pokemonlegends.com/images/blank.png';
battleLoading = false;
//battle_id needs to be provided.
curOpp = null;
scriptAddLine("battlescreen","PVP");
//bInBattle = true; - this is set in the above script funciton
battleSelectedMenu = 2;
playSFX("battle");
playMusic("battle1");
if( prevPlayingSong )
prevPlayingSong.currentTime = 0;
bWildBattle = false;
wipeWildMonsterBox();
}
function updateChat(data) {
var dataRow = data.split("^");
var dataMsg = dataRow[1].split("|");
var isadmin = dataMsg[0];
var userids = dataMsg[1];
var user = dataMsg[2];
var msg = dataMsg[3];
var isPM = dataMsg[4];
var changeColor = true;
var title = "A Legend";
messages.push(new ChatMessage(isadmin,userids,user,msg));
var sender = mmoUserByName(user);
if( sender != null ) {
sender.msg = msg;
sender.msgTick = 0;
} else {
if( userids == userID ) {
userEvent.msg = msg;
userEvent.msgTick = 0;
}
}
if (msg.toLowerCase().indexOf(userName.toLowerCase()) > -1)
{
color = "#CE93D8";
changeColor = false;
}
if (changeColor) //if name is mentioned on a word, do not change unless it's
PM. PM is always in the special color.
{
var color = "#fff";
if( isadmin > 1 ) {
color = "#99FF99";
title = "Game Moderators";
}
else if ( isadmin == 1)
{
color = "#72C065";
title = "Chat Moderators";
}
if (isadmin > 2)
{
title = "Administrators";
}
if( userids == 0 ) {
color = "#FF9999";
}
if ( msg.toLowerCase().indexOf("pm to") > -1 &&
user.toLowerCase().indexOf("you") > -1) //pm sent msg
{
color = "#FFCC99";
}
}
if (isPM == 1)
{
color = "#FFCC99";
}
//sharks remove html tags from user input
msg = msg.replace(/<(?:.|n)*?>/gm, '');
var html = "<p data-username='"+user+"' onclick=quickPM(this)
style='color:"+color+";margin-bottom:2px;'><b>";
if (userids > 0)
{
html = html + "<a href='user?id="+userids+"' style='color:"+color+"'
target='_blank' title = '"+title+"'>";
}
html = html + user;
if (userids > 0)
{
html = html + "</a>";
}
html = html + ":</b> " + msg + "</p>";
$('#chat').append(html);
$('#chat')[0].scrollTop = $('#chat')[0].scrollHeight;
}
function quickPM(msg)
{
if (msg.getAttribute("data-username") != "You" )
document.getElementById("txtUpdate").value = "/pm
"+msg.getAttribute("data-username")+" ";
}
//### AUDIO FUNCTIONS ###############
function restoreLastSong() {
if( musicEnabled == false )
return;
if( prevPlayingSong )
prevPlayingSong.play();
}
function playMusicOnce(key) {
if( musicEnabled == false )
return;
var audio = musicResourceByKey(key);
if( audio ) {
if( prevPlayingSong )
prevPlayingSong.pause();
if( playOnceSong )
playOnceSong.pause();
if( audio.audio == null ) {
audio.audio = new Audio();
audio.audio.src = audio.src;
audio.audio.volume = 0.5;
//this.audio.play();
//this.audio.pause();
}
audio.audio.loop = false;
audio.audio.addEventListener('ended', restoreLastSong);
audio.audio.currentTime = 0;
audio.audio.play();
playOnceSong = audio.audio;
}
}
function playMusic(key) {
if( musicEnabled == false )
return;
var audio = musicResourceByKey(key);
if( audio ) {
if( prevPlayingSong )
prevPlayingSong.pause();
if( playOnceSong )
playOnceSong.pause();
if( audio.audio == null ) {
audio.audio = new Audio();
audio.audio.src = audio.src;
audio.audio.volume = 0.35;
//this.audio.play();
//this.audio.pause();
}
audio.audio.loop = true;
audio.audio.play();
prevPlayingSong = audio.audio;
prevPlaying = key;
}
}
function playSFX(key) {
if( soundEnabled == false )
return;
var audio = effectResourceByKey(key);
if( audio ) {
audio.play();
}
}
//### SUPPORT FUNCTIONS ###############
function isNumber(n) {
return !isNaN(parseFloat(n)) && isFinite(n);
}
// ################################################
// ### MMO USER CLASS ###########################
// ################################################
function MMOUser(id,name,trainerimg) {
this.id = id;
this.name = name;
this.trainerimg = trainerimg;
this.mapid = 0;
this.x = 0;
this.y = 0;
this.NewX = 0;
this.NewY = 0;
this.direction = 0;
this.step = 0;
this.inbattle = 0;
this.drawPosX = 0;
this.drawPosY = 0;
this.drawStartX = 0;
this.drawStartY = 0;
this.isRunning = 0;
this.stepPart = 0;
this.stepAnimation = 0;
this.offsetX = 0;
this.offsetY = 0;
this.stepX = 0;
this.stepY = 0;
this.moveQueue = new Array();
this.msg = "";
this.msgTick = 0;
this.frameCount = 2;
this.ImageRef = null;
this.updated = false;
this.evaluate = function() {
this.stepX = 0;
this.stepY = 0;
if( this.moveQueue.length > 0 ) {
if( this.moveQueue[0] == "up" ) {
this.stepY = -this.stepPart;
} else if( this.moveQueue[0] == "down" ) {
this.stepY = this.stepPart;
} else if( this.moveQueue[0] == "left" ) {
this.stepX = -this.stepPart;
} else {
this.stepX = this.stepPart;
}
}
this.drawPosX = mapLeft + (this.x * 16)+ this.stepX +13;
this.drawPosY = -mapTop-currentMap.mapHeight/2 + ((this.y+2) * 16)+
this.stepY +2-130+32;
var additionalDown = currentMap.mapHeight/2-cvsHeight/2;
this.drawPosY = -mapTop-cvsHeight/2-currentMap.mapHeight/2 +
((this.y+2) * 16) + this.stepY +2+28 + (additionalDown-192);
this.updateTextureCoords();
//process move queue - in between movequeue syncs check for position
reevaluate
this.processMoveQueue();
if( this.msg != "" ) {
this.msgTick++;
if( this.msgTick > 250 ) {
this.msg = "";
}
}
}
this.updatesWithoutMove = 0;
this.processMoveQueue = function() // Define Method
{
if( currentMap == null ) {
return false;
}
if( this.moveQueue.length > 0 ) {
if( this.moveQueue[0].toLowerCase() == "up" ) {
this.direction = 0;
} else if( this.moveQueue[0].toLowerCase() == "down" ) {
this.direction = 1;
} else if( this.moveQueue[0].toLowerCase() == "left" ) {
this.direction = 2;
} else if( this.moveQueue[0].toLowerCase() == "right" ) {
this.direction = 3;
}
if( this.stepPart == 8 || this.stepPart == 0 ) {
this.stepAnimation++;
if( this.stepAnimation > this.frameCount )
this.stepAnimation = 0;
}
this.stepPart = this.stepPart + 4;
if( this.isRunning == 1 && this.moveQueue.length == 1 )
this.stepPart = this.stepPart + 4;
if( this.stepPart >= 16 ) {
this.stepPart = 0;
//update the coordanates at the end of the step.
if( this.moveQueue[0] == "up" ) {
this.y = this.y - 1;
} else if( this.moveQueue[0] == "down" ) {
this.y = this.y + 1;
} else if( this.moveQueue[0] == "left" ) {
this.x = this.x - 1;
} else {
this.x = this.x + 1;
}
this.moveQueue.splice(0,1);
if( Math.abs(this.NewX - this.x) > 6 || Math.abs(this.NewY - this.y) >
6 ) {
this.x = this.NewX;
this.y = this.NewY;
this.moveQueue.length = 0;
}
}
}
if( this.moveQueue.length == 0 ) {
//add to moveQueue based on position
if( this.y > this.NewY ) {
if( currentMap.tileIsWalkable( Point(this.x,this.y-2-1)) ) {
this.addMoveQueue("up");
}
} else if( this.y < this.NewY ) {
if( currentMap.tileIsWalkable( Point(this.x,this.y-2+1)) ) {
this.addMoveQueue("down");
}
} else if( this.x > this.NewX ) {
if( currentMap.tileIsWalkable( Point(this.x-1,this.y-2)) ) {
this.addMoveQueue("left");
}
} else if( this.x < this.NewX ) {
if( currentMap.tileIsWalkable( Point(this.x+1,this.y-2)) ) {
this.addMoveQueue("right");
}
}
this.updatesWithoutMove++;
if( this.updatesWithoutMove > 10 ) {
this.x=this.NewX;
this.y=this.NewY;
this.updatesWithoutMove = 0;
}
} else {
this.updatesWithoutMove = 0;
}
}
this.addMoveQueue = function(moveDirection) // Define Method
{
this.moveQueue.push(moveDirection.toLowerCase());
}
this.drawNames = function(ctx) // Define Method
{
if( this.name.indexOf("'s Pet") > -1 ) {
return;
}
ctx.font = "bold 11px sans-serif";
ctx.textAlign = "center";
drawShadowText(ctx,this.name, this.drawPosX+12, this.drawPosY-1);
if( this.msg != "" ) {
drawShadowText(ctx,this.msg, this.drawPosX+12, this.drawPosY-
14,"#c4d52b");
}
}
this.drawImage = function(ctx) // Define Method
{
//context.drawImage(img,sx,sy,swidth,sheight,dx,dy,dwidth,dheight);
if( this.ImageRef == null ) {
for(var i=0;i< charsets.length;i++) {
var img = charsets[i];
if( img.src ) {
if( img.src.indexOf("/" + this.trainerimg) > 0 ) {
this.ImageRef = img;
if( img.width == 64 ) {
this.frameCount = 1;
}
if( img.width == 32 ) {
this.frameCount = 0;
}
}
}
}
}
if( this.ImageRef != null ) {
ctx.drawImage(this.ImageRef, this.drawStartX, this.drawStartY, 32, 32,
this.drawPosX-5, this.drawPosY, 32, 32 );
}
if( parseInt(this.inbattle) == 1 ) {
ctx.drawImage(resourceByKey("pokeballicon"), this.drawPosX+4,
this.drawPosY-26);
}
}
this.updateTextureCoords = function() // Define Method
{
var startX = 0;
var startY = 0;
if( this.direction == 0 ) {
switch(this.stepAnimation) {
case 0 :
startX = 0;
startY = 0;
break;
case 1 :
startX = 1;
startY = 0;
break;
case 2 :
startX = 2;
startY = 0;
break;
}
} else if( this.direction == 1 ) {
switch(this.stepAnimation) {
case 0 :
startX = 0;
startY = 1;
break;
case 1 :
startX = 1;
startY = 1;
break;
case 2 :
startX = 2;
startY = 1;
break;
}
} else if( this.direction == 2 ) {
switch(this.stepAnimation) {
case 0 :
startX = 0;
startY = 2;
break;
case 1 :
startX = 1;
startY = 2;
break;
case 2 :
startX = 2;
startY = 2;
break;
}
} else {
switch(this.stepAnimation) {
case 0 :
startX = 0;
startY = 3;
break;
case 1 :
startX = 1;
startY = 3;
break;
case 2 :
startX = 2;
startY = 3;
break;
}
}
this.drawStartX = startX*32;
this.drawStartY = startY*32;
}
return this;
}
var mmoUsers = new Array();
function updateMMOEvents(updateData) {
for(var k=0;k<mmoUsers.length;k++) {
mmoUsers[k].updated = false;
}
var dataRaw = updateData.split("^");
for(var k=1;k<dataRaw.length;k++) {
if( dataRaw[k] != "" ) {
var dataUser = dataRaw[k].split("|");
var user = mmoUserByName(dataUser[1]);
if( user == null ) {
//add id,name,trainerimg
user = new MMOUser(dataUser[0],dataUser[1],dataUser[2]);
mmoUsers.push(user);
}
//update mapid,x,y,direction,step,inbattle
user.mapid = dataUser[3];
user.NewX = parseInt(dataUser[4]);
user.NewY = parseInt(dataUser[5]);
if( user.x == 0 ) {
user.x = user.NewX;
user.y = user.NewY;
}
user.direction = parseInt(dataUser[6]);
user.step = parseInt(dataUser[7]);
user.isRunning = parseInt(dataUser[8]);
user.inbattle = dataUser[9];
user.updated = true;
}
}
//remove old connections
for(var k=0;k<mmoUsers.length;k++) {
if( k < mmoUsers.length ) {
if( mmoUsers[k].updated == false ) {
mmoUsers.splice(k,1);
k--;
}
}
}
}
function mmoUserByName(name) {
for(var k=0;k<mmoUsers.length;k++) {
if( name == mmoUsers[k].name ) {
return mmoUsers[k];
}
}
return null;
}
function Point(x,y) {
this.X = x;
this.Y = y;
return this;
}
// ################################################
// ### GAME EVENT CLASS ###########################
// ################################################
function ScriptLine(line,func,args) {
this.func = func;
this.args = args;
this.line = line;
return this;
}
function GameEgg(node) {
if( node ) {
this.id = nodeValue(firstChildNodeNamed("id", node));
this.steps = nodeValue(firstChildNodeNamed("steps", node));
}
return this;
}
function GameItem(node) {
if( node ) {
this.id = nodeValue(firstChildNodeNamed("id", node));
this.name = nodeValue(firstChildNodeNamed("name", node));
this.file = nodeValue(firstChildNodeNamed("file", node));
this.qty = nodeValue(firstChildNodeNamed("qty", node));
}
return this;
}
function gameEvent(node)
{
this.moveQueue = new Array();
this.mapPosition = new Object;
this.bEventEnabled = false;
this.bHidden = false;
this.bIsUser = true;
this.id = 0;
this.name = "";
this.mapPosition.X = 0;
this.mapPosition.Y = 0;
this.spriteName = "";
this.type = "";
this.direction = 0;
this.moveType = "";
this.quest = 0;
this.frameCount = 2;
//Event Properties
this.eventData = new Array();
this.mapPosition.X = 0;
this.mapPosition.Y = 0;
//Core Variables
if( node ) {
this.id = nodeValue(firstChildNodeNamed("id", node));
this.name = nodeValue(firstChildNodeNamed("name", node));
this.mapPosition.X = parseInt(nodeValue(firstChildNodeNamed("x",
node)))-1;
this.mapPosition.Y = parseInt(nodeValue(firstChildNodeNamed("y",
node)))+1;
this.type = nodeValue(firstChildNodeNamed("type", node));
this.spriteName = nodeValue(firstChildNodeNamed("style", node));
this.direction = parseInt(nodeValue(firstChildNodeNamed("direction",
node)));
this.moveType = nodeValue(firstChildNodeNamed("movement", node));
this.bIsUser = false;
this.bEventEnabled = true;
this.quest = parseInt(nodeValue(firstChildNodeNamed("quest", node)));
var script = firstChildNodeNamed("script", node);
for(var i=0;i<script.childNodes.length;i++) {
line = script.childNodes[i];
this.eventData.push(new
ScriptLine( nodeValue(firstChildNodeNamed("line", line)) ,
nodeValue(firstChildNodeNamed("function", line)) ,
nodeValue(firstChildNodeNamed("arguments", line)) ));
}
}
//Movement
this.stepPart = 0;
this.stepAnimation = 0;
this.bJumping = false;;
this.jumpYAdd = 0;
this.jumpYAcc = 0;
this.drawStartX = 0;
this.drawStartY = 0;
this.X = 0;
this.Y = 0;
this.offsetX = 0;
this.offsetY = 0;
this.stepX = 0;
this.stepY = 0;
this.msg = "";
this.msgTick = 0;
this.bHasAppearance = false;
if( this.spriteName != "" ) {
this.bHasAppearance = true;
}
this.ImageRef = null;
this.drawImage = function(ctx) // Define Method
{
//context.drawImage(img,sx,sy,swidth,sheight,dx,dy,dwidth,dheight);
if( this.ImageRef == null ) {
for(var i=0;i< charsets.length;i++) {
var img = charsets[i];
if( img.src ) {
if( img.src.indexOf("/" + this.spriteName) > 0 ) {
this.ImageRef = img;
if( img.width == 64 ) {
this.frameCount = 1;
}
if( img.width == 32 ) {
this.frameCount = 0;
}
}
}
}
}
if( this.ImageRef != null ) {
if( this.bHidden == false ) {
ctx.drawImage(this.ImageRef, this.drawStartX, this.drawStartY, 32,
32, this.X-5, this.Y, 32, 32 );
if( parseInt(this.quest) > 0 ) {
ctx.drawImage(resourceByKey("battleicon"), this.X+2,
this.Y-14);
}
}
}
}
this.initWithData = function(data) // Define Method
{
this.processConditions();
this.evaluate();
}
this.initAsPlayer = function(position) // Define Method
{
this.bIsUser = true;
this.bEventEnabled = true;
this.spriteName = userSprite;
this.direction = 1;
this.mapPosition.X = position.X;
this.mapPosition.Y = position.Y;
this.evaluate();
}
this.processConditions = function() // Define Method
{
this.bEventEnabled = true;
}
this.addMoveQueue = function(moveDirection) // Define Method
{
this.moveQueue.push(moveDirection.toLowerCase());
}
/*
THESE NEED TO BE CODED TO HAPPEN WHEN THEY HIT THE TOP
OF THE QUEUE #####
} else if( moveDirection.ToLower() == "jump" ) {
bJumping = true;
jumpYAcc = -8;
bAllow = true;
} else if( moveDirection.ToLower() == "face up" ) {
direction = 0;
} else if( moveDirection.ToLower() == "face down" ) {
direction = 1;
} else if( moveDirection.ToLower() == "face left" ) {
direction = 2;
} else if( moveDirection.ToLower() == "face right" ) {
direction = 3;
} else if( moveDirection.ToLower() == "hide" ) {
sprite.Alpha = 0;
bHidden = true;
} else if( moveDirection.ToLower() == "show" ) {
sprite.Alpha = 1;
bHidden = false;
}
*/
this.evaluate = function() // Define Method
{
if( this.bEventEnabled == false ) {
return;
}
if( currentMap == null ) {
return;
}
if( this.bIsUser == false && this.bHidden == false ) {
this.processNPCMovement();
}
this.processMoveQueue();
this.updatePosition();
if( this.msg != "" ) {
this.msgTick++;
if( this.msgTick > 250 ) {
this.msg = "";
}
}
}
this.processNPCMovement = function() // Define Method
{
if( this.moveQueue.length == 0 && activeScript.length == 0 &&
bInBattle == false) {
if( this.moveType == "Slow Random" || this.moveType == "Fast
Random" ) {
//Random Movement
if( Math.floor(Math.random() * 10) == 1 ) {
var randDirection = Math.floor(Math.random() * 4);
if( randDirection == 0 ) {
if( currentMap.tileIsWalkable( Point(this.mapPosition.X,this.mapPosition.Y-2-
1)) ) {
this.addMoveQueue("up");
}
} else if( randDirection == 1 ) {
if( currentMap.tileIsWalkable( Point(this.mapPosition.X,this.mapPosition.Y-2+1))
) {
this.addMoveQueue("down");
}
} else if( randDirection == 2 ) {
if( currentMap.tileIsWalkable( Point(this.mapPosition.X-1,this.mapPosition.Y-
2)) ) {
this.addMoveQueue("left");
}
} else {
if( currentMap.tileIsWalkable( Point(this.mapPosition.X+1,this.mapPosition.Y-2))
) {
this.addMoveQueue("right");
}
}
}
} else if( this.moveType == "Follow User" ) {
var xDif = userEvent.mapPosition.X - this.mapPosition.X;
var yDif = userEvent.mapPosition.Y + 2 - this.mapPosition.Y;
steps = 0;
var dir = "";
if( userEvent.moveQueue.length != 0 ) {
if( xDif != 0 ) {
if( xDif < 0 ) {
dir = "left";
steps = -xDif-2;
} else {
dir = "right";
steps = xDif+2;
}
}
if( yDif != 0 ) {
if( yDif < 0 ) {
dir = "up";
steps = -yDif;
} else {
dir = "down";
steps = yDif;
}
}
if( dir != "" ) {
this.addMoveQueue(dir);
}
}
}
}
}
this.processMoveQueue = function() // Define Method
{
if( currentMap == null ) {
return false;
}
var bPassedCheck = false;
if( !this.bIsUser ) {
bPassedCheck = true;
if( this.moveQueue.length > 0 ) {
if( this.moveQueue[0].toLowerCase() == "face up" ) {
this.direction = 0;
this.moveQueue.splice(0,1);
} else if( this.moveQueue[0].toLowerCase() == "face down" ) {
this.direction = 1;
this.moveQueue.splice(0,1);
} else if( this.moveQueue[0].toLowerCase() == "face left" ) {
this.direction = 2;
this.moveQueue.splice(0,1);
} else if( this.moveQueue[0].toLowerCase() == "face right" ) {
this.direction = 3;
this.moveQueue.splice(0,1);
} else if( this.moveQueue[0].toLowerCase() == "hide" ) {
this.bHidden = true;
this.moveQueue.splice(0,1);
} else if( this.moveQueue[0].toLowerCase() == "show" ) {
this.bHidden = false;
this.moveQueue.splice(0,1);
}
}
} else {
while( bPassedCheck == false ) {
if( this.moveQueue.length > 0 ) {
if( this.moveQueue[0] == "up" ) {
if( !
currentMap.tileIsWalkable( Point(this.mapPosition.X,this.mapPosition.Y-1)) ) {
this.moveQueue.splice(0,1);
this.direction = 0;
} else {
bPassedCheck = true;
}
} else if( this.moveQueue[0] == "down" ) {
if( !
currentMap.tileIsWalkable( Point(this.mapPosition.X,this.mapPosition.Y+1)) ) {
this.moveQueue.splice(0,1);
this.direction = 1;
} else {
bPassedCheck = true;
}
} else if( this.moveQueue[0] == "left" ) {
if( !
currentMap.tileIsWalkable( Point(this.mapPosition.X-1,this.mapPosition.Y)) ) {
this.moveQueue.splice(0,1);
this.direction = 2;
} else {
bPassedCheck = true;
}
} else if( this.moveQueue[0] == "right" ) {
if( !
currentMap.tileIsWalkable( Point(this.mapPosition.X+1,this.mapPosition.Y)) ) {
this.moveQueue.splice(0,1);
this.direction = 3;
} else {
bPassedCheck = true;
}
} else if( this.moveQueue[0] == "jump" ) {
bPassedCheck = true;
} else if( this.moveQueue[0].toLowerCase() == "face up" ) {
this.direction = 0;
this.moveQueue.splice(0,1);
} else if( this.moveQueue[0].toLowerCase() == "face down"
) {
this.direction = 1;
this.moveQueue.splice(0,1);
} else if( this.moveQueue[0].toLowerCase() == "face left" )
{
this.direction = 2;
this.moveQueue.splice(0,1);
} else if( this.moveQueue[0].toLowerCase() == "face
right" ) {
this.direction = 3;
this.moveQueue.splice(0,1);
} else if( this.moveQueue[0].toLowerCase() == "hide" ) {
this.bHidden = true;
this.moveQueue.splice(0,1);
} else if( this.moveQueue[0].toLowerCase() == "show" ) {
this.bHidden = false;
this.moveQueue.splice(0,1);
} else {
bPassedCheck = true;
}
} else {
bPassedCheck = true;
}
if( bPassedCheck == false ) {
//this.moveQueue.splice(0, 1);
}
}
}
if( this.moveQueue.length > 0 ) {
if( this.moveQueue[0].toLowerCase() == "up" ) {
this.direction = 0;
} else if( this.moveQueue[0].toLowerCase() == "down" ) {
this.direction = 1;
} else if( this.moveQueue[0].toLowerCase() == "left" ) {
this.direction = 2;
} else if( this.moveQueue[0].toLowerCase() == "right" ) {
this.direction = 3;
} else if( this.moveQueue[0].toLowerCase() == "jump" ) {
this.jumpYAcc = this.jumpYAcc + 2;
this.jumpYAdd = this.jumpYAdd + this.jumpYAcc;
if( this.jumpYAcc == 4 ) {
this.jumpYAcc = 0;
this.jumpYAdd = 0;
this.bJumping = false;
this.moveQueue.splice(0,1);
}
return;
}
if( this.stepPart == 8 || this.stepPart == 0 ) {
this.stepAnimation++;
if( this.stepAnimation > this.frameCount )
this.stepAnimation = 0;
}
this.stepPart = this.stepPart + 4;
if( this.moveType == "Slow Random" )
this.stepPart = this.stepPart - 2;
if( keyState.btn2 && this.moveQueue.length == 1 && (this.bIsUser
|| this.id==-1))
this.stepPart = this.stepPart + 4;
if( this.stepPart >= 16 ) {
this.stepPart = 0;
//update the coordanates at the end of the step.
if( this.moveQueue[0] == "up" ) {
this.mapPosition.Y = this.mapPosition.Y - 1;
} else if( this.moveQueue[0] == "down" ) {
this.mapPosition.Y = this.mapPosition.Y + 1;
} else if( this.moveQueue[0] == "left" ) {
this.mapPosition.X = this.mapPosition.X - 1;
} else {
this.mapPosition.X = this.mapPosition.X + 1;
}
if( this.bIsUser ) {
if( activeScript.length == 0 ) {
if( this.eventCheck() == true ) {
this.arrivedOnTile();
}
}
}
this.moveQueue.splice(0,1);
}
}
}
this.eventCheck = function() // Define Method
{
for(var i=0;i<currentMap.events.length;i++) {
var evnt = currentMap.events[i];
if( evnt.mapPosition.X == userEvent.mapPosition.X &&
evnt.mapPosition.Y == userEvent.mapPosition.Y + 2 ) {
if (evnt.type == "On Walk" && evnt.bEventEnabled &&
activeScript.length == 0 && evnt.eventData.length > 0)
{
if( triggerEvent( evnt , false) ) {
return false;
}
}
}
//type
if( evnt.bEventEnabled && (evnt.type == "X1" || evnt.type == "X2" ||
evnt.type == "X3" || evnt.type == "X10" || evnt.type == "X15") &&
activeScript.length == 0 && evnt.eventData.length > 0 ) {
var stepsCheck = 1;
if( evnt.type == "X2" )
stepsCheck = 2;
if( evnt.type == "X3" )
stepsCheck = 3;
if( evnt.type == "X10" )
stepsCheck = 10;
if( evnt.type == "X15" )
stepsCheck = 15;
for(var check = 1;check <= stepsCheck;check++) {
if( evnt.mapPosition.X+check == userEvent.mapPosition.X &&
evnt.mapPosition.Y == userEvent.mapPosition.Y + 2 && evnt.direction == 3 ) {
if( triggerEvent( evnt , true) ) {
return false;
}
}
if( evnt.mapPosition.X-check == userEvent.mapPosition.X &&
evnt.mapPosition.Y == userEvent.mapPosition.Y + 2 && evnt.direction == 2 ) {
if( triggerEvent( evnt , true) ) {
return false;
}
}
if( evnt.mapPosition.X == userEvent.mapPosition.X &&
evnt.mapPosition.Y+check == userEvent.mapPosition.Y + 2 && evnt.direction == 1 )
{
if( triggerEvent( evnt , true) ) {
return false;
}
}
if( evnt.mapPosition.X == userEvent.mapPosition.X &&
evnt.mapPosition.Y-check == userEvent.mapPosition.Y + 2 && evnt.direction == 0 )
{
if( triggerEvent( evnt , true) ) {
return false;
}
}
}
}
}
return true;
}
this.arrivedOnTile = function() // Define Method
{
if( this.mapPosition.X == -1 ) {
if( firstChildNodeNamed("west", mapEvents) != null ) {
loadMap(nodeValue(firstChildNodeNamed("west",
mapEvents)), "wrap", 2)
return;
}
}
if( this.mapPosition.X+2 == Math.floor(mapWidth/16) ) {
if( firstChildNodeNamed("east", mapEvents) != null ) {
loadMap(nodeValue(firstChildNodeNamed("east", mapEvents)),
"wrap", 3)
return;
}
}
if( this.mapPosition.Y+2 == Math.floor(mapHeight/16) ) {
if( firstChildNodeNamed("south", mapEvents) != null ) {
loadMap(nodeValue(firstChildNodeNamed("south",
mapEvents)), "wrap", 1)
return;
}
}
if( this.mapPosition.Y == -1 ) {
if( firstChildNodeNamed("north", mapEvents) != null ) {
loadMap(nodeValue(firstChildNodeNamed("north",
mapEvents)), "wrap", 0)
return;
}
}
if( this.isInGrass() ) {
stepsInGrass++;
} else {
}
if( stepsInGrass > 8 ) {
if( parseInt(Math.random()*4) == 2 ) {
//TODO: START A BATTLE!!!
battleMonsterAtCoord();
stepsInGrass=0;
}
}
if( activeScript.length == 0 ) {
if( parseInt(Math.random()*15) == 2 ) {
if( eggs.length > 0 ) {
for(var i=0;i<eggs.length;i++) {
if( eggs[i].steps > 45 ) {
hatchingEgg = true;
loadUtility("action=hatch");
break;
}
}
}
}
}
}
this.isInGrass = function() // Define Method
{
for(var i=0;i<currentMap.grassPatches.length;i++) {
var patch = currentMap.grassPatches[i];
if( this.mapPosition.X >= patch.X1 && this.mapPosition.X <=
patch.X2-2 ) {
if( this.mapPosition.Y+2 >= patch.Y1 && this.mapPosition.Y+2
<= patch.Y2 ) {
return true;
}
}
}
return false;
}
this.updatePosition = function() // Define Method
{
var ySink = 0;
this.stepX = 0;
this.stepY = 0;
this.offsetX = 0;
this.offsetY = 0;
var MyX = this.mapPosition.X * 16;
var MyY = this.mapPosition.Y * 16;
if( currentMap == null ) {
return;
}
if( this.bIsUser == false ) {
//NPC EVENT POSITIONING
if( this.moveQueue.length > 0 ) {
if( this.moveQueue[0] == "up" ) {
this.stepY = -this.stepPart;
} else if( this.moveQueue[0] == "down" ) {
this.stepY = this.stepPart;
} else if( this.moveQueue[0] == "left" ) {
this.stepX = -this.stepPart;
} else {
this.stepX = this.stepPart;
}
}
var additionalDown = currentMap.mapHeight/2-cvsHeight/2;
this.X = mapLeft + MyX + this.stepX+13;
//this.Y = -mapTop-currentMap.mapHeight/2 + MyY + this.stepY -
Math.floor(this.jumpYAdd)+2-130+32;
this.Y = -mapTop-cvsHeight/2-currentMap.mapHeight/2 + MyY +
this.stepY - Math.floor(this.jumpYAdd)+2+28 + (additionalDown-192);
} else {
//USER EVENT POSITIONING
if( this.moveQueue.length > 0 ) {
if( this.moveQueue[0] == "left" ) {
if( MyX <= cvsWidth/2 || MyX > currentMap.mapWidth -
cvsWidth/2 ) {
this.stepX = -this.stepPart;
}
} else if( this.moveQueue[0] == "right" ) {
if( MyX < cvsWidth/2 || MyX >= currentMap.mapWidth -
cvsWidth/2 ) {
this.stepX = this.stepPart;
}
}
}
if( MyY <= cvsHeight/2 || MyY >= currentMap.mapHeight -
cvsHeight/2 ) {
if( this.moveQueue.length > 0 ) {
if( this.moveQueue[0] == "up" ) {
this.stepY = -this.stepPart;
} else if( this.moveQueue[0] == "down" ) {
this.stepY = this.stepPart;
}
}
}
if( this.moveQueue.length > 0 ) {
if( this.moveQueue[0] == "right" ) {
if( MyX+this.stepX >= currentMap.mapWidth -
cvsWidth/2 ) {
this.offsetX = cvsWidth/2 + ( currentMap.mapWidth -
MyX-this.stepX ) * -1;
}
} else {
if( MyX-this.stepX > currentMap.mapWidth - cvsWidth/2 )
{
this.offsetX = cvsWidth/2 + ( currentMap.mapWidth -
MyX-this.stepX ) * -1;
}
}
} else {
if( MyX-this.stepX > currentMap.mapWidth - cvsWidth/2 ) {
this.offsetX = cvsWidth/2 + ( currentMap.mapWidth - MyX-
this.stepX ) * -1;
}
}
if( this.moveQueue.length > 0 ) {
if( this.moveQueue[0] == "left" ) {
if( MyX+this.stepX <= cvsWidth/2 ) {
this.offsetX = (cvsWidth/2-MyX-this.stepX)*-1;
}
} else {
if( MyX-this.stepX < cvsWidth/2 ) {
this.offsetX = (cvsWidth/2-MyX-this.stepX)*-1;
}
}
} else {
if( MyX-this.stepX < cvsWidth/2 ) {
this.offsetX = (cvsWidth/2-MyX-this.stepX)*-1;
}
}
if( MyY+this.stepY > currentMap.mapHeight - cvsHeight/2 ) {
this.offsetY = cvsHeight/2 + (currentMap.mapHeight - MyY-
this.stepY ) * -1;
}
if( MyY+this.stepY < cvsHeight/2 ) {
this.offsetY = (cvsHeight/2-MyY-this.stepY)*-1;
}
var half = (cvsWidth - currentMap.mapWidth);
if( half < 0 )
half = 0;
this.X = half+cvsWidth/2 + this.offsetX+13;
this.Y = cvsHeight/2 + this.offsetY - ySink -
Math.floor(this.jumpYAdd);
}
this.updateTextureCoords();
}
this.updateTextureCoords = function() // Define Method
{
var startX = 0;
var startY = 0;
if( this.direction == 0 ) {
switch(this.stepAnimation) {
case 0 :
startX = 0;
startY = 0;
break;
case 1 :
startX = 1;
startY = 0;
break;
case 2 :
startX = 2;
startY = 0;
break;
}
} else if( this.direction == 1 ) {
switch(this.stepAnimation) {
case 0 :
startX = 0;
startY = 1;
break;
case 1 :
startX = 1;
startY = 1;
break;
case 2 :
startX = 2;
startY = 1;
break;
}
} else if( this.direction == 2 ) {
switch(this.stepAnimation) {
case 0 :
startX = 0;
startY = 2;
break;
case 1 :
startX = 1;
startY = 2;
break;
case 2 :
startX = 2;
startY = 2;
break;
}
} else {
switch(this.stepAnimation) {
case 0 :
startX = 0;
startY = 3;
break;
case 1 :
startX = 1;
startY = 3;
break;
case 2 :
startX = 2;
startY = 3;
break;
}
}
this.drawStartX = startX*32;
this.drawStartY = startY*32;
}
return this;
}
// ################################################
// ### MAP CLASS ###########################
// ################################################
function Region(x1,y1,x2,y2) {
this.X1 = x1;
this.Y1 = y1;
this.X2 = x2;
this.Y2 = y2;
return this;
}
// ################################################
// ### GAME MAP CLASS #############################
// ################################################
function gameMap()
{
this.mapCollisionData = null;
this.mapWidth = 0;
this.mapHeight = 0;
this.mapMusic = '';
this.tileSize = 16;
this.grassPatches = new Array();
this.events = new Array();
this.loadEvents = function(mapEvents) // Define Method
{
events = new Array();
var npcs = firstChildNodeNamed("npcs", mapEvents);
for(var k=0;k<npcs.childNodes.length;k++) {
var npc = npcs.childNodes[k];
events.push(new gameEvent(npc));
}
eggs = [];
var eggsNode = firstChildNodeNamed("eggs", mapEvents);
for(var k=0;k<eggsNode.childNodes.length;k++) {
var egg = eggsNode.childNodes[k];
eggs.push(new GameEgg(egg));
}
inventory = [];
var inv = firstChildNodeNamed("inventory", mapEvents);
for(var k=0;k<inv.childNodes.length;k++) {
var item = inv.childNodes[k];
inventory.push(new GameItem(item));
}
if( tagAlong != "" ) {
follower = new gameEvent();
events.push(follower);
follower.id = -1;
follower.name = tagAlong;
follower.mapPosition.X = userEvent.mapPosition.X;
follower.mapPosition.Y = userEvent.mapPosition.Y+2;
follower.type = "Action Button";
follower.spriteName = tagAlong + ".png";
follower.direction = userEvent.direction;
follower.moveType = "Follow User";
follower.bIsUser = false;
follower.bEventEnabled = true;
follower.eventData.push(new ScriptLine( 1, "Display Message"
,tagAlongName + "!"));
follower.eventData.push(new ScriptLine( 2, "MOVE EVENT" , "-
1^move to user^1"));
follower.eventData.push(new ScriptLine( 3, "SYNC ALL" , ""));
follower.eventData.push(new ScriptLine( 4, "MOVE EVENT" ,
"0^forward^1"));
}
}
this.getEvent = function(id)
{
for(var k=0;k<events.length;k++) {
if( events[k].id == id ) {
return events[k];
}
}
return null;
}
this.evaluateEvents = function() // Define Method
{
for(var k=0;k<events.length;k++) {
events[k].evaluate();
}
for(var k=0;k<mmoUsers.length;k++) {
mmoUsers[k].evaluate();
}
}
this.drawEvents = function(ctx,positionToDraw) // Define Method
{
for(var k=0;k<events.length;k++) {
if( positionToDraw == "above" ) {
if( events[k].mapPosition.Y > userEvent.mapPosition.Y+2 ) {
events[k].drawImage(ctx);
}
} else {
if( events[k].mapPosition.Y <= userEvent.mapPosition.Y+2 ) {
events[k].drawImage(ctx);
}
}
}
for(var k=0;k<mmoUsers.length;k++) {
if( positionToDraw == "above" ) {
if( mmoUsers[k].y > userEvent.mapPosition.Y ) {
mmoUsers[k].drawImage(ctx);
}
} else {
if( mmoUsers[k].y <= userEvent.mapPosition.Y ) {
mmoUsers[k].drawImage(ctx);
}
}
}
}
this.drawNames = function(ctx) // Define Method
{
for(var k=0;k<mmoUsers.length;k++) {
mmoUsers[k].drawNames(ctx);
}
if( userEvent.msg != "" ) {
ctx.font = "bold 11px sans-serif";
ctx.textAlign = "center";
drawShadowText(ctx,userEvent.msg, userEvent.X+12, userEvent.Y-
1,"#c4d52b");
} else {
ctx.font = "bold 11px sans-serif";
ctx.textAlign = "center";
drawShadowText(ctx,"You", userEvent.X+12, userEvent.Y-1);
}
}
this.load = function(mapData) // Define Method
{
this.tileSize = mapData.getAttribute("tilewidth");
this.mapWidth = mapData.getAttribute("width") * this.tileSize;
this.mapHeight = mapData.getAttribute("height") * this.tileSize;
var tileCount = (this.mapWidth / this.tileSize) * (this.mapHeight /
this.tileSize);
this.mapCollisionData = new Array(tileCount);
for(var i=0;i<mapData.childNodes.length;i++) {
var node = mapData.childNodes[i];
if( node.nodeName == "layer") {
if( node.getAttribute("name") == "Collision" ) {
var dataNode = firstChildNodeNamed("data",node);
var data = getDataOfImmediateChild(dataNode);
data = data.replace(/rn/i, '').trim();
rawMapData = stringToBytes(base64_decode(data));
//for (var k = 0; k < tileCount; k++)
// mapCollisionData[k] = getIntAt(rawData,k*4);
}
} else if( node.nodeName == "objectgroup") {
if( node.getAttribute("name").toLowerCase() == "grass" ) {
this.grassPatches = new Array();
for (var k = 0; k < node.childNodes.length; k++) {
var object = node.childNodes[k];
if( object.nodeName != "#text" ) {
var x1 =
parseInt(object.getAttribute("x"))/this.tileSize;
var y1 =
parseInt(object.getAttribute("y"))/this.tileSize;
var width =
parseInt(object.getAttribute("width"))/this.tileSize;
var height =
parseInt(object.getAttribute("height"))/this.tileSize;
var x2 = x1 + (width+1);
var y2 = y1 + (height+1);
this.grassPatches.push(new Region(x1,y1,x2,y2));
}
}
}
}
}
}
this.getTile = function( x, y)
{
var tilesWide = mapWidth / tileSize;
var pos = 0;
x++;
y++;
if( y * tilesWide + x >= 0 && y * tilesWide + x < mapCollisionData.length )
{
if( rawMapData ) {
pos = (y * tilesWide + x)*4;
if( rawMapData[pos] == 0 && rawMapData[pos+1] == 0 &&
rawMapData[pos+2] == 0 && rawMapData[pos+3] == 0 ) {
return 0;
}
return 1;
}
//return mapCollisionData[y * tilesWide + x];
}
return -1;
}
this.tileIsWalkable = function(position) // Define Method
{
if( position.X < -1 )
return false;
if( position.Y < -1 )
return false;
if( position.X > this.mapWidth/16 )
return false;
if( position.Y > this.mapHeight/16 )
return false;
if( this.tileIsFreeFromEvents(position) == false ) {
return false;
}
if( this.getTile(position.X,position.Y) == 0 ) {
return true;
}
return false;
}
this.tileIsFreeFromEvents = function(position) // Define Method
{
for(var k=0;k<events.length;k++) {
if( events[k].spriteName != "" && events[k].spriteName != null &&
events[k].bHidden == false && events[k].bEventEnabled == true ) {
if( events[k].mapPosition.X == position.X ) {
if( events[k].mapPosition.Y == position.Y+2 ) {
return false;
}
}
}
}
//TODO: Complete Event Collision Detection
return true;
}
return this;
}
function base64_decode (data) {
// Decodes string using MIME base64 algorithm
var b64 =
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789
+/=";
var o1, o2, o3, h1, h2, h3, h4, bits, i = 0,
ac = 0,
dec = "",
tmp_arr = [];
if (!data) {
return data;
}
data += '';
do { // unpack four hexets into three octets using index points in b64
h1 = b64.indexOf(data.charAt(i++));
h2 = b64.indexOf(data.charAt(i++));
h3 = b64.indexOf(data.charAt(i++));
h4 = b64.indexOf(data.charAt(i++));
bits = h1 << 18 | h2 << 12 | h3 << 6 | h4;
o1 = bits >> 16 & 0xff;
o2 = bits >> 8 & 0xff;
o3 = bits & 0xff;
if (h3 == 64) {
tmp_arr[ac++] = String.fromCharCode(o1);
} else if (h4 == 64) {
tmp_arr[ac++] = String.fromCharCode(o1, o2);
} else {
tmp_arr[ac++] = String.fromCharCode(o1, o2, o3);
}
} while (i < data.length);
dec = tmp_arr.join('');
//dec = this.utf8_decode(dec);
return dec;
}
String.prototype.trim = function() {
return this.replace(/^s+|s+$/g,"");
}
function stringToBytes ( str ) {
var ch, st, re = [];
for (var i = 0; i < str.length; i++ ) {
ch = str.charCodeAt(i); // get char
st = []; // set up "stack"
do {
st.push( ch & 0xFF ); // push byte to stack
ch = ch >> 8; // shift value down by 1 byte
}
while ( ch );
// add stack contents to result
// done because chars have "wrong" endianness
re = re.concat( st.reverse() );
}
// return an array of bytes
return re;
}
function getIntAt ( arr, offs ) {
if( arr[offs+0] == 0 && arr[offs+1] == 0 && arr[offs+2] == 0 && arr[offs+3] ==
0 ) {
return 0;
}
return 1;
return (arr[offs+0] << 24) +
(arr[offs+1] << 16) +
(arr[offs+2] << 8) +
arr[offs+3];
}
// ################################################
// ### BATTLE CLASS ###########################
// ################################################
//Battle Variables
var bInBattle = false;
var battleStage = 0;
var battleTaskQueue = new Array();
var teamMonsters = new Array();
var opponentMonsters = new Array();
var monSkills = new Array();
var battleItems = new Array();
var doingCaptcha = false;
var captchaImages = new Array();
var captchaKeys = new Array();
var curMon = null;
var curOpp = null;
var nextMon = null;
var nextOpp = null;
var battleScript = new Array();
var battleSelectedMenu = 0;
var battleItemSelectedMenu = 0;
var battleSwappedMonsters = false;
var battleTick1 = 0;
var battleTick2 = 0;
var battleTick3 = 0;
var battleLoading = false;
var loadExplore = false;
var drawMons = true;
var drawMyHp = true;
var drawOpHp = true;
var bWildBattle = false;
function addToCaptcha(letter) {
if( doingCaptcha ) {
if( captchaKeypress[parseInt(letter)-1]== false ) {
captchaKeys.push(letter);
if( captchaKeys.length == 3 ) {
$str = captchaKeys[0] + captchaKeys[1] + captchaKeys[2];
loadBattle("captcha=" + $str);
}
captchaKeypress[parseInt(letter)-1] = true;
}
}
}
function MonsterSkill(id,name) {
this.id = id;
this.name = name;
}
function BattleItem(id,name,file,qty) {
this.id = id;
this.name = name;
this.file = file;
this.qty = qty;
}
function
BattleMonsterLineup(id,name,level,special,specialName,gender,hpleft,hp,image,type1
,type2,reborn) {
this.id = id;
this.name = name;
this.level = level;
this.special = special;
this.specialName = specialName;
this.gender = gender;
this.hpleft = parseInt(hpleft);
this.hp = parseInt(hp);
this.image = image;
this.type1 = type1;
this.type2 = type2;
this.reborn = reborn;
return this;
}
function showMonsterAtCoord() {
if( !battleLoading ) {
bIsLoadingWildDialog = true;
var form = document.getElementById('mws-explore-encounter');
form.innerHTML = "<center><img
src='http://cache.pokemonlegends.com/images/preloader.gif'
tag='loading'/><br/>Loading</center>";
loadBattle("x="+userEvent.mapPosition.X+"&y="+userEvent.mapPosition.Y+"&actio
n=encounter");
}
}
function showMonsterAtCoordCallback() {
var form = document.getElementById('mws-explore-encounter');
if( curOpp != null ) {
//mws-jui-dialog-monster
var gender = " Male ";
if( curOpp.gender != "M" )
gender = " Female ";
var level = curOpp.level;
var specialName = curOpp.specialName;
if( specialName != "" )
specialName = specialName + " ";
bWildBattleIsReady = true;
form.innerHTML = "<center><img src='"+curOpp.image+"' style='padding-
top:10px;'/><div style='padding-left: 8px;padding-right: 8px;'>You have encountered
a level "+level+gender+specialName+curOpp.name+". </div><input type='button'
id='btnBattle' onclick='battleWildSelected();' class='mws-button red' value='Battle'
style='margin-bottom:5px;'/></center>";
} else {
form.innerHTML = "";
}
bIsLoadingWildDialog = false;
}
function battleMonsterAtCoord() {
battleScript = new Array();
playSFX("MonAppear");
showMonsterAtCoord() ;
return;
//bInBattle = true; - this is set in the above script funciton
}
function battleWildSelected() {
battleSelectedMenu = 2;
playSFX("battle");
playMusic("battle1");
if( prevPlayingSong ) {
try
{
prevPlayingSong.currentTime = 0;
}
catch(err)
{
}
}
battleLoading = false;
bWildBattle = true;
bInBattle = true;
wipeWildMonsterBox();
}
function battleWithTrainer() {
curOpp = null;
scriptAddLine("battlescreen","TRAINER");
//bInBattle = true; - this is set in the above script funciton
battleSelectedMenu = 2;
playSFX("battle");
playMusic("battle1");
curOpp = null;
nextOpp = null;
curMon = null;
nextMon = null;
curMonImage.src = 'http://cache.pokemonlegends.com/images/blank.png';
curOppImage.src = 'http://cache.pokemonlegends.com/images/blank.png';
if( prevPlayingSong )
prevPlayingSong.currentTime = 0;
bWildBattle = false;
wipeWildMonsterBox();
}
function wipeWildMonsterBox() {
bWildBattleIsReady = false;
var form = document.getElementById('mws-explore-encounter');
if( form ) {
form.innerHTML = "";
}
}
function battleScriptEndLine() {
battleScript.splice(0, 1);
battleScriptStartLine();
drawMons = true;
drawOpHp = true;
drawMyHp = true;
}
function battleScriptStartLine() {
battleTick1 = 0;
battleTick2 = 0;
battleTick3 = 0;
if( !bInBattle )
return;
var centerX = cvsWidth/2;
var centerY = cvsHeight/2;
if( battleScript.length > 0 ) {
var data = battleScript[0].split("|");
//battleSelectedMenu = 2;
if( data[0] == "MSG" ) {
drawMons = true;
drawOpHp = true;
drawMyHp = true;
repositionMonsters();
curMonImage.style.display = 'block';
curOppImage.style.display = 'block';
} else if( data[0] == "ATTACK" ) {
drawMons = true;
drawOpHp = true;
drawMyHp = true;
playSFX("hit");
} else if( data[0] == "MUTATE" ) {
drawMons = false;
drawOpHp = false;
drawMyHp = false;
var args = data[1].split("-");
//load required images: Monster Image
var img = resourceByKey(args[1]);
if( img == null )
screenResources.push(new ResourceImage(args[1],args[1]));
//load required images: Arrow Image
img = resourceByKey("resultset_next.png");
if( img == null )
screenResources.push(new
ResourceImage("http://cache.pokemonlegends.com/css/icons/32/resultset_next.png","r
esultset_next.png"));
} else if( data[0] == "HPCHANGE" ) {
battleTick3 = parseInt(data[2]) / 10;
} else if( data[0] == "DEFEAT" ) {
if( (parseInt(data[1]) < 6 && !battlePlayerAwayTeam) ||
(parseInt(data[1]) >= 6 && battlePlayerAwayTeam) ) {
battleSelectedMenu = 7;
curMon.hpleft = 0;
curMonImage.src =
'http://cache.pokemonlegends.com/images/blank.png';
} else {
curOpp.hpleft = 0;
curOpp = nextOpp;
curOppImage.src =
'http://cache.pokemonlegends.com/images/blank.png';
}
} else if( data[0] == "SWAP" ) {
var monImage = null;
if( (parseInt(data[1]) < 6 && !battlePlayerAwayTeam) ||
(parseInt(data[1]) >= 6 && battlePlayerAwayTeam) ) {
if( nextMon != null ) {
curMon = nextMon;
}
//sharks
if (data[2] == null)
data[2] = 0;
//end
if( curMon != null ) {
curMon.hpleft = parseInt(data[2]);
curMonImage.src = curMon.image;
curMonImage.style.display = 'block';
}
repositionMonsters();
} else if( (parseInt(data[1]) < 6 && battlePlayerAwayTeam) ||
(parseInt(data[1]) >= 6 && !battlePlayerAwayTeam) ) {
if( nextOpp != null ) {
curOpp = nextOpp;
}
curOpp.hpleft = parseInt(data[2]);
curOppImage.src = curOpp.image;
curOppImage.style.display = 'block';
repositionMonsters();
}
battleScriptEndLine();
} else if( data[0] == "SFX" ) {
playSFX(data[1]);
battleScriptEndLine();
} else if( data[0] == "LEVELUP" ) {
playSFX("levelup");
battleScriptEndLine();
} else if( data[0] == "CLIENT SCRIPT" ) {
scriptAddLine(data[1],data[2]);
battleScriptEndLine();
} else if( data[0] == "SCRIPT" ) {
if( data[1] != "" ) {
scriptAddLine("server side",data[1]);
}
battleScriptEndLine();
battleEnd();
}
} else { //
if( !battleLoading ) {
if( parseInt(battleStage) == 3 || parseInt(battleStage) == 4 ) {
battleEnd();
if( parseInt(battleStage) == 4 ) {
userFaint();
} else {
//if( !bWildBattle ) {
playMusicOnce("victory");
//}
}
} else if( parseInt(battleStage) == 5 || parseInt(battleStage) == 6 ) {
battleEnd();
if( battlePlayerAwayTeam ) {
if( parseInt(battleStage) == 6 ) {
playMusicOnce("victory");
} else {
userFaint();
}
} else {
if( parseInt(battleStage) == 5 ) {
playMusicOnce("victory");
} else {
userFaint();
}
}
}
}
}
}
function battleEnd() {
bInBattle=false;
battleSelectedMenu = 0;
battleScript = new Array();
teamMonsters = new Array();
opponentMonsters = new Array();
curMon = null;
curOpp = null;
curOppImage.style.display = 'none';
curMonImage.style.display = 'none';
playMusic(currentMap.mapMusic);
}
function battleScriptDraw() {
var centerX = cvsWidth/2;
var centerY = cvsHeight/2;
if( battleScript.length > 0 ) {
var data = battleScript[0].split("|");
if( data[0] == "MSG" ) {
battleTick1++;
if( battleTick1 > 1 ) {
battleTick2++;
battleTick1=0;
}
if( (keyState.btn1 || keyState.btn2) && battleTick2 > data[1].length ) {
battleScriptEndLine();
keyState.btn1 = false;
keyState.btn2 = false;
playSFX("beep");
} else if( keyState.btn1 || keyState.btn2 ) {
battleTick2 = data[1].length;
keyState.btn1 = false;
keyState.btn2 = false;
playSFX("beep");
}
//ctx.textAlign = "left";
//ctx.font = "bold 9px sans-serif";
//drawShadowText(ctx,data[1].substr(0,battleTick2), centerX-
230,centerY+103);
ctx.textAlign = "left";
ctx.font = "bold 12px sans-serif";
var line1 = data[1];
var line2 = "";
if( line1.length > 32 ) {
var lastSpace = line1.lastIndexOf(" ", 32);
line2 = line1.substr(lastSpace+1,line1.length-lastSpace-1);
line1 = line1.substr(0,lastSpace);
}
if( battleTick2 <= line1.length ) {
drawShadowText(ctx,line1.substr(0,battleTick2), centerX-
234,centerY+100);
} else {
drawShadowText(ctx,line1, centerX-234,centerY+100);
drawShadowText(ctx,line2.substr(0,battleTick2-line2.length),
centerX-234,centerY+ 116);
}
} else if( data[0] == "MUTATE" ) {
drawMons = false;
drawOpHp = false;
drawMyHp = false;
var args = data[1].split("-");
ctx.textAlign = "left";
ctx.font = "bold 12px sans-serif";
drawShadowText(ctx,"Let the Pokemon Evolve?", centerX-
234,centerY+100);
drawShadowText(ctx,"Press 'X' to confirm, 'Z' to cancel.", centerX-
234,centerY+ 116);
ctx.textAlign = "center";
ctx.font = "bold 14px sans-serif";
//Draw Monster
var mon = resourceByKey(curMon.image);
ctx.drawImage(mon, centerX-80-mon.width/2,centerY-mon.height/2);
drawShadowText(ctx,curMon.name, centerX-80,centerY+60);
//Draw Monster Evolution
mon = resourceByKey(args[1]);
ctx.drawImage(mon, centerX+80-mon.width/2,centerY-mon.height/2);
drawShadowText(ctx,"???", centerX+80,centerY+60);
//Draw Arrow
mon = resourceByKey("resultset_next.png");
ctx.drawImage(mon, centerX-mon.width/2-mon.width,centerY-
mon.height/2);
ctx.drawImage(mon, centerX-mon.width/2,centerY-mon.height/2);
ctx.drawImage(mon, centerX-mon.width/2+mon.width,centerY-
mon.height/2);
if( keyState.btn1 ) {
loadBattle("mutate=true");
keyState.btn1 = false;
battleScriptEndLine();
} else if( keyState.btn2 ) {
keyState.btn2 = false;
battleScriptEndLine();
}
//
//curMon
} else if( data[0] == "ATTACK" ) {
var img = resourceByKey("ani-"+data[4]);
battleTick1++;
if( img == null ) {
battleScriptEndLine();
} else {
if( (parseInt(data[2]) < 6 && !battlePlayerAwayTeam) ||
(parseInt(data[2]) >= 6 && battlePlayerAwayTeam) ) {
ctx.drawImage(img, battleTick2 ,0,80,80,centerX-120-
80/2,centerY-img.height/2+40,80,80);
} else {
ctx.drawImage(img, battleTick2 ,0,80,80,centerX+120-
80/2,centerY-img.height/2-40 ,80,80);
}
if( battleTick2 > img.width ) {
battleScriptEndLine();
}
}
battleTick2=battleTick2+80;
} else if( data[0] == "DEFEAT" ) {
battleScriptEndLine();
} else if( data[0] == "HPCHANGE" ) {
battleTick1++;
if( battleTick1 < 10 ) {
if( (parseInt(data[1]) < 6 && !battlePlayerAwayTeam) ||
(parseInt(data[1]) >= 6 && battlePlayerAwayTeam) ) {
curMon.hpleft = curMon.hpleft - battleTick3;
} else {
curOpp.hpleft = curOpp.hpleft - battleTick3;
}
} else {
if( (parseInt(data[1]) < 6 && !battlePlayerAwayTeam) ||
(parseInt(data[1]) >= 6 && battlePlayerAwayTeam) ) {
curMon.hpleft = parseInt(data[3]);
} else {
curOpp.hpleft = parseInt(data[3]);
}
battleScriptEndLine();
}
} else if( data[0] == "BATTLEEND" ) {
battleEnd();
}
}
}
function battleUpdate() {
//If nothings happening and everything has loaded check for input.
if( battleScript.length == 0 && ImageResourceLoadedCount ==
screenResources.length && !battleLoading ) {
//0 == Run
//1 == Item
//2-5 == Attacks
//6 == Swap
if( doingCaptcha )
return;
var bChangedSomething = false;
//Collect Keyboard Input.
if( keyState.up ) {
playSFX("beep");
if( battleSelectedMenu < 4 ) {
battleSelectedMenu = 6;
} else if( battleSelectedMenu == 4 || battleSelectedMenu == 5 ) {
battleSelectedMenu = battleSelectedMenu - 2;
} else if( battleSelectedMenu == 13 ) {
battleItemSelectedMenu = battleItemSelectedMenu - 1;
if( battleItemSelectedMenu < 0 )
battleItemSelectedMenu=0;
} else if( battleSelectedMenu > 6 && battleSelectedMenu <= 12 ) {
battleSelectedMenu--;
if( battleSelectedMenu < 7 )
battleSelectedMenu = 7;
}
keyState.up = false;
bChangedSomething=true;
} else if( keyState.right ) {
playSFX("beep");
if( battleSelectedMenu > 6 && battleSelectedMenu <= 12 ) {
if( battleSelectedMenu < 10 ) {
battleSelectedMenu = battleSelectedMenu+3;
if( battleSelectedMenu-7 > teamMonsters.length )
battleSelectedMenu = teamMonsters.length + 6;
}
} else if( battleSelectedMenu == 13 ) {
battleItemSelectedMenu = battleItemSelectedMenu + 4;
if( battleItemSelectedMenu >= battleItems.length )
battleItemSelectedMenu = battleItems.length-1;
} else if( battleSelectedMenu != 3 ) {
battleSelectedMenu++;
if( battleSelectedMenu > 5 )
battleSelectedMenu = 5;
}
keyState.right = false;
bChangedSomething=true;
} else if( keyState.left ) {
playSFX("beep");
if( battleSelectedMenu == 4 ) {
battleSelectedMenu = 1;
} else if( battleSelectedMenu > 6 && battleSelectedMenu <= 12 ) {
if( battleSelectedMenu >= 10 ) {
battleSelectedMenu = battleSelectedMenu-3;
}
} else if( battleSelectedMenu == 13 ) {
battleItemSelectedMenu = battleItemSelectedMenu - 4;
if( battleItemSelectedMenu < 0 )
battleItemSelectedMenu=0;
} else {
battleSelectedMenu--;
if( battleSelectedMenu < 0 )
battleSelectedMenu = 0;
}
keyState.left = false;
bChangedSomething=true;
} else if( keyState.down ) {
playSFX("beep");
if( battleSelectedMenu == 6 ) {
battleSelectedMenu = 0;
} else if( battleSelectedMenu == 2 || battleSelectedMenu == 3 ) {
battleSelectedMenu=battleSelectedMenu+2;
} else if( battleSelectedMenu == 13 ) {
battleItemSelectedMenu = battleItemSelectedMenu + 1;
if( battleItemSelectedMenu >= battleItems.length )
battleItemSelectedMenu = battleItems.length-1;
} else if( battleSelectedMenu > 6 && battleSelectedMenu <= 12 ) {
battleSelectedMenu++;
if( battleSelectedMenu-6 > teamMonsters.length )
battleSelectedMenu = teamMonsters.length + 6;
}
keyState.down = false;
bChangedSomething=true;
} else if( keyState.btn1 ) {
playSFX("beep");
if( battleSelectedMenu == 0 ) {
//bInBattle
if( bWildBattle ) {
battleScript.push("MSG|You ran away from the battle.");
battleScript.push("BATTLEEND|");
} else {
battleScript.push("MSG|You can not run from a trainer battle.");
}
} else if( battleSelectedMenu > 1 && battleSelectedMenu < 6 ) {
//Attacks
var skill = monSkills[battleSelectedMenu-2];
loadBattle("selatk=" + skill.id);
} else if( battleSelectedMenu == 6 ) { //Swap
battleSelectedMenu = 7;
} else if( battleSelectedMenu > 6 && battleSelectedMenu <= 12 ) {
battleSwappedMonsters = true;
if( teamMonsters.length > battleSelectedMenu-7 ) {
if( teamMonsters[battleSelectedMenu-7].hpleft > 0 ) {
loadBattle("selmon=" + teamMonsters[battleSelectedMenu-
7].id);
}
}
} else if( battleSelectedMenu == 13) {
loadBattle("selitem=" + battleItems[battleItemSelectedMenu].id);
} else if( battleSelectedMenu == 1 ) {
//Enter the Item Menu
battleSelectedMenu = 13;
}
keyState.btn1 = false;
bChangedSomething=true;
} else if( keyState.btn2 ) {
playSFX("beep");
if( battleSelectedMenu > 6 && battleSelectedMenu <= 12 ) {
if( battleStage != 1 ) {
battleSelectedMenu = 6;
}
} else if( battleSelectedMenu == 13 ) {
battleSelectedMenu = 1;
}
keyState.btn2 = false;
bChangedSomething=true;
}
if( bChangedSomething ) {
battleUpdatedMenu();
}
} else {
}
}
KODE JS POKENNNNN
KODE JS POKENNNNN
KODE JS POKENNNNN
KODE JS POKENNNNN
KODE JS POKENNNNN
KODE JS POKENNNNN
KODE JS POKENNNNN
KODE JS POKENNNNN
KODE JS POKENNNNN
KODE JS POKENNNNN
KODE JS POKENNNNN
KODE JS POKENNNNN
KODE JS POKENNNNN
KODE JS POKENNNNN
KODE JS POKENNNNN
KODE JS POKENNNNN
KODE JS POKENNNNN
KODE JS POKENNNNN
KODE JS POKENNNNN
KODE JS POKENNNNN
KODE JS POKENNNNN
KODE JS POKENNNNN
KODE JS POKENNNNN
KODE JS POKENNNNN
KODE JS POKENNNNN
KODE JS POKENNNNN
KODE JS POKENNNNN
KODE JS POKENNNNN
KODE JS POKENNNNN
KODE JS POKENNNNN
KODE JS POKENNNNN
KODE JS POKENNNNN
KODE JS POKENNNNN

More Related Content

What's hot

Go Beast Mode with Realtime Reactive Interfaces in Angular 2 and Firebase
Go Beast Mode with Realtime Reactive Interfaces in Angular 2 and FirebaseGo Beast Mode with Realtime Reactive Interfaces in Angular 2 and Firebase
Go Beast Mode with Realtime Reactive Interfaces in Angular 2 and Firebase
Lukas Ruebbelke
 
Tinkerbelles return home from their Guinness world-record attempt on Sunday
Tinkerbelles return home from their Guinness world-record attempt on SundayTinkerbelles return home from their Guinness world-record attempt on Sunday
Tinkerbelles return home from their Guinness world-record attempt on Sunday
chicagonewsyesterday
 
The Pied Piper of Selenium
The Pied Piper of SeleniumThe Pied Piper of Selenium
The Pied Piper of Selenium
Michelle Macdonald
 
20/20 | Investigative Journalism & News Magazine
20/20 | Investigative Journalism & News Magazine20/20 | Investigative Journalism & News Magazine
20/20 | Investigative Journalism & News Magazine
demonicrhythm3717
 
Technology and Science News - ABC News
Technology and Science News - ABC NewsTechnology and Science News - ABC News
Technology and Science News - ABC News
racialgimmick716
 
Health News & Articles | Healthy Living
Health News & Articles | Healthy LivingHealth News & Articles | Healthy Living
Health News & Articles | Healthy Living
abortivecatcall84
 
Wii Ruby All Work And No Play Just Wont Do
Wii Ruby All Work And No Play Just Wont DoWii Ruby All Work And No Play Just Wont Do
Wii Ruby All Work And No Play Just Wont DoLittleBIGRuby
 
iOS. EventKit Framework. Work with calendars and reminders
iOS. EventKit Framework. Work with calendars and remindersiOS. EventKit Framework. Work with calendars and reminders
iOS. EventKit Framework. Work with calendars and remindersVoityuk Alexander
 
Technology and Science News - ABC News
Technology and Science News - ABC NewsTechnology and Science News - ABC News
Technology and Science News - ABC News
wonderfulshuttl70
 
Event handling using jQuery
Event handling using jQueryEvent handling using jQuery
Event handling using jQuery
Iban Martinez
 
What Would You Do? With John Quinones
What Would You Do? With John QuinonesWhat Would You Do? With John Quinones
What Would You Do? With John Quinones
wrathfulmedal3110
 
Technology and Science News - ABC News
Technology and Science News - ABC NewsTechnology and Science News - ABC News
Technology and Science News - ABC News
cafresno51
 
Technology and Science News - ABC News
Technology and Science News - ABC NewsTechnology and Science News - ABC News
Technology and Science News - ABC News
painstakingsled66
 
Special Events: Beyond Custom Events
Special Events: Beyond Custom EventsSpecial Events: Beyond Custom Events
Special Events: Beyond Custom EventsBrandon Aaron
 
Delivering a Responsive UI
Delivering a Responsive UIDelivering a Responsive UI
Delivering a Responsive UIRebecca Murphey
 
International News | World News
International News | World NewsInternational News | World News
International News | World News
agonizingspeed722
 
International News | World News
International News | World NewsInternational News | World News
International News | World News
whisperingwhiz946
 

What's hot (20)

Sbaw091117
Sbaw091117Sbaw091117
Sbaw091117
 
Go Beast Mode with Realtime Reactive Interfaces in Angular 2 and Firebase
Go Beast Mode with Realtime Reactive Interfaces in Angular 2 and FirebaseGo Beast Mode with Realtime Reactive Interfaces in Angular 2 and Firebase
Go Beast Mode with Realtime Reactive Interfaces in Angular 2 and Firebase
 
Ushahidi
UshahidiUshahidi
Ushahidi
 
Tinkerbelles return home from their Guinness world-record attempt on Sunday
Tinkerbelles return home from their Guinness world-record attempt on SundayTinkerbelles return home from their Guinness world-record attempt on Sunday
Tinkerbelles return home from their Guinness world-record attempt on Sunday
 
I os 15
I os 15I os 15
I os 15
 
The Pied Piper of Selenium
The Pied Piper of SeleniumThe Pied Piper of Selenium
The Pied Piper of Selenium
 
20/20 | Investigative Journalism & News Magazine
20/20 | Investigative Journalism & News Magazine20/20 | Investigative Journalism & News Magazine
20/20 | Investigative Journalism & News Magazine
 
Technology and Science News - ABC News
Technology and Science News - ABC NewsTechnology and Science News - ABC News
Technology and Science News - ABC News
 
Health News & Articles | Healthy Living
Health News & Articles | Healthy LivingHealth News & Articles | Healthy Living
Health News & Articles | Healthy Living
 
Wii Ruby All Work And No Play Just Wont Do
Wii Ruby All Work And No Play Just Wont DoWii Ruby All Work And No Play Just Wont Do
Wii Ruby All Work And No Play Just Wont Do
 
iOS. EventKit Framework. Work with calendars and reminders
iOS. EventKit Framework. Work with calendars and remindersiOS. EventKit Framework. Work with calendars and reminders
iOS. EventKit Framework. Work with calendars and reminders
 
Technology and Science News - ABC News
Technology and Science News - ABC NewsTechnology and Science News - ABC News
Technology and Science News - ABC News
 
Event handling using jQuery
Event handling using jQueryEvent handling using jQuery
Event handling using jQuery
 
What Would You Do? With John Quinones
What Would You Do? With John QuinonesWhat Would You Do? With John Quinones
What Would You Do? With John Quinones
 
Technology and Science News - ABC News
Technology and Science News - ABC NewsTechnology and Science News - ABC News
Technology and Science News - ABC News
 
Technology and Science News - ABC News
Technology and Science News - ABC NewsTechnology and Science News - ABC News
Technology and Science News - ABC News
 
Special Events: Beyond Custom Events
Special Events: Beyond Custom EventsSpecial Events: Beyond Custom Events
Special Events: Beyond Custom Events
 
Delivering a Responsive UI
Delivering a Responsive UIDelivering a Responsive UI
Delivering a Responsive UI
 
International News | World News
International News | World NewsInternational News | World News
International News | World News
 
International News | World News
International News | World NewsInternational News | World News
International News | World News
 

Similar to KODE JS POKENNNNN

JavaScript APIs - The Web is the Platform - MDN Hack Day, Sao Paulo
JavaScript APIs - The Web is the Platform - MDN Hack Day, Sao PauloJavaScript APIs - The Web is the Platform - MDN Hack Day, Sao Paulo
JavaScript APIs - The Web is the Platform - MDN Hack Day, Sao PauloRobert Nyman
 
Workshop 5: JavaScript testing
Workshop 5: JavaScript testingWorkshop 5: JavaScript testing
Workshop 5: JavaScript testing
Visual Engineering
 
Leaving Flatland: getting started with WebGL
Leaving Flatland: getting started with WebGLLeaving Flatland: getting started with WebGL
Leaving Flatland: getting started with WebGL
gerbille
 
Dion Almaer & Ben Galbraith - Build Once, Deploy Everywhere
Dion Almaer & Ben Galbraith - Build Once, Deploy EverywhereDion Almaer & Ben Galbraith - Build Once, Deploy Everywhere
Dion Almaer & Ben Galbraith - Build Once, Deploy Everywhere
Carsonified Team
 
Advanced jQuery
Advanced jQueryAdvanced jQuery
Advanced jQuery
sergioafp
 
Y Map Mashup Camp
Y Map Mashup CampY Map Mashup Camp
Y Map Mashup Camp
Jinho Jung
 
You will learn RxJS in 2017
You will learn RxJS in 2017You will learn RxJS in 2017
You will learn RxJS in 2017
名辰 洪
 
Javascript & jQuery: A pragmatic introduction
Javascript & jQuery: A pragmatic introductionJavascript & jQuery: A pragmatic introduction
Javascript & jQuery: A pragmatic introduction
Iban Martinez
 
04 Advanced Javascript
04 Advanced Javascript04 Advanced Javascript
04 Advanced Javascript
crgwbr
 
The Open Web and what it means
The Open Web and what it meansThe Open Web and what it means
The Open Web and what it meansRobert Nyman
 
Javascript 基础
Javascript 基础Javascript 基础
Javascript 基础Alipay
 
ViewController.swift Calculatorimport Cocoaimport UIKit.pdf
 ViewController.swift Calculatorimport Cocoaimport UIKit.pdf ViewController.swift Calculatorimport Cocoaimport UIKit.pdf
ViewController.swift Calculatorimport Cocoaimport UIKit.pdf
arasanlethers
 
jQuery: Events, Animation, Ajax
jQuery: Events, Animation, AjaxjQuery: Events, Animation, Ajax
jQuery: Events, Animation, Ajax
Constantin Titarenko
 
Firefox OS learnings & visions, WebAPIs - budapest.mobile
Firefox OS learnings & visions, WebAPIs - budapest.mobileFirefox OS learnings & visions, WebAPIs - budapest.mobile
Firefox OS learnings & visions, WebAPIs - budapest.mobileRobert Nyman
 
HTML5 & The Open Web - at Nackademin
HTML5 & The Open Web -  at NackademinHTML5 & The Open Web -  at Nackademin
HTML5 & The Open Web - at NackademinRobert Nyman
 
Reactive programming with RxJS - ByteConf 2018
Reactive programming with RxJS - ByteConf 2018Reactive programming with RxJS - ByteConf 2018
Reactive programming with RxJS - ByteConf 2018
Tracy Lee
 
JavaScript: Events Handling
JavaScript: Events HandlingJavaScript: Events Handling
JavaScript: Events Handling
Yuriy Bezgachnyuk
 
Workshop 1: Good practices in JavaScript
Workshop 1: Good practices in JavaScriptWorkshop 1: Good practices in JavaScript
Workshop 1: Good practices in JavaScript
Visual Engineering
 

Similar to KODE JS POKENNNNN (20)

JavaScript APIs - The Web is the Platform - MDN Hack Day, Sao Paulo
JavaScript APIs - The Web is the Platform - MDN Hack Day, Sao PauloJavaScript APIs - The Web is the Platform - MDN Hack Day, Sao Paulo
JavaScript APIs - The Web is the Platform - MDN Hack Day, Sao Paulo
 
Workshop 5: JavaScript testing
Workshop 5: JavaScript testingWorkshop 5: JavaScript testing
Workshop 5: JavaScript testing
 
Leaving Flatland: getting started with WebGL
Leaving Flatland: getting started with WebGLLeaving Flatland: getting started with WebGL
Leaving Flatland: getting started with WebGL
 
Dion Almaer & Ben Galbraith - Build Once, Deploy Everywhere
Dion Almaer & Ben Galbraith - Build Once, Deploy EverywhereDion Almaer & Ben Galbraith - Build Once, Deploy Everywhere
Dion Almaer & Ben Galbraith - Build Once, Deploy Everywhere
 
Advanced jQuery
Advanced jQueryAdvanced jQuery
Advanced jQuery
 
Y Map Mashup Camp
Y Map Mashup CampY Map Mashup Camp
Y Map Mashup Camp
 
You will learn RxJS in 2017
You will learn RxJS in 2017You will learn RxJS in 2017
You will learn RxJS in 2017
 
Javascript & jQuery: A pragmatic introduction
Javascript & jQuery: A pragmatic introductionJavascript & jQuery: A pragmatic introduction
Javascript & jQuery: A pragmatic introduction
 
04 Advanced Javascript
04 Advanced Javascript04 Advanced Javascript
04 Advanced Javascript
 
The Open Web and what it means
The Open Web and what it meansThe Open Web and what it means
The Open Web and what it means
 
Javascript 基础
Javascript 基础Javascript 基础
Javascript 基础
 
ViewController.swift Calculatorimport Cocoaimport UIKit.pdf
 ViewController.swift Calculatorimport Cocoaimport UIKit.pdf ViewController.swift Calculatorimport Cocoaimport UIKit.pdf
ViewController.swift Calculatorimport Cocoaimport UIKit.pdf
 
ev
evev
ev
 
JQuery Flot
JQuery FlotJQuery Flot
JQuery Flot
 
jQuery: Events, Animation, Ajax
jQuery: Events, Animation, AjaxjQuery: Events, Animation, Ajax
jQuery: Events, Animation, Ajax
 
Firefox OS learnings & visions, WebAPIs - budapest.mobile
Firefox OS learnings & visions, WebAPIs - budapest.mobileFirefox OS learnings & visions, WebAPIs - budapest.mobile
Firefox OS learnings & visions, WebAPIs - budapest.mobile
 
HTML5 & The Open Web - at Nackademin
HTML5 & The Open Web -  at NackademinHTML5 & The Open Web -  at Nackademin
HTML5 & The Open Web - at Nackademin
 
Reactive programming with RxJS - ByteConf 2018
Reactive programming with RxJS - ByteConf 2018Reactive programming with RxJS - ByteConf 2018
Reactive programming with RxJS - ByteConf 2018
 
JavaScript: Events Handling
JavaScript: Events HandlingJavaScript: Events Handling
JavaScript: Events Handling
 
Workshop 1: Good practices in JavaScript
Workshop 1: Good practices in JavaScriptWorkshop 1: Good practices in JavaScript
Workshop 1: Good practices in JavaScript
 

Recently uploaded

SAP Sapphire 2024 - ASUG301 building better apps with SAP Fiori.pdf
SAP Sapphire 2024 - ASUG301 building better apps with SAP Fiori.pdfSAP Sapphire 2024 - ASUG301 building better apps with SAP Fiori.pdf
SAP Sapphire 2024 - ASUG301 building better apps with SAP Fiori.pdf
Peter Spielvogel
 
The Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and SalesThe Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and Sales
Laura Byrne
 
A tale of scale & speed: How the US Navy is enabling software delivery from l...
A tale of scale & speed: How the US Navy is enabling software delivery from l...A tale of scale & speed: How the US Navy is enabling software delivery from l...
A tale of scale & speed: How the US Navy is enabling software delivery from l...
sonjaschweigert1
 
Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...
Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...
Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...
James Anderson
 
Accelerate your Kubernetes clusters with Varnish Caching
Accelerate your Kubernetes clusters with Varnish CachingAccelerate your Kubernetes clusters with Varnish Caching
Accelerate your Kubernetes clusters with Varnish Caching
Thijs Feryn
 
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 previewState of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
Prayukth K V
 
Enhancing Performance with Globus and the Science DMZ
Enhancing Performance with Globus and the Science DMZEnhancing Performance with Globus and the Science DMZ
Enhancing Performance with Globus and the Science DMZ
Globus
 
FIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance Osaka Seminar: Overview.pdfFIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance
 
The Future of Platform Engineering
The Future of Platform EngineeringThe Future of Platform Engineering
The Future of Platform Engineering
Jemma Hussein Allen
 
Assure Contact Center Experiences for Your Customers With ThousandEyes
Assure Contact Center Experiences for Your Customers With ThousandEyesAssure Contact Center Experiences for Your Customers With ThousandEyes
Assure Contact Center Experiences for Your Customers With ThousandEyes
ThousandEyes
 
Introduction to CHERI technology - Cybersecurity
Introduction to CHERI technology - CybersecurityIntroduction to CHERI technology - Cybersecurity
Introduction to CHERI technology - Cybersecurity
mikeeftimakis1
 
Climate Impact of Software Testing at Nordic Testing Days
Climate Impact of Software Testing at Nordic Testing DaysClimate Impact of Software Testing at Nordic Testing Days
Climate Impact of Software Testing at Nordic Testing Days
Kari Kakkonen
 
Monitoring Java Application Security with JDK Tools and JFR Events
Monitoring Java Application Security with JDK Tools and JFR EventsMonitoring Java Application Security with JDK Tools and JFR Events
Monitoring Java Application Security with JDK Tools and JFR Events
Ana-Maria Mihalceanu
 
PCI PIN Basics Webinar from the Controlcase Team
PCI PIN Basics Webinar from the Controlcase TeamPCI PIN Basics Webinar from the Controlcase Team
PCI PIN Basics Webinar from the Controlcase Team
ControlCase
 
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdfFIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance
 
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
James Anderson
 
Essentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FMEEssentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FME
Safe Software
 
Video Streaming: Then, Now, and in the Future
Video Streaming: Then, Now, and in the FutureVideo Streaming: Then, Now, and in the Future
Video Streaming: Then, Now, and in the Future
Alpen-Adria-Universität
 
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
UiPathCommunity
 
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdfSmart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
91mobiles
 

Recently uploaded (20)

SAP Sapphire 2024 - ASUG301 building better apps with SAP Fiori.pdf
SAP Sapphire 2024 - ASUG301 building better apps with SAP Fiori.pdfSAP Sapphire 2024 - ASUG301 building better apps with SAP Fiori.pdf
SAP Sapphire 2024 - ASUG301 building better apps with SAP Fiori.pdf
 
The Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and SalesThe Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and Sales
 
A tale of scale & speed: How the US Navy is enabling software delivery from l...
A tale of scale & speed: How the US Navy is enabling software delivery from l...A tale of scale & speed: How the US Navy is enabling software delivery from l...
A tale of scale & speed: How the US Navy is enabling software delivery from l...
 
Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...
Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...
Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...
 
Accelerate your Kubernetes clusters with Varnish Caching
Accelerate your Kubernetes clusters with Varnish CachingAccelerate your Kubernetes clusters with Varnish Caching
Accelerate your Kubernetes clusters with Varnish Caching
 
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 previewState of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
 
Enhancing Performance with Globus and the Science DMZ
Enhancing Performance with Globus and the Science DMZEnhancing Performance with Globus and the Science DMZ
Enhancing Performance with Globus and the Science DMZ
 
FIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance Osaka Seminar: Overview.pdfFIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance Osaka Seminar: Overview.pdf
 
The Future of Platform Engineering
The Future of Platform EngineeringThe Future of Platform Engineering
The Future of Platform Engineering
 
Assure Contact Center Experiences for Your Customers With ThousandEyes
Assure Contact Center Experiences for Your Customers With ThousandEyesAssure Contact Center Experiences for Your Customers With ThousandEyes
Assure Contact Center Experiences for Your Customers With ThousandEyes
 
Introduction to CHERI technology - Cybersecurity
Introduction to CHERI technology - CybersecurityIntroduction to CHERI technology - Cybersecurity
Introduction to CHERI technology - Cybersecurity
 
Climate Impact of Software Testing at Nordic Testing Days
Climate Impact of Software Testing at Nordic Testing DaysClimate Impact of Software Testing at Nordic Testing Days
Climate Impact of Software Testing at Nordic Testing Days
 
Monitoring Java Application Security with JDK Tools and JFR Events
Monitoring Java Application Security with JDK Tools and JFR EventsMonitoring Java Application Security with JDK Tools and JFR Events
Monitoring Java Application Security with JDK Tools and JFR Events
 
PCI PIN Basics Webinar from the Controlcase Team
PCI PIN Basics Webinar from the Controlcase TeamPCI PIN Basics Webinar from the Controlcase Team
PCI PIN Basics Webinar from the Controlcase Team
 
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdfFIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
 
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
 
Essentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FMEEssentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FME
 
Video Streaming: Then, Now, and in the Future
Video Streaming: Then, Now, and in the FutureVideo Streaming: Then, Now, and in the Future
Video Streaming: Then, Now, and in the Future
 
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
 
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdfSmart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
 

KODE JS POKENNNNN

  • 1. var buffer = document.createElement('canvas'); var bufferCtx = buffer.getContext('2d'); var bIsIPhone = false; var bIsIPad = false; var bWildBattleIsReady = false; var bIsLoadingWildDialog = false; var inventory = []; var eggs = []; if( navigator.userAgent.match(/iPhone/i) || navigator.userAgent.match(/iPod/i) ) { bIsIPhone = true; rebindClicks(); } else if( navigator.userAgent.match(/iPad/i) ) { bIsIPad = true; rebindClicks(); } var bMagnify = false; //User Variables var userID = ''; var userName = ''; var userSprite = ''; var userMoney = 0; var userEvent = null; var serverToken = ''; var userX = 0; var userY = 0; var userDirection = 0; var userStepPart = 0; var userStepX = 0; var userStepY = 0; //Rendering Variables var bLoading = true; var loadAction = ""; var tick = 0; var ctx = null; var cvsWidth = 0; var cvsHeight = 0; var tagAlong = ""; var tagAlongName = ""; var follower = null; var captchaKeypress = new Array(false,false,false,false,false,false); //Drawing Resources
  • 2. var screenResources = new Array(); var ImageResourceLoadedCount = 0; var ImageResourceTotalCount = 0; function ResourceImage(src,key) { this.img = new Image(); this.img.src = src; this.url = src; this.img.onload = loadedResource; this.key = key; ImageResourceTotalCount++; return this; } //Audio Resources var musicResources = new Array(); var MusicResourceLoadedCount = 0; var MusicResourceTotalCount = 0; function ResourceMusic(src,key) { this.audio = null; MusicResourceTotalCount++; this.key = key; this.src = src; if(navigator.userAgent.toLowerCase().indexOf('firefox') > -1) { this.audio = new Audio(); this.audio.src = src; this.audio.load(); } return this; } var prevPlaying = ""; var prevPlayingSong = null; var playOnceSong = null; var soundEnabled = 0; var musicEnabled = 0; var effectResources = new Array(); var EffectResourceLoadedCount = 0; var EffectResourceTotalCount = 0; function ResourceEffect(src,key) { this.audio = new Audio(); this.audio.src = src; //this.audio.onload = loadedEffectResource; this.audio.oncanplaythrough = loadedEffectResource; //this.audio.load(); if(navigator.userAgent.toLowerCase().indexOf('firefox') > -1) { this.audio.load(); } //this.audio.play(); //this.audio.pause(); this.audio.volume = 0.5;
  • 3. this.key = key; EffectResourceTotalCount++; return this; } //Map Variables var currentMap = null; var mapName = ''; var mapCode = ''; var mapID = ''; var mapWidth = 0; var mapHeight = 0; var mapData = null; var mapEvents = null; var bMapDataLoaded = false; var bMapEventsLoaded = false; var mapLoadedCount = 0; var rawMapData = null; var mapAbove = new Image(); var mapBase = new Image(); mapAbove.onload = loadedMapImage; mapBase.onload = loadedMapImage; var stepsInGrass = 0; var mapEventObjects = new Array(); //Map - runtime draw,centerMap functions var mapLeft = 0; var mapTop = 0; //Charset Variables var charsets = new Array(); var charsetLoadedCount = 0; //Scripting Variables var events = new Array(); var lastTriggeredEventName = ""; //User Interaction var keyState = new Object; keyState.up = false; keyState.down = false; keyState.left = false; keyState.right = false; keyState.btn1 = false; keyState.btn2 = false; keyState.btn3 = false; var bMouseDown = false; //########################################################### //### SOCKET FUNCTIONS ############## Chat, Support Dialog //###########################################################
  • 4. //Sockets Variables var foregnusers = new Array(); var ws = null; var bConnected = false; var updateTick = 0; var messages = new Array(); function ChatMessage(isadmin,userid,username,message) { this.isadmin = isadmin; this.userid = userid; this.username = username; this.message = message; return this; } function chatKeyPress(e){ e = e || event; var unicode=e.keyCode? e.keyCode : e.charCode if( unicode == 13 ) { e.preventDefault(); if( document.getElementById("txtUpdate").value != "" ) { ws.send("/msg^" + document.getElementById("txtUpdate").value + "rnrn"); document.getElementById("txtUpdate").value = ""; return true; } } return false; } function chatBoxIsActive() { var curElement = document.activeElement; if( document.getElementById("txtUpdate") == curElement ) { return true; } return false; } function selectChatBox() { if( bConnected ) { var curElement = document.activeElement; if( document.getElementById("txtUpdate") != curElement ) { document.getElementById("txtUpdate").focus(); } /* else { document.getElementById("txtUpdate").blur(); return true; }*/ } } function showChatBox() { if( bConnected ) {
  • 5. document.getElementById("txtUpdate").value = ""; $("#mws-jui-dialog-post").dialog({ autoOpen: false, title: "Chat Window", modal: true, width: "480", buttons: [] }); $("#mws-jui-dialog-post").dialog("option", {modal: false}).dialog("open"); document.getElementById("txtUpdate").focus(); } } function showUnsupportedMessage() { var html = "<p>Some of the functionality needed to dsplay this page correctly is missing from the browser you are using. You can continue to play but you will not be able to see or chat to other players of the game.</p>"; document.getElementById("mws-jui-dialog-data").innerHTML = html; $("#mws-jui-dialog-data").dialog({ autoOpen: false, title: "Partial Functionality Support Notification", modal: true, width: "480", buttons: [] }); $("#mws-jui-dialog-data").dialog("option", {modal: true}).dialog("open"); } function rebindClicks(){ var userAgent = navigator.userAgent.toLowerCase(); var isIphone = (userAgent.indexOf('iphone') != -1) ? true : false; if (isIphone) { // For each event with an inline onclick $('[onclick]').each(function() { var onclick = $(this).attr('onclick'); $(this).removeAttr('onclick'); // Remove the onclick attribute $(this).bind("click", preventClickEvent); // See to it that clicks never happen $(this).bind('tap', onclick); // Point taps to the onclick }); } } function preventClickEvent(event) { event.preventDefault(); }
  • 6. //########################################################### //### GAME FUNCTIONS ############## update, draw, centerMap //########################################################### function update() { if( bLoading ) { if( ImageResourceLoadedCount == screenResources.length ) if( charsetLoadedCount == charsets.length ) if( mapLoadedCount == 2 ) if( bMapEventsLoaded && bMapDataLoaded ) { bLoading = false; mapWidth = mapAbove.width; mapHeight = mapAbove.height; clearInterval(gameInterval); gameInterval = setInterval(function() { update(); draw(); }, 50); } } else { if( bConnected ) { updateTick++; if( updateTick > 10 ) { var sendStr = ""; var running = "0"; if( keyState.btn2 ) running = "1"; if( tagAlong != "" && follower != null ) { sendStr = "/update^" + mapID +"^" + userEvent.mapPosition.X +"^" + userEvent.mapPosition.Y +"^" + userEvent.direction +"^" + userEvent.stepAnimation + "^" + running + "^" + (bInBattle ? "1" : "0") + "^" + tagAlong +"^" + follower.mapPosition.X +"^" + (follower.mapPosition.Y-2) +"^" + follower.direction +"^" + follower.stepAnimation + "^" + running +"^rnrn"; } else { sendStr = "/update^" + mapID +"^" + userEvent.mapPosition.X +"^" + userEvent.mapPosition.Y +"^" + userEvent.direction +"^" + userEvent.stepAnimation + "^" + running + "^" + (bInBattle ? "1" : "0") + "rnrn"; } ws.send(sendStr); updateTick = 0; } }
  • 7. if( activeScript.length > 0 ) { scriptUpdate(); } else if( bInBattle ) { battleUpdate(); } else { //Process input and movement. if( activeScript.length == 0 ) { if( userEvent.moveQueue.length == 0 ) { if( keyState.up ) { userEvent.addMoveQueue("Up"); } else if( keyState.down ) { userEvent.addMoveQueue("Down"); } else if( keyState.left ) { userEvent.addMoveQueue("Left"); } else if( keyState.right ) { userEvent.addMoveQueue("Right"); } } } if( keyState.btn1 ) { for(var k=0;k<currentMap.events.length;k++) { var evnt = currentMap.events[k]; if (evnt.bEventEnabled && (evnt.type == "Action Button" || evnt.type == "X1" || evnt.type == "X2" || evnt.type == "X3" || evnt.type == "X10" || evnt.type == "X15") && activeScript.length == 0 && evnt.eventData.length > 0) { var checkX = 0; var checkY = 0; if (userEvent.direction == 0) checkY = -1; if (userEvent.direction == 1) checkY = 1; if (userEvent.direction == 2) checkX = -1; if (userEvent.direction == 3) checkX = 1; if (evnt.mapPosition.X == userEvent.mapPosition.X + checkX && evnt.mapPosition.Y == userEvent.mapPosition.Y + checkY + 2 ) { //sfx(SOUND_CONFIRM); if (triggerEvent(evnt, false)) { keyState.btn1 = false; return; } } } } } }
  • 8. //Evaluate our hero userEvent.evaluate(); centerMap(); currentMap.evaluateEvents(ctx); if( bWildBattleIsReady ) { if( keyState.btn1 == true ) { wipeWildMonsterBox(); battleWildSelected(); keyState.btn1 = false; } } } } function draw() { ctx.fillStyle="#000000"; ctx.fillRect(0,0,cvsWidth,cvsHeight); if( bLoading ) { var status = "Loading"; if( tick > 2 ) status = status + "."; if( tick > 5 ) status = status + "."; if( tick > 7 ) status = status + "."; if( tick > 10 ) tick = 0; ctx.font = "bold 14px sans-serif"; ctx.textAlign = "center"; drawShadowText(ctx,status, cvsWidth/2, 40); if( ImageResourceLoadedCount > ImageResourceTotalCount) ImageResourceLoadedCount = ImageResourceTotalCount; if( EffectResourceLoadedCount > EffectResourceTotalCount) EffectResourceLoadedCount = EffectResourceTotalCount; status = ImageResourceLoadedCount + " of " + ImageResourceTotalCount + " images loaded"; drawShadowText(ctx,status, cvsWidth/2, 65); status = EffectResourceLoadedCount + " of " + EffectResourceTotalCount + " sound effects loaded"; drawShadowText(ctx,status, cvsWidth/2, 85);
  • 9. } else { //context.drawImage(img,sx,sy,swidth,sheight,dx,dy,dwidth,dheight); var drawWidth = mapWidth > cvsWidth ? cvsWidth : mapWidth; var drawHeight = mapHeight > cvsHeight ? cvsHeight : mapHeight; if( drawHeight > mapHeight +(-mapTop-cvsHeight)-130 ) drawHeight = mapHeight +(-mapTop-cvsHeight)-130; if( drawWidth > mapWidth + mapLeft ) drawWidth = mapWidth + mapLeft; //Draw Base Layer ctx.drawImage(mapBase, -mapLeft, -(-mapTop-cvsHeight)+130, drawWidth, drawHeight, 0, 0, drawWidth, drawHeight ); currentMap.drawEvents(ctx,"below"); userEvent.drawImage(ctx); currentMap.drawEvents(ctx,"above"); //Draw Above Layer ctx.drawImage(mapAbove, -mapLeft, -(-mapTop-cvsHeight)+130, drawWidth, drawHeight,0, 0, drawWidth, drawHeight); currentMap.drawNames(ctx); if( bMagnify ) { bufferCtx.fillStyle="#000000"; bufferCtx.fillRect(0,0,cvsWidth,cvsHeight); bufferCtx.drawImage(ctx.canvas, ctx.canvas.width/4+userEvent.offsetX, ctx.canvas.height/4+userEvent.offsetY, ctx.canvas.width/2, ctx.canvas.height/2,0, 0, drawWidth, drawHeight); ctx.fillStyle="#000000"; ctx.fillRect(0,0,cvsWidth,cvsHeight); ctx.drawImage(bufferCtx.canvas,0,0,drawWidth, drawHeight); //ctx.drawImage(ctx.canvas, ctx.canvas.width/4, ctx.canvas.height/4, ctx.canvas.width/4*3, ctx.canvas.height/4*3,0, 0, drawWidth, drawHeight); } ctx.font = "bold 12px sans-serif"; ctx.textAlign = "left"; drawShadowText(ctx,mapName,10, cvsHeight-15); //ctx.textAlign = "left"; //drawShadowText(ctx,"Use Arrow Keys to move and Battle. Confirm with X, Cancel with Z.",10, cvsHeight-25); ctx.textAlign = "right"; drawShadowText(ctx,"Username: " + userName,cvsWidth-27, cvsHeight- 45); ctx.textAlign = "right"; if( bConnected ) drawShadowText(ctx,"Connected: True" ,cvsWidth-27, cvsHeight-
  • 10. 30); else drawShadowText(ctx,"Connected: False" ,cvsWidth-27, cvsHeight- 30); drawShadowText(ctx,userCount + " Trainers Online" ,cvsWidth-27, cvsHeight-15); ctx.textAlign = "right"; drawShadowText(ctx,"Currency: " + userMoney + "¢",cvsWidth-27, 20); if( bInBattle ) { battleDraw(); } if( activeScript.length > 0 ) { scriptDraw(); } if( eggs.length > 0 ) { var egg = resourceByKey("pokemonegg"); for(var i=0;i<eggs.length;i++) { ctx.drawImage(egg, -25 + (i*30), cvsHeight-100); } } } tick++; } function centerMap() { var MyX = userEvent.mapPosition.X * 16; var MyY = userEvent.mapPosition.Y * 16; var winSize = new Object; winSize.Width = cvsWidth; winSize.Height = cvsHeight; var xTmp = Math.max(MyX, cvsWidth / 2); var yTmp = Math.max(MyY, cvsHeight / 2); xTmp = Math.min(xTmp, mapWidth - winSize.Width / 2); yTmp = Math.min(yTmp, mapHeight - winSize.Height / 2); var actualPosition = new Object; actualPosition.X = xTmp; actualPosition.Y = yTmp; var centerOfView = new Object; centerOfView.X = cvsWidth / 2; centerOfView.Y = cvsHeight / 2;
  • 11. var viewPoint = new Object; viewPoint.X = centerOfView.X - actualPosition.X; viewPoint.Y = centerOfView.Y - actualPosition.Y; if( userEvent.direction == 0 ) { userStepY = userEvent.stepPart; } else if( userEvent.direction == 1 ) { userStepY = -userEvent.stepPart; } else if( userEvent.direction == 2 ) { userStepX = userEvent.stepPart; } else if( userEvent.direction == 3 ) { userStepX = -userEvent.stepPart; } //TODO: Check mapSize Worked if( MyX-userStepX > mapWidth - cvsWidth/2) { userStepX = 0; } if( MyX-userStepX < cvsWidth/2 ) { userStepX = 0; } if( MyY-userStepY > mapHeight - cvsHeight/2 ) { userStepY = 0; } if( MyY-userStepY < cvsHeight/2 ) { userStepY = 0; } var additionalDown = -cvsHeight-mapHeight/8; mapLeft = viewPoint.X + userStepX; mapTop = (viewPoint.Y + userStepY) * -1 + additionalDown; //User position should update as if it was an event, theirfore it should not be done in this function but rather in the gameEvent Class. } //########################################################### //### RENDERING FUNCTIONS ############## //########################################################### //drawShadowText(context,text,postionX,positionY) function drawShadowText(ctx,text,posX,posY,color) { ctx.fillStyle = 'black'; ctx.fillText(text, posX+1, posY-1); ctx.fillText(text, posX-1, posY-1); ctx.fillText(text, posX+1, posY+1); ctx.fillText(text, posX-1, posY+1); if(!color) color = 'white';
  • 12. ctx.fillStyle = color; ctx.fillText(text, posX, posY); } //########################################################### //### AJAX FUNCTIONS ############## //########################################################### function requestObject() { var xmlHttpReq = false; // Mozilla/Safari if (window.XMLHttpRequest) { self.xmlHttpReq = new XMLHttpRequest(); } // IE else if (window.ActiveXObject) { self.xmlHttpReq = new ActiveXObject("Microsoft.XMLHTTP"); } return xmlHttpReq; } function loadMapData() { wipeWildMonsterBox(); var xmlHttpReq = requestObject(); self.xmlHttpReq.open("GET", "/maps/" + mapCode + ".xml", true); self.xmlHttpReq.onreadystatechange = loadMapDataCallback; self.xmlHttpReq.send(); } function loadMapDataCallback() { if (self.xmlHttpReq.readyState == 4) { if (self.xmlHttpReq.responseXML) { var resultsNode = self.xmlHttpReq.responseXML.childNodes[1]; if (!resultsNode) { resultsNode = self.xmlHttpReq.responseXML.childNodes[0]; } if (resultsNode == null) { loadMapData(); return; } mapData = resultsNode; bMapDataLoaded = true; currentMap.load(mapData); if( loadAction != "" ) { if( loadAction.substr(0,4) == "wrap" ) { var direction = loadAction.substr(5,1);
  • 13. if( direction == 0 ) { userEvent.mapPosition.Y = Math.floor(mapHeight/16)- 3; } else if( direction == 1 ) { userEvent.mapPosition.Y = 0; } else if( direction == 2 ) { userEvent.mapPosition.X = Math.floor(mapWidth/16)- 3; } else if( direction == 3 ) { userEvent.mapPosition.X = 0; } } } loadMapEvents(); } } } function loadMapEvents() { var xmlHttpReq = requestObject(); var finalPostString = "mapid="+encodeURIComponent(mapCode) +"&x="+userEvent.mapPosition.X+"&y="+userEvent.mapPosition.Y; self.xmlHttpReq.open("POST", "/xml/explore.xml.php?rand=" + (Math.random() * 1000000), true); self.xmlHttpReq.setRequestHeader("Content-type", "application/x-www- form-urlencoded"); self.xmlHttpReq.onreadystatechange = loadMapEventsCallback; self.xmlHttpReq.send(finalPostString); } function loadMapEventsCallback() { if (self.xmlHttpReq.readyState == 4) { if (self.xmlHttpReq.responseXML) { var resultsNode = self.xmlHttpReq.responseXML.childNodes[1]; if (!resultsNode) { resultsNode = self.xmlHttpReq.responseXML.childNodes[0]; } if (resultsNode == null) { loadMapEvents(); return; } mapEvents = resultsNode; mapName = nodeValue(firstChildNodeNamed("name", mapEvents)); mapID = nodeValue(firstChildNodeNamed("id", mapEvents)); //Load the map's events currentMap.loadEvents(mapEvents); currentMap.mapMusic = nodeValue(firstChildNodeNamed("music",
  • 14. mapEvents)); if( currentMap.mapMusic != "" && currentMap.mapMusic != prevPlaying ) { playMusic(currentMap.mapMusic); } if( currentMap.mapMusic != "" ) { playMusic(currentMap.mapMusic); } bMapEventsLoaded = true; } else { alert("Error loading events."); bMapEventsLoaded = true; } } } function firstChildNodeNamed(name, node) { for (var i = 0; i < node.childNodes.length; i++) { if (node.childNodes[i].nodeName == name) return node.childNodes[i]; } return null; } function nodeValue(node) { var str = node.nodeValue; if (str == null) if (node.childNodes.length > 0) str = node.childNodes[0].nodeValue; return str; } function getDataOfImmediateChild(parentNode) { var val = ""; for (n=0; n < parentNode.childNodes.length; n++) { val = val + nodeValue(parentNode.childNodes[n]); } return val; } //########################################################### //### LOADING & SETUP ############## //########################################################### $(document).ready(function() {
  • 15. curMonImage = document.getElementById("curMonImage"); curOppImage = document.getElementById("curOppImage"); var c=document.getElementById("cvsGame"); ctx = c.getContext("2d"); ctx.canvas.width = $("#mws-explore-area").innerWidth(); ctx.canvas.height = $("#mws-explore-area").innerHeight(); cvsWidth = Math.floor(ctx.canvas.width/16+1)*16; cvsHeight = Math.floor(ctx.canvas.height/16+1)*16; if( cvsWidth > 1024 ) { cvsWidth = 1024; } loadUserData(); //Instant / Async loadCharacterSets(); //Async loadImages(); loadMapData(); //Async //CALLS: loadMapEvents(); UPON COMPLETION. //Async userEvent = new gameEvent(); userEvent.initAsPlayer(Point(userX,userY)); currentMap = gameMap(); //KEY DOWN $(document).bind('keydown', 'up', function (evt){ keyState.up = true; return false; } ); $(document).bind('keydown', 'down', function (evt){ keyState.down = true; return false; }); $(document).bind('keydown', 'left', function (evt){ keyState.left = true; return false; }); $(document).bind('keydown', 'right', function (evt){ keyState.right = true; return false; }); $(document).bind('keydown', 'x', function (evt){ if( !chatBoxIsActive() ) {keyState.btn1 = true;} return true; }); $(document).bind('keydown', 'z', function (evt){ if( !chatBoxIsActive() ) {keyState.btn2 = true;} return true; }); $(document).bind('keydown', 'c', function (evt){ if( !chatBoxIsActive() ) {keyState.btn3 = true;} return true; }); $(document).bind('keydown', 'esc', function (evt){ menuOpen(); return true; }); $(document).bind('keydown', 'w', function (evt){ if( !chatBoxIsActive() ) {keyState.up = true;} return true; } ); $(document).bind('keydown', 's', function (evt){ if( !chatBoxIsActive() ) {keyState.down = true;} return true; }); $(document).bind('keydown', 'a', function (evt){ if( !chatBoxIsActive() ) {keyState.left = true;} return true; }); $(document).bind('keydown', 'd', function (evt){ if( !chatBoxIsActive() )
  • 16. {keyState.right = true;} return true; }); $(document).bind('keydown', '1', function (evt){ captchaKeypress[0] = false; return true; }); $(document).bind('keydown', '2', function (evt){ captchaKeypress[1] = false; return true; }); $(document).bind('keydown', '3', function (evt){ captchaKeypress[2] = false; return true; }); $(document).bind('keydown', '4', function (evt){ captchaKeypress[3] = false; return true; }); $(document).bind('keydown', '5', function (evt){ captchaKeypress[4] = false; return true; }); $(document).bind('keydown', '6', function (evt){ captchaKeypress[5] = false; return true; }); $(document).bind('keyup', '1', function (evt){ addToCaptcha("1"); return true; }); $(document).bind('keyup', '2', function (evt){ addToCaptcha("2"); return true; }); $(document).bind('keyup', '3', function (evt){ addToCaptcha("3"); return true; }); $(document).bind('keyup', '4', function (evt){ addToCaptcha("4"); return true; }); $(document).bind('keyup', '5', function (evt){ addToCaptcha("5"); return true; }); $(document).bind('keyup', '6', function (evt){ addToCaptcha("6"); return true; }); //KEY UP/RELEASE $(document).bind('keyup', 'up', function (evt){ keyState.up = false; return false; } ); $(document).bind('keyup', 'down', function (evt){ keyState.down = false; return false; }); $(document).bind('keyup', 'left', function (evt){ keyState.left = false; return false; }); $(document).bind('keyup', 'right', function (evt){ keyState.right = false; return false; }); $(document).bind('keyup', 'x', function (evt){ if( !chatBoxIsActive() ) {keyState.btn1 = false;} return true; }); $(document).bind('keyup', 'z', function (evt){ if( !chatBoxIsActive() ) {keyState.btn2 = false;} return true; }); $(document).bind('keyup', 'c', function (evt){ if( !chatBoxIsActive() ) {keyState.btn3 = false;} return true; }); $(document).bind('keyup', 'w', function (evt){ if( !chatBoxIsActive() ) {keyState.up = false;} return true; } ); $(document).bind('keyup', 's', function (evt){ if( !chatBoxIsActive() ) {keyState.down = false;} return true; }); $(document).bind('keyup', 'a', function (evt){ if( !chatBoxIsActive() ) {keyState.left = false;} return true; }); $(document).bind('keyup', 'd', function (evt){ if( !chatBoxIsActive() ) {keyState.right = false;} return true; }); $(document).bind('keyup', 'return', function (evt){ selectChatBox(); return false; });
  • 17. $(document).bind('keyup', '/', function (evt){ selectChatBox(); return true; }); $(document).bind('keydown', 'm', function (evt){ if( document.getElementById("txtUpdate") == document.activeElement ) { return true; } bMagnify=!bMagnify; return false; }); $("#cvsGame").mousedown(function(e) { if (!e) var e = window.event; canvasMouseDown(e); }); $("#cvsGame").mouseup(function(e) { if (!e) var e = window.event; canvasMouseUp(e); }); $("#cvsGame").mousemove(function(e) { if (!e) var e = window.event; canvasMouseMove(e); }); if( bIsIPhone || bIsIPad ) { c.addEventListener('touchstart', canvasMouseDown, true); c.addEventListener('touchend', canvasMouseUp, true); c.addEventListener('touchmove', canvasMouseMove, true); c.addEventListener("mousedown", canvasMouseDown, true); c.addEventListener("mouseup", canvasMouseUp, true); c.addEventListener("mousemove", canvasMouseMove, true); } // test if the browser supports web sockets if ("WebSocket" in window) { //connect("ws://www.pokemonlegends.com:8082/game"); connect("ws://www.pokemonlegends.com:8082/game"); } else { showUnsupportedMessage(); }; if( bIsIPhone || bIsIPad ) { rebindClicks(); } timeoutInterval = setInterval(keepSession, 120000); // gameInterval = setInterval(function() {
  • 18. update(); draw(); }, 500); reszeWindow(); }); var timeoutInterval = null; var gameInterval = null; // connect to the specified host function connect(host) { $.jGrowl("Note: Connecting to Pokemon Legends Server.", {life: 5000, header: "Connectivity Notification.", position: "bottom-right"}); try { ws = new WebSocket(host); // create the web socket } catch (err) { $.jGrowl("Note: Connection Error"+err, {life: 5000, header: "Connectivity Notification.", position: "bottom-right"}); } ws.onopen = function () { ws.send("/auth^" + serverToken + "rnrn"); $.jGrowl("Note: Connection Established.", {life: 5000, header: "Connectivity Notification.", position: "bottom-right"}); bConnected = true; }; ws.onmessage = function (evt) { if (typeof evt.data == "string") { if( evt.data.indexOf("/update") > -1 ) { updateMMOEvents(evt.data); } else if( evt.data.indexOf("/msg") > -1 ) { updateChat(evt.data); } else if( evt.data.indexOf("/pvprequest") > -1 ) { pvpRequested(evt.data); } else if( evt.data.indexOf("/pvpaccepted") > -1 ) { pvpLoadBattle(evt.data); } else if( evt.data.indexOf("/ping") > -1 ) { serverPing(evt.data); } } }; ws.onclose = function () { $.jGrowl("Note: Connection Closed. Will retry in 2 minutes.", {life: 5000, header: "Connectivity Notification.", position: "bottom-right"}); bConnected = false; mmoUsers = new Array(); }; };
  • 19. function rebindClicks(){ var userAgent = navigator.userAgent.toLowerCase(); var isIphone = (userAgent.indexOf('iphone') != -1) ? true : false; if (isIphone) { // For each event with an inline onclick $('[onclick]').each(function() { var onclick = $(this).attr('onclick'); $(this).removeAttr('onclick'); // Remove the onclick attribute $(this).bind("click", preventClickEvent); // See to it that clicks never happen $(this).bind('tap', onclick); // Point taps to the onclick }); } } function preventClickEvent(event) { event.preventDefault(); } function keepSession() { if( bConnected == false ) { connect("ws://www.pokemonlegends.com:8082/game"); } loadUtility("keepAlive=true"); } function loadMap(newMapCode, arrivalMethod, arrivalDirection) { mapLoadedCount = 0; bMapEventsLoaded = false; bMapDataLoaded = false; bLoading = true; clearInterval(gameInterval); gameInterval = setInterval(function() { update(); draw(); }, 500); mapCode = newMapCode; loadMapData(); currentMap = gameMap(); mapWidth = mapAbove.width; mapHeight = mapAbove.height; mapAbove = new Image(); mapBase = new Image(); mapAbove.onload = loadedMapImage; mapBase.onload = loadedMapImage;
  • 20. mapAbove.src='http://cache.pokemonlegends.com/maps/' +mapCode+ ' above.png'; mapBase.src='http://cache.pokemonlegends.com/maps/' +mapCode+ ' base.png'; if( arrivalDirection != null ) { loadAction = "wrap:" + arrivalDirection; } else { loadAction = ""; } mmoUsers = new Array(); } $(window).resize(function() { if( ctx == null ) return; reszeWindow(); }); function reszeWindow() { var heightPotential = $( window ).height(); var usableHeight = heightPotential-175; if( $(".adDiv").length > 0 ) { usableHeight-=$(".adDiv").innerHeight(); } $("#mws-explore-area").css("height",usableHeight+"px"); $("#cvsGame").css("height",usableHeight+"px"); $(".mws-panel-content").css("height",(usableHeight-33)+"px"); if( $("#mws-explore-area").innerWidth() > 502 ) { usableHeight-=19; } $("#mws-explore-encounter").css("top",-(usableHeight+30)+"px"); $("#mws-explore-trade-or-battle").css("top",-(usableHeight+30)+"px"); $("#mws-explore-requests").css("top",-(usableHeight+30)+"px"); ctx.canvas.width = $("#mws-explore-area").innerWidth(); ctx.canvas.height = $("#mws-explore-area").innerHeight(); cvsWidth = Math.floor(ctx.canvas.width/16+1)*16; cvsHeight = Math.floor(ctx.canvas.height/16+1)*16; buffer.width = ctx.canvas.width;
  • 21. buffer.height = ctx.canvas.height; if( cvsWidth > 1024 ) { cvsWidth = 1024; } repositionMonsters(); } function repositionMonsters() { cvsWidth = Math.floor(ctx.canvas.width/16+1)*16; cvsHeight = Math.floor(ctx.canvas.height/16+1)*16; var left = $("#cvsGame").offset().left + $("#cvsGame").position().left; var top = $("#cvsGame").offset().top + $("#cvsGame").position().top; var centerX = cvsWidth/2; var centerY = cvsHeight/2; //if( top > 158 ) { //centerY += top-158; //} curMonImage.style.left = (centerX-120-curMonImage.width/2) + 'px'; curMonImage.style.top = (centerY-curMonImage.height/2+70) + 'px'; curOppImage.style.left = (centerX+120-curOppImage.width/2) + 'px'; curOppImage.style.top = (centerY-curOppImage.height/2) + 'px'; } function loadedMapImage() { mapLoadedCount++; } function resourceByKey(key) { for(var i=0;i<screenResources.length;i++) { if( screenResources[i].key == key) return screenResources[i].img; } return null; } function musicResourceByKey(key) { for(var i=0;i<musicResources.length;i++) { if( musicResources[i].key == key) return musicResources[i]; } return null; } function effectResourceByKey(key) { for(var i=0;i<effectResources.length;i++) { if( effectResources[i].key == key) return effectResources[i].audio;
  • 22. } return null; } function loadedMusicResource() { MusicResourceLoadedCount++; } function loadedEffectResource() { EffectResourceLoadedCount++; } function loadedResource() { ImageResourceLoadedCount++; for(var k=0;k<screenResources.length;k++) { if( this.src.indexOf(screenResources[k].url) > -1 ) { screenResources[k].width = this.width; screenResources[k].height = this.height; } } } function loadImages() { //Images screenResources.push(new ResourceImage("http://cache.pokemonlegends.com/images/battlescreen.png","battlesc reen")); screenResources.push(new ResourceImage("http://cache.pokemonlegends.com/images/BattleIcon.png","battleico n")); screenResources.push(new ResourceImage("http://cache.pokemonlegends.com/images/pokeball_bubble.png","po keballicon")); screenResources.push(new ResourceImage("http://cache.pokemonlegends.com/images/pokemonEgg.png","poke monegg")); screenResources.push(new ResourceImage("http://cache.pokemonlegends.com/images/btnHighlightAttack.png"," btnHighlightAttack")); screenResources.push(new ResourceImage("http://cache.pokemonlegends.com/images/btnHighlightOption.png"," btnHighlightOption")); screenResources.push(new ResourceImage("http://cache.pokemonlegends.com/images/btnHighlightSwap.png","b tnHighlightSwap")); var elements = new Array("ani-air","ani-ancient","ani-basic","ani- demonic","ani-divine","ani-earth","ani-electric","ani-fire","ani-ghost","ani- psychic","ani-steel","ani-water", "ani-berserk","ani-confusion","ani-heal","ani- paralyze","ani-poison","ani-seed","ani-sleep"); for(var k=0;k<elements.length;k++) screenResources.push(new
  • 23. ResourceImage("http://cache.pokemonlegends.com/images/typeanimations/"+element s[k]+".png",elements[k])); //sfx effectResources.push(new ResourceEffect("http://cache.pokemonlegends.com/audio/MonAppear.wav","MonApp ear")); effectResources.push(new ResourceEffect("http://cache.pokemonlegends.com/audio/beep.wav","beep")); effectResources.push(new ResourceEffect("http://cache.pokemonlegends.com/audio/door.wav","door")); effectResources.push(new ResourceEffect("http://cache.pokemonlegends.com/audio/hit.mp3","hit")); effectResources.push(new ResourceEffect("http://cache.pokemonlegends.com/audio/intro.mp3","intro")); effectResources.push(new ResourceEffect("http://cache.pokemonlegends.com/audio/levelup.mp3","levelup")); effectResources.push(new ResourceEffect("http://cache.pokemonlegends.com/audio/coinchange.mp3","coinchan ge")); effectResources.push(new ResourceEffect("http://cache.pokemonlegends.com/audio/battle.wav","battle")); //music musicResources.push(new ResourceMusic("http://cache.pokemonlegends.com/audio/Vaniville Town.mp3","vanivilletown")); musicResources.push(new ResourceMusic("http://cache.pokemonlegends.com/audio/Route 8.mp3","route8")); musicResources.push(new ResourceMusic("http://cache.pokemonlegends.com/audio/victory.mp3","victory")); musicResources.push(new ResourceMusic("http://cache.pokemonlegends.com/audio/Scary House.mp3","cave")); musicResources.push(new ResourceMusic("http://cache.pokemonlegends.com/audio/fail.mp3","fail")); musicResources.push(new ResourceMusic("http://cache.pokemonlegends.com/audio/healing.mp3","healing")); musicResources.push(new ResourceMusic("http://cache.pokemonlegends.com/audio/Pokemon Center.mp3","pokecenter")); musicResources.push(new ResourceMusic("http://cache.pokemonlegends.com/audio/overworld1.mp3","overworl d1")); musicResources.push(new ResourceMusic("http://cache.pokemonlegends.com/audio/overworld2.mp3","overworl d2")); musicResources.push(new ResourceMusic("http://cache.pokemonlegends.com/audio/Magic Forest.mp3","Magic Forest")); musicResources.push(new ResourceMusic("http://cache.pokemonlegends.com/audio/battle1.mp3","battle1")); musicResources.push(new ResourceMusic("http://cache.pokemonlegends.com/audio/tournament.mp3","tourname nt"));
  • 24. musicResources.push(new ResourceMusic("http://cache.pokemonlegends.com/audio/Sharks.mp3","Sharks")); musicResources.push(new ResourceMusic("http://cache.pokemonlegends.com/audio/Dark Intentions.mp3","Dark Intentions")); } //Loads all NPC and main character sprites into an array function loadCharacterSets() { //no longer used. All are loaded from explore.php. } function loadedSprite() { charsetLoadedCount++; } //Adds a sprite to the charsets array function addCharset(imgURL) { var newImage = new Image(); newImage.src = imgURL; newImage.onload = loadedSprite; charsets.push(newImage); } //### SCRIPTING FUNCTIONS ############## function triggerEvent( Event, fromCollision) { if( Event.bEventEnabled ) { lastTriggeredEventName = Event.name; //face the user if( Event.mapPosition.X > userEvent.mapPosition.X ) { scriptAddLine("move event",Event.id + "^Face Left^1"); } else if( Event.mapPosition.X < userEvent.mapPosition.X ) { scriptAddLine("move event",Event.id + "^Face Right^1"); } else if( Event.mapPosition.Y > userEvent.mapPosition.Y+2 ) { scriptAddLine("move event",Event.id + "^Face Up^1"); } else if( Event.mapPosition.Y < userEvent.mapPosition.Y+2 ) { scriptAddLine("move event",Event.id + "^Face Down^1"); } for(var i=0;i<Event.eventData.length;i++) { activeScript.push(Event.eventData[i]); } if( activeScript.length > 0 ) { scriptProgress(); return true; } else {
  • 25. return false; } } return false; } //### KEY PRESS / MOUSE FUNCTIONS ############## function getPosition(e) { e = e || window.event; var cursor = {x:0, y:0}; if (e.pageX || e.pageY) { cursor.x = e.pageX; cursor.y = e.pageY; } else { var de = document.documentElement; var b = document.body; cursor.x = e.clientX + (de.scrollLeft || b.scrollLeft) - (de.clientLeft || 0); cursor.y = e.clientY + (de.scrollTop || b.scrollTop) - (de.clientTop || 0); } return cursor; } function hitTest(x,y,boxX1,boxY1,boxX2,boxY2) { if( x >= boxX1 && x <= boxX2 ) { if( y >= boxY1 && y <= boxY2 ) { return true; } } return false; } function checkMousePosition(posX,posY) { var boxWidth = 160; var boxHeight = 40; var centerX = cvsWidth/2; var centerY = cvsHeight/2; var boxX = centerX+46; var boxY = centerY+110-50; if( hitTest(posX,posY,boxX-boxWidth/2,boxY- boxHeight/2,boxX+boxWidth/2,boxY+boxHeight/2) ) { return "atk1"; } boxX = centerX+174; boxY = centerY+110-50; if( hitTest(posX,posY,boxX-boxWidth/2,boxY- boxHeight/2,boxX+boxWidth/2,boxY+boxHeight/2) ) { return "atk2"; }
  • 26. boxX = centerX+46; boxY = centerY+145-50; if( hitTest(posX,posY,boxX-boxWidth/2,boxY- boxHeight/2,boxX+boxWidth/2,boxY+boxHeight/2) ) { return "atk3"; } boxX = centerX+174; boxY = centerY+145-50; if( hitTest(posX,posY,boxX-boxWidth/2,boxY- boxHeight/2,boxX+boxWidth/2,boxY+boxHeight/2) ) { return "atk4"; } boxWidth = 100; boxX = centerX-232+45; boxY = centerY+125-40; if( hitTest(posX,posY,boxX-boxWidth/2,boxY- boxHeight/2,boxX+boxWidth/2,boxY+boxHeight/2) ) { return "run"; } boxX = centerX-138+45; boxY = centerY+125-40; if( hitTest(posX,posY,boxX-boxWidth/2,boxY- boxHeight/2,boxX+boxWidth/2,boxY+boxHeight/2) ) { return "item"; } boxWidth = 50; boxHeight = 50; boxX = centerX-220; boxY = centerY-111-80; if( hitTest(posX,posY,boxX-boxWidth/2,boxY- boxHeight/2,boxX+boxWidth/2,boxY+boxHeight/2) ) { return "swap"; } if( battleSelectedMenu > 6 && battleSelectedMenu <= 12 ) { for(var k=0;k< teamMonsters.length;k++) { var pos = k+1; var x = centerX; var y = centerY-75-60; if( pos < 4 ) { x = x - 110; y = y + pos * 30; } else { x = x + 110; y = y + (pos-3) * 30; } boxWidth = 200;
  • 27. boxHeight = 40; boxX = x; boxY = y; if( hitTest(posX,posY,boxX-boxWidth/2,boxY- boxHeight/2,boxX+boxWidth/2,boxY+boxHeight/2) ) { return "swap" + pos; } } } if( battleSelectedMenu == 13 ) { for(var k=0;k< battleItems.length;k++) { var pos = k+1; var x = centerX; var y = centerY-75-60; if( pos < 5 ) { x = x - 110; y = y + pos * 30; } else { x = x + 110; y = y + (pos-4) * 30; } boxWidth = 200; boxHeight = 40; boxX = x; boxY = y; if( hitTest(posX,posY,boxX-boxWidth/2,boxY- boxHeight/2,boxX+boxWidth/2,boxY+boxHeight/2) ) { return "item" + pos; } } } return ""; } function canvasMouseDown(e) { var pos = getPosition(e); var centerX = cvsWidth/2; var centerY = cvsHeight/2; bMouseDown = true; var left = $("#cvsGame").offset().left + $("#cvsGame").position().left; var top = $("#cvsGame").offset().top + $("#cvsGame").position().top; var posX = pos.x-left; var posY = pos.y-top; /* var pos = getPosition(e); if( pos.x - left < 64 ) {
  • 28. keyState.left = true; } else if( pos.x - left > cvsWidth - 64 ) { keyState.right = true; } else if( pos.y - top < 64 ) { keyState.up = true; } else if( pos.y - top > cvsHeight - 64 ) { keyState.down = true; } else { keyState.btn1 = true; } */ if( bInBattle ) { if( battleScript.length > 0 ) { keyState.btn1 = true; } else { var activeMenu = checkMousePosition(posX,posY); if( activeMenu != "") { if( activeMenu != "item" && activeMenu != "swap" ) { keyState.btn1 = true; } } } } else { document.getElementById('mws-explore-trade-or-battle').innerHTML = ""; for(var i=0;i< mmoUsers.length;i++) { var user = mmoUsers[i]; if( pos.x-left > user.drawPosX && pos.x-left < user.drawPosX +32 ) { if( pos.y-top < user.drawPosY && pos.y-top > user.drawPosY -48 ) { if( user.name.indexOf("'s Pet") == -1 ) { displayMMOUser(user); } } } } } return false; } function canvasMouseUp(e) { var pos = getPosition(e); var centerX = cvsWidth/2; var centerY = cvsHeight/2; bMouseDown = false; //var pos = getPosition(e); /*
  • 29. keyState.up = false; keyState.down = false; keyState.left = false; keyState.right = false; keyState.btn1 = false; keyState.btn2 = false; keyState.btn3 = false; */ return false; } function canvasMouseMove(e) { var pos = getPosition(e); var centerX = cvsWidth/2; var centerY = cvsHeight/2; var left = $("#cvsGame").offset().left + $("#cvsGame").position().left; var top = $("#cvsGame").offset().top + $("#cvsGame").position().top; var posX = pos.x-left; var posY = pos.y-top; if( bInBattle ) { if( battleScript.length == 0 ) { var activeMenu = checkMousePosition(posX,posY); if( activeMenu == "atk1" && parseInt(battleStage) != 1) { battleSelectedMenu = 2; } else if( activeMenu == "atk2" && parseInt(battleStage) != 1) { battleSelectedMenu = 3; } else if( activeMenu == "atk3" && parseInt(battleStage) != 1) { battleSelectedMenu = 4; } else if( activeMenu == "atk4" && parseInt(battleStage) != 1) { battleSelectedMenu = 5; } else if( activeMenu == "run" && parseInt(battleStage) != 1) { battleSelectedMenu = 0; } else if( activeMenu == "item" && battleSelectedMenu != 13 && parseInt(battleStage) != 1) { battleSelectedMenu = 13; } else if( activeMenu == "swap" && parseInt(battleStage) != 1 ) { battleSelectedMenu = 7; } else if( activeMenu.indexOf('swap') > -1 && activeMenu != "swap" ) { var pos = parseInt(activeMenu.replace(/swap/gi,'')); battleSelectedMenu = pos+6; } else if( activeMenu.indexOf('item') > -1 && battleSelectedMenu == 13 && parseInt(battleStage) != 1 ) { var pos = parseInt(activeMenu.replace(/item/gi,'')); battleItemSelectedMenu = pos-1; } if( activeMenu != "" )
  • 30. battleUpdatedMenu(); } } /* keyState.up = false; keyState.down = false; keyState.left = false; keyState.right = false; keyState.btn1 = false; keyState.btn2 = false; keyState.btn3 = false; var left = $("#cvsGame").offset().left + $("#cvsGame").position().left; var top = $("#cvsGame").offset().top + $("#cvsGame").position().top; if( pos.x - left < 64 ) { keyState.left = true; } else if( pos.x - left > cvsWidth - 64 ) { keyState.right = true; } else if( pos.y - top < 64 ) { keyState.up = true; } else if( pos.y - top > cvsHeight - 64 ) { keyState.down = true; } */ } //### MMO FUNCTIONS ############### function displayMMOUser(user) { var div = document.getElementById('mws-explore-trade-or-battle'); var html = "<center><b>" + user.name + "</b><br/>"; //html += '<input type="button" style="width:120px;" class="mws-tooltip-s mws-button blue" value="Trade" title="Offer to Trade with this Player."><br/>'; html += '<input type="button" style="width:120px;" class="mws-tooltip-s mws-button red" value="Battle" onclick="pvpRequest('' + user.name + '');" title="Request a Battle with this Player."><br/>'; html += '<input type="button" style="width:120px;" class="mws-tooltip-s mws-button green" value="PM" onclick="pmUser('' + user.name + '')" title="Send a Private Message to this Player."><br/>'; html += "</center>"; div.innerHTML = html; } function pmUser(name) { document.getElementById("txtUpdate").value = "/pm " + name + " "; document.getElementById("txtUpdate").focus(); } function pvpRequest(name) {
  • 31. ws.send("/msg^/pvprequest " + name + "rnrn"); document.getElementById('mws-explore-trade-or-battle').innerHTML = ""; } function pvpAccept(name) { ws.send("/msg^/pvpaccept " + name + "rnrn"); document.getElementById("mws-explore-requests").innerHTML = ""; } function pvpRequested(data) { var dataRow = data.split("^"); document.getElementById("mws-explore-requests").innerHTML = '<div style="padding:8px;"><b>'+dataRow[1]+'</b> wants to battle: <br/><center><input type="button" style="width:120px;" class="mws-tooltip-s mws-button green" value="Accept PvP" onclick="pvpAccept('' +dataRow[1]+ '')" title="Accept"></center></div>'; } var userCount = "?"; function serverPing(data) { var dataRow = data.split("^"); userCount = parseInt(dataRow[1]); } function pvpLoadBattle(data) { var dataRow = data.split("^"); battleRoundTacker = 0; curOpp = null; nextOpp = null; curMon = null; nextMon = null; curMonImage.src = 'http://cache.pokemonlegends.com/images/blank.png'; curOppImage.src = 'http://cache.pokemonlegends.com/images/blank.png'; battleLoading = false; //battle_id needs to be provided. curOpp = null; scriptAddLine("battlescreen","PVP"); //bInBattle = true; - this is set in the above script funciton battleSelectedMenu = 2; playSFX("battle"); playMusic("battle1"); if( prevPlayingSong ) prevPlayingSong.currentTime = 0; bWildBattle = false; wipeWildMonsterBox(); } function updateChat(data) { var dataRow = data.split("^"); var dataMsg = dataRow[1].split("|"); var isadmin = dataMsg[0]; var userids = dataMsg[1];
  • 32. var user = dataMsg[2]; var msg = dataMsg[3]; var isPM = dataMsg[4]; var changeColor = true; var title = "A Legend"; messages.push(new ChatMessage(isadmin,userids,user,msg)); var sender = mmoUserByName(user); if( sender != null ) { sender.msg = msg; sender.msgTick = 0; } else { if( userids == userID ) { userEvent.msg = msg; userEvent.msgTick = 0; } } if (msg.toLowerCase().indexOf(userName.toLowerCase()) > -1) { color = "#CE93D8"; changeColor = false; } if (changeColor) //if name is mentioned on a word, do not change unless it's PM. PM is always in the special color. { var color = "#fff"; if( isadmin > 1 ) { color = "#99FF99"; title = "Game Moderators"; } else if ( isadmin == 1) { color = "#72C065"; title = "Chat Moderators"; } if (isadmin > 2) { title = "Administrators"; } if( userids == 0 ) { color = "#FF9999"; } if ( msg.toLowerCase().indexOf("pm to") > -1 && user.toLowerCase().indexOf("you") > -1) //pm sent msg { color = "#FFCC99"; } } if (isPM == 1) {
  • 33. color = "#FFCC99"; } //sharks remove html tags from user input msg = msg.replace(/<(?:.|n)*?>/gm, ''); var html = "<p data-username='"+user+"' onclick=quickPM(this) style='color:"+color+";margin-bottom:2px;'><b>"; if (userids > 0) { html = html + "<a href='user?id="+userids+"' style='color:"+color+"' target='_blank' title = '"+title+"'>"; } html = html + user; if (userids > 0) { html = html + "</a>"; } html = html + ":</b> " + msg + "</p>"; $('#chat').append(html); $('#chat')[0].scrollTop = $('#chat')[0].scrollHeight; } function quickPM(msg) { if (msg.getAttribute("data-username") != "You" ) document.getElementById("txtUpdate").value = "/pm "+msg.getAttribute("data-username")+" "; } //### AUDIO FUNCTIONS ############### function restoreLastSong() { if( musicEnabled == false ) return; if( prevPlayingSong ) prevPlayingSong.play(); } function playMusicOnce(key) { if( musicEnabled == false ) return; var audio = musicResourceByKey(key); if( audio ) { if( prevPlayingSong ) prevPlayingSong.pause();
  • 34. if( playOnceSong ) playOnceSong.pause(); if( audio.audio == null ) { audio.audio = new Audio(); audio.audio.src = audio.src; audio.audio.volume = 0.5; //this.audio.play(); //this.audio.pause(); } audio.audio.loop = false; audio.audio.addEventListener('ended', restoreLastSong); audio.audio.currentTime = 0; audio.audio.play(); playOnceSong = audio.audio; } } function playMusic(key) { if( musicEnabled == false ) return; var audio = musicResourceByKey(key); if( audio ) { if( prevPlayingSong ) prevPlayingSong.pause(); if( playOnceSong ) playOnceSong.pause(); if( audio.audio == null ) { audio.audio = new Audio(); audio.audio.src = audio.src; audio.audio.volume = 0.35; //this.audio.play(); //this.audio.pause(); } audio.audio.loop = true; audio.audio.play(); prevPlayingSong = audio.audio; prevPlaying = key; } } function playSFX(key) { if( soundEnabled == false ) return; var audio = effectResourceByKey(key); if( audio ) { audio.play(); }
  • 35. } //### SUPPORT FUNCTIONS ############### function isNumber(n) { return !isNaN(parseFloat(n)) && isFinite(n); } // ################################################ // ### MMO USER CLASS ########################### // ################################################ function MMOUser(id,name,trainerimg) { this.id = id; this.name = name; this.trainerimg = trainerimg; this.mapid = 0; this.x = 0; this.y = 0; this.NewX = 0; this.NewY = 0; this.direction = 0; this.step = 0; this.inbattle = 0; this.drawPosX = 0; this.drawPosY = 0; this.drawStartX = 0; this.drawStartY = 0; this.isRunning = 0; this.stepPart = 0; this.stepAnimation = 0; this.offsetX = 0; this.offsetY = 0; this.stepX = 0; this.stepY = 0; this.moveQueue = new Array(); this.msg = ""; this.msgTick = 0; this.frameCount = 2; this.ImageRef = null; this.updated = false; this.evaluate = function() { this.stepX = 0;
  • 36. this.stepY = 0; if( this.moveQueue.length > 0 ) { if( this.moveQueue[0] == "up" ) { this.stepY = -this.stepPart; } else if( this.moveQueue[0] == "down" ) { this.stepY = this.stepPart; } else if( this.moveQueue[0] == "left" ) { this.stepX = -this.stepPart; } else { this.stepX = this.stepPart; } } this.drawPosX = mapLeft + (this.x * 16)+ this.stepX +13; this.drawPosY = -mapTop-currentMap.mapHeight/2 + ((this.y+2) * 16)+ this.stepY +2-130+32; var additionalDown = currentMap.mapHeight/2-cvsHeight/2; this.drawPosY = -mapTop-cvsHeight/2-currentMap.mapHeight/2 + ((this.y+2) * 16) + this.stepY +2+28 + (additionalDown-192); this.updateTextureCoords(); //process move queue - in between movequeue syncs check for position reevaluate this.processMoveQueue(); if( this.msg != "" ) { this.msgTick++; if( this.msgTick > 250 ) { this.msg = ""; } } } this.updatesWithoutMove = 0; this.processMoveQueue = function() // Define Method { if( currentMap == null ) { return false; } if( this.moveQueue.length > 0 ) { if( this.moveQueue[0].toLowerCase() == "up" ) { this.direction = 0; } else if( this.moveQueue[0].toLowerCase() == "down" ) { this.direction = 1; } else if( this.moveQueue[0].toLowerCase() == "left" ) { this.direction = 2; } else if( this.moveQueue[0].toLowerCase() == "right" ) { this.direction = 3; }
  • 37. if( this.stepPart == 8 || this.stepPart == 0 ) { this.stepAnimation++; if( this.stepAnimation > this.frameCount ) this.stepAnimation = 0; } this.stepPart = this.stepPart + 4; if( this.isRunning == 1 && this.moveQueue.length == 1 ) this.stepPart = this.stepPart + 4; if( this.stepPart >= 16 ) { this.stepPart = 0; //update the coordanates at the end of the step. if( this.moveQueue[0] == "up" ) { this.y = this.y - 1; } else if( this.moveQueue[0] == "down" ) { this.y = this.y + 1; } else if( this.moveQueue[0] == "left" ) { this.x = this.x - 1; } else { this.x = this.x + 1; } this.moveQueue.splice(0,1); if( Math.abs(this.NewX - this.x) > 6 || Math.abs(this.NewY - this.y) > 6 ) { this.x = this.NewX; this.y = this.NewY; this.moveQueue.length = 0; } } } if( this.moveQueue.length == 0 ) { //add to moveQueue based on position if( this.y > this.NewY ) { if( currentMap.tileIsWalkable( Point(this.x,this.y-2-1)) ) { this.addMoveQueue("up"); } } else if( this.y < this.NewY ) { if( currentMap.tileIsWalkable( Point(this.x,this.y-2+1)) ) { this.addMoveQueue("down"); } } else if( this.x > this.NewX ) { if( currentMap.tileIsWalkable( Point(this.x-1,this.y-2)) ) { this.addMoveQueue("left"); } } else if( this.x < this.NewX ) { if( currentMap.tileIsWalkable( Point(this.x+1,this.y-2)) ) {
  • 38. this.addMoveQueue("right"); } } this.updatesWithoutMove++; if( this.updatesWithoutMove > 10 ) { this.x=this.NewX; this.y=this.NewY; this.updatesWithoutMove = 0; } } else { this.updatesWithoutMove = 0; } } this.addMoveQueue = function(moveDirection) // Define Method { this.moveQueue.push(moveDirection.toLowerCase()); } this.drawNames = function(ctx) // Define Method { if( this.name.indexOf("'s Pet") > -1 ) { return; } ctx.font = "bold 11px sans-serif"; ctx.textAlign = "center"; drawShadowText(ctx,this.name, this.drawPosX+12, this.drawPosY-1); if( this.msg != "" ) { drawShadowText(ctx,this.msg, this.drawPosX+12, this.drawPosY- 14,"#c4d52b"); } } this.drawImage = function(ctx) // Define Method { //context.drawImage(img,sx,sy,swidth,sheight,dx,dy,dwidth,dheight); if( this.ImageRef == null ) { for(var i=0;i< charsets.length;i++) { var img = charsets[i]; if( img.src ) { if( img.src.indexOf("/" + this.trainerimg) > 0 ) { this.ImageRef = img; if( img.width == 64 ) { this.frameCount = 1; } if( img.width == 32 ) { this.frameCount = 0;
  • 39. } } } } } if( this.ImageRef != null ) { ctx.drawImage(this.ImageRef, this.drawStartX, this.drawStartY, 32, 32, this.drawPosX-5, this.drawPosY, 32, 32 ); } if( parseInt(this.inbattle) == 1 ) { ctx.drawImage(resourceByKey("pokeballicon"), this.drawPosX+4, this.drawPosY-26); } } this.updateTextureCoords = function() // Define Method { var startX = 0; var startY = 0; if( this.direction == 0 ) { switch(this.stepAnimation) { case 0 : startX = 0; startY = 0; break; case 1 : startX = 1; startY = 0; break; case 2 : startX = 2; startY = 0; break; } } else if( this.direction == 1 ) { switch(this.stepAnimation) { case 0 : startX = 0; startY = 1; break; case 1 : startX = 1; startY = 1; break; case 2 : startX = 2;
  • 40. startY = 1; break; } } else if( this.direction == 2 ) { switch(this.stepAnimation) { case 0 : startX = 0; startY = 2; break; case 1 : startX = 1; startY = 2; break; case 2 : startX = 2; startY = 2; break; } } else { switch(this.stepAnimation) { case 0 : startX = 0; startY = 3; break; case 1 : startX = 1; startY = 3; break; case 2 : startX = 2; startY = 3; break; } } this.drawStartX = startX*32; this.drawStartY = startY*32; } return this; } var mmoUsers = new Array(); function updateMMOEvents(updateData) { for(var k=0;k<mmoUsers.length;k++) { mmoUsers[k].updated = false; } var dataRaw = updateData.split("^"); for(var k=1;k<dataRaw.length;k++) { if( dataRaw[k] != "" ) { var dataUser = dataRaw[k].split("|"); var user = mmoUserByName(dataUser[1]);
  • 41. if( user == null ) { //add id,name,trainerimg user = new MMOUser(dataUser[0],dataUser[1],dataUser[2]); mmoUsers.push(user); } //update mapid,x,y,direction,step,inbattle user.mapid = dataUser[3]; user.NewX = parseInt(dataUser[4]); user.NewY = parseInt(dataUser[5]); if( user.x == 0 ) { user.x = user.NewX; user.y = user.NewY; } user.direction = parseInt(dataUser[6]); user.step = parseInt(dataUser[7]); user.isRunning = parseInt(dataUser[8]); user.inbattle = dataUser[9]; user.updated = true; } } //remove old connections for(var k=0;k<mmoUsers.length;k++) { if( k < mmoUsers.length ) { if( mmoUsers[k].updated == false ) { mmoUsers.splice(k,1); k--; } } } } function mmoUserByName(name) { for(var k=0;k<mmoUsers.length;k++) { if( name == mmoUsers[k].name ) { return mmoUsers[k]; } } return null; } function Point(x,y) { this.X = x; this.Y = y; return this; }
  • 42. // ################################################ // ### GAME EVENT CLASS ########################### // ################################################ function ScriptLine(line,func,args) { this.func = func; this.args = args; this.line = line; return this; } function GameEgg(node) { if( node ) { this.id = nodeValue(firstChildNodeNamed("id", node)); this.steps = nodeValue(firstChildNodeNamed("steps", node)); } return this; } function GameItem(node) { if( node ) { this.id = nodeValue(firstChildNodeNamed("id", node)); this.name = nodeValue(firstChildNodeNamed("name", node)); this.file = nodeValue(firstChildNodeNamed("file", node)); this.qty = nodeValue(firstChildNodeNamed("qty", node)); } return this; } function gameEvent(node) { this.moveQueue = new Array(); this.mapPosition = new Object; this.bEventEnabled = false; this.bHidden = false; this.bIsUser = true; this.id = 0; this.name = ""; this.mapPosition.X = 0; this.mapPosition.Y = 0; this.spriteName = ""; this.type = ""; this.direction = 0; this.moveType = ""; this.quest = 0; this.frameCount = 2;
  • 43. //Event Properties this.eventData = new Array(); this.mapPosition.X = 0; this.mapPosition.Y = 0; //Core Variables if( node ) { this.id = nodeValue(firstChildNodeNamed("id", node)); this.name = nodeValue(firstChildNodeNamed("name", node)); this.mapPosition.X = parseInt(nodeValue(firstChildNodeNamed("x", node)))-1; this.mapPosition.Y = parseInt(nodeValue(firstChildNodeNamed("y", node)))+1; this.type = nodeValue(firstChildNodeNamed("type", node)); this.spriteName = nodeValue(firstChildNodeNamed("style", node)); this.direction = parseInt(nodeValue(firstChildNodeNamed("direction", node))); this.moveType = nodeValue(firstChildNodeNamed("movement", node)); this.bIsUser = false; this.bEventEnabled = true; this.quest = parseInt(nodeValue(firstChildNodeNamed("quest", node))); var script = firstChildNodeNamed("script", node); for(var i=0;i<script.childNodes.length;i++) { line = script.childNodes[i]; this.eventData.push(new ScriptLine( nodeValue(firstChildNodeNamed("line", line)) , nodeValue(firstChildNodeNamed("function", line)) , nodeValue(firstChildNodeNamed("arguments", line)) )); } } //Movement this.stepPart = 0; this.stepAnimation = 0; this.bJumping = false;; this.jumpYAdd = 0; this.jumpYAcc = 0; this.drawStartX = 0; this.drawStartY = 0; this.X = 0; this.Y = 0; this.offsetX = 0; this.offsetY = 0; this.stepX = 0; this.stepY = 0;
  • 44. this.msg = ""; this.msgTick = 0; this.bHasAppearance = false; if( this.spriteName != "" ) { this.bHasAppearance = true; } this.ImageRef = null; this.drawImage = function(ctx) // Define Method { //context.drawImage(img,sx,sy,swidth,sheight,dx,dy,dwidth,dheight); if( this.ImageRef == null ) { for(var i=0;i< charsets.length;i++) { var img = charsets[i]; if( img.src ) { if( img.src.indexOf("/" + this.spriteName) > 0 ) { this.ImageRef = img; if( img.width == 64 ) { this.frameCount = 1; } if( img.width == 32 ) { this.frameCount = 0; } } } } } if( this.ImageRef != null ) { if( this.bHidden == false ) { ctx.drawImage(this.ImageRef, this.drawStartX, this.drawStartY, 32, 32, this.X-5, this.Y, 32, 32 ); if( parseInt(this.quest) > 0 ) { ctx.drawImage(resourceByKey("battleicon"), this.X+2, this.Y-14); } } } } this.initWithData = function(data) // Define Method { this.processConditions(); this.evaluate(); } this.initAsPlayer = function(position) // Define Method
  • 45. { this.bIsUser = true; this.bEventEnabled = true; this.spriteName = userSprite; this.direction = 1; this.mapPosition.X = position.X; this.mapPosition.Y = position.Y; this.evaluate(); } this.processConditions = function() // Define Method { this.bEventEnabled = true; } this.addMoveQueue = function(moveDirection) // Define Method { this.moveQueue.push(moveDirection.toLowerCase()); } /* THESE NEED TO BE CODED TO HAPPEN WHEN THEY HIT THE TOP OF THE QUEUE ##### } else if( moveDirection.ToLower() == "jump" ) { bJumping = true; jumpYAcc = -8; bAllow = true; } else if( moveDirection.ToLower() == "face up" ) { direction = 0; } else if( moveDirection.ToLower() == "face down" ) { direction = 1; } else if( moveDirection.ToLower() == "face left" ) { direction = 2; } else if( moveDirection.ToLower() == "face right" ) { direction = 3; } else if( moveDirection.ToLower() == "hide" ) { sprite.Alpha = 0; bHidden = true; } else if( moveDirection.ToLower() == "show" ) { sprite.Alpha = 1; bHidden = false; } */ this.evaluate = function() // Define Method { if( this.bEventEnabled == false ) { return; }
  • 46. if( currentMap == null ) { return; } if( this.bIsUser == false && this.bHidden == false ) { this.processNPCMovement(); } this.processMoveQueue(); this.updatePosition(); if( this.msg != "" ) { this.msgTick++; if( this.msgTick > 250 ) { this.msg = ""; } } } this.processNPCMovement = function() // Define Method { if( this.moveQueue.length == 0 && activeScript.length == 0 && bInBattle == false) { if( this.moveType == "Slow Random" || this.moveType == "Fast Random" ) { //Random Movement if( Math.floor(Math.random() * 10) == 1 ) { var randDirection = Math.floor(Math.random() * 4); if( randDirection == 0 ) { if( currentMap.tileIsWalkable( Point(this.mapPosition.X,this.mapPosition.Y-2- 1)) ) { this.addMoveQueue("up"); } } else if( randDirection == 1 ) { if( currentMap.tileIsWalkable( Point(this.mapPosition.X,this.mapPosition.Y-2+1)) ) { this.addMoveQueue("down"); } } else if( randDirection == 2 ) { if( currentMap.tileIsWalkable( Point(this.mapPosition.X-1,this.mapPosition.Y- 2)) ) { this.addMoveQueue("left"); } } else { if( currentMap.tileIsWalkable( Point(this.mapPosition.X+1,this.mapPosition.Y-2)) ) { this.addMoveQueue("right"); } } } } else if( this.moveType == "Follow User" ) { var xDif = userEvent.mapPosition.X - this.mapPosition.X;
  • 47. var yDif = userEvent.mapPosition.Y + 2 - this.mapPosition.Y; steps = 0; var dir = ""; if( userEvent.moveQueue.length != 0 ) { if( xDif != 0 ) { if( xDif < 0 ) { dir = "left"; steps = -xDif-2; } else { dir = "right"; steps = xDif+2; } } if( yDif != 0 ) { if( yDif < 0 ) { dir = "up"; steps = -yDif; } else { dir = "down"; steps = yDif; } } if( dir != "" ) { this.addMoveQueue(dir); } } } } } this.processMoveQueue = function() // Define Method { if( currentMap == null ) { return false; } var bPassedCheck = false; if( !this.bIsUser ) { bPassedCheck = true; if( this.moveQueue.length > 0 ) { if( this.moveQueue[0].toLowerCase() == "face up" ) { this.direction = 0; this.moveQueue.splice(0,1); } else if( this.moveQueue[0].toLowerCase() == "face down" ) { this.direction = 1; this.moveQueue.splice(0,1); } else if( this.moveQueue[0].toLowerCase() == "face left" ) { this.direction = 2; this.moveQueue.splice(0,1); } else if( this.moveQueue[0].toLowerCase() == "face right" ) {
  • 48. this.direction = 3; this.moveQueue.splice(0,1); } else if( this.moveQueue[0].toLowerCase() == "hide" ) { this.bHidden = true; this.moveQueue.splice(0,1); } else if( this.moveQueue[0].toLowerCase() == "show" ) { this.bHidden = false; this.moveQueue.splice(0,1); } } } else { while( bPassedCheck == false ) { if( this.moveQueue.length > 0 ) { if( this.moveQueue[0] == "up" ) { if( ! currentMap.tileIsWalkable( Point(this.mapPosition.X,this.mapPosition.Y-1)) ) { this.moveQueue.splice(0,1); this.direction = 0; } else { bPassedCheck = true; } } else if( this.moveQueue[0] == "down" ) { if( ! currentMap.tileIsWalkable( Point(this.mapPosition.X,this.mapPosition.Y+1)) ) { this.moveQueue.splice(0,1); this.direction = 1; } else { bPassedCheck = true; } } else if( this.moveQueue[0] == "left" ) { if( ! currentMap.tileIsWalkable( Point(this.mapPosition.X-1,this.mapPosition.Y)) ) { this.moveQueue.splice(0,1); this.direction = 2; } else { bPassedCheck = true; } } else if( this.moveQueue[0] == "right" ) { if( ! currentMap.tileIsWalkable( Point(this.mapPosition.X+1,this.mapPosition.Y)) ) { this.moveQueue.splice(0,1); this.direction = 3; } else { bPassedCheck = true; } } else if( this.moveQueue[0] == "jump" ) { bPassedCheck = true; } else if( this.moveQueue[0].toLowerCase() == "face up" ) { this.direction = 0; this.moveQueue.splice(0,1); } else if( this.moveQueue[0].toLowerCase() == "face down" ) { this.direction = 1; this.moveQueue.splice(0,1);
  • 49. } else if( this.moveQueue[0].toLowerCase() == "face left" ) { this.direction = 2; this.moveQueue.splice(0,1); } else if( this.moveQueue[0].toLowerCase() == "face right" ) { this.direction = 3; this.moveQueue.splice(0,1); } else if( this.moveQueue[0].toLowerCase() == "hide" ) { this.bHidden = true; this.moveQueue.splice(0,1); } else if( this.moveQueue[0].toLowerCase() == "show" ) { this.bHidden = false; this.moveQueue.splice(0,1); } else { bPassedCheck = true; } } else { bPassedCheck = true; } if( bPassedCheck == false ) { //this.moveQueue.splice(0, 1); } } } if( this.moveQueue.length > 0 ) { if( this.moveQueue[0].toLowerCase() == "up" ) { this.direction = 0; } else if( this.moveQueue[0].toLowerCase() == "down" ) { this.direction = 1; } else if( this.moveQueue[0].toLowerCase() == "left" ) { this.direction = 2; } else if( this.moveQueue[0].toLowerCase() == "right" ) { this.direction = 3; } else if( this.moveQueue[0].toLowerCase() == "jump" ) { this.jumpYAcc = this.jumpYAcc + 2; this.jumpYAdd = this.jumpYAdd + this.jumpYAcc; if( this.jumpYAcc == 4 ) { this.jumpYAcc = 0; this.jumpYAdd = 0; this.bJumping = false; this.moveQueue.splice(0,1); } return; } if( this.stepPart == 8 || this.stepPart == 0 ) { this.stepAnimation++; if( this.stepAnimation > this.frameCount )
  • 50. this.stepAnimation = 0; } this.stepPart = this.stepPart + 4; if( this.moveType == "Slow Random" ) this.stepPart = this.stepPart - 2; if( keyState.btn2 && this.moveQueue.length == 1 && (this.bIsUser || this.id==-1)) this.stepPart = this.stepPart + 4; if( this.stepPart >= 16 ) { this.stepPart = 0; //update the coordanates at the end of the step. if( this.moveQueue[0] == "up" ) { this.mapPosition.Y = this.mapPosition.Y - 1; } else if( this.moveQueue[0] == "down" ) { this.mapPosition.Y = this.mapPosition.Y + 1; } else if( this.moveQueue[0] == "left" ) { this.mapPosition.X = this.mapPosition.X - 1; } else { this.mapPosition.X = this.mapPosition.X + 1; } if( this.bIsUser ) { if( activeScript.length == 0 ) { if( this.eventCheck() == true ) { this.arrivedOnTile(); } } } this.moveQueue.splice(0,1); } } } this.eventCheck = function() // Define Method { for(var i=0;i<currentMap.events.length;i++) { var evnt = currentMap.events[i]; if( evnt.mapPosition.X == userEvent.mapPosition.X && evnt.mapPosition.Y == userEvent.mapPosition.Y + 2 ) { if (evnt.type == "On Walk" && evnt.bEventEnabled && activeScript.length == 0 && evnt.eventData.length > 0) { if( triggerEvent( evnt , false) ) { return false; }
  • 51. } } //type if( evnt.bEventEnabled && (evnt.type == "X1" || evnt.type == "X2" || evnt.type == "X3" || evnt.type == "X10" || evnt.type == "X15") && activeScript.length == 0 && evnt.eventData.length > 0 ) { var stepsCheck = 1; if( evnt.type == "X2" ) stepsCheck = 2; if( evnt.type == "X3" ) stepsCheck = 3; if( evnt.type == "X10" ) stepsCheck = 10; if( evnt.type == "X15" ) stepsCheck = 15; for(var check = 1;check <= stepsCheck;check++) { if( evnt.mapPosition.X+check == userEvent.mapPosition.X && evnt.mapPosition.Y == userEvent.mapPosition.Y + 2 && evnt.direction == 3 ) { if( triggerEvent( evnt , true) ) { return false; } } if( evnt.mapPosition.X-check == userEvent.mapPosition.X && evnt.mapPosition.Y == userEvent.mapPosition.Y + 2 && evnt.direction == 2 ) { if( triggerEvent( evnt , true) ) { return false; } } if( evnt.mapPosition.X == userEvent.mapPosition.X && evnt.mapPosition.Y+check == userEvent.mapPosition.Y + 2 && evnt.direction == 1 ) { if( triggerEvent( evnt , true) ) { return false; } } if( evnt.mapPosition.X == userEvent.mapPosition.X && evnt.mapPosition.Y-check == userEvent.mapPosition.Y + 2 && evnt.direction == 0 ) { if( triggerEvent( evnt , true) ) { return false; } } } } } return true; } this.arrivedOnTile = function() // Define Method { if( this.mapPosition.X == -1 ) { if( firstChildNodeNamed("west", mapEvents) != null ) {
  • 52. loadMap(nodeValue(firstChildNodeNamed("west", mapEvents)), "wrap", 2) return; } } if( this.mapPosition.X+2 == Math.floor(mapWidth/16) ) { if( firstChildNodeNamed("east", mapEvents) != null ) { loadMap(nodeValue(firstChildNodeNamed("east", mapEvents)), "wrap", 3) return; } } if( this.mapPosition.Y+2 == Math.floor(mapHeight/16) ) { if( firstChildNodeNamed("south", mapEvents) != null ) { loadMap(nodeValue(firstChildNodeNamed("south", mapEvents)), "wrap", 1) return; } } if( this.mapPosition.Y == -1 ) { if( firstChildNodeNamed("north", mapEvents) != null ) { loadMap(nodeValue(firstChildNodeNamed("north", mapEvents)), "wrap", 0) return; } } if( this.isInGrass() ) { stepsInGrass++; } else { } if( stepsInGrass > 8 ) { if( parseInt(Math.random()*4) == 2 ) { //TODO: START A BATTLE!!! battleMonsterAtCoord(); stepsInGrass=0; } } if( activeScript.length == 0 ) { if( parseInt(Math.random()*15) == 2 ) { if( eggs.length > 0 ) { for(var i=0;i<eggs.length;i++) { if( eggs[i].steps > 45 ) { hatchingEgg = true; loadUtility("action=hatch"); break; } } }
  • 53. } } } this.isInGrass = function() // Define Method { for(var i=0;i<currentMap.grassPatches.length;i++) { var patch = currentMap.grassPatches[i]; if( this.mapPosition.X >= patch.X1 && this.mapPosition.X <= patch.X2-2 ) { if( this.mapPosition.Y+2 >= patch.Y1 && this.mapPosition.Y+2 <= patch.Y2 ) { return true; } } } return false; } this.updatePosition = function() // Define Method { var ySink = 0; this.stepX = 0; this.stepY = 0; this.offsetX = 0; this.offsetY = 0; var MyX = this.mapPosition.X * 16; var MyY = this.mapPosition.Y * 16; if( currentMap == null ) { return; } if( this.bIsUser == false ) { //NPC EVENT POSITIONING if( this.moveQueue.length > 0 ) { if( this.moveQueue[0] == "up" ) { this.stepY = -this.stepPart; } else if( this.moveQueue[0] == "down" ) { this.stepY = this.stepPart; } else if( this.moveQueue[0] == "left" ) { this.stepX = -this.stepPart; } else { this.stepX = this.stepPart; } }
  • 54. var additionalDown = currentMap.mapHeight/2-cvsHeight/2; this.X = mapLeft + MyX + this.stepX+13; //this.Y = -mapTop-currentMap.mapHeight/2 + MyY + this.stepY - Math.floor(this.jumpYAdd)+2-130+32; this.Y = -mapTop-cvsHeight/2-currentMap.mapHeight/2 + MyY + this.stepY - Math.floor(this.jumpYAdd)+2+28 + (additionalDown-192); } else { //USER EVENT POSITIONING if( this.moveQueue.length > 0 ) { if( this.moveQueue[0] == "left" ) { if( MyX <= cvsWidth/2 || MyX > currentMap.mapWidth - cvsWidth/2 ) { this.stepX = -this.stepPart; } } else if( this.moveQueue[0] == "right" ) { if( MyX < cvsWidth/2 || MyX >= currentMap.mapWidth - cvsWidth/2 ) { this.stepX = this.stepPart; } } } if( MyY <= cvsHeight/2 || MyY >= currentMap.mapHeight - cvsHeight/2 ) { if( this.moveQueue.length > 0 ) { if( this.moveQueue[0] == "up" ) { this.stepY = -this.stepPart; } else if( this.moveQueue[0] == "down" ) { this.stepY = this.stepPart; } } } if( this.moveQueue.length > 0 ) { if( this.moveQueue[0] == "right" ) { if( MyX+this.stepX >= currentMap.mapWidth - cvsWidth/2 ) { this.offsetX = cvsWidth/2 + ( currentMap.mapWidth - MyX-this.stepX ) * -1; } } else { if( MyX-this.stepX > currentMap.mapWidth - cvsWidth/2 ) { this.offsetX = cvsWidth/2 + ( currentMap.mapWidth - MyX-this.stepX ) * -1; } } } else { if( MyX-this.stepX > currentMap.mapWidth - cvsWidth/2 ) { this.offsetX = cvsWidth/2 + ( currentMap.mapWidth - MyX- this.stepX ) * -1; } }
  • 55. if( this.moveQueue.length > 0 ) { if( this.moveQueue[0] == "left" ) { if( MyX+this.stepX <= cvsWidth/2 ) { this.offsetX = (cvsWidth/2-MyX-this.stepX)*-1; } } else { if( MyX-this.stepX < cvsWidth/2 ) { this.offsetX = (cvsWidth/2-MyX-this.stepX)*-1; } } } else { if( MyX-this.stepX < cvsWidth/2 ) { this.offsetX = (cvsWidth/2-MyX-this.stepX)*-1; } } if( MyY+this.stepY > currentMap.mapHeight - cvsHeight/2 ) { this.offsetY = cvsHeight/2 + (currentMap.mapHeight - MyY- this.stepY ) * -1; } if( MyY+this.stepY < cvsHeight/2 ) { this.offsetY = (cvsHeight/2-MyY-this.stepY)*-1; } var half = (cvsWidth - currentMap.mapWidth); if( half < 0 ) half = 0; this.X = half+cvsWidth/2 + this.offsetX+13; this.Y = cvsHeight/2 + this.offsetY - ySink - Math.floor(this.jumpYAdd); } this.updateTextureCoords(); } this.updateTextureCoords = function() // Define Method { var startX = 0; var startY = 0; if( this.direction == 0 ) { switch(this.stepAnimation) { case 0 : startX = 0; startY = 0; break; case 1 : startX = 1; startY = 0; break; case 2 : startX = 2; startY = 0;
  • 56. break; } } else if( this.direction == 1 ) { switch(this.stepAnimation) { case 0 : startX = 0; startY = 1; break; case 1 : startX = 1; startY = 1; break; case 2 : startX = 2; startY = 1; break; } } else if( this.direction == 2 ) { switch(this.stepAnimation) { case 0 : startX = 0; startY = 2; break; case 1 : startX = 1; startY = 2; break; case 2 : startX = 2; startY = 2; break; } } else { switch(this.stepAnimation) { case 0 : startX = 0; startY = 3; break; case 1 : startX = 1; startY = 3; break; case 2 : startX = 2; startY = 3; break; } } this.drawStartX = startX*32; this.drawStartY = startY*32; } return this;
  • 57. } // ################################################ // ### MAP CLASS ########################### // ################################################ function Region(x1,y1,x2,y2) { this.X1 = x1; this.Y1 = y1; this.X2 = x2; this.Y2 = y2; return this; } // ################################################ // ### GAME MAP CLASS ############################# // ################################################ function gameMap() { this.mapCollisionData = null; this.mapWidth = 0; this.mapHeight = 0; this.mapMusic = ''; this.tileSize = 16; this.grassPatches = new Array(); this.events = new Array(); this.loadEvents = function(mapEvents) // Define Method { events = new Array(); var npcs = firstChildNodeNamed("npcs", mapEvents); for(var k=0;k<npcs.childNodes.length;k++) { var npc = npcs.childNodes[k]; events.push(new gameEvent(npc)); } eggs = []; var eggsNode = firstChildNodeNamed("eggs", mapEvents); for(var k=0;k<eggsNode.childNodes.length;k++) { var egg = eggsNode.childNodes[k]; eggs.push(new GameEgg(egg)); } inventory = [];
  • 58. var inv = firstChildNodeNamed("inventory", mapEvents); for(var k=0;k<inv.childNodes.length;k++) { var item = inv.childNodes[k]; inventory.push(new GameItem(item)); } if( tagAlong != "" ) { follower = new gameEvent(); events.push(follower); follower.id = -1; follower.name = tagAlong; follower.mapPosition.X = userEvent.mapPosition.X; follower.mapPosition.Y = userEvent.mapPosition.Y+2; follower.type = "Action Button"; follower.spriteName = tagAlong + ".png"; follower.direction = userEvent.direction; follower.moveType = "Follow User"; follower.bIsUser = false; follower.bEventEnabled = true; follower.eventData.push(new ScriptLine( 1, "Display Message" ,tagAlongName + "!")); follower.eventData.push(new ScriptLine( 2, "MOVE EVENT" , "- 1^move to user^1")); follower.eventData.push(new ScriptLine( 3, "SYNC ALL" , "")); follower.eventData.push(new ScriptLine( 4, "MOVE EVENT" , "0^forward^1")); } } this.getEvent = function(id) { for(var k=0;k<events.length;k++) { if( events[k].id == id ) { return events[k]; } } return null; } this.evaluateEvents = function() // Define Method { for(var k=0;k<events.length;k++) { events[k].evaluate(); } for(var k=0;k<mmoUsers.length;k++) { mmoUsers[k].evaluate(); } } this.drawEvents = function(ctx,positionToDraw) // Define Method
  • 59. { for(var k=0;k<events.length;k++) { if( positionToDraw == "above" ) { if( events[k].mapPosition.Y > userEvent.mapPosition.Y+2 ) { events[k].drawImage(ctx); } } else { if( events[k].mapPosition.Y <= userEvent.mapPosition.Y+2 ) { events[k].drawImage(ctx); } } } for(var k=0;k<mmoUsers.length;k++) { if( positionToDraw == "above" ) { if( mmoUsers[k].y > userEvent.mapPosition.Y ) { mmoUsers[k].drawImage(ctx); } } else { if( mmoUsers[k].y <= userEvent.mapPosition.Y ) { mmoUsers[k].drawImage(ctx); } } } } this.drawNames = function(ctx) // Define Method { for(var k=0;k<mmoUsers.length;k++) { mmoUsers[k].drawNames(ctx); } if( userEvent.msg != "" ) { ctx.font = "bold 11px sans-serif"; ctx.textAlign = "center"; drawShadowText(ctx,userEvent.msg, userEvent.X+12, userEvent.Y- 1,"#c4d52b"); } else { ctx.font = "bold 11px sans-serif"; ctx.textAlign = "center"; drawShadowText(ctx,"You", userEvent.X+12, userEvent.Y-1); } } this.load = function(mapData) // Define Method { this.tileSize = mapData.getAttribute("tilewidth"); this.mapWidth = mapData.getAttribute("width") * this.tileSize; this.mapHeight = mapData.getAttribute("height") * this.tileSize; var tileCount = (this.mapWidth / this.tileSize) * (this.mapHeight /
  • 60. this.tileSize); this.mapCollisionData = new Array(tileCount); for(var i=0;i<mapData.childNodes.length;i++) { var node = mapData.childNodes[i]; if( node.nodeName == "layer") { if( node.getAttribute("name") == "Collision" ) { var dataNode = firstChildNodeNamed("data",node); var data = getDataOfImmediateChild(dataNode); data = data.replace(/rn/i, '').trim(); rawMapData = stringToBytes(base64_decode(data)); //for (var k = 0; k < tileCount; k++) // mapCollisionData[k] = getIntAt(rawData,k*4); } } else if( node.nodeName == "objectgroup") { if( node.getAttribute("name").toLowerCase() == "grass" ) { this.grassPatches = new Array(); for (var k = 0; k < node.childNodes.length; k++) { var object = node.childNodes[k]; if( object.nodeName != "#text" ) { var x1 = parseInt(object.getAttribute("x"))/this.tileSize; var y1 = parseInt(object.getAttribute("y"))/this.tileSize; var width = parseInt(object.getAttribute("width"))/this.tileSize; var height = parseInt(object.getAttribute("height"))/this.tileSize; var x2 = x1 + (width+1); var y2 = y1 + (height+1); this.grassPatches.push(new Region(x1,y1,x2,y2)); } } } } } } this.getTile = function( x, y) { var tilesWide = mapWidth / tileSize; var pos = 0; x++;
  • 61. y++; if( y * tilesWide + x >= 0 && y * tilesWide + x < mapCollisionData.length ) { if( rawMapData ) { pos = (y * tilesWide + x)*4; if( rawMapData[pos] == 0 && rawMapData[pos+1] == 0 && rawMapData[pos+2] == 0 && rawMapData[pos+3] == 0 ) { return 0; } return 1; } //return mapCollisionData[y * tilesWide + x]; } return -1; } this.tileIsWalkable = function(position) // Define Method { if( position.X < -1 ) return false; if( position.Y < -1 ) return false; if( position.X > this.mapWidth/16 ) return false; if( position.Y > this.mapHeight/16 ) return false; if( this.tileIsFreeFromEvents(position) == false ) { return false; } if( this.getTile(position.X,position.Y) == 0 ) { return true; } return false; } this.tileIsFreeFromEvents = function(position) // Define Method { for(var k=0;k<events.length;k++) { if( events[k].spriteName != "" && events[k].spriteName != null && events[k].bHidden == false && events[k].bEventEnabled == true ) { if( events[k].mapPosition.X == position.X ) { if( events[k].mapPosition.Y == position.Y+2 ) { return false; } } } }
  • 62. //TODO: Complete Event Collision Detection return true; } return this; } function base64_decode (data) { // Decodes string using MIME base64 algorithm var b64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789 +/="; var o1, o2, o3, h1, h2, h3, h4, bits, i = 0, ac = 0, dec = "", tmp_arr = []; if (!data) { return data; } data += ''; do { // unpack four hexets into three octets using index points in b64 h1 = b64.indexOf(data.charAt(i++)); h2 = b64.indexOf(data.charAt(i++)); h3 = b64.indexOf(data.charAt(i++)); h4 = b64.indexOf(data.charAt(i++)); bits = h1 << 18 | h2 << 12 | h3 << 6 | h4; o1 = bits >> 16 & 0xff; o2 = bits >> 8 & 0xff; o3 = bits & 0xff; if (h3 == 64) { tmp_arr[ac++] = String.fromCharCode(o1); } else if (h4 == 64) { tmp_arr[ac++] = String.fromCharCode(o1, o2); } else { tmp_arr[ac++] = String.fromCharCode(o1, o2, o3); } } while (i < data.length); dec = tmp_arr.join(''); //dec = this.utf8_decode(dec); return dec; } String.prototype.trim = function() { return this.replace(/^s+|s+$/g,""); }
  • 63. function stringToBytes ( str ) { var ch, st, re = []; for (var i = 0; i < str.length; i++ ) { ch = str.charCodeAt(i); // get char st = []; // set up "stack" do { st.push( ch & 0xFF ); // push byte to stack ch = ch >> 8; // shift value down by 1 byte } while ( ch ); // add stack contents to result // done because chars have "wrong" endianness re = re.concat( st.reverse() ); } // return an array of bytes return re; } function getIntAt ( arr, offs ) { if( arr[offs+0] == 0 && arr[offs+1] == 0 && arr[offs+2] == 0 && arr[offs+3] == 0 ) { return 0; } return 1; return (arr[offs+0] << 24) + (arr[offs+1] << 16) + (arr[offs+2] << 8) + arr[offs+3]; } // ################################################ // ### BATTLE CLASS ########################### // ################################################ //Battle Variables var bInBattle = false; var battleStage = 0; var battleTaskQueue = new Array(); var teamMonsters = new Array(); var opponentMonsters = new Array(); var monSkills = new Array(); var battleItems = new Array(); var doingCaptcha = false; var captchaImages = new Array(); var captchaKeys = new Array(); var curMon = null; var curOpp = null;
  • 64. var nextMon = null; var nextOpp = null; var battleScript = new Array(); var battleSelectedMenu = 0; var battleItemSelectedMenu = 0; var battleSwappedMonsters = false; var battleTick1 = 0; var battleTick2 = 0; var battleTick3 = 0; var battleLoading = false; var loadExplore = false; var drawMons = true; var drawMyHp = true; var drawOpHp = true; var bWildBattle = false; function addToCaptcha(letter) { if( doingCaptcha ) { if( captchaKeypress[parseInt(letter)-1]== false ) { captchaKeys.push(letter); if( captchaKeys.length == 3 ) { $str = captchaKeys[0] + captchaKeys[1] + captchaKeys[2]; loadBattle("captcha=" + $str); } captchaKeypress[parseInt(letter)-1] = true; } } } function MonsterSkill(id,name) { this.id = id; this.name = name; } function BattleItem(id,name,file,qty) { this.id = id; this.name = name; this.file = file; this.qty = qty; } function BattleMonsterLineup(id,name,level,special,specialName,gender,hpleft,hp,image,type1 ,type2,reborn) { this.id = id; this.name = name; this.level = level; this.special = special;
  • 65. this.specialName = specialName; this.gender = gender; this.hpleft = parseInt(hpleft); this.hp = parseInt(hp); this.image = image; this.type1 = type1; this.type2 = type2; this.reborn = reborn; return this; } function showMonsterAtCoord() { if( !battleLoading ) { bIsLoadingWildDialog = true; var form = document.getElementById('mws-explore-encounter'); form.innerHTML = "<center><img src='http://cache.pokemonlegends.com/images/preloader.gif' tag='loading'/><br/>Loading</center>"; loadBattle("x="+userEvent.mapPosition.X+"&y="+userEvent.mapPosition.Y+"&actio n=encounter"); } } function showMonsterAtCoordCallback() { var form = document.getElementById('mws-explore-encounter'); if( curOpp != null ) { //mws-jui-dialog-monster var gender = " Male "; if( curOpp.gender != "M" ) gender = " Female "; var level = curOpp.level; var specialName = curOpp.specialName; if( specialName != "" ) specialName = specialName + " "; bWildBattleIsReady = true; form.innerHTML = "<center><img src='"+curOpp.image+"' style='padding- top:10px;'/><div style='padding-left: 8px;padding-right: 8px;'>You have encountered a level "+level+gender+specialName+curOpp.name+". </div><input type='button' id='btnBattle' onclick='battleWildSelected();' class='mws-button red' value='Battle' style='margin-bottom:5px;'/></center>"; } else { form.innerHTML = ""; } bIsLoadingWildDialog = false; }
  • 66. function battleMonsterAtCoord() { battleScript = new Array(); playSFX("MonAppear"); showMonsterAtCoord() ; return; //bInBattle = true; - this is set in the above script funciton } function battleWildSelected() { battleSelectedMenu = 2; playSFX("battle"); playMusic("battle1"); if( prevPlayingSong ) { try { prevPlayingSong.currentTime = 0; } catch(err) { } } battleLoading = false; bWildBattle = true; bInBattle = true; wipeWildMonsterBox(); } function battleWithTrainer() { curOpp = null; scriptAddLine("battlescreen","TRAINER"); //bInBattle = true; - this is set in the above script funciton battleSelectedMenu = 2; playSFX("battle"); playMusic("battle1"); curOpp = null; nextOpp = null; curMon = null; nextMon = null; curMonImage.src = 'http://cache.pokemonlegends.com/images/blank.png'; curOppImage.src = 'http://cache.pokemonlegends.com/images/blank.png'; if( prevPlayingSong ) prevPlayingSong.currentTime = 0; bWildBattle = false; wipeWildMonsterBox(); } function wipeWildMonsterBox() { bWildBattleIsReady = false; var form = document.getElementById('mws-explore-encounter');
  • 67. if( form ) { form.innerHTML = ""; } } function battleScriptEndLine() { battleScript.splice(0, 1); battleScriptStartLine(); drawMons = true; drawOpHp = true; drawMyHp = true; } function battleScriptStartLine() { battleTick1 = 0; battleTick2 = 0; battleTick3 = 0; if( !bInBattle ) return; var centerX = cvsWidth/2; var centerY = cvsHeight/2; if( battleScript.length > 0 ) { var data = battleScript[0].split("|"); //battleSelectedMenu = 2; if( data[0] == "MSG" ) { drawMons = true; drawOpHp = true; drawMyHp = true; repositionMonsters(); curMonImage.style.display = 'block'; curOppImage.style.display = 'block'; } else if( data[0] == "ATTACK" ) { drawMons = true; drawOpHp = true; drawMyHp = true; playSFX("hit"); } else if( data[0] == "MUTATE" ) { drawMons = false; drawOpHp = false; drawMyHp = false; var args = data[1].split("-"); //load required images: Monster Image var img = resourceByKey(args[1]);
  • 68. if( img == null ) screenResources.push(new ResourceImage(args[1],args[1])); //load required images: Arrow Image img = resourceByKey("resultset_next.png"); if( img == null ) screenResources.push(new ResourceImage("http://cache.pokemonlegends.com/css/icons/32/resultset_next.png","r esultset_next.png")); } else if( data[0] == "HPCHANGE" ) { battleTick3 = parseInt(data[2]) / 10; } else if( data[0] == "DEFEAT" ) { if( (parseInt(data[1]) < 6 && !battlePlayerAwayTeam) || (parseInt(data[1]) >= 6 && battlePlayerAwayTeam) ) { battleSelectedMenu = 7; curMon.hpleft = 0; curMonImage.src = 'http://cache.pokemonlegends.com/images/blank.png'; } else { curOpp.hpleft = 0; curOpp = nextOpp; curOppImage.src = 'http://cache.pokemonlegends.com/images/blank.png'; } } else if( data[0] == "SWAP" ) { var monImage = null; if( (parseInt(data[1]) < 6 && !battlePlayerAwayTeam) || (parseInt(data[1]) >= 6 && battlePlayerAwayTeam) ) { if( nextMon != null ) { curMon = nextMon; } //sharks if (data[2] == null) data[2] = 0; //end if( curMon != null ) { curMon.hpleft = parseInt(data[2]); curMonImage.src = curMon.image; curMonImage.style.display = 'block'; } repositionMonsters(); } else if( (parseInt(data[1]) < 6 && battlePlayerAwayTeam) || (parseInt(data[1]) >= 6 && !battlePlayerAwayTeam) ) { if( nextOpp != null ) { curOpp = nextOpp; } curOpp.hpleft = parseInt(data[2]); curOppImage.src = curOpp.image;
  • 69. curOppImage.style.display = 'block'; repositionMonsters(); } battleScriptEndLine(); } else if( data[0] == "SFX" ) { playSFX(data[1]); battleScriptEndLine(); } else if( data[0] == "LEVELUP" ) { playSFX("levelup"); battleScriptEndLine(); } else if( data[0] == "CLIENT SCRIPT" ) { scriptAddLine(data[1],data[2]); battleScriptEndLine(); } else if( data[0] == "SCRIPT" ) { if( data[1] != "" ) { scriptAddLine("server side",data[1]); } battleScriptEndLine(); battleEnd(); } } else { // if( !battleLoading ) { if( parseInt(battleStage) == 3 || parseInt(battleStage) == 4 ) { battleEnd(); if( parseInt(battleStage) == 4 ) { userFaint(); } else { //if( !bWildBattle ) { playMusicOnce("victory"); //} } } else if( parseInt(battleStage) == 5 || parseInt(battleStage) == 6 ) { battleEnd(); if( battlePlayerAwayTeam ) { if( parseInt(battleStage) == 6 ) { playMusicOnce("victory"); } else { userFaint(); } } else { if( parseInt(battleStage) == 5 ) { playMusicOnce("victory"); } else { userFaint(); } } } } } }
  • 70. function battleEnd() { bInBattle=false; battleSelectedMenu = 0; battleScript = new Array(); teamMonsters = new Array(); opponentMonsters = new Array(); curMon = null; curOpp = null; curOppImage.style.display = 'none'; curMonImage.style.display = 'none'; playMusic(currentMap.mapMusic); } function battleScriptDraw() { var centerX = cvsWidth/2; var centerY = cvsHeight/2; if( battleScript.length > 0 ) { var data = battleScript[0].split("|"); if( data[0] == "MSG" ) { battleTick1++; if( battleTick1 > 1 ) { battleTick2++; battleTick1=0; } if( (keyState.btn1 || keyState.btn2) && battleTick2 > data[1].length ) { battleScriptEndLine(); keyState.btn1 = false; keyState.btn2 = false; playSFX("beep"); } else if( keyState.btn1 || keyState.btn2 ) { battleTick2 = data[1].length; keyState.btn1 = false; keyState.btn2 = false; playSFX("beep"); } //ctx.textAlign = "left"; //ctx.font = "bold 9px sans-serif"; //drawShadowText(ctx,data[1].substr(0,battleTick2), centerX- 230,centerY+103); ctx.textAlign = "left"; ctx.font = "bold 12px sans-serif";
  • 71. var line1 = data[1]; var line2 = ""; if( line1.length > 32 ) { var lastSpace = line1.lastIndexOf(" ", 32); line2 = line1.substr(lastSpace+1,line1.length-lastSpace-1); line1 = line1.substr(0,lastSpace); } if( battleTick2 <= line1.length ) { drawShadowText(ctx,line1.substr(0,battleTick2), centerX- 234,centerY+100); } else { drawShadowText(ctx,line1, centerX-234,centerY+100); drawShadowText(ctx,line2.substr(0,battleTick2-line2.length), centerX-234,centerY+ 116); } } else if( data[0] == "MUTATE" ) { drawMons = false; drawOpHp = false; drawMyHp = false; var args = data[1].split("-"); ctx.textAlign = "left"; ctx.font = "bold 12px sans-serif"; drawShadowText(ctx,"Let the Pokemon Evolve?", centerX- 234,centerY+100); drawShadowText(ctx,"Press 'X' to confirm, 'Z' to cancel.", centerX- 234,centerY+ 116); ctx.textAlign = "center"; ctx.font = "bold 14px sans-serif"; //Draw Monster var mon = resourceByKey(curMon.image); ctx.drawImage(mon, centerX-80-mon.width/2,centerY-mon.height/2); drawShadowText(ctx,curMon.name, centerX-80,centerY+60); //Draw Monster Evolution mon = resourceByKey(args[1]); ctx.drawImage(mon, centerX+80-mon.width/2,centerY-mon.height/2); drawShadowText(ctx,"???", centerX+80,centerY+60); //Draw Arrow mon = resourceByKey("resultset_next.png"); ctx.drawImage(mon, centerX-mon.width/2-mon.width,centerY- mon.height/2); ctx.drawImage(mon, centerX-mon.width/2,centerY-mon.height/2);
  • 72. ctx.drawImage(mon, centerX-mon.width/2+mon.width,centerY- mon.height/2); if( keyState.btn1 ) { loadBattle("mutate=true"); keyState.btn1 = false; battleScriptEndLine(); } else if( keyState.btn2 ) { keyState.btn2 = false; battleScriptEndLine(); } // //curMon } else if( data[0] == "ATTACK" ) { var img = resourceByKey("ani-"+data[4]); battleTick1++; if( img == null ) { battleScriptEndLine(); } else { if( (parseInt(data[2]) < 6 && !battlePlayerAwayTeam) || (parseInt(data[2]) >= 6 && battlePlayerAwayTeam) ) { ctx.drawImage(img, battleTick2 ,0,80,80,centerX-120- 80/2,centerY-img.height/2+40,80,80); } else { ctx.drawImage(img, battleTick2 ,0,80,80,centerX+120- 80/2,centerY-img.height/2-40 ,80,80); } if( battleTick2 > img.width ) { battleScriptEndLine(); } } battleTick2=battleTick2+80; } else if( data[0] == "DEFEAT" ) { battleScriptEndLine(); } else if( data[0] == "HPCHANGE" ) { battleTick1++; if( battleTick1 < 10 ) { if( (parseInt(data[1]) < 6 && !battlePlayerAwayTeam) || (parseInt(data[1]) >= 6 && battlePlayerAwayTeam) ) { curMon.hpleft = curMon.hpleft - battleTick3; } else { curOpp.hpleft = curOpp.hpleft - battleTick3; } } else { if( (parseInt(data[1]) < 6 && !battlePlayerAwayTeam) || (parseInt(data[1]) >= 6 && battlePlayerAwayTeam) ) {
  • 73. curMon.hpleft = parseInt(data[3]); } else { curOpp.hpleft = parseInt(data[3]); } battleScriptEndLine(); } } else if( data[0] == "BATTLEEND" ) { battleEnd(); } } } function battleUpdate() { //If nothings happening and everything has loaded check for input. if( battleScript.length == 0 && ImageResourceLoadedCount == screenResources.length && !battleLoading ) { //0 == Run //1 == Item //2-5 == Attacks //6 == Swap if( doingCaptcha ) return; var bChangedSomething = false; //Collect Keyboard Input. if( keyState.up ) { playSFX("beep"); if( battleSelectedMenu < 4 ) { battleSelectedMenu = 6; } else if( battleSelectedMenu == 4 || battleSelectedMenu == 5 ) { battleSelectedMenu = battleSelectedMenu - 2; } else if( battleSelectedMenu == 13 ) { battleItemSelectedMenu = battleItemSelectedMenu - 1; if( battleItemSelectedMenu < 0 ) battleItemSelectedMenu=0; } else if( battleSelectedMenu > 6 && battleSelectedMenu <= 12 ) { battleSelectedMenu--; if( battleSelectedMenu < 7 ) battleSelectedMenu = 7; } keyState.up = false; bChangedSomething=true; } else if( keyState.right ) { playSFX("beep"); if( battleSelectedMenu > 6 && battleSelectedMenu <= 12 ) { if( battleSelectedMenu < 10 ) { battleSelectedMenu = battleSelectedMenu+3; if( battleSelectedMenu-7 > teamMonsters.length ) battleSelectedMenu = teamMonsters.length + 6;
  • 74. } } else if( battleSelectedMenu == 13 ) { battleItemSelectedMenu = battleItemSelectedMenu + 4; if( battleItemSelectedMenu >= battleItems.length ) battleItemSelectedMenu = battleItems.length-1; } else if( battleSelectedMenu != 3 ) { battleSelectedMenu++; if( battleSelectedMenu > 5 ) battleSelectedMenu = 5; } keyState.right = false; bChangedSomething=true; } else if( keyState.left ) { playSFX("beep"); if( battleSelectedMenu == 4 ) { battleSelectedMenu = 1; } else if( battleSelectedMenu > 6 && battleSelectedMenu <= 12 ) { if( battleSelectedMenu >= 10 ) { battleSelectedMenu = battleSelectedMenu-3; } } else if( battleSelectedMenu == 13 ) { battleItemSelectedMenu = battleItemSelectedMenu - 4; if( battleItemSelectedMenu < 0 ) battleItemSelectedMenu=0; } else { battleSelectedMenu--; if( battleSelectedMenu < 0 ) battleSelectedMenu = 0; } keyState.left = false; bChangedSomething=true; } else if( keyState.down ) { playSFX("beep"); if( battleSelectedMenu == 6 ) { battleSelectedMenu = 0; } else if( battleSelectedMenu == 2 || battleSelectedMenu == 3 ) { battleSelectedMenu=battleSelectedMenu+2; } else if( battleSelectedMenu == 13 ) { battleItemSelectedMenu = battleItemSelectedMenu + 1; if( battleItemSelectedMenu >= battleItems.length ) battleItemSelectedMenu = battleItems.length-1; } else if( battleSelectedMenu > 6 && battleSelectedMenu <= 12 ) { battleSelectedMenu++; if( battleSelectedMenu-6 > teamMonsters.length ) battleSelectedMenu = teamMonsters.length + 6; } keyState.down = false; bChangedSomething=true; } else if( keyState.btn1 ) { playSFX("beep"); if( battleSelectedMenu == 0 ) { //bInBattle if( bWildBattle ) { battleScript.push("MSG|You ran away from the battle.");
  • 75. battleScript.push("BATTLEEND|"); } else { battleScript.push("MSG|You can not run from a trainer battle."); } } else if( battleSelectedMenu > 1 && battleSelectedMenu < 6 ) { //Attacks var skill = monSkills[battleSelectedMenu-2]; loadBattle("selatk=" + skill.id); } else if( battleSelectedMenu == 6 ) { //Swap battleSelectedMenu = 7; } else if( battleSelectedMenu > 6 && battleSelectedMenu <= 12 ) { battleSwappedMonsters = true; if( teamMonsters.length > battleSelectedMenu-7 ) { if( teamMonsters[battleSelectedMenu-7].hpleft > 0 ) { loadBattle("selmon=" + teamMonsters[battleSelectedMenu- 7].id); } } } else if( battleSelectedMenu == 13) { loadBattle("selitem=" + battleItems[battleItemSelectedMenu].id); } else if( battleSelectedMenu == 1 ) { //Enter the Item Menu battleSelectedMenu = 13; } keyState.btn1 = false; bChangedSomething=true; } else if( keyState.btn2 ) { playSFX("beep"); if( battleSelectedMenu > 6 && battleSelectedMenu <= 12 ) { if( battleStage != 1 ) { battleSelectedMenu = 6; } } else if( battleSelectedMenu == 13 ) { battleSelectedMenu = 1; } keyState.btn2 = false; bChangedSomething=true; } if( bChangedSomething ) { battleUpdatedMenu(); } } else { } }