16 May 2012

Coursework 2: JavaScript Animation Game Spiced Up – Post 6

Welcome to the final blog about coursework 2! I have completed all the required coding, so know I am going to post about the last two functions of my game, which are:


  • Score Keeping
  • User Notifications
In my 3rd post on this coursework I had shown you the structure of my users table, which consisted of two particular fields; Score and Last_Beat_By. The use of these fields will be explained in this post.



Users table structure


Score Keeping Functionality
So now, to make any game that bit more exiting, it must have some sort of scoring, not only that but scoring is also the unit of measure when users want to compete against each other!
Therefore I was time add this all important scoring functionality to my game and I came up with the following list of things I had to include:

  • Set up the rules of how points are given or taken
  • Accumulate on user's latest score
  • Save the score once the user ends the game
  • Display a Score Board at the end
Scoring Rules:
I decided to make the user able to increase as well as decrease his/her latest score and to do so I decided on the following way of how this would apply.


Accumulate Latest Score:
For a user to continue improving...or ruining his/her latest score, it had to be queried from the database and stored in memory. This task is handled during user authentication, as when I query for the user's record, I store the user's score in a session variable via PHP, along with other details such as the Last_Beat_By:

function authUser($userID, $password) {

    $authUserSQL = "SELECT * FROM users WHERE USER_NAME = '" . $userID . "' AND USER_PASSWORD = '" . $password . "'";
    //queries the database for the user record with the received parameters.
    $result = execute($authUserSQL);

    if (mysql_num_rows($result) > 0) {//record found
        $record = mysql_fetch_array($result, MYSQLI_ASSOC);//stores the returned result in an associative array
        //stores user's related data in session variables
        $_SESSION['userName'] = $record['USER_FULL_NAME'];
        $_SESSION['highScore'] = $record['SCORE'];
        $_SESSION['lastBeatenBy'] = $record['LAST_BEAT_BY'];
        $_SESSION['userID'] = $record['USER_NAME'];
        $_SESSION['Authenticated'] = "yes";
        return TRUE;
    } else {//no record found
        return FALSE;
    }
}


Score Keeping with JavaScript:
After this is done the user gets redirected to the game. To avoid having to retrieve the session variables via JavaScript, I output the session variables to JavaScript variables using PHP as shown below:

<html>
 <head>
   <title>Paper Toss Game</title>
   <script type="text/javascript">
    <?php echo "var userName = '" . $_SESSION['userName'] . "';"; ?>
    <?php echo "var origScore = " . $_SESSION['highScore'] . ";"; ?>
    <?php echo "var lastBeatenBy = '" . $_SESSION['lastBeatenBy'] . "';"; ?>
    <?php echo "var userID = '" . $_SESSION['userID'] . "';"; ?>
    var newScore = origScore;//running score counter
    var myPaper;//the paper object (image)
    var myBin;//the bin object (image)
    var binXLocation;
    var ammo1XLocation;


Once the paper toss page is sent to the client, the variables which are outputted by PHP will look exactly like all the other variables, therefore keeping in mind that JavaScript is a client side technology, I can reference these variables normally.
Back to score keeping, in the above code you can see I am storing the retrieved score in a variable name 'origScore' and then storing this variable in another, named 'newScore'. This is because at the end of the game I want to  know what was the user's score at the beginning. I will explain later when I cover the user notifications function.


Now that I have the user's latest score in memory on the client side, all I have to do is increment or decrement this value according to where the paper ball lands, for example:

        if(paperYLoc>=-150 && paperXLoc>binXLocation){//dunk
            clearInterval(landMotion);
            newScore = newScore + 20;
            alert("Dunk! YOU WIN!!!  +20 points");
        }else if(paperYLoc<-150 && paperXLoc>binXLocation){//overshoot
            clearInterval(landMotion);
            newScore = newScore - 5;
            alert("Over Shoot!  -5 points!!");
        }else if(paperYLoc>=-20){//not far enough
            clearInterval(landMotion);
            newScore = newScore - 10;
            alert("Not far enough!  -10 points!!");
        }
