Wednesday, May 16, 2012

Adding and Viewing High Scores Part 1


This 2-part post describes the process of playing the game, and viewing the high scores table.

Part 1: Adding High Scores

A Note About Passing the Score from JavaScript to PHP

The score is passed from the JavaScript game using the HTTP GET method. The score is embedded within the client's URL.

A file called "processScore.php" will receive the score. It will then be stored is as a session variable, and redirect the user again to a file called "finalScore.php". While it represents a minor security flaw, the script executes very quickly as it is very short.

This process is described in depth, complete with source code excerpts, in this post.

How to get to the High Scores Page

I've provided several ways to get to the high scores list.

After logging in, the user is given the option view the high scores from either the large button in the middle of the screen, or from the navigation bar at the top. The navigation bar displays login information (logged in as: simon), and options, including a link to High scores.

Another way is to play the game. After playing the game, the user's score is processed and recorded into the database. They are then offered a way to quickly get to their high scores table.

The High Scores Page

The High Scores page is split into two distinct sections:

User's Best 5 Scores

Global Top 10

Adding the Score to the Database

The score needs to be added to the database. I need to add it the user_score table. This table contains a user_id and a score field.
As with other PHP scripts in Coursework 2, the file references an important external script called "mysqlHandler.php". More info is available here.

The final SQL command needs to look something like this:

INSERT INTO user_score (user_id, score) VALUES ("1", "250")

Getting the User ID

The first thing that needs to be done is to get the user_id. We can get this from the username, which is stored in a cookie on the user's computer.

Getting the user id requires the following code:

if ($score > 0) {
 if (!empty($_COOKIE['user'])) {
  $result = executeQuery
  ('select user_id from user where username ="' . $_COOKIE['user'] . '"');
 while ($row = mysql_fetch_array($result)) {
  $user_id = $row['user_id'];
 } [...]

Adding the Score

Once we have a valid user_id, we can generate a query to insert the data into the database:

if ((!empty($user_id)) && $user_id > 0) { 
 $sql = "insert into user_score (user_id, score) values (" . $user_id . ", " . $score . ")";
 $result = executeQuery($sql);

Congratulating the User

A page was added that informs the user of their score, and prompts them to visit the high scores page.

Conclusion and Source Code Download

That's it for part 1. This post detailed the process of inserting a user's score into a database.

Jump to Part 2: Viewing High Scores

No comments:

Post a Comment