Surface Game JavaScript Source Code: Model

Free HTML5 Game Tutorial for Beginners: Page 30

Load XML Data Get Previous Game State Set Current Game State

HTML5 Web Development

Free Online Game Development Course: Design with HTML5

The following few listings on this Web page include all of the JavaScript source code for the model portion of the model-view-controller design pattern applied to the Surface Game. The source code resides in JavaScript file surface-game-model.js.

The model portion of Surface Game downloads XML which contains answers, and image files, for each question. The model portion of the game saves and restores user data including the score, question number, and level.

// XMLHttpRequest object or 
// ActiveXObject, depending on the browser:
var xmlhttp = null; 

//XML DOM object.
var xmlDoc = null; 

// iScore is the current 
// total score for all levels.
var iScore  = new Number(0);

// iIdx is the index into the 
// current level's list of questions.
var iIdx  = new Number(0);

// iLvl is passed to the library 
// from individual levels at startup. 
var iLvl = new Number(1);

// bStorage is used only in
// the library. 
// 'true' if HTML5 localStorage 
// is available. Otherwise use cookies.
var bStorage  = false;

// nLevelMax is a Number 
// representing the 
// maximum game level.
var nLevelMax = null;

// nIndexMax is a Number representing 
// the maximum question number, 
// per level.
var nIndexMax = null;

// Relative path to XML files.
var sPath  = null;

Load XML Data

/**
 * function loadXML() is called 
 * for each level.
 * @param lvl is the level 
 * currently being loaded.
 * @returns an XML DOM object or NULL.
 * If there's an error attempting to 
 * load an XML file:
 * 1. An alert box displays 
 *    an error message. 
 * 2. NULL is returned 
 */
function loadXML(lvl){
 
var sFile = sPath+lvl.toString()+".xml";
 
var xd = null;
 
if (window.XMLHttpRequest)
{
  
// code for IE7+, Firefox, 
// Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();

}

else
{
 
// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");

}

try {
 
xmlhttp.open("GET",sFile,false);

xmlhttp.send();

xd=xmlhttp.responseXML; 

}

catch (e) {
 
alert("Unable to load the requested file."+sFile+" error:"+e.toString());


}

return xd;

}

Get Previous Game State

/**
 * scoreModelGet() retrieves
 * the level, score, and 
 * last answered question for this level.
 */
function scoreModelGet(sp,nl,ni){ 
 
sPath = sp;

nLevelMax = nl;

nIndexMax = ni; 

scoreGet(); 

return [iLvl,iIdx,iScore];

}

Set Current Game State

/**
 * Every section calls scoreModelSet() 
 * to save the score.
 * @param lv: a Number representing 
 * the current level.
 * @param idx: a Number representing
 * the last answered
 * question in the current level.
 * @param s: a Number 
 * representing the current score. 
 */
function scoreModelSet(lv,idx,s){ 
 
iLvl = lv;

iIdx = idx;

iScore = s; 

resetIndexAndLevel();

if (bStorage == true){
 
localStorageSet();

}
else {
 
localCookiesSet();

}  
}

/**
 * function cookieGet(sCookieName) obtains
 * the list of cookies and searches for the
 * name passed as a parameter.
 * @param sCookieName a String representing the
 * name of the current cookie.
 * @returns the value of the cookie
 */
function cookieGet(sCookieName) {
 
var i,x,y,ARRcookies=document.cookie.split(";");

for (i=0;i < ARRcookies.length;i++) 
{
x=ARRcookies[i].substr(0,ARRcookies[i].indexOf("="));

y=ARRcookies[i].substr(ARRcookies[i].indexOf("=")+1);

x=x.replace(/^\s+|\s+$/g,"");

if (x==sCookieName)
{ 
 
return unescape(y);

}
}
}

/**
 * function cookieSet(sCookieName,value,exdays)
 * @param sCookieName is a String representing the
 * name of the cookie to save.
 * @param value is the value to be stored with sCookieName.
 * @param exdays is the number of days before the cookie will expire.
 */
function cookieSet(sCookieName,value,exdays) {
 
var exdate=new Date();

exdate.setDate(exdate.getDate() + exdays);

var sCookieValue=escape(value) + ((exdays==null) ? "" : "; expires="+exdate.toUTCString());     

document.cookie=sCookieName + "=" + sCookieValue;

}  

/**
 * function scoreGet() obtains 
 * the stored score data
 * from either cookies
 * or localStorage.
 */
function scoreGet() {  

// If Web Storage is available, then
// save a Boolean, so we 
// don't have to check again.
// Also get data from 
// local storage, if it exists.
 
if(typeof(Storage)!=="undefined") {

bStorage = true;

localStorageGet();

}
// If there's no local storage,
// then get any cookies 
// that have been stored
// for this game.
else {
 
localCookiesGet(); 

}

}

/**
 * function localCookiesGet()
 * obtains Surface Game cookies 
 * for score, level, and index.
 */
function localCookiesGet(){
 
var prevScore = cookieGet("sgscore");

var prevLevel = cookieGet("sglevel");

var prevIndex = cookieGet("sgindex");

if (prevScore!=null && prevScore != "" && prevScore != "undefined") { 
      
iScore = Number(prevScore);

iLvl = Number(prevLevel);

iIdx = Number(prevIndex); 

}
}

/**
 * function localStorageGet()
 * obtains Surface Game local storage 
 * for score, level, and index.
 */
function localStorageGet(){
 
try {
 
if (localStorage == null){
 
bStorage = false;   

alert("Please enable cookies or local storage to save your score.");  
   
}

if (localStorage.sgscore){
 
iScore = Number(localStorage.sgscore);

}
if (localStorage.sglevel){

iLvl = Number(localStorage.sglevel);

}

if (localStorage.sgindex){
 
iIdx = Number(localStorage.sgindex);

}      
}

catch(err){
 
bStorage = false; 

alert("Please enable cookies or local storage to save your score.");   

} 

}

/**
 * function localStorageSet()
 * saves the current score, level, and
 * question number to Web Local Storage.
 */
function localStorageSet(){ 
 
localStorage.sgscore = Number(iScore);

localStorage.sglevel = Number(iLvl); 

localStorage.sgindex = Number(iIdx);

}    

/**
 * function localCookiesGet()
 * saves the current score, level,
 * and question number as cookies.
 */
function localCookiesSet(){
 
cookieSet("sgscore",iScore,128);

cookieSet("sglevel",iLvl,128);

cookieSet("sgindex",iIdx,128); 

}

/**
 * function resetIndexAndLevel()
 * Adjusts the index and level if necessary.
 * If the index has gone beyond the max,
 * then increment the level, and set index to zero.
 * If the level has gone beyond the max,
 * then set the level to zero also.
 */
function resetIndexAndLevel(){
 
var index = iIdx;

if (index > nIndexMax){

 index = 0;

 var lvl = new Number(iLvl + 1);

 if (lvl > nLevelMax){
 
  iLvl = new Number(1);
 }
 
 else {
  
  iLvl = lvl;
  
}

}

}

For the next section, tap the image icon containing text which says Next Lesson, or the right pointing arrow at the bottom of the page.

Previous Page Next Page
Copyright © 2015 Seven Thunder Software. All Rights Reserved.