4 Replies - 2358 Views - Last Post: 26 January 2012 - 11:54 AM

#1 YnattirB  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 7
  • Joined: 26-January 12

Converting Javascript Hangman game code to JQuery

Posted 26 January 2012 - 08:06 AM

Here's my javascript code with some Jquery that works fine on the simulator, I just need to know what and how will I change it to be all Jquery which will be easier to edit in the future and more app friendly...

function onBodyLoad()
{		
	document.addEventListener("deviceready", onDeviceReady, false);
}
	
	/* When this function is called, PhoneGap has been initialized and is ready to roll */
	/* If you are supporting your own protocol, the var invokeString will contain any arguments to the app launch.
	see http://iphonedevelopertips.com/cocoa/launching-your-own-application-via-a-custom-url-scheme.html
	for more details -jm */

function onDeviceReady(){
	// do your thing!
}

var jQT = new $.jQTouch({
	statusBar: 'black',
	useFastTouch: true
});


function alertme(){
alert('I am a example');
};

</script>

</head>

<body onload="onBodyLoad()">
<script language="Javascript" type="text/javascript">

var currentImage = 0;
var i;
var mypics=new Array();
mypics[0]="graphics/1.jpg"; 
mypics[1]="graphics/2.jpg";
mypics[2]="graphics/3.jpg";
mypics[3]="graphics/4.jpg";
mypics[4]="graphics/5.jpg";
mypics[5]="graphics/6.jpg";
mypics[6]="graphics/7.jpg";

var colors = ["red", "yellow", "green"];  // The array of color class names.
var tries = [2, 2, 2, 2, 2];              // The array of tries that the user has left. It may be better practice to start at 0 and count up to 2.
var numComplete = 0;                      // The number of completed letters.
var numWrong = 0;                         //The number of wrong guesses.
var playAgain = false;
var letters = ["T", "O", "R", "C", "H"];  // The array of letters to display.

function checkAnswer(quizForm,
                     theAnswer,
                     questionNumber)
{
  var s = "?";

  // go through the "current choices"
  // to find the selected choice.
  // radio boxes pointing to choices
  // must be named "cc"
  // change if necessary
  //

  var i = 0;

  for(;i<quizForm.elements.length;i++)
  {
    if(("cc" == quizForm.elements[i].name) && (quizForm.elements[i].checked))
    {
      s = quizForm.elements[i].value;
    }
  }

  // no choice was selected
  //

  if("?" == s)
  {
    alert("Please make a selection.");
    return false;
  }

  // check if we have the correct
  // choice selected
  //

  if(s == theAnswer)
  {
    alert("'"+s+"' is correct, Good job!");
    
    var id = "#home #q" + questionNumber;   // 'id' is the jQuery selector that we'll use to select the question mark button on the home page
    
    // Once we select the question mark button,
    // we replace it with a div that has the class 'custom', which gives it the proper style and size
    //(You can change the name 'custom' if you want, but make sure you change it elsewhere in this file).
    // We also give it the class that corresponds to the color it should be. This is based on the number of tries the player has left.  
    $(id).replaceWith("<div class='"+colors[tries[questionNumber-1]]+" custom'>"+letters[questionNumber-1]+"</div>");  
    
    numComplete++;    // Increment the number of completed letters.
  }
  else  // If the wrong answer was chosen,
  {
    tries[questionNumber-1]--;              // Decrement the number of tries the player has left for that question.
    
    alertString = "'"+s+"' is incorrect. "  // Start building string to alert to user.
    
    if ( tries[questionNumber-1] === 1) 
    {
      // If the player has 1 more try,      
      alertString += "You have 1 more try for Question "+questionNumber+"!";
      var image = "#home #q" + questionNumber + " img";
      $(image).attr("src", "graphics/yellowQ.png");     // Change the question mark to the yellow button.
    }
    else if ( tries[questionNumber-1] < 1) 
    {
      // If the player has no more tries,      
      alertString += "You have no more tries for Question "+questionNumber+"!";
      alertString += "\nThe answer was "+theAnswer+".";
      
      // Change the question mark button on the home page to to the 'custom' div with the proper color.
      var id = "#home #q" + questionNumber;
      $(id).replaceWith("<div class='"+colors[tries[questionNumber-1]]+" custom'>"+letters[questionNumber-1]+"</div>");
      
      numComplete++;    // Increment the number of completed letters.
    }
    else
    {
      alertString += "You have "+tries[questionNumber-1]+" more tries for Question "+questionNumber+"!";
    }

    alert(alertString);
    
    // Highlight the wrong answer that the player selected.
    var selector = "input[value="+s+"]";
    $(quizForm).find(selector).parent().css("backgroundColor","pink");
    
    $("form").each(function(){this.reset()});                 // Clear all the forms.
    $("#something img").attr("src", mypics[++currentImage]);  // Change the gallow picture.
    
    numWrong++;    // Increment the number of wrong guesses.
  }
  
  
  jQT.goTo("#home");
  
  
  // The following if statement can probably be collapsed, but I didn't spend too much time on that.
  
  
  if (numComplete === 5)  // If all questions are complete, 
  { 
    if (numWrong >= 6) // If the number of wrong answers is 6 or greater, 
    { 
      // then go through and find any question mark buttons that haven't 
      // been changed to letters, and change them to red letters.
      for (var i = 1; i <= 5; i++)
      {
        var id = "#home #q" + i;
        var object = $(id);
        if (object.length != 0) 
        {        
          object.replaceWith("<div class='red custom'>"+letters[i-1]+"</div>");
        }
      }      
      // Make a delay and tell the user they lost.
      setTimeout('playAgain = confirm("You lost. Click OK to try again. Click Cancel to exit.");if (playAgain == true){location.reload()}', 2500);
    }
    else // If the number of wrong answers is less than 6,
    {
      // Make a delay and tell the user they won.
      setTimeout('playAgain = confirm("You won! Click OK to play again. Click Cancel to exit.");if (playAgain == true){location.reload()}', 2500);
    }
  } 
  else if (numWrong >= 6)
  {    
    for (var i = 1; i <= 5; i++)
    {
      var id = "#home #q" + i;
      var object = $(id);
      if (object.length != 0) 
      {
        object.replaceWith("<div class='red custom'>"+letters[i-1]+"</div>");
      }
    }
    
    setTimeout('playAgain = confirm("You lost. Click OK to try again. Click Cancel to exit.");if (playAgain == true){location.reload()}', 2500);
  } 

  // return "false" to indicate not to
  // submit the form.
  // change this to "true" if the form
  // "action" is valid,
  // i.e. points to a valid CGI script
  //

  return false;
}