Saving the latest score:
Once the user clicks on the 'End Game' button at the bottom, he/she gets redirected to another page named 'saveGame.php' and the required values are posted to this PHP file just like I explained in post 4 of coursework 2.
Once the request passes the verification that it's an authorised one, a function gets called which updates the user's record with the latest score.


function saveScore($userID, $score){
    $updateScoreSQL = "UPDATE users SET SCORE = ".$score.", LAST_BEAT_BY='' WHERE USER_NAME = '".$userID."'";
    $result = execute($updateScoreSQL);
    return $result;
}


This function returns the a boolean which states whether the update was a success or not.
If the update was successful the user gets redirected once more to a page called 'scoreBoard.php'


The Score Board:


<?php
    $rowCount = 0;
    $result = execute("SELECT USER_NAME, USER_FULL_NAME, SCORE FROM users ORDER BY SCORE DESC, DATE_JOINED");

    //loop through all the returned records and create a table row for each
    while ($row = mysql_fetch_array($result, MYSQLI_ASSOC)) {
       $rowCount = $rowCount + 1;
       if ($row['USER_NAME'] == $_SESSION['userID']) {
          //Use the echo to output HTML code with the retrieved data
          echo "<tr>";
          echo "<td align=\"center\" style=\"color: #FF0000\">" . $rowCount . "</td>";
          echo "<td align=\"center\" style=\"color: #FF0000\">" . $row['USER_FULL_NAME'] . "</td>";
          echo "<td align=\"center\" style=\"color: #FF0000\">" . $row['SCORE'] . "</td>";
          echo "</tr>";
       } else {
          //Use the echo to output HTML code with the retrieved data
          echo "<tr>";
          echo "<td align=\"center\">" . $rowCount . "</td>";
          echo "<td align=\"center\">" . $row['USER_FULL_NAME'] . "</td>";
          echo "<td align=\"center\">" . $row['SCORE'] . "</td>";
          echo "</tr>";
       }
    }
?>


Once this page is requested, before sending it to the client-side, PHP code is run on the server, which queries for all the names and their respective score and outputs the appropriate HTML code to build dynamic table rows in order to create the score board.
A small touch I decided to include is a check for the current user's record and highlight it in red font. The screen shot below illustrates this score board.



Notifications Function
I decided I wanted to fuel up a little bit the competitiveness between the players, therefore I wanted to display a notification upon logging in, which tells the user if a player beat his last score while he/she was away.
In the previous section I already mentioned where I am storing this value in the table and how I am retrieving it, so I am going to skip that part and move on to when I populate this value and display the notification.


Keeping track of who beat who's latest score:
I previously said that, once a user clicks on 'End Game' his/her score is saved and the  score board is displayed, well...I what I didn't say is that between those two actions lies something else. After saving the user's score an IF statement checks if the user's original score, stored in 'origScore' which I already mentioned, is less that the new score. If this is the case, I call a function named 'updateBeatenUsers()' which updates all the user records which had their score beaten by this player, with the player's full name in the Last_Beat_By field.


function updateBeatenUsers($userName, $origScore, $newScore){
  $beatenSQL = "UPDATE users SET LAST_BEAT_BY = '".$userName."' WHERE SCORE >= ".$origScore." AND SCORE < ".$newScore."";
  $result = execute($beatenSQL);
  return $result;
}


Displaying the Notification
Now that I am keeping track of who is beating who's score, all I need to do is notify the user on first login. This part is quite easy as once the user is redirected to the game page I have a variable representing the Last_Beat_Value (I explained this in the "Score Keeping with JavaScript" section), therefore its a simple matter of checking whether or not the variable contains a value and if so, display it in a JavaScript alert box like so:



After this, I reset the user's Last_Beat_By field back to null during the saving of the score so that this message will not get displayed the second time the user logs on.

Conclusion
So know, that's the last of this coursework, I must say that its been quite a learning curve but I enjoyed it as I got an exposure over a range of web technologies and managed to create a simple game with a social aspect, which by the way I could host online and have my friends join in!

I hope that my experience was of some use for you who read these blog posts and I would like to say, feel free to comment on my work.

Now, if you excuse me...I've got another round of paper toss to attend to, see you!!

No comments:

Post a Comment