OSdata.com |
Building a game open source code This is the actual source code from a new web game. See the game at thissideofsanity.com and read how this was built starting at on this web page.
The theory of computer science is very pretty. Real world programming (except at a few companies that specialize in high quality products) is an ugly mess.
I thought it might be very useful to show the compromises that are required in real world programming.
This is a game. The owners are unable to afford reasonable development resources. They are relying primarily on broken equipment they can find in their closet. They cant even afford the fee to sign up for Apples developer program or provide me with a working smart phone, but they insist that they need a phone app version as well as a web-based version of the game.
When I first started programming, programmers were rare and we were given high quality equipment. Nowadays there are far more programmers than jobs and we are treated as expendible, replaceable garbage.
The first problem is that programmers and programming are an expense to business people. Therefore, their attitude is to do everything possible to cut down the expense of programming, just as they take measures to cut down their electricity bill.
This is the source of the inevitable lack of sufficient equipment or adequate work environment. It just doesnt make sense for businesses to spend more for a higher quality product (unless they are a company like Apple, which has a sales reputation of making high quality products).
This is why they treat programmers as interchangeable parts. You are in competition with programmers from India who have PhDs and will work for $10 an hour.
This example is about the real world struggles of trying to get real world work done under the ridiculous conditions provided by business.
This is example code from the SlamZee project and This Side of Sanity, released under Apache License 2.0.
Copyright 2013, 2014 Milo (for software), Distribution and website handled by Strazbick.com
Licensed under the Apache License, Version 2.0 (the License); you may not use this file except in compliance with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an AS IS BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
This narrative uses anchor links so that you can follow the building of this software in chronological order. Go to thissideofsanity.com to see the working software.
Working with a broken computer running outdated software is a real hassle. It makes it very difficult to get anything written at all. If you are wondering why Im not using modern techniques, it is because I am working under absurd conditions. For some of the problems, see below.
This is example code from the SlamZee project and This Side of Sanity, released under Apache License 2.0.
This is written with procedural programming techniques because the site owners can only provide an antique computer (that crashes a lot) and comes with a broken keyboard (no shift key or space bar) and a broken mouse (no horizontal or vertical scroll). I am doing the best I can under the circumstances.
My first step was to build the structure of the data base. This took surprisingly long because the demands of MySQL and/or phpMyAdmin caused the computer to crash every few minutes and in between various windows or parts of windows would display various kinds of random garbage.
Next I wrote some simple procedural PHP to connect to the data base and report success or failure, along with a matching piece of code in a simple test page that attempted to open the data base connection and report the result. The simple wrapper code is reproduced below and the simple data base connection sode is located at
The simple procedure for connecting to the database is in databasefunctions.php.
Note that I dont even create the normal html, head, and body tags. The error correction in modern browsers will compensate and I will see my results without any clutter code.
<?php require_once('./php/databasefunctions.php'); $result = ConnectCelebDataBase(0); echo '
the result is *'.$result.'*'; ?>
The good news is that the data base connection worked.
I have seeded the data base using a combination of information from Star and TMZ, with fake vote totals that reflect the opinions of those two sources.
Now I need to display these totals.
The sample code, the first item in index.php, creates the HTML header, opens the data base connection, does an SQL query for the 25 most hated celebrities, and then cycles through the rows outputting an ordered list.
Once again I use outdated PHP functions and I also mix computation and presentation. Very bad example. Slap my fingers.
The results:
Go see the source code at index.php.
Now I modify the source code slightly to put labelled spans around the vote counts so that I can update them with AJAX.
The example code only shows the parts that have changed.
Go see the source code at index.php.
I add a JavaScript function that sends a message to increment the vote count for a single celebrity and a link for the user to press. Later this link will be replaced with a pretty button.
Go see the source code at index.php.
I was surprised that the working code for AJAX suddenly stopped working. After a ridiculous amount of time testing, I discovered that I had a cross-domain JavaScript problem.
My PHP script inserts a hard-wired URL of "http://www.slamorjam.com/addvote.php?celebrity="+celebritynumber
. When I connected to slamorjam.com
instead of www.slamorjam.com
(the difference is the lack of the www.
), the JavaScript was rejecting any results because of alleged cross-domain scripting. The www. subdomain is mapped to the actual domain. That aint cross-domain.
So, a quick fix. I inserted the following bit of PHP to replace the domain name:
<?php echo $_SERVER['SERVER_NAME']; ?>
I provide the fixed source code with a little bit of extra debugging code at index.php.
Now we make the AJAX actually work, in this case incrementing a vote count.
The receiving PHP file uses an SQL UPDATE to increment the selected vote count and then an SQL SELECT to get the new total and echoes the new total, which in turn is placed into the correct target span by JavaScript on the browser side.
See the working code at addvote.php.
Our next step is to start displaying random celebrities. The code in the main index file includes a JavaScript for loading a new celebrity every six seconds and a simple include to show the first celebrity. The JavaScript accesses the exact same file for each subsequent celebrity.
First a look at the JavaScript, which uses a simple six second timer and an AJAX load. See index.php.
Then look at the code to generate a random celebrity at newcelebrity.php.
The previous attempt shows a default picture in the location where a celebrity picture should go. Now we add some simple code that tests to see if we have a celebrity picture stored and if so we display the celebrity picture, otherwise we show the default picture.
The code is at newcelebrity.php.
Now we add the code for celebrity information. There is a little arrow button. If the user clicks oon the arrow, the timer stops on the current celebrity and the information block on that celebrity is fetched from the server and inserted into the web page. If the user clicks on the arrow again, then the celebrity info disappears and the timer resumes.
The web browser client side of the code is at index.php.
A small change is made to the server side code at newcelebrity.php.
The server side of the code is at celebrityinfo.php.
The next batch of changes are cosmetic to make the website look better.
In newcelebrity.php we add a div tage to set the background color for the action message.
<div style="font-family:Arial, Geneva, Helvetica, serif;color:black;background-color:#ff5555;"> <h2 align="center" style="font-family:Arial, Geneva, Helvetica, serif;color:black;font-size:20">click the sledgehammer to slam</h2> <p align="center"><span id="anotherarea"></span></p> </div>
The next step is adding code to present the top 21 most slammed celebrities as a picture list. Note that the picture list is not yet connected up to celebrity profiles, but you can easily predict how that step will get added because it is a variation of already existing code.
I changed the default state of the temptationswitch in the JavaScript so that the timer initially rejects loading new celebrities.
var temptingswitch = true;
And I changed from loading the first random celebrity to loading the top 21 most slammed celebrities.
require_once('./top21celebrities.php');
The server side of the code is at top21celebrities.php.
There is some ugliness in the presentation, but I have been told that the owners will make arrangements for artwork and design work, so I am only concerned about software for now.
Now we start building the account system. These are four basic routines.
SessionManagement is called near the beginning of processing the main page -- it sets session variables fromt he cookie. Relies on built-in function, but easy to swap out with something soon.
CheckValidUser relies on the work of SessionManagement and returns the user name if there is a valid user, otherwise returns the empty string
GetAccountNumberFromAccountName does exactly what the title says.
GetAccountNameFromAccountNumber also does exactly what the title says.
The code is at accounts.php.
A few data validation routines.
The code is at datavalidation.php.
The new registration facility will temporarily go to the index page. Later we will convert it to AJAX. The is done as a two step process to keep the work more simple and cut down on the possible causes of failures in new code.
The code is at newregistration.php.
Visitor authorization functions.
The code is at visitorauthorization.php.
Add code to the index.php file to react to an incoming new registration form.
The code is at index.php.
The login facility will temporarily go to the index page. Later we will convert it to AJAX. The is done as a two step process to keep the work more simple and cut down on the possible causes of failures in new code.
The code is at login.php.
Now we hook up the new code on the front page. Note that once again this is a temporary method just to get us up and running.
The code is at index.php.
The logout facility will temporarily go to the index page. Later we will convert it to AJAX. The is done as a two step process to keep the work more simple and cut down on the possible causes of failures in new code.
The code is at logout.php.
Temporarily relying on the built-in default PHP session management.
The code is at index.php.
The JavaScript timer is changed to be a general dispatcher for various different activities. It will fire every 1/100th of a second and use countdown timers to decide what actions should be performed.
The code is at index.php.
Minor changes to invite people to play the game:
The code is at index.php.
Now we set up a debugging version of the game server.
The code is at gameserver.php.
We modify the code to start running the blank game (which for now just gives the debug message).
The code is at index.php.
Start the code for the game server dispatcher.
The code is at gameserver.php.
Display a static layout for the game round.
The code is at gamefunctions.php.
Create a persistent data base record for a new game.
The code is at gamefunctions.php.
Created a new account function and modified an existing account function to support the switch from account name to email being the unique identifier. We will now allow duplicate account (screen) names.
The code is at accounts.php.
Report the current scores (which better be zero). Note that this code relies on the SQL database assigning a default value of zero to each score when the new game record is created.
The code is at gamefunctions.php.
Create the next round for a game.
The code is at gamefunctions.php.
Pick the two villains for the round.
The code is at gamefunctions.php.
Display the two villains for the round.
The code is at gamefunctions.php.
Accept game input.
The server code is at gameserver.php.
Generate game input from the browser side.
The code is at index.php.
Generate game input from the browser side.
The code is at gamefunctions.php.
Show the next round (until the round is actually incremented, this will show the current working round for debug purposes).
The code is at gameserver.php.
The game creation call is in the wrong place -- move so it only occurs at start of new game.
function NewRound($gamechoice,$reporteduser,$gamenumber)
/* dispatch based on what game activity requested */ if ( $startcode != '' ) StartGame($startcode,$reporteduser); elseif ( $roundchoice != '' ) NewRound($roundchoice,$reporteduser,$gamenumber);
Change to StartGame.
The code is at gameserver.php.
Add the game number.
onclick="submitround(1,<?php echo $gamenumber; ?>);"
And send to server.
var submitroundurlstring = "http://<?php echo $_SERVER['SERVER_NAME']; ?>/gameserver.php?choice="+whichchoice+"&game="+gamenumber;
And receive game number at server.
$gamenumber = $_GET['game']; /* have a game number */
And debug reporting.
echo '<p align="center">New round with input '.$gamechoice.' for player '.$reporteduser.' and game number '.$gamenumber.'</p>';
Record the slam made by the player.
Call the routine.
UpdatePlayerSlam($gamechoice,$playernumber,$gamenumber); /* located in gamefunctions.php */
Code for the routine.
The code is at gamefunctions.php.
Fetch the current total for a celebrity slam.
The code is at gamefunctions.php.
Start building the round scoring function.
The calling routine is at gameserver.php.
The actual routine is at gamefunctions.php.
I built this function one section at a time. Rather than bore you (because everything worked on the first attempt), I will show the finished function.
The actual routine is at gamefunctions.php.
Now add the check for the end of game.
The check for end of game is at gameserver.php.
The end game function is at gamefunctions.php.
Add code to create the first round.
The check for end of game is at gameserver.php.
Record the starting time and date of each game.
The end game function is at gamefunctions.php.
Points double in the bonus rounds (7-10).
The end game function is at gamefunctions.php.
Add graphic bulls eye to show who earned points each round.
The end game function is at gamefunctions.php.
Simple contact form.
The end game function is at contact.php.
Add a broken glass effect for slams.
Several changes in the main index file at index.php.
And a change in the matching JavaScript in gamefunctions.php.
We are going to use a bar graph effect to show the points awarded.
And a change in the matching JavaScript in gamefunctions.php.
At this point we comment out (remove) the timer debug information from index.php. This is a cosmetic change to make the game look better. We can always bring back the timer info if there is a need.
Instead of displaying the players email address, we display the screen name. This is a very minor change.
echo '<p align="center">currently logged in as ',GetAccountNameFromAccountNumber(GetAccountNumberFromEmail($accountemail)),'<br>';
Display the trivia question.
See the source code at gamefunctions.php.
Move the bonus round message to the top of the game.
See the source code at gamefunctions.php.
Add a little bit of code to check to see if the cookie timed out. If so, ask them to log back in rather than let them see a game with lots of SQL errors.
The check for end of game is at gameserver.php.
No reason to show the registration form if someone is already logged in. So remove it when logged in.
Several changes in the main index file at index.php.
React to the form radio buttons.
See the source code at gamefunctions.php.
Check to see when the trivia question is answered.
A couple of changes in the main index file at index.php.
And a change in the gamefunctions.php.
Remove the question when a choice is made.
A change in the main index file at index.php.
And a change in the gamefunctions.php.
The call for the trivia question was moved from after the slam stuff to before it.
Now we add a variable for whether we are in the trivia or the slam game state and toggle back and forth on trivia answers and slams.
See the main index file at index.php.
When we are in trivia mode, we lock out the slamming function and even remind people to answer trivia question first.
See the main index file at index.php.
Send the trivia results to the server.
See the main index file at index.php.
Process the trivia answer.
See code at gameserver.php.
Set player points based on trivia answer.
See code at gamefunctions.php.
Make the points chart variable height.
See code at gamefunctions.php.
A question generator function.
See code at gamefunctions.php.
Add the love or like button.
See code at gamefunctions.php.
See the main index file at index.php.
See code at gameserver.php.
Start converting the game functions and variables into an object and class.
See code at gameobject.php.
Start converting the celebrity functions and variables into an object and class.
Note that we also replaced every reference to villains to be a reference to Celebrities in function and varaible names, because the game has long since been about celebrities.
See code at celebrityobject.php.
Create the game object and use it to store the game number.
See code at gameserver.php.
See code at gamefunctions.php.
New header for the web page.
See the main index file at index.php.
Check to see if birth places of two celebrities match.
See code at gamefunctions.php.
Generate a trivia question about a celebrity birth place.
See code at gamefunctions.php.
Generate a trivia question about a celebrity birth date.
See code at gamefunctions.php.
Generate a trivia question about a celebrity real name.
See code at gamefunctions.php.
Eliminate the start game message (and link/button)
See the main index file at index.php.
The graphics are in the official artwork, so I am adding it. I hope that the artist will tell me what the box is for, because he has refused to tell me the purposes of any of his new game functions.
See the main index file at index.php.
Add the info button.
See code at gamefunctions.php.
See the main index file at index.php.
Have the server provide information on a celebrity.
See code at gameserver.php.
See code at celebrityinfo.php.
If the screen is wide, show the celebrity info blocks after every trivia question.
See the main index file at index.php.
If the screen is narrow (smartphones), have info button or picture activate the celebrity info in the trivia area.
See code at gamefunctions.php.
See the main index file at index.php.
Add occupation questions to the trivia game.
See code at gamefunctions.php.
Add the spin button.
See the main index file at index.php.
See code at gamefunctions.php.
Add the red and green buttons.
See the main index file at index.php.
See code at gamefunctions.php.
Add three indicators, two of which have unknown purposes.
See code at gamefunctions.php.
The owners have provided a used iPhone 4 for development. The current generation at the time of this writing is the iPhone 5s. While it is far better to have any smartphone than have none, this old iPhone is overwhelmed by the software being written. I have no easy way of knowing whether a modern iPhone would also be overwhelmed.
The owners wanted a slot machine effect. The visual presentation is based on the little CSS3 experiment by Jonathan Shook, located at http://snook.ca/technical/slots/. Please compare the original to see how easy it is to avoid reinventing the wheel. There are many great examples of starter code that you can use to expand into real projects. Look for things that are published as examples or tutorials and follow the license restrictions imposed by the original author. And always give appropriate credit, as I have done in this case.
Our version uses JavaScript, becaause we want to have greater control over the slot machine effect.
Also, our version generates the eight picture strip on the fly using the PHP implementation of GD.
See code for the browser side at game.php.
See code for generating a random picture for the slot machine at makepicture.php.
The next major step is combining the slot machine game into the trivia and slam games.
The two different efforts both had a function named spin(). These are now named.slotspin()
and.divspin()
.
Realized that we werent recording the slams or loves in the game database (just which celebrity the action was on, not what the action was). So some quick updates to record that information.
See code at gameserver.php.
See code at gamefunctions.php.
See code at makepicture.php.
Partial merger of the two files (the slot machine and the trivia game). In particular, make sure that the two sets of JavaScript are compatible (which took some work).
See code at game.php.
Add integer fields to the data base for money, credits, and tokens, with each defaulting to one.
The code is at visitorauthorization.php.
Every trivia game point is an additional credit for the player.
See code at gamefunctions.php.
Display the token, credit, and money results.
See code at game.php.
See code at gamefunctions.php.
Add new game segment for slots.
See code at gameserver.php.
See code at gamefunctions.php.
See code at game.php.
Change the picture so that it also an answer during trivia.
See code at gamefunctions.php.
See code at game.php.
Show money in DisplayThreeIndicators.
See code at gamefunctions.php.
Add tokens with any slam or love.
See code at gameserver.php.
See code at gamefunctions.php.
Move the calculation of the account number to before the dispatcher.
See code at gameserver.php.
Hide the slot pictures at the start of slot, then reveal on a spin.
See code at gamefunctions.php.
See code at game.php.
The slot machine starts with three pictures labelled begin, so we are going to activate these and make them begin buttons.
See code at gamefunctions.php.
Show round number in slots.
See code at gamefunctions.php.
Shrink the size of the slots to fit in portrait format on smart phones.
See code at game.php.
See code at makepicture.php.
See code at gamefunctions.php.
We want to show the trivia points in the entire game, including the slots section. We therefore need persistent (database) storage of the current point earner, as well as add the code to show the trivia points display under the slots.
See code at gamefunctions.php.
Grant the tokens and credits for winning slots.
See code at gamefunctions.php.
Add location data to sign up.
The code is at newregistration.php.
Message for slot winnings.
See code at game.php.
See code at gamefunctions.php.
Started work on the flash sports pages.
See code at sports.php.
See code at team.php.
See code at teamfunctions.php.
This work is split off into its own set of example code for the time being.
Change the slots animation timer to get a JavaScript time and add two seconds. On older iPhones the two second animation is running more than 20 seconds because the counter approach is not running often enough.
See code at game.php.
Add specialty rounds for different categories of celebrities.
See code at gamefunctions.php.
Convert credits to money at the end of a game.
See code at gamefunctions.php.
Changed the end of game message.
See code at gamefunctions.php.
Added more categories for celebrity game rounds.
See code at gamefunctions.php.
Dont confuse singers and rappers on trivia questions.
See code at gamefunctions.php.
A quick sample that shows how to draw the basic items in Canvas.
See code at draw in canvas.
Started work on the Eliza chatterbot.
See the main index file at index.php.
See code at eliza.php.
See code at elizaserver.php.
See code at elizafunctions.php.
This is the end of the example work so far.
OSdata.com is used in more than 300 colleges and universities around the worldFind out how to get similar high web traffic and search engine placement. |
OSdata.com is used in more than 300 colleges and universities around the world |
Tweets by @osdata |
A web site on dozens of operating systems simply cant be maintained by one person. This is a cooperative effort. If you spot an error in fact, grammar, syntax, or spelling, or a broken link, or have additional information, commentary, or constructive criticism, please e-mail Milo. If you have any extra copies of docs, manuals, or other materials that can assist in accuracy and completeness, please send them to Milo, PO Box 1361, Tustin, CA, USA, 92781.
Click here for our privacy policy.
previous page | next page |
This web site handcrafted on Macintosh computers using Tom Benders Tex-Edit Plus and served using FreeBSD .
Names and logos of various OSs are trademarks of their respective owners.
Copyright © 2013, 2014 Milo
Last Updated: January 16, 2014
Created: September 9, 2013
previous page | next page |