JavaScript - Colour Game
Aim
To use HTML Forms and Tables elements to create a web page that plays a simple colour-matching game.
Tasks
(a) Create a new web page called "ColourGame.htm", and type in the following code.
<html> <head> <script language="javascript"> var cols = ['blue','red','green','yellow','orange']; var vals = [0, 1, 2, 3, 4]; function setup() { for (var i=0; i<5; i++) { changeColor(i, vals[i]); } } function changeColor(i, c) { var n = 't' + i; document.getElementById(n).bgColor = cols[c]; } function update(n) { for (var i=0; i<n.length; i++) { vals[n[i]]++; if (vals[n[i]] >= cols.length) vals[n[i]] = 0; changeColor(n[i], vals[n[i]]); } } </script> </head> <body onLoad="setup()"> <h1>Colour Game</h1> <p>Make all squares the same colour</p> <table width="100%" cellspacing=0 border=1> <tr height=200> <td id="t0"> </td> <td id="t1"> </td> <td id="t2"> </td> <td id="t3"> </td> <td id="t4"> </td> </tr> </table> <form name="frm1"> <p> <input type="button" value="A" onClick="update([0,2]);"> <input type="button" value="B" onClick="update([1,4]);"> <input type="button" value="C" onClick="update([0,1,3]);"> <input type="button" value="D" onClick="update([1,2,4]);"> </p> </form> </body> </html>
(b) Play the game a couple of times. How easy is it to win the game?
(c) Add two more colours to the list of colours (such as 'brown' and 'pink'). Has the game become easier or harder now?
page revision: 6, last edited: 06 Jul 2010 12:34






