Archive for March, 2008

876Part VCase StudiesWe now take a tour of (Web hosting servers)

Thursday, March 13th, 2008

876Part VCase StudiesWe now take a tour of the code file listings. Rather than building from the ground up as wesometimes do, in this chapter we work from the top down: first the very first page that isactually loaded, then the code that page depends on, and so on until we bottom out in utilityfunctions and database calls. Finally, at the end of the chapter, we show how to construct thedatabase and populate it with questions. index.phpListing 46-1 shows index.php, which is the user s entry point. The primary job of this file isto determine where we are in the cycle of play, set up the appropriate PHP objects (either bycreating them or by retrieving them from the user s session), and echo out the display codethat the objects generate. Where we are in the course of a game is determined by a combination of session and POSTinformation; as users arrive for the first time, they find neither a current session nor anyPOST arguments. Successive pages, however, should have both an active session and usefulinformation submitted from the previous page. Listing 46-1:index.phphandleHighScore(); } } // CASE 2: Player is in middle of game that we are trackingelseif (get_session_value( game ) && !get_post_value( NEW )) { $lower = get_post_value( lower ); $upper = get_post_value( upper ); $game_display = new GameDisplay(get_session_value( game ));
We highly recommend you visit web and email hosting services if you need stable and cheap web hosting platform for your web applications.

875Chapter 46A Trivia Gameas guessing wrong (-4 points). (Web hosting directory)

Wednesday, March 12th, 2008

875Chapter 46A Trivia Gameas guessing wrong (-4 points). The player is better off narrowing the range as much as possi- ble, while still being sure that the real answer is still included. Playing the game yourselfWe have a playable version of this game up at www.troutworks.com/games/certainty/ index.html, containing many more questions than we include in the sample databases in thischapter. We may change some aspects of the publicly playable game between the time we arewriting this and when the book comes out, so we can t guarantee that the public game matchesthis chapter s code in every respect. The code from this chapter, however, is available at theWeb site for this book (www.troutworks.com/phpbook). The CodeThe code for this example is almost completely written in an object-oriented style (seeChapter 20 for an introduction to PHP s version of object-oriented programming). Amongtheclasses we define are: .Question:Each Questionobject includes the text of the question, the correct answer, the lower and upper bounds that are presented to the player, and enough informationto display the range of choices that the player can choose from. In addition, Questioninstances track whether or not they are answered correctly. .Game:There should be one and only one Gameobject in existence at a particular time. Game objects may include up to two question objects (the current question and theprevious one), as well as a GameParameterinstance. .GameParameters:Contains all the numerical settings that affect how the game behavesand manages some globally available resources such as the database connection. .GameDisplay:Contains a Gameinstance as a component and does all the work of actu- ally displaying HTML and receiving input. Also contains an instance of GameText. .GameText:A repository for boilerplate HTML that is not dependent on any knowledgeof the state of the game. Only this class and GameDisplayactually have HTML code in them. Code filesThe code files include definitions for all the classes in the preceding section: question_ class.php, game_class.php, game_parameters_class.php, game_display_class.php, and game_text_class.php. In addition, there are some code files that don t define classes: .index.php:The first file loaded, that handles sessions and post arguments and createsthe GameDisplayobject. .certainty_utils.php:A grab bag of initialization statements (seeding the random- number generator, for example) and math utility functions. .entry_form.php:A form for adding new questions to the database. .dbvars.php:The usual file with definitions for username, password, and host for thedatabase connection.
If you are looking for affordable and reliable webhost to host and run your business application visit our ftp web hosting services.

874Part VCase (Web design rates) StudiesFinally, Figure 46-3 shows Game Over,

Wednesday, March 12th, 2008

874Part VCase StudiesFinally, Figure 46-3 shows Game Over, complete with taunting message and a list of highscorers. (There s a corresponding Game Won screen in the unlikely event that the user survived all the questions the game could come up with.) Figure 46-3:Game overThe rulesThe basic play cycle is simple: The player is asked a question that requires a numerical answer, and the player responds by choosing a range of values that should include the answer. The goalis to answer as many questions correctly as possible, while surviving in the meantime. Survivaldepends on credit, which is accumulated by answering questions correctly with a narrow rangeand is spent by giving wrong answers or answering questions too broadly. The exact rewards and penalties are easily tweakable in the code, but in this chapter s versionthey are: .Correct answers:One point added to credit, minus a penalty for the size of the rangespecified. The penalty ranges from zero for answers that use only one step of the possi- ble range, up to four points for making the range as wide as possible. .Incorrect answers:Four points deducted from credit. Credit starts at five points and can rise only as high as fifteen points. The game is over whencredit goes below zero. It is easy to pass by simply submitting your answer without making a choice, since the radiobuttons are set to specify the widest possible answer range unless the player changes them. The penalties are set up so that passing is costly (a total of 1 - 4 = -3 points), but not as costly52
Please visit Domain Name Hosting services for high quality webhost to host and run your jsp applications.

