scg/ch08/BoxParadeWithRed

From FANG

Jump to: navigation, search

01 package scg.ch08;
02 
03 import fang2.core.Game;
04 import fang2.sprites.RectangleSprite;
05 
06 import java.awt.Color;
07 import java.util.ArrayList;
08 
09 /**
10  * Place random boxes on screen and move them up (and loop to bottom).
11  * Mark the one closest to the top in red.
12  */
13 public class BoxParadeWithRed
14   extends Game {
15   /** index of highest box (in boxes) */
16   int highest;
17 
18   /** original color of the highest box in boxes */
19   Color highestColor;
20 
21   /** The collection of RectangleSprites */
22   ArrayList<RectangleSprite> boxes;
23 
24   /**
25    * 10 randomly colored and placed rectangles on the screen
26    */
27   @Override
28   public void setup() {
29     // Make sure you initialize the collection!
30     boxes = new ArrayList<RectangleSprite>();
31 
32     for (int = 0; i != 10++i{
33       RectangleSprite curr = new RectangleSprite(0.10.1);
34       curr.setLocation(randomDouble(), randomDouble());
35       curr.setColor(randomColor());
36       addSprite(curr);
37       boxes.add(curr);
38     }
39 
40     highest = indexOfHighestBox();
41     highestColor = boxes.get(highest).getColor();
42     boxes.get(highest).setColor(getColor("red"));
43   }
44 
45   /**
46    * Find index of "highest" box on the screen. The lower the
47    * y-coordinate, the higher the box.
48    *
49    @return  an index into boxes, the index of the highest box
50    */
51   public int indexOfHighestBox() {
52     int indexOfHighestSoFar = 0;
53 
54     for (int nextIndexToCheck = 0; nextIndexToCheck != boxes.size();
55         ++nextIndexToCheck{
56       if (boxes.get(nextIndexToCheck).getY() <
57           boxes.get(indexOfHighestSoFar).getY()) {
58         indexOfHighestSoFar = nextIndexToCheck;
59       }
60     }
61 
62     return indexOfHighestSoFar;
63   }
64 
65   /**
66    * Move all the rectangles upward at a fixed speed.
67    */
68   @Override
69   public void advance(double dT{
70     int currHighest = indexOfHighestBox();
71 
72     if (currHighest != highest{
73       boxes.get(highest).setColor(highestColor);
74       highest = currHighest;
75       highestColor = boxes.get(highest).getColor();
76       boxes.get(highest).setColor(getColor("SCG Red"));
77     }
78 
79     for (int = 0; i != boxes.size()++i{
80       boxes.get(i).translateY(-0.5 * dT);// move up
81 
82       if (boxes.get(i).getY() 0.0{// loop around at top
83         boxes.get(i).setY(1.0);
84       }
85     }
86   }
87 }
88 
89 //Uploaded on Mon Mar 29 21:41:36 EDT 2010


Download/View scg/ch08/BoxParadeWithRed.java





Views
Personal tools
Add to 
del.icio.usAdd to 
diggAdd to 
FacebookAdd to 
favoritesAdd to 
GoogleAdd to 
MySpaceAdd to 
PrintAdd to 
SlashdotAdd to 
StumbleUponAdd to 
Twitter

Games
Games