//-->

</SCRIPT>

<div id="jqt">

<div id="home">
    <div class="toolbar">
        <h1>HANGMAN</h1> 
        <a href="#" class="button">Exit</a>
	 </div>
    <div class="info">Select a green box to start the game.</div>
    
            
    <div class="s-scrollwrapper" vScrollbar="false">
    	<div align=center class="content">
        
            <div id="question">
            <h2>What is the main element on the Financial Management School's crest?
            
            
            </h2>
            </div>
            <br>
            
            
          <div align=center id="something">
         <img src="graphics/1.jpg" name="hm">
          
          
            </div>
          
            <div id="boxbutton">       
                <a id="q1" href="#Question1"><img src="graphics/greenq.png"></a>
                <a id="q2" href="#Question2"><img src="graphics/greenq.png"></a>
                <a id="q3" href="#Question3"><img src="graphics/greenq.png"></a>
                <a id="q4" href="#Question4"><img src="graphics/greenq.png"></a>
                <a id="q5" href="#Question5"><img src="graphics/greenq.png"></a>
            </div>
		</div>
	</div>
</div>

<div id="Question1">
    <div class="toolbar">
        <h1>HANGMAN</h1>
         
        <a href="#home" class="back2">Back</a>
    </div>
    <div class="info">Select an answer and Submit</div>
    <div class="s-scrollwrapper" vScrollbar="false"><div class="content">

    
    <form class="member" method="post" action="" onsubmit="return checkAnswer(this,'A', 1);">
   
    
    
    <h2>Funding is provided on what two documents?</h2>
    
    <ul class="pq">
        <li><input type="radio" value="A" name="cc" />A. Funding Allowance Document(FAD) and Funding Target Memorandum<br class="clear"></li>
        <li><input type="radio" value="B" name="cc" />B. Funding Control Document and Flow of Funds Memorandum<br class="clear"></li>
        <li><input type="radio" value="C" name="cc" />C. Budget Analysis Spreadsheet and Budgeting for the Quarter Sheet<br class="clear"></li>
        <li><input type="radio" value="D" name="cc" />D. Allowable Funding Document and Budget Analysis Spreadsheet<br class="clear"></li>
    </ul>
    
    <input type="submit" value="Submit Answer">
 
    </form>
    
</div></div></div>
</div>
  </body>
</html>



Is This A Good Question/Topic? 0
  • +

Replies To: Converting Javascript Hangman game code to JQuery

#2 Dormilich  Icon User is offline

  • 痛覚残留
  • member icon

Reputation: 3515
  • View blog
  • Posts: 10,143
  • Joined: 08-June 10

Re: Converting Javascript Hangman game code to JQuery

Posted 26 January 2012 - 08:55 AM

that's a strange kind of hangman ...

anyways, first thing to do is split up that monstrous checkAnswer() function into manageable bits.

do you know how events are done in jQuery?
Was This Post Helpful? 0
  • +
  • -

#3 YnattirB  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 7
  • Joined: 26-January 12

Re: Converting Javascript Hangman game code to JQuery

Posted 26 January 2012 - 09:42 AM

:smile2: yeah my game is a little different from the basic game because instead of it being a letter keyboard and categories for the user to choose from, its set up more as a learning game and asks questions and based on if the user answers right or wrong it will add to the counter, alert messages, change letter color, and if wrong build hangman.

I have somewhat of an idea how events are done in jQuery like the syntax but thats really it being this is my first time and im new to it... :/
Was This Post Helpful? 0
  • +
  • -

#4 Dormilich  Icon User is offline

  • 痛覚残留
  • member icon

Reputation: 3515
  • View blog
  • Posts: 10,143
  • Joined: 08-June 10

Re: Converting Javascript Hangman game code to JQuery

Posted 26 January 2012 - 11:48 AM

well. then it's probably best to play a bit with jQuery events to get an understanding how they work (cf. jQuery().bind()).

when that’s done you need to break that 150 line function monster in manageable chunks (rule of thumb: the whole function body needs to fit in the visible editor area (not in full screen mode, more something like 24 rows x 80 columns)).
Was This Post Helpful? 0
  • +
  • -

#5 YnattirB  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 7
  • Joined: 26-January 12

Re: Converting Javascript Hangman game code to JQuery

Posted 26 January 2012 - 11:54 AM

ok i will try to play around with some events to get a better understanding and break that function up, thanks for this tip..
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1