Archive for March, 2008

Web hosting services - 896Part VCase Studies3.Query the previous question to discover

Thursday, March 27th, 2008

896Part VCase Studies3.Query the previous question to discover the range of the guess and whether the ques- tion was correctly answered. Update all scores (credit, correct answers) appropriately. 4.Decide whether to promote the player to a new level now. If so, retrieve the databaseIDs of all questions that may be asked at that level. Randomize the order of the ques- tion list. 5.If the game has not yet ended, grab a new question ID from the randomized list and useit to ask the database for a new question. Turn that data into a Questionobject andmake it the current question. Serialization and sleep() The sleep()function is called to do cleanup whenever an object is serialized and alsoreturns a list of all the member variables that should be recorded in a serialization. The Gameclass makes use of only the latter capability all member variables except the previousquestion and the database connection itself are retained as the object is stored in the sessionfor the next page s use. Unlike with some other class definitions, we ve defined Game s variables to be public. This isbecause in our testing with PHP5.0b1, we discovered that private variables were not surviv- ing the serialization process. This may be fixed by the time PHP5.0 is released. game_parameters.phpThe single instance of the GameParametersclass, shown in Listing 46-5, packages up all thedefault numbers that we may want to customize in making a new version of the game (thepenalties and rewards, the number of levels, the starting and maximum credit, and so on). In addition, this object manages global access to the database connection. Listing 46-5:game_parameters.phpIn case you need quality webspace to host and run your web applications, try our personal web hosting services.