Submit web site - 873Chapter 46A Trivia GameFigure 46-1:Start screenFigure 46-2:Continuing play52

Tuesday, March 11th, 2008

873Chapter 46A Trivia GameFigure 46-1:Start screenFigure 46-2:Continuing play52
If you are looking for affordable and reliable webhost to host and run your business application visit our ftp web hosting services.

872Part VCase StudiesThe GameSeveral years ago, a friend (Make web site)

Tuesday, March 11th, 2008

872Part VCase StudiesThe GameSeveral years ago, a friend asked one of us to try a quiz he d seen somewhere on the Internet. After I agreed, he told me that he would ask me ten questions, each of which had a numericalanswer (dates, weights, lengths, counts, and so on). The unusual part was that instead ofanswering with a number, I was to give a lower bound and an upper bound on the answer. Icould make the ranges as large as I wanted, and otherwise I had only one instruction: Makesure that you answer nine out of ten questions correctly. I answered the questions confidently and was surprised at the end to find that my final scorewas six (or was it four?). At any rate, I did surprisingly badly, but my friend said that every- one else he had tried it on had done even worse. Now, how could anyone lose such an easilywinnable game? After all, when asked when Shakespeare was born, I could have said Sometime between 30,000 B.C. and A.D. 30,000 and been pretty sure that I would be right. What trips people up seems to be some combination of pride and overconfidence. The prideprevents you from giving a ridiculously large range (because then your questioner knows you don t have the foggiest idea when Shakespeare was born); the overconfidence makes youwilling to narrow the range beyond your real range of certainty. In the end, the game isn ttesting your knowledge it s testing your knowledge of your own knowledge (or lack ofknowledge). Our versionIn this chapter, we implement something like this quiz game, but with some changes to makeit more Web-friendly. For one thing, rather than having the player type in numbers freely, wepresent a range of choices that the player narrows down further. For another, we don t relyon pride to make the ranges narrow (because people may end up playing this over the Webinthe privacy of their own home). Instead we add incentives to the scoring system to make people guess narrowly rather than broadly. Finally, we add some features familiar from onlinegames, such as levels of difficulty and a list of top scorers. The upshot is a game that, while it may or may not be fun, is certainly frustrating, which formany people is nearly as good. Sample screensFigure 46-1 shows the game screen as it may look to a new arrival. There is a welcome message to the right, and a question to the left, with radio buttons for choosing a range ofanswers. Figure 46-2 shows the screen immediately after the player has answered the first question. Another question is offered on the left, and now the state of the game score is highlighted onthe right, showing the correct answers to date, the credit remaining, and the level attained. (See the next section for an explanation of what these things mean.)
In case you need affordable webhost to host your website, our recommendation is ecommerce web host services.

Web hosting isp - A Trivia GameIn this chapter, we present a

Sunday, March 9th, 2008

A Trivia GameIn this chapter, we present a full working example of a small PHPapplication: a Web-based trivia game with a twist (the CertaintyQuiz ). The main virtue of the chapter is its completeness: Instead ofusing code fragments to illustrate talking points, as we do in mostother chapters, we re showing everything, soup to nuts. As a result, this is one of the larger examples in the book, weighing in at morethan 1300 lines of PHP code. Concepts Used in This ChapterThe code in this chapter uses a wide variety of techniques, tricks, and technologies that we ve presented elsewhere in the book. In particular: .We make heavy use of the object-oriented features of PHP(Chapter 20). .We rely on PHP s session mechanism to propagate game datafrom page to page (Chapter 24). .We use a back end database (MySQL) to store questions andhigh scores (Part II). .We do some behind-the-scenes mathematics, including approxi- mating nth roots (Chapters 10 and 27). .We use arrays for storing data and for manipulating datareturned from the database (Chapters 9 and 21). .We do a lot of string processing and concatenation to build ourdisplay pages, including the heredoc technique for templatingpages (Chapters 8 and 21). .We use the new exception-handling features of PHP5 to catchdatabase and session problems (Chapter 31). We highlight some of these topics in various sections later in thechapter as we delve into the code. 4646CHAPTER …In This ChapterA guessing game withapproximate answersThe object-orientedimplementation of thegameDatabase and sessionsupportDesign considerations …
We recommend high quality webhost to host and run your jsp application: christian web host services.

870Part VCase StudiesFor one thing, we don t like (My web site)

Saturday, March 8th, 2008

