The Essential Guide to HTML5

(Greg DeLong) #1

DICE GAME


bank +=20; Use the += operator to increase the value of bank by
20


document.f.bank.value = String(bank); Put the string representation of the bank amount in the
bank field


When the player loses, or when it is a follow-up turn, you dont add any code. The bank value goes down
before each new game.

Testing and uploading the application..........................................................................................................


These applications are complete in the HTML file. No other files, such as image files, are used. Instead,
the dice faces are drawn on the canvas. (For your information, my versions of dice games written in the
older HTML used one or two img elements. To make these fixed img elements display different images, I
wrote code that changed the src attribute to be a different external image file. When I uploaded the
application, I had to upload all the image files.)

Open up the HTML file in the browser. The first application needs to be reloaded to get a new (single) die.
The second and third applications (the third one being the craps game) use a button to roll the dice.

I repeat what I wrote earlier. To test this program, you do need to check the many cases. You are not done
when you, acting as the player, win. Typical problems include


  • missing or mismatched opening and closing tags

  • mismatched opening and closing brackets, the { and the } surrounding functions, switch
    statements, and if clauses

  • missing quotation marks. The color coding, as available when using TextPad and some other
    editors, can help here, as it will highlight keywords it recognizes.

  • inconsistency in naming and use of variables and functions. These names can be anything
    you choose, but you need to be consistent. The function draw2mid will not be invoked by
    drawmid2().


These are all, except arguably the last, mistakes in syntax, analogous to mistakes in grammar and
punctuation. A mistake of semantics, that is, meaning, can be more difficult to detect. If you write the
second switch statement to win on a 7 and lose on the point value, you may have written correct
JavaScript code, but it won't be the game of craps.

It shouldnt happen here because you can copy my code, but a common mistake is to get confused about
the coordinate system and think that vertical values increase going up the screen instead of down.

Summary ........................................................................................................................................................


In this chapter, you learned how to


  • declare variables and use global variables to represent application state

  • write code to perform arithmetic operations

  • define and use programmer-defined functions

Free download pdf