1. This site uses cookies. By continuing to use this site, you are agreeing to our use of cookies. Learn More.
  2. To chat with the GameOgre community, you need to have at least 100 posts. Once you have the 100 posts, post at Become A New Ogre
    Dismiss Notice

PHP Game Development Course

Discussion in 'Online Game Development' started by quinn, Aug 11, 2010.

Thread Status:
Not open for further replies.
  1. shugo

    shugo Elite Ogre Ogre Veteran

    Messages:
    2,093
    Likes Received:
    12
    Trophy Points:
    38
    Credit:
    15,378.42
    again the example, this time the finished register page:

    Code:
    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> 
    <HTML> 
    <HEAD>
     <TITLE>Rock Paper Cissors</TITLE>
     <META NAME="description" CONTENT="registration"/> 
    <META NAME="keywords" CONTENT="registration"/> 
    </HEAD> 
    <BODY> 
    <?php 
    
    //CONNECTION
    $con = mysql_connect("localhost","username","password");
    if (!$con)
      {
      die('Could not connect: ' . mysql_error());
      }
      
    //GAME DATABASE
    mysql_select_db("database1", $con);
    
    
    if (isset($_POST["password"]) && isset($_POST["username"]) && isset($_POST["rpc"])){
    
    
    
    /*SANITIZATION*/
    
    filter_var($_POST["password"], FILTER_SANITIZE_STRING);
    filter_var($_POST["username"], FILTER_SANITIZE_STRING);
    filter_var($_POST["rpc"], FILTER_SANITIZE_STRING);
    
    /*FILTERING*/
    
    //CHECK PASSWORD
    if(!filter_has_var(INPUT_POST, "password")){
    echo "<P>No password provided<BR><A HREF='register.php'>Return</A></P>";}
    else {
    $password = $_POST["password"];
    
    //CHECK USERNAME
    if(!filter_has_var(INPUT_POST, "username")){
    echo "<P>No username provided<BR><A HREF='register.php'>Return</A></P>";}
    else {
    $username = $_POST["username"];
    
    //CHECK CLAN
    if(!filter_has_var(INPUT_POST, "rpc")){
    echo "<P>No clan chosen<BR><A HREF='register.php'>Return</A></P>";}
    else {
    $choice = $_POST["rpc"];
    
    /*VALIDATION*/
    
    //VALIDATE PASSWORD
    $checkpasslength = strlen("$password");
    if ($checkpasslength <4 || $checkpasslength >12){
    echo "<P>The password is too short or too long<BR><A HREF='register.php'>Return</A></P>";}
    else {
    
    //VALIDATE USERNAME
    $checknamelength = strlen("$username");
    if ($checknamelength <4 || $checknamelength >20){
    echo "<P>The username is too short or too long<BR><A HREF='register.php'>Return</A></P>";}
    else {
    
    //VALIDATE CHOICE
    if ($choice =="rock" || $choice =="paper" || $choice=="cissors"){
    
    //CHECK USERNAME AVAILABILITY
    $countres = mysql_query ("SELECT COUNT(username) AS usercount FROM users WHERE username ='$username'");
    $countrow = mysql_fetch_array($countres);
    $countuser = $countrow[usercount];
    
    if ($countuser <1){
    
    /*INSERTING DATA*/
    
    mysql_query("INSERT INTO users (username, password, rpc)
    VALUES ('$username', '$password', '$choice')");
    
    echo "<P>Congratulations you have registered<BR><A HREF='login.htm'>Continue</A></P>";
    
    }
    else {
    echo "<P>That username is already used<BR><A HREF='register.php'>Return</A></P>";}
    
    
    }
    else {
    echo "<P>Not a valid choice<BR><A HREF='register.php'>Return</A></P>";}
    }
    
    }
    }
    }
    }
    }
    
    
    }
    else {
    echo "<FORM action='register.php' method='POST'>
    <input type='text' size='20' maxlength='20' name='username'>
    <input type='password' size='12' maxlength='12' name='password'>
    <SELECT name='rpc'>
    <option value='rock'>rock</option>
    <option value='paper'>paper</option>
    <option value='cissors'>cissors</option>
    </SELECT>
    <INPUT type='Submit' value='register'>
    </FORM>";
    }
    
    ?> 
    </BODY> 
    </HTML>
     
    Last edited by a moderator: Aug 26, 2010
  2. shugo

    shugo Elite Ogre Ogre Veteran

    Messages:
    2,093
    Likes Received:
    12
    Trophy Points:
    38
    Credit:
    15,378.42
    LESSON 4 (stage 2, example explained)

    The first thing we do is filter the external variables which were submitted to the file by the player who filled in the registration form and pressed register.

    We need to filter and sanitize all external variables for security reasons! This is to prevent hackers from using a commonly known hack method known as an sql injection. An sql injection is where the hacker inserts a line of php containing sql commands instead of a normally expected variable. Clearly we don't want that to happen, because it can mess up our sql table, so we filter every available external variable we get. After the sanitization we continue to the filtering, we check to see if the variables are actually there. I wrote this in the example, because you can also dump variables if the external variables don't get through the sanitization part.

    Next we need to validate the data we received. We use the strlen php function on the password variable to see how long this string is. Php has numerous build-in functions and the strlen function is one of them. Some of these functions are very neat and you can do a lot of cool things with these functions. We will show a few more of these functions in later lessons.
    The password variable is a string in this case. If the length of the string corresponding to the password variable is shorter than 4 characters or longer than 12 characters, then we display an error message "The password is too short or too long", in which case the script will abort the registration process. Only if all our conditions are met will the user be able to register, else he or she will get an error message.

    Remember in stage 1, I mentioned that you couldn't rely on the html made limit, but that you need to validate the external variable, in this case the password and username variable. Here is why! Suppose some hacker makes his own version of the html registration form and then puts the url of our registration page in the "action". If the hacker omits the limits we put in place in the form, then he can insert a password or username of virtually unlimited length. Clearly we don't want that to happen, hence we need to validate the length of the username and password strings.

    We also need to validate the part of the choice made in the dropdown list for somewhat similar reasons. Suppose a hacker makes his own dropdown list and puts in a 4th choice, something like I dunno, "flower"
    , then that 4th choice will be an invalid one. Again that's something we don't want to happen, so that's why we validate to make sure it can't happen. In this case we do it with the condition:

    Code:
    ($choice =="rock" || $choice =="paper" || $choice=="cissors")
    
    this condition checks if the choice is rock or paper or cissors, as the || stands for OR

    After the choice we check the username again. This time we need to make sure that the chosen username hasn't already been registered, as we can't have 2 quinn's, or 2 ec2's, or 2 noche's. Not only will it be confusing to the players, but it will also cause problems for the login process. One way to go about it is this:

    First we query the users table, we count the username column, because count is an aggregate sql function we need to give it an alias, we do this with "AS" and by giving the SELECT a name, else the result can't be fetched. We give the query a WHERE clause, because we only need to count the row that may or may not have the username. For that is logical.
    Next we fetch the selected result from the sql select query. We reference the selected variable as a php variable (in this case $countuser) and finally we make a condition. This condition checks if the variable is smaller than 1. If it is smaller than 1, then clearly the username has not been chosen before and we can proceed further.


    If everything checks out as valid, then we register the player. We do this with an INSERT command in the sql query.

    Code:
    mysql_query("INSERT INTO users (username, password, rpc)
    VALUES ('$username', '$password', '$choice')");
    
    We only need to insert these 3 cells of the player's row in the table, because as you may remember from previous lessons, the userID column is automatically incremented, and the alive column is set to the default value of 1, so we don't need to do this ourselves. Handy this sql isn't it? ;)

    OK that's all there is to it, tune in next time, when we will make the login page. After the login page is completed, we will make the actual game pages. It is in the final lessons when things will get really fun and interesting. So if you managed to get through this boring part, then the fun bit will come later...
     
    Last edited by a moderator: Aug 26, 2010
  3. shugo

    shugo Elite Ogre Ogre Veteran

    Messages:
    2,093
    Likes Received:
    12
    Trophy Points:
    38
    Credit:
    15,378.42
    LESSON 5 (how to create a login and portal page; stage 1)

    Like in lesson 4 I will explain the login process in 2 stages. For clarity sake we will make 2 different pages. The first page will be the login page, called "login.htm", the second page will be the portal page, called "portal.php". As you can see the first page is a really simple html file, with a html form, which I'll show below:

    Code:
    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> 
    <HTML> 
    <HEAD> 
    <TITLE>Rock Paper Cissors</TITLE> 
    <META NAME="description" CONTENT="login"/>
     <META NAME="keywords" CONTENT="login"/> 
    </HEAD>
     <BODY>
    <FORM action="portal.php" method="POST"> 
    <input type="text" size="20" maxlength="20" name="username"> 
    <input type="password" size="12" maxlength="12" name="password"> 
    <INPUT type="Submit" value="login">
    </FORM>
    </BODY> 
    </HTML>
    
    This bit of code contains nothing new that you have not already learned in the previous lessons, the only thing different about this form, is that the "action" is set to a different page, instead of the same page like we did at lesson 4 with the register.php file.

    We will get to the portal page soon. In the portal page we will: (1) filter and validate the external variables of the login page, (2) check if the username and password is valid, (3) set the cookie, and (4) let php make a link to the actual game page.

    The second page (portal.php) however is the most difficult part of the whole game creation. So should you manage to understand that stage, then all things are set for you from then on. Stage 2 of lesson 5 will be the most boring and difficult part of all the lessons, but I promise you afterwards we will move on to the actual game pages.
     
    Last edited by a moderator: Aug 26, 2010
  4. shugo

    shugo Elite Ogre Ogre Veteran

    Messages:
    2,093
    Likes Received:
    12
    Trophy Points:
    38
    Credit:
    15,378.42
    LESSON 5 (stage 2, the portal page)

    OK now we move on to the portal page.

    Code:
    <?php 
    
    //CONNECTION
    $con = mysql_connect("localhost","username","password");
    if (!$con)
      {
      die('Could not connect: ' . mysql_error());
      }
      
    //GAME DATABASE
    mysql_select_db("database1", $con);
    
    
    if (isset($_POST["username"]) && isset($_POST["password"])){
    
    /*SANITIZATION*/
    
    filter_var($_POST["password"], FILTER_SANITIZE_STRING);
    filter_var($_POST["username"], FILTER_SANITIZE_STRING);
    
    $password = $_POST["password"];
    $username =  $_POST["username"];
    
    /*VALIDATION*/
    
    //VALIDATE PASSWORD
    $checkpasslength = strlen("$password");
    if ($checkpasslength <4 || $checkpasslength >12){
    $Allowlogin = 2;}
    else {
    
    //VALIDATE USERNAME
    $checknamelength = strlen("$username");
    if ($checknamelength <4 || $checknamelength >20){
    $Allowlogin = 3;}
    else {
    
    $result = mysql_query ("SELECT * FROM users WHERE username ='$username'");
    $row = mysql_fetch_assoc($result);
    $tablepassword = $row["password"];
    
    if ($password == $tablepassword) {
    $Allowlogin = 1;
    setcookie("person", $username, time()+7200);
    
    }
    else {
    $Allowlogin = 4;}
    
    }
    }
    }
    mysql_close($con);
    ?>
    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> 
    <HTML> 
    <HEAD>
     <TITLE>Rock Paper Cissors</TITLE>
     <META NAME="description" CONTENT="portal"/> 
    <META NAME="keywords" CONTENT="portal"/> 
    </HEAD>
    <BODY><H1>Portal</H1>
    
    <?php
    if ($Allowlogin ==1) {
    
    echo "<P>Welcome ".$username." "<BR><a href='overview.php'>Continue</A>";
    }
    elseif ($Allowlogin ==2){
    echo "<P><BR>The password is too short or too long<A HREF='login.htm'>Return</A>";
    }
    elseif ($Allowlogin ==3){
    echo "<P><BR>The username is too short or too long<A HREF='login.htm'>Return</A>";
    }
    else {
    echo "<P>Incorrect password or username<BR><A HREF='login.htm'>Return</A>";
    }
    ?>
    </BODY>
    </HTML>
    
    
     
    Last edited by a moderator: Aug 27, 2010
  5. shugo

    shugo Elite Ogre Ogre Veteran

    Messages:
    2,093
    Likes Received:
    12
    Trophy Points:
    38
    Credit:
    15,378.42
    LESSON 5 (stage 2, example explained)

    I will not go into much detail about every single line as there is a lot here that you have already seen before in earlier lessons. I will however explain all the new things you see.

    In lesson 2 I mentioned that you can start and stop a php script anywhere you like. In this example we inmediately start a php script before any html is written. We do this for a very good reason. We need to set a cookie if the password and username checks out allright. Cookies have one peculiar thing in that you have to set them before any html is present, else you will be unable to set a cookie. This is the main reason why we do things like this in this example.

    As you can see, first we make a connection, again this is nothing new, that we have not done before.

    Then we check if anything was submitted in the login form. If there was nothing submitted, then nothing will happen, because there is no else statement in this construction. We can do this, as you don't need to make an else statement, if you only made an if statement. You do however need to make an else statement, if you have made an "elseif" statement previously. A hacker will simply get a blanc page when he opens this page on his own and when he hasn't submitted anything in the login page and pressed login.

    Next we sanitize and validate the password and username. Remember the password and username are external variables, so we need to filter them first, before we do anything else with them. If the password is invalid then we set a variable called $Allowlogin to 2, likewise if the username is invalid this variable becomes 3. There is again a good reason for doing it this way. Suppose the username is invalid then we want to make the player aware of that, but the problem is that we can't show that message before any html was written. Text like any other html needs to be in the "body" part of the file. So this is why we store it as a variable for the time being.

    Finally with the filtering complete we check if the username and password are actually valid. First we get the password that corresponds to the submitted username from the users table. We do that with these 3 lines of code:

    Code:
    $result = mysql_query ("SELECT * FROM users WHERE username ='$username'");
    $row = mysql_fetch_assoc($result); 
    $tablepassword = $row["password"]; 
    
    Next we check with this condition:

    Code:
    ($password == $tablepassword)
    
    if the password that was submitted during login matches the password listed in the users table, then we know the password and username are valid. If it does not match, then the Allowlogin variable will be set to 4, else it will be set to 1. Remember this is basic logic. Suppose the username is wrong, then sql can't find the username in the table, because it simply isn't there. Php will then set the $tablepassword to null, because remember nothing is actually being fetched. Because null does not match the password submitted in the login form, it will of course lead to the condition being false, so the Allowlogin variable will be set to 4. Now suppose the password is wrong, but the username is correct. Then the sql query will fetch the correct password from the users table, and php will try to match the submitted password with the password fetched from the table. If the password does not match, then again the condition will be false.

    Now we will assume that the password and username are correct. First we set the Allowlogin variable to 1, and next we set the cookie. We call this cookie "person" and it will contain the username. We can use this cookie later in the game to check who is playing. If we don't set a cookie or a session, then the server will not be able to tell who is who. I will not explain how sessions work, but for now we do with just a cookie. Cookies aren't fully secure, there are ways to get round the security measures we've imposed in the game. But for now this will do, as we want to keep things simple and clear in these lessons.

    The time()+7200 is the expiration date of the cookie. With time() we fetch the current time of the server. We could also use javascript to set cookies, but because javascript is client side, it will fetch the time of the player's computer, because php is serverside it fetches the time of the server. The +7200 stands for plus 7200 seconds, which corresponds to 2 hours. Remember this is basic elementary math. Afterall there are 60 seconds in a minute and 60 minutes in an hour, so 60 times 60 times 2 is 7200 seconds. So the cookie is set to expire 2 hours after the current time.

    Finally we finish the if-else constructions and we close the sql connection. The reason that we are doing this now, is that we don't intend to use sql anymore beyond this point, so rather than keeping the connection open and hence put more stress on the server, we close the connection now.

    We stop the php script, write the html and then open the script again. In this last part of the php script we make an if-elseif-elseif-else construction and see what the Allowlogin variable is. If the variable is 1, then php will write a welcome message containing the username (pretty neat isn't it?), followed by a link to the first actual game file, which we call overview.php. If the submitted password or username is invalid then php will display one of the other messages and show a link to the login page, where the user may return and try again.

    OK that's all for now. In the next lessons I will show you how to make 2 game files for our "rock paper cissors" game. The first page called the overview.php page will show the rankings and a list of all the players. The second page which I will call attack.php is where the player will do the actual attacking.
     
    Last edited by a moderator: Aug 27, 2010
  6. shugo

    shugo Elite Ogre Ogre Veteran

    Messages:
    2,093
    Likes Received:
    12
    Trophy Points:
    38
    Credit:
    15,378.42
    LESSON 6 the game files (stage 1, the overview page)

    OK now we're finally getting to the good stuff. The code below in this post is the script of the overview.php file. It does not contain the rankings yet, I will explain that in later lessons. In stage 2 of lesson 6 I will show you how to make the attack page.

    But first the code of the overview page:

    Code:
    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> 
    <HTML> 
    <HEAD>
     <TITLE>Rock Paper Cissors</TITLE>
     <META NAME="description" CONTENT="overview"/> 
    <META NAME="keywords" CONTENT="overview"/> 
    </HEAD> 
    <BODY>
    <H1>Overview</h1>
     <?php
    if (isset($_COOKIE["person"])){
    $player = $_COOKIE['person'];
    
    //CONNECTION
    $con = mysql_connect("localhost","username","password");
    if (!$con)
      {
      die('Could not connect: ' . mysql_error());
      }
      
    //GAME DATABASE
    mysql_select_db("database1", $con);
    
    $result = mysql_query ("SELECT * FROM users WHERE username ='$player'");
    $row = mysql_fetch_array($result);
    $rpc = $row['rpc'];
    $alive = $row['alive'];
    
    if ($alive ==0){
    echo "<P>You are dead</P>";}
    else {
    
    echo "<H2>Players</H2>
    <P>
    <table border='0'><tr><th>Situation</th><th>Player</th></tr>";
    
    
    $resultover = mysql_query ("SELECT * FROM users WHERE username <>'$player' ORDER BY userID");
    while($rowover = mysql_fetch_array($resultover))
      {
    $tabuserid = $rowover['userID'];
    $tabusername = $rowover['username'];
    $tabrpc = $rowover['rpc'];
    $tabalive = $rowover['alive'];
    if ($tabrpc =="$rpc" && $tabalive ==0){
    echo "<tr><td>dead</td><td>".$tabusername."</td></tr>";}
    elseif ($tabrpc =="$rpc" && $tabalive ==1){){
    echo "<tr><td>ally</td><td>".$tabusername."</td></tr>";}
    elseif ($tabrpc !="$rpc" && $tabalive ==0){){
    echo "<tr><td>dead</td><td>".$tabusername."</td></tr>";}
    else {
    echo "<tr><td><A HREF='attack.php?opponent=".$tabuserid."'>attack</A></td><td>".$tabusername."</td></tr>";}
      }
    echo "</table>";
    
    }
    mysql_close($con);
    
    }
    else {
    echo "<P>No cookie detected</P>";}
    
    ?>
     </BODY> 
    </HTML>
    
    
     
  7. shugo

    shugo Elite Ogre Ogre Veteran

    Messages:
    2,093
    Likes Received:
    12
    Trophy Points:
    38
    Credit:
    15,378.42
    LESSON 6 (stage 1, example explained)

    OK lets go through the code bit by bit.

    First we check to see if the cookie is set. If the cookie is set we proceed further, else we get the error message "no cookie detected" at the bottom of the file.

    Second we make a connection and select the database.

    Third we fetch some variables from the users table. We want to know the following things: (1) if the player who logged in and whose cookie it is we have checked is still alive and (2) what this player is. Is he rock, or paper, or cissors? The way to do this is that we search for the row that corresponds to the username fetched from the cookie, as you can see in the WHERE clause.

    Next we make an if-else construction and see if the player is actually still alive. If he or she is dead, then we display the message "you are dead", else we proceed further and show the list of all the players, except the player from the cookie.

    We make a players table, that shows 2 columns, the first column has the player's situation and the second has the player's username. We get the results we want this way:

    Code:
    $resultover = mysql_query ("SELECT * FROM users WHERE username <>'$player' ORDER BY userID");
    
    the $resultover gets all the rows where the username does not correspond to the username fetched from the cookie, as "<>" is sql for NOT. We order the results by the userID, so the first user is on the top of the list and so on. These arrays (because they are called arrays) we got from the resultover variable contain all the rows from the users table, that we want to have. We don't want to have the row of the player from the cookie, since there is no need to (I'll explain later). In previous lessons the WHERE clause only fetched 1 row. In this example we fetch as many rows as there are players registered for the game minus 1, that 1 is of course the player from the cookie. We have to make a loop to display all these rows, we do that with a WHILE loop. Next we fetch and reference all the variables, except the password column. We don't want to show the password column for obvious reasons, as we don't want the player who logged in to see all the other players' passwords. In the while loop we make an if-elseif-elseif-else construction. In this construction there are 4 possible situations.

    To explain all these 4 situations we assume the following: (1) the player fetched from the cookie is alive and (2) the player fetched from the cookie is a rock.

    Situation 1 is where the player in the table row is a rock and dead. We show his or her situation as dead ally, followed by his or her username.

    Situation 2 is where the player in the table row is again a rock, but this time alive.

    Situation 3 is where the player in the table row is either paper or cissors and dead. Naturally we show him or her as dead enemy.

    Situation 4 is where the player in the table is either paper or cissors but this time alive. This is the situation in the else statement, for it is logical that this is the only available situation not mentioned in the previous 3 conditions. You'll notice that instead of mere words, this cell actually contains a link called attack, which leads to the attack.php page. You see that the url is a little unusual, this is because we want to set the userID variable in the url and get this variable on the attack page with the GET method, which I explained in previous lessons. How exactly this is done, I will explain in stage 2 of lesson 6.
     
  8. shugo

    shugo Elite Ogre Ogre Veteran

    Messages:
    2,093
    Likes Received:
    12
    Trophy Points:
    38
    Credit:
    15,378.42
    LESSON 6 (stage 2, the attack page)

    OK now we move on to stage 2 and make the attack page.

    Code:
    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> 
    <HTML> 
    <HEAD>
     <TITLE>Rock Paper Cissors</TITLE>
     <META NAME="description" CONTENT="attack"/> 
    <META NAME="keywords" CONTENT="attack"/> 
    </HEAD> 
    <BODY>
    <H1>Overview</h1>
     <?php
    if (isset($_COOKIE["person"])){
    $player = $_COOKIE['person'];
    
    if (isset($_GET['opponent'])) {
    filter_var($_GET["opponent"], FILTER_SANITIZE_STRING);
    
    if(filter_var($_GET["opponent"], FILTER_VALIDATE_INT)){
    $him = $_GET["opponent"]; 
    
    //CONNECTION
    $con = mysql_connect("localhost","username","password");
    if (!$con)
      {
      die('Could not connect: ' . mysql_error());
      }
      
    //GAME DATABASE
    mysql_select_db("database1", $con);
    
    /*VALIDATION*/
    
    $foecoresult = mysql_query ("SELECT COUNT(*) foecount FROM users WHERE userID ='$him'");
    $foecorow = mysql_fetch_array($foecoresult);
    $himcount = $foecorow[foecount];
    
    if ($himcount >=1) {
    
    $himresult = mysql_query ("SELECT * FROM users WHERE userID ='$him'");
    $himrow = mysql_fetch_array($himresult);
    $hisname = $himrow['username'];
    $hisrpc = $himrow['rpc'];
    $hisalive = $himrow['alive'];
    
    $result = mysql_query ("SELECT * FROM users WHERE username ='$player'");
    $row = mysql_fetch_array($result);
    $rpc = $row['rpc'];
    $alive = $row['alive'];
    
    if ($alive ==1){
    
    if ($hisalive ==1){
    
    /*PROCESSING ATTACK*/
    
    if ($hisrpc =="rock" && $rpc =="cissors"){
    mysql_query("UPDATE users SET alive ='0' WHERE username ='$player'");
    mysql_query("INSERT INTO kills (killer, victim)
    VALUES ('$hisname', '$player')");
    echo "you were defeated";
    }
    elseif ($hisrpc =="rock" && $rpc =="paper"){
    mysql_query("UPDATE users SET alive ='0' WHERE username ='$hisname'");
    mysql_query("INSERT INTO kills (killer, victim)
    VALUES ('$player', '$hisname')");
    echo "you were victorious<BR><A HREF='overview.php'>Continue</A>";
    }
    elseif ($hisrpc =="paper" && $rpc =="rock"){
    mysql_query("UPDATE users SET alive ='0' WHERE username ='$player'");
    mysql_query("INSERT INTO kills (killer, victim)
    VALUES ('$hisname', '$player')");
    echo "you were defeated";
    }
    elseif ($hisrpc =="paper" && $rpc =="cissors"){
    mysql_query("UPDATE users SET alive ='0' WHERE username ='$hisname'");
    mysql_query("INSERT INTO kills (killer, victim)
    VALUES ('$player', '$hisname')");
    echo "you were victorious<BR><A HREF='overview.php'>Continue</A>";
    }
    elseif ($hisrpc =="cissors" && $rpc =="paper"){
    mysql_query("UPDATE users SET alive ='0' WHERE username ='$player'");
    mysql_query("INSERT INTO kills (killer, victim)
    VALUES ('$hisname', '$player')");
    echo "you were defeated";
    }
    elseif ($hisrpc =="cissors" && $rpc =="rock"){
    mysql_query("UPDATE users SET alive ='0' WHERE username ='$hisname'");
    mysql_query("INSERT INTO kills (killer, victim)
    VALUES ('$player', '$hisname')");
    echo "you were victorious<BR><A HREF='overview.php'>Continue</A>";
    }
    else {
    echo "<P>You  may not attack your ally</P>";}
    
    /*ERROR MESSAGES*/
    
    }
    else {
    echo "<P>That player is already dead</P>";}
    
    }
    else {
    echo "<P>No such player exists</P>";}
    
    }
    else {
    echo "<P>You are dead and may not attack anymore</P>";}
    
    mysql_close($con);
    
    }
    else {
    echo "<P>An invalid integer</P>";}
    
    }
    else {
    echo "<P>You are not allowed to do that</P>";}
    
    }
    else {
    echo "<P>No cookie detected</P>";}
    
    ?>
     </BODY> 
    </HTML>
    
    
     
    Last edited by a moderator: Aug 27, 2010
  9. shugo

    shugo Elite Ogre Ogre Veteran

    Messages:
    2,093
    Likes Received:
    12
    Trophy Points:
    38
    Credit:
    15,378.42
    LESSON 6 (stage 2 explained)

    There are a few new things in this page that I will explain in greater detail. Lets go through the code step by step.

    First we check for a cookie and make sure that it is there.

    Next we check to see if the opponent variable is set. Remember in the overview page we made a link, with a weird looking url with a question mark in it. Now we use the GET method to fetch that variable. Because it is an external variable it has to be filtered and validated. The first thing we do is sanitize the variable. Next we make sure that is actually an integer (a number), as we will want to select numbers from the table not strings. We open a connection. We count the row and make sure with the where clause that we get the right row. We reference the row to a variable called $himcount. Finally we check to see if it is higher than 0. If no row exists, than the variable will be null or 0. If the player does exist, then the himcount variable has to be 1. The reason that we do this is that we don't want the player to attack a non-existing player. Remember someone (a hacker) might try to open the page manually by typing in the url and type in a bogus number for the opponent variable. We don't want that to happen, so this is one way how we prevent that.

    Next we check to see if both the attacker and the defender are actually still alive, because we can't have a dead attacker, keep attacking, nor can we have an alive attacker attack an already dead defender.

    Finally we come to the area where we process the attack. I will not explain all possible situations, but I will explain the if statement and the else statement. In the attack there are 9 possible outcomes. Because we don't want a rock to attack another rock, we put that situation in the "else" statement, likewise the same thing happens, when a paper attacks a paper. So in the ELSE situation we prevent the attack from occuring and send a message to the player saying "You may not attack your ally". In the IF statement the attacker (the player fetched from the cookie) is a "cissors" and he has attacked a "rock". Since we know that rock beats cissors, then attacker loses the attack. We then perform a mysql query with an update command and set the default value of 1 (which stands for alive) to 0 (which stands for dead). The player who was a cissors is now dead. After the update we insert a row in the kills table where we store the kill. We could have done this in other more convenient ways and just add a column to the users table, that stores the kills, but we will not be able to track who killed who and that is what we want to do in this case. We can use this kills table for our rankings. I'll explain how to make the rankings in lesson 7. We finalize the attack page with the error messages and close off the connection.
     
    Last edited by a moderator: Aug 27, 2010
  10. shugo

    shugo Elite Ogre Ogre Veteran

    Messages:
    2,093
    Likes Received:
    12
    Trophy Points:
    38
    Credit:
    15,378.42
    LESSON SUMMARY

    That is all there is to it. We now have a fully flegded game, ready to be uploaded on the hosts's server. This very simple game will work fine. I guess by now you're wondering, "is that it"? "Woah it can't be that simple?" And the truth is, you're right. Although the game works, it is far from finished. There are many things not there!

    For starters we haven't made our rankings yet (to be explained in lesson 7).

    But there are many more things missing:

    -we haven't shown how to set a victory condition for whichever group of rock paper or cissors who wins the game (to be explained in lesson 7)
    -there is no logout page
    -there are no ways to determine who has more than one account and therefore there is no way to detect who is cheating
    -we have used cookies, which aren't secure, sessions are really prefered, because suppose someone alters their cookie (good hackers know how to do this)
    -the looks of all the pages are terrible. All the pages have the default white background, with blue links, black font and the font is likely to be the default font (usually sans serif). It is likely that most people will find those pages to be ugly. We need some CSS, to make the pages more pleasing to the eye.
    -we have not used any javascript. The way we made the attack is in fact rather cumbersome, we could have kept the player on the same overview page with use of a scripting style called AJAX (a combination of javascrip and php).

    Some of this will be explained into greater detail in lesson 7 (the last lesson). The rest I leave up to you to find out.

    Here are some useful links where you can find more information:

    W3Schools Online Web Tutorials
    SQL Tutorial - SQL Query Reference and Programming Examples

    If you followed these 6 lessons, then by now you are no longer a rookie, but you are no expert either. There are many more things you can do with php.

    You can make anything you want, just use your inmagination....
     
    Last edited by a moderator: Aug 27, 2010
  11. shugo

    shugo Elite Ogre Ogre Veteran

    Messages:
    2,093
    Likes Received:
    12
    Trophy Points:
    38
    Credit:
    15,378.42
    LESSON 7 (rankings)

    There are several ways to solve the problem of creating rankings with the 2 tables we have. I'll discuss 2 ways of solving that problem.

    There is an easy way and a hard way. I'll show the easy way first. The real problem is that we want to have the number of kills to go alongside the name, if we simply did a while on the kills table, then we get persons who have more than one kill, displayed more than one time. That is of course something we don't want. So how do we solve that?

    With the easy way you only need the kills table. Basically what you do is SELECT a DISTINCT player (killer column) who has kills or rows (victim column) on his username and then COUNT how many he or she has. Since we want the person who has the most kills to be on top of the rankings, we ORDER the rows BY the amount of kills they have in a DESCending order.

    Code:
    $result = mysql_query ("SELECT DISTINCT killer, COUNT(victim) AS victims FROM kills ORDER BY victims DESC"); 
    while($row = mysql_fetch_array($result))
    {
    /*PLACE WHERE YOU DISPLAY THE TABLE ROWS*/
    }
    
    OK so much for an easy way of doing that.

    There is also a difficult way of doing, which involves using both tables. What we do is take the username from the users table and count the number of victims in the kills table. The problem is that these two columns are in 2 different tables. We solve this problem by making a thing called an SQL JOIN, WHERE username (of the users table) = killer (of the kills table), we then select the username from the users table and count the victims from the kills table.

    OK with that out of the way, we move on to the victory condition. The game should be won by a group, either all the rocks left alive, or all the papers left alive, or all the cissors left alive. If there are no more cissors and no more papers, then clearly the rocks have won. So how do we do this? First we count how many rocks there are, then how many papers, and next how many cissors there are. Second we count how many alive rocks there, then how many alive papers there are and finally how many alive cissors there are. If the amount of alive cissors equals 0, then clearly all cissors must be dead or not present in the game. Likewise we can do this for papers. If there are papers, but they are all dead, then we set a variable to 1, which stands for true. Likewise we do this for cissors and for rocks too. We add these 3 variables. If the resulting variable equals 2, then we know there are rocks, papers and cissors in the game, and that either rocks and papers, or papers and cissors, or rocks and cissors are all dead, which means some group must have won the game. That's how we do it.

    This situation is of course not quite satisfactory nor entirely fair. Suppose you only have 3 players in the game, 1 rock, 1 paper and 1 cissors, then rock could let paper win the game, if he or she killed cissors first. So how do we solve that, well we could count the total number of players in the game and make sure the number is 6 or higher, but that still wouldn't solve things. The real underlying problem is that we let players choose what they want to be. We could have simply eliminated that input field from the register page, and let a script decide at random. So now you might ask how do you do that?

    Code:
    $rpcpick = $rand(1,3);
    
    With that line we make a random number, with an if-elseif-else construction we can set the rpc column to be rock, paper or cissors. This way 1 can stand for rock, 2 for paper and so on. If we then have at least 2 rocks, 2 papers, 2 cissors in the game (we can count that too), then things would be a lot fairer.

    Now we are almost done with our final lesson, but I'll explain one last thing to you, before we are finished. The last thing is the logout page. I bet you are wondering how you let the logout page to delete a cookie. Actually we don't delete the cookie, we simply let it expire. What we do is reverse the process, instead of adding 2 hours like we did in the login page, we substract the 2 hours.

    Code:
    setcookie("person", $username, time()-7200);
    
    Simple enough, eh?!

    That's it, our final lesson is finished. If you happen to read these lessons and think there is still some stuff left unanswered that you really want to know, then you may also pose your questions in this thread and maybe if you're lucky we'll answer them for you.

    That's all folks!
     
    Last edited by a moderator: Aug 28, 2010
  12. Joker

    Joker Ogre Hall of Fame Ogre Veteran

    Messages:
    11,331
    Likes Received:
    468
    Trophy Points:
    83
    Credit:
    10,336.17
    I really to read this when I have time. Coding is cool.
     
  13. shugo

    shugo Elite Ogre Ogre Veteran

    Messages:
    2,093
    Likes Received:
    12
    Trophy Points:
    38
    Credit:
    15,378.42
    Well I tried to be as concise as possible, but it still makes for a long read in some areas. I hope you like it so far.
     
Thread Status:
Not open for further replies.

Share This Page