The Magic 8-Ball

The Magic 8-Ball is a toy used for fortune-telling. The fortunes are given by a white plastic die in the shape of an icosahedron, floating in a blue liquid, with answers to yes-no questions in raised letters on its 20 triangular faces. There is a transparent window on the bottom of the 8-ball, and when the ball is held so that the window faces up, the die floats to the top randomly exposing one of its faces in the window.

We want to reproduce the fortune-telling mechanism on a web page, by using a form where inserting questions and obtaining answers, and exploiting JavaScript for the dynamic needings of our application. The following list enumerate requirements for our Magic 8-Ball web page, and a suggested path to... enlightenment by fortune-telling! ;-)

  1. Start the HTML page with a form containing a text area where the user can enter their question, and a button to submit that question. When the user clicks on the button, a random response should be generated and displayed in a text box.
  2. After writing the form, the simplest step further you can take is to hook the event handler for clicks on the button to a call to a JavaScript function.
  3. The handler could invoke a JavaScript predefined function, or a function you defined by yourself, e.g. in a script element contained in the head or body elements of the web page.
  4. The JavaScript code will need a data structure (e.g. an array) containing the answers from which the Magic 8-Ball will randomly pick up. A function will also be needed for generating a random number so as to randomly index your data structure. (Hint: look at Math.random and Math.floor)
  5. Finally, you'll need to pick the question from the HTML page and put the answer on the text box via JavaScript. Look at the predefined document object, and at how it can help traverse forms and their children elements.

Solution

Try a proposed solution to the Magic 8-Ball problem.

Questions and extensions

The Slot Machine

A slot machine is a type of casino game. Traditional slot machines are coin-operated machines with three (or more) reels, which spin when a lever on the side of the machine is pulled. The object of the game is to win money from the machine, which awards prizes when all the reels display the same symbol.

In order to reproduce a slot machine on a web page, you will need three images (for example, a clam, an octopus and a shrimp) representing the possible symbols to display. Then, you will also need a form containing: three spots for the screen of the slot machine (three spots, three images... you like to win easy, eh?); a button to have the images spin; an indicator of the amount of money you have; an indicator of the current bet, with two buttons to increase or decrease it. The game is over when all the money is lost.

Solution

Try a proposed solution to the Slot Machine problem.

Questions and extensions