OSdata.com: holistic issues 

OSdata.com

example source code

    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 can’t even afford the fee to sign up for Apple’s 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 doesn’t 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.

license

    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 I’m not using modern techniques, it is because I am working under absurd conditions. For some of the problems, see below.

Google

example source code

    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.

data base

    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.

create code to connect to the database

    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 don’t 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.

display current top 25 rankings

    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.

preparing for interactivity

    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.

add JavaScript to send vote increment

    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.

fixed cross-domain JavaScript

    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 ain’t 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.

increment count in data base

    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.

random celebrity

    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.

celebrity picture

    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.

celebrity info

    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.

cosmetic changes

    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>

top 21

    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.

account utilities

    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.

data validation

    A few data validation routines.

    The code is at datavalidation.php.

new registration

    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

    Visitor authorization functions.

    The code is at visitorauthorization.php.

react to submitted registration form

    Add code to the index.php file to react to an incoming new registration form.

    The code is at index.php.

login

    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.

changes to front page

    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.

logout

    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.

session management

    Temporarily relying on the built-in default PHP session management.

    The code is at index.php.

change timer

    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.

invitation to play

    Minor changes to invite people to play the game:

    The code is at index.php.

game server

    Now we set up a debugging version of the game server.

    The code is at gameserver.php.

run blank game

    We modify the code to start running the blank game (which for now just gives the debug message).

    The code is at index.php.

game dispatcher

    Start the code for the game server dispatcher.

    The code is at gameserver.php.

static game layout

    Display a static layout for the game round.

    The code is at gamefunctions.php.

initiate game record

    Create a persistent data base record for a new game.

    The code is at gamefunctions.php.

change account functions

    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 scores

    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 round

    Create the next round for a game.

    The code is at gamefunctions.php.

pick villains

    Pick the two villains for the round.

    The code is at gamefunctions.php.

display villains

    Display the two villains for the round.

    The code is at gamefunctions.php.

accept input

    Accept game input.

    The server code is at gameserver.php.

generate game input

    Generate game input from the browser side.

    The code is at index.php.

button to slam

    Generate game input from the browser side.

    The code is at gamefunctions.php.

show new round

    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.

move game creation

    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

    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 celebrity slam total

    Fetch the current total for a celebrity slam.

    The code is at gamefunctions.php.

start round scoring function

    Start building the round scoring function.

    The calling routine is at gameserver.php.

    The actual routine is at gamefunctions.php.

complete round update function

    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.

end game

    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.

create first round

    Add code to create the first round.

    The check for end of game is at gameserver.php.

store time and date

    Record the starting time and date of each game.

    The end game function is at gamefunctions.php.

bonus rounds

    Points double in the bonus rounds (7-10).

    The end game function is at gamefunctions.php.

show points

    Add graphic bull’s eye to show who earned points each round.

    The end game function is at gamefunctions.php.

add contact form

    Simple contact form.

    The end game function is at contact.php.

broken glass effect

    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.

bar graph

    We are going to use a bar graph effect to show the points awarded.

    And a change in the matching JavaScript in gamefunctions.php.

remove timer info

    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.

minor account change

    Instead of displaying the player’s 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 trivia question

    Display the trivia question.

    See the source code at gamefunctions.php.

move bonus round to top

    Move the bonus round message to the top of the game.

    See the source code at gamefunctions.php.



check for timed out cookie

    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.

remove registration form is signed in

    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.

start to hook up radio buttons

    React to the form radio buttons.

    See the source code at gamefunctions.php.

check for trivia question answer

    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 trivia question

    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.

move trivia question

    The call for the trivia question was moved from after the slam stuff to before it.

toggle game state

    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.

lock out slamming

    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 in trivia data

    Send the trivia results to the server.

    See the main index file at index.php.

process trivia data

    Process the trivia answer.

    See code at gameserver.php.

process trivia points

    Set player points based on trivia answer.

    See code at gamefunctions.php.

variable height points chart

    Make the points chart variable height.

    See code at gamefunctions.php.

question generator

    A question generator function.

    See code at gamefunctions.php.

add love/like button

    Add the love or like button.

    See code at gamefunctions.php.

    See the main index file at index.php.

    See code at gameserver.php.