895Chapter 46A Trivia Game$current_level = $this->_level; if ($current_level (Web server setup)

Thursday, March 27th, 2008

895Chapter 46A Trivia Game$current_level = $this->_level; if ($current_level > $params->getMaximumLevel()) { $this->_gameWon = TRUE; } else { // find out if questions remain to be // asked at this levelif (($this->_questionsAskedAtLevel >= $params->getQuestionsPerLevel($current_level)) || (count($this->_questionIdsAtLevel) == 0)) { // either we have asked the limit of // questions per level, OR we have simply run out$this->_level++; $this->_questionsAskedAtLevel = 0; $this->_setupQuestionIds(); // note recursive call — it s possible// that no questions were found, and we have// to keep going$this->_maybeChangeLevel(); } } } } function __sleep () { // make sure to serialize all fields except// the database connection (has to be recreated) // and the previous question (no point). return(array( gameParameters , currentQuestion , _credit , _level , _questionIdsAtLevel , _questionsAskedAtLevel , _correctAnswers , _totalQuestions , _gameLost , _gameWon )); } } ?> Handling an answerHere are the steps that a Gameobject goes through in dealing with a guess range submittedby a player (in the function updateWithAnswer): 1.Move the current question object to the previous question slot. 2.Update the (now previous) question with the upper and lower ranges of the guess(which are still in terms of step numbers from the form rather than actual values).
If you are looking for affordable and reliable webhost to host and run your business application visit our ftp web hosting services.

Web hosting mysql - 894Part VCase StudiesListing 46-4(continued) $this->getDbConnection(); if (!$this->_dbConnection) {

Wednesday, March 26th, 2008

894Part VCase StudiesListing 46-4(continued) $this->getDbConnection(); if (!$this->_dbConnection) { throw new Exception( No database connection ); } else { $result = mysql_query($query, $this->_dbConnection); while ($row = mysql_fetch_assoc($result)) { array_push($return_array, $row[ id ]); } } // randomize the order of the questions$return_array = create_randomized_array($return_array); return($return_array); } public function _updateScores () { // Change the current score based both on // whether the player got the answer right and on// the spread between the player s upper and lower// guess. Calculations depend on settings from // the GameParameters class. if ($this->previousQuestion->rightAnswer()) { $this->_correctAnswers = $this->_correctAnswers + 1; $this->_credit += $this->gameParameters->getRightAnswerCredit() - ($this->previousQuestion->getAnswerSpread() * $this->gameParameters->getAnswerSpreadDebit()); } else { $new_credit = $this->_credit = $this->_credit - $this->gameParameters->getWrongAnswerDebit(); } // enforce cap on credit$this->_credit = min($this->_credit, $this->gameParameters->getMaximumCredit()); } function _maybeChangeLevel () { if ($this->_credit < 0.0) { $this->_gameLost = TRUE; } else { $params = $this->gameParameters;
Looking for affordable and reliable webhost to host and run your business application? Then look no more and go to servlet web hosting services.

893Chapter 46A Trivia Gameupper_limit, lower_limit, (Web host) scaling_typefrom questionwhere id

Tuesday, March 25th, 2008

893Chapter 46A Trivia Gameupper_limit, lower_limit, scaling_typefrom questionwhere id = $question_id ; if (!$this->_dbConnection) { $this->_dbConnection = $this->gameParameters->getDbConnection(); } if ($this->_dbConnection && is_resource($this->_dbConnection)) { $result = mysql_query($query, $this->_dbConnection); if ($row = mysql_fetch_assoc($result)) { $this->currentQuestion = new Question( $row[ id ], $row[ question ], $row[ answer ], $row[ lower_limit ], $row[ upper_limit ], 10, $row[ scaling_type ]); $this->_questionsAskedAtLevel++; } else { throw new Exception( Problem retrieving question from database ); } } else { throw new Exception( Problem querying question database ); } } else { throw new Exception( Could not find any questions to ask ); } } function _setupQuestionIds () { $this->_questionIdsAtLevel = $this->_getQuestionIdsAtLevel($this->_level); } function _getQuestionIdsAtLevel ($level) { // to be used at time of graduation to a new level - // retrieves the new ids (only) of all questions at// the level, and shuffles them into a random order. $return_array = array(); $query = select id from question where level = $level ; Continued52
We recommend high quality webhost to host and run your jsp application: christian web host services.

892Part VCase StudiesListing 46-4(continued) function getGameWon() {return($this->_gameWon);} function (Web hosting service)

Tuesday, March 25th, 2008

892Part VCase StudiesListing 46-4(continued) function getGameWon() {return($this->_gameWon);} function getCurrentQuestionText() { if (!is_object($this->currentQuestion)) { print( What is it?
); print_r($this->currentQuestion); } else { return($this->currentQuestion->getQuestion()); } } function previousQuestionCorrect() { return($this->previousQuestion->getCorrect()); } function getDbConnection () { if (!$this->_dbConnection) { $this->_dbConnection = $this->gameParameters->getDbConnection(); } return($this->_dbConnection); } function updateWithAnswer ($lower, $upper) { // The main modifying function for a game object. // Takes a player s upper and lower guess, determines// correctness, updates scores, determines if the // player has graduated to the next level, and// swaps in the next question. $this->previousQuestion = $this->currentQuestion; $this->previousQuestion->updateWithAnswer($lower, $upper); $this->_updateScores(); $this->_maybeChangeLevel(); if (!($this->_gameLost || $this->_gameWon)) { $this->_installQuestion(); } } // PRIVATE FUNCTIONSfunction _installQuestion () { // actually retrieve a question from the database// and create a corresponding instance of Questionif (count($this->_questionIdsAtLevel) > 0) { // pop a question off the randomized list$question_id = array_pop($this->_questionIdsAtLevel); $query = select id, question, answer,
In case you need quality webspace to host and run your web applications, try our personal web hosting services.

891Chapter 46A Trivia Gamepublic $_gameLost = FALSE; public (Best web design)

Monday, March 24th, 2008

891Chapter 46A Trivia Gamepublic $_gameLost = FALSE; public $_gameWon = FALSE; // CONSTRUCTORfunction __construct () { $this->gameParameters = new GameParameters(); $this->_dbConnection = $this->gameParameters->getDbConnection(); if (!$this->_dbConnection) { throw new Exception( No database connection ); } else { $this->_correctAnswers = 0; $this->_level = $this->gameParameters->getStartingLevel(); $this->_credit = $this->gameParameters->getStartingCredit(); // make a list of questions to be asked at the// starting level$this->_setupQuestionIds(); // actually retrieve the first question$this->_installQuestion(); } } // PUBLIC FUNCTIONS// accessorsfunction getGameParameters() {return($this->gameParameters);} function getCurrentQuestion() {return($this->currentQuestion);} function getPreviousQuestion() {return($this->previousQuestion);} function getCredit() {return($this->_credit);} function getLevel() {return($this->_level);} function getQuestionsAskedAtLevel() {return($this->_questionsAskedAtLevel);} function getTotalQuestions() {return($this->_totalQuestions);} function getCorrectAnswers() {return($this->_correctAnswers);} function getGameLost() {return($this->_gameLost);} Continued52
Searching for affordable and proven webhost to host and run your servlet applications? Go to Linux Web Hosting services and you will find it.

890Part VCase Studies .The game s numerical (Hosting web) defaults (an

Sunday, March 23rd, 2008

890Part VCase Studies .The game s numerical defaults (an instance of class GameParameters). .Numerical variables that track the game s state (credit, questions answered, and so on). Public functionsAs with the GameDisplayclass, let s list the functions that the Gameclass exposes to callers: .The constructor function. .Various accessor functions for member data. .updateWithAnswer()takes the player s upper and lower guesses and updates thegame s state accordingly, including both update of scores and setting up the next question to be asked. Database interactionThe actual questions and answers that the game displays are retrieved from a back-endMySQL database. There are two main types of interaction with that database: .Whenever the player moves to a new level (including the first one), the Gameobjectretrieves the IDs of all questions that may be asked at that level and scrambles theirordering. This randomized list is propagated along with the Gameobject from page topage within a particular level of the game. .Whenever a new question is actually ready to be asked, the Gameobject pops itsdatabase ID off the list constructed and then queries the question database to retrieveall the rest of the question s information (the text of the question, the correct answer, the range of possible values to present, and so on). Listing 46-4 shows game_class.php. Listing 46-4:game_class.phpIf you are in need for cheap and reliable webhost to host your website, we recommend http web server services.

889Chapter 46A Trivia GameCredit is capped at (Web server extensions) 15.

Saturday, March 22nd, 2008

889Chapter 46A Trivia Game

  • Credit is capped at 15.
  • Whenever your credit falls below zero, the game is over. EOT; return($rules); } function gameLostText () { global $PHP_SELF; $game_over = <<Thanks for playing! Thanks for taking the certainty quiz, and for beingsuch a good LOSER!
    EOT; return($game_over); } function gameWonText () { global $PHP_SELF; $game_over = <<You won! Thanks for taking the certainty quiz, and for beating it. We bow to your superior knowledgeof what you know, and what you don t know.
    EOT; return($game_over); } } ?> game_class.phpIn this section, we get to the basic logic of the game. The Gameobject contains everythingworth remembering about the current state of the game, as well as methods for updating it. Data membersIt s worth listing the important pieces of data that the Gameobject tracks: .The current question (an instance of class Question). .The previous question, if any (an instance of class Question). .The questions that have been asked at this level (an array of database IDs). .The questions that could still be asked at this level (an array of database IDs).
    You need excellent and relaible webhost company to host your web applications? Then pay a visit to Inexpensive Web Hosting services.

  • 888Part VCase Studiesgame_text_class.phpYour humble authors try really hard (Web site hosting)

    Saturday, March 22nd, 2008

    888Part VCase Studiesgame_text_class.phpYour humble authors try really hard to make this stuff interesting, but in this case, we mustdeclare defeat. The GameTextclass just wraps up some boilerplate HTML into member func- tions so that the GameDisplayclass can ask for it. Enough said? The functions use our favorite technique for creating large chunks of boilerplate, which is theheredocsyntax. (See Chapter 8 for more on the uses of heredoc.) Listing 46-3 shows thegame_text_class.php. Listing 46-3:game_text_class.phpWelcome to the Certainty Quiz! The game that tests

  • how much you know about how much and
  • how much you know abouthow much you know about how much!

    The object

    The goal is to answer as many questionscorrectly as possible. Answer questions(starting with the first one at the left), by choosingvalues above and below where you think the right answer lies. Answers are correct if they include the real answer in the range. The narrower your guesses, the longer you ll survive. There are ten levels; if you think the questions are too easy, keep going. EOT; return($intro); } function rules () { $rules = <<Rules and scoring
  • Four points subtracted from your credit for every incorrect answer.
  • One point added to your credit for every correct answer, minus a penalty for the range of your answer. Specifying the entire range possible subtracts four points (for a total of -3); specifying a single step of the range subtracts nothing(for a total of +1). Intermediate ranges give intermediate results.
    You need excellent and relaible webhost company to host your web applications? Then pay a visit to Inexpensive Web Hosting services.

  • 887Chapter 46A Trivia Game $rank$name . (Web hosting servers) $answer_count$credit ; $rank++; } $result_string

    Friday, March 21st, 2008

    887Chapter 46A Trivia Game $rank$name . $answer_count$credit ; $rank++; } $result_string .= ; return($result_string); } else { throw newException( Game display has no database connection ); } } private function _gameStateString () { // The HTML table $correct_answers = $this->_game->getCorrectAnswers(); $credit = round_to_digits($this->_game->getCredit(), 2); $level = $this->_game->getLevel(); return(

    . _blueColor> . . . _redColor> . . _blueColor> . .
    Total correct answers:$correct_answers
    Credit remaining:$credit
    You have reached level:$level
    ); } } ?> Note that in the GameDisplayclass we use some object-oriented constructs that are new asof PHP5. The constructor function is called __construct(), rather than having the samename as the class. And we have designated the functions that are not intended for externaluse as private, which will prevent any such use by other classes. Most of the class s private functions involve querying the Gameobject for information that it then wraps up in HTML strings. One of the more interesting functions of this type is distractor_string(), which creates the actual display of alternatives for the answer range. The general division of labor here is: .The upper and lower bounds for the answer are specified in the database, as well ashow many choices should be displayed and how they should be scaled. .The Questionobject takes this information and creates all the intermediate steps ofthe answer range as it is constructed. .The GameDisplayobject queries the game for the current question and then queriesthat question to discover the upper and lower bounds and the intermediate steps. Itthen simply wraps those values in HTML to present radio-button alternatives, with themaximum answer range preselected.
    If you are in need for cheap and reliable webhost to host your website, we recommend http web server services.