870Part VCase StudiesFor one thing, we don t like the fact that you have to do two things to submit a rating (choosea radio button and then click Submit) rather than one. Long before we were aware of any one-click patent controversy, we had a one-click version of such a rating system on theMysteryGuide site (www.mysteryguide.com) this made each voting alternative into itsown Submit button, so that only one user action was needed. The problem with this is that, although the radio-button code in this chapter manipulates three different values (the vari- able name, the corresponding submitted value, and the text displayed in association with thebutton), you really only have two alternatives with a Submit button: the name of the variableand the value (which will also be the text displayed in the button). There is no good way, forexample, to display meaningful text and actually submit something else when clicked (like adatabase ID). The alternatives are 1) to resort to JavaScript; 2) to use radio buttons instead(as in this chapter); or 3) to somehow map from submitted text back to the value you reallywant to send (as we do on the MysteryGuide site). Probably Javascript is the way to go. Another improvement that our rating system needs is better prevention of ballot stuffing. Inthis chapter, we present the weakest defense to multiple voting for the same item: The ratingsform disappears in response to detecting a ratings submission, so the user cannot simplyclick a button on the same page over and over. However, nothing stops our user from hittingthe Back button or typing in the original URL to get the form back again, and repeating adnauseum. Any better technique needs to start with identifying multiple requests as actuallycoming from the same person see Chapter 24 for a discussion of how to do this. SummaryIn this chapter, we have shown you a system that lets users rate your pages, and we havetaken you through how it hooks up to a minimal content site. The code lets users rateitems, and it displays a summary page of votes. We also discussed some ways in which youcould take this code and extend it to make it more useful and interesting. We hope we vemade it easy to detach it from our sample content domain (a small set of quotations) and tosnap it back on to some content you care about. …
We highly recommend you visit web and email hosting services if you need stable and cheap web hosting platform for your web applications.

869Chapter 45A User-Rating SystemThe aggregated page is pretty (My web site)

Saturday, March 8th, 2008

869Chapter 45A User-Rating SystemThe aggregated page is pretty much just a sorted and aggregated view of the underlying ratings table, with some tricks to make the display more concise. (We round the averaged rat- ings to a reasonable precision and truncate the quotes at the first sign of punctuation.) Theaggregation happens as a result of grouping the ratings rows (of which there are many perquotation) by quotation in the SQL statement and averaging the ranks. We also turn the trun- cated quotations into links back to the display pages, using the ID of the content as a GETargument. (Note that although this is a top-ten list, there are only eight quotations in our sample dataset.) Figure 45-3:A top-ten view of the rated quotationsThe analysis this page provides is a direct product of the SQL statement it displays. Ratherthan displaying the most highly rated items, it would be easy to display the most poorlyrated, or the items with the most ratings overall, or any number of other analyses, simply byvarying the SQL statement and the title. What about performance? We don t have any hard data, but you can look at www.mysteryguide.com/readerratings.html, which uses roughly these techniques, and see how suchapage performs with three best of analyses on approximately 30,000 individual ratings. Asyou may be able to tell, it s just beginning to slow up perceptibly, taking a second or two torespond under typical conditions on our Web host. Extensions and AlternativesWe have tried to make this example as bare bones as possible, focusing on the ratings codewhile also retaining the minimum functionality to make a functioning mini-site. There are sev- eral ways in which you could improve or extend the code if you feel so moved.
Check Tomcat Web Hosting services for best quality webspace to host your web application.

868Part VCase StudiesListing 45-5(continued) group by quotations.idorder by (Web domain)

Friday, March 7th, 2008

868Part VCase StudiesListing 45-5(continued) group by quotations.idorder by avg_rank desc limit 10 ; $result = $db->query($query_best); if (DB::isError($result)) { $errorMessage = $result->getMessage(); die ($errorMessage); } $table_rows_string = QuoteAttributionAverage rating ; while ($row_array = $result->fetchRow()) { $quotation_id = $row_array[ ID ]; $quotation_text = $row_array[ quotation ]; $truncated_quotation = truncate_quotation($quotation_text); $quotation_attribution = $row_array[ attribution ]; $avg_rank = $row_array[ avg_rank ]; $rounded_avg_rank = sprintf( %.1f , $avg_rank); $table_rows_string .= $truncated_quotation $quotation_attribution . $rounded_avg_rank ; } $db->disconnect(); // lay out the page$title = Ratings page for quotes ; $page_string = <<

$title

Top ten most popular quotes

$table_rows_string
EOP; echo $page_string; ?>
If you are searching for cheap webhost for your web application, please visit MySQL5 Web Hosting services.

867Chapter 45A User-Rating System ); } function make_ratings_submission_box ($target_page, (1 on 1 web hosting)

Thursday, March 6th, 2008

867Chapter 45A User-Rating System ); } function make_ratings_submission_box ($target_page, $rated_id) { $rating_array = rating_types_as_array(); // Beginning of HTML table$return_string =

.
What did you think?
; foreach ($rating_array as $id => $text) { $return_string .=
. &nbsp $text ; } $return_string .= ; $return_string .=
; $return_string .=
; return($return_string); } ?> Aggregating ResultsFinally, we offer a simple page that shows a top ten ranking of the quotations that havebeen rated. Code for this is shown in Listing 45-5, and a browser view of the generated pageisshown in Figure 45-3. Listing 45-5:all_ratings.phpIf you are in need for cheap and reliable webhost to host your website, we recommend http web server services.