Rectangle racing - Friday, April 4th

  1. Code for version without using Arrays: Animation driver by a Timer object example.

  2. Latter half of the lab: Using Arrays and 04/04 for statement to be able to use ActionScript on the 4 rectangles r1, r2, r3 and r4 without mentioning the specific names anymore.

  3. VIP - NEW: The following code was added to this page on Thursday, May 22nd, 2008. It shows the additional features that the above Racing Rectangles applicaton has.

race_btn.addEventListener(MouseEvent.CLICK, race);      Here is the code for the above application.  
                                                        This includes the starting Blocks BUTTON and the naming of the rectangles.
var tmr:Timer = new Timer(50);                          var t:TextField = new TextField();
                                                        t.text = max.name2 + " Wins!";
                                                        t.x = max.x;
tmr.addEventListener("timer", raceEm);                  t.y = max.y;   
                                                        t.visible = true;
function race(evt:MouseEvent):void {
   tmr.start();
}

r1.name2 = "Gray";
r2.name2 = "Turquoise";
r3.name2 = "Yellow";
r4.name2 = "Green";

function raceEm(evt:Event):void {
   r1.x += Math.random()*21;
   r2.x += Math.random()*21;
   r3.x += Math.random()*21;
   r4.x += Math.random()*21;

   if (r1.x > finish.x || r2.x > finish.x || r3.x > finish.x || r4.x > finish.x) {
       tmr.stop();
       reportWinner();
   }
}

var t:TextField = new TextField();
addChild(t);
t.visible = false;

reset_btn.addEventListener(MouseEvent.CLICK, reset);

function reportWinner():void {
   var max:Object = r1;

   if (r2.x > max.x) {
       max = r2;
   }
   if (r3.x > max.x) {
       max = r3;
   }
   if (r4.x > max.x) {
       max = r4;
   }
 	
   t.text = max.name2 + " Wins!";
   t.x = max.x;
   t.y = max.y;
   t.visible = true;
}

function reset(evt:MouseEvent):void {
   r1.x = 0;
   r2.x = 0;
   r3.x = 0;
   r4.x = 0;
   t.visible = false;
}