game object

    Start converting the game functions and variables into an object and class.

    See code at gameobject.php.

celebrity object

    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.

start using game object

    Create the game object and use it to store the game number.

    See code at gameserver.php.

    See code at gamefunctions.php.

new header

    New header for the web page.

    See the main index file at index.php.

birth place check

    Check to see if birth places of two celebrities match.

    See code at gamefunctions.php.

birth place question generator

    Generate a trivia question about a celebrity birth place.

    See code at gamefunctions.php.

birth date question generator

    Generate a trivia question about a celebrity birth date.

    See code at gamefunctions.php.

real name question generator

    Generate a trivia question about a celebrity real name.

    See code at gamefunctions.php.

eliminate start game message

    Eliminate the start game message (and link/button)

    See the main index file at index.php.

add play4pay graphics

    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.

info button

    Add the info button.

    See code at gamefunctions.php.

    See the main index file at index.php.

celebrity info block

    Have the server provide information on a celebrity.

    See code at gameserver.php.

    See code at celebrityinfo.php.

show celebrity info blocks

    If the screen is wide, show the celebrity info blocks after every trivia question.

    See the main index file at index.php.

phone version

    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.

occupation questions

    Add occupation questions to the trivia game.

    See code at gamefunctions.php.

spin button

    Add the spin button.

    See the main index file at index.php.

    See code at gamefunctions.php.

red and green buttons

    Add the red and green buttons.

    See the main index file at index.php.

    See code at gamefunctions.php.

three indicators

    Add three indicators, two of which have unknown purposes.

    See code at gamefunctions.php.

obsolete iPhone

    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.

slot machine

    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.

preparation for combining

    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().

add slams and loves

    Realized that we weren’t 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

    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.

tokens/credits/money

    Add integer fields to the data base for money, credits, and tokens, with each defaulting to one.

    The code is at visitorauthorization.php.

trivia points = credits

    Every trivia game point is an additional credit for the player.

    See code at gamefunctions.php.

display money, credits, tokens

    Display the token, credit, and money results.

    See code at game.php.

    See code at gamefunctions.php.

add new game segment for slots

    Add new game segment for slots.

    See code at gameserver.php.

    See code at gamefunctions.php.

    See code at game.php.

picture answer in trivia

    Change the picture so that it also an answer during trivia.

    See code at gamefunctions.php.

    See code at game.php.

show money

    Show money in DisplayThreeIndicators.

    See code at gamefunctions.php.

add tokens with slam or love

    Add tokens with any slam or love.

    See code at gameserver.php.

    See code at gamefunctions.php.

calculate account number before dispatcher

    Move the calculation of the account number to before the dispatcher.

    See code at gameserver.php.

hide initial slot pictures

    Hide the slot pictures at the start of slot, then reveal on a spin.

    See code at gamefunctions.php.

    See code at game.php.

activate begin images

    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

    Show round number in slots.

    See code at gamefunctions.php.

shrink width of slots

    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.

show trivia points

    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 slot tokens

    Grant the tokens and credits for winning slots.

    See code at gamefunctions.php.

add loation data to signup

    Add location data to sign up.

    The code is at newregistration.php.

message for slot winnings

    Message for slot winnings.

    See code at game.php.

    See code at gamefunctions.php.

flash sports

    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 slots timer

    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.

specialty rounds

    Add specialty rounds for different categories of celebrities.

    See code at gamefunctions.php.

pass out money

    Convert credits to money at the end of a game.

    See code at gamefunctions.php.

changed end of game message

    Changed the end of game message.

    See code at gamefunctions.php.

added more categories

    Added more categories for celebrity game rounds.

    See code at gamefunctions.php.

singers and rappers

    Don’t confuse singers and rappers on trivia questions.

    See code at gamefunctions.php.

drawing in canvas

    A quick sample that shows how to draw the basic items in Canvas.

    See code at draw in canvas.

Eliza

    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.

list of source code example pages


OSdata.com is used in more than 300 colleges and universities around the world

Find 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

Read details here.


    A web site on dozens of operating systems simply can’t 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
previous page next page

home page


Made with Macintosh

    This web site handcrafted on Macintosh computers using Tom Bender’s Tex-Edit Plus and served using FreeBSD .

Viewable With Any Browser


    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
previous page next page