Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống
1
/ 98 trang
THÔNG TIN TÀI LIỆU
Thông tin cơ bản
Định dạng
Số trang
98
Dung lượng
6,14 MB
Nội dung
Black Art of Java Game Programming:Using Objects for Animations locy++; if (locx == bottom_x) { state = NE; } break; case NE: locx++; locy ; if (locx == right_x) { state = W; } break; case W: locx ; if (locx == left_x) { state = SE; } break; } } } The WaltzRect and BoogieRect constructors illustrate the use of super to invoke the superclass constructor. For example, the first line of WaltzRect’s constructor is super(x,y,w,h,c); // call superclass constructor which calls the constructor of DancingRect. You are almost ready to put the dancing rectangle classes on stage! Before you do, there’s one more feature of object-oriented programming left to discuss, called dynamic method binding. Using Dynamic Method Binding Dynamic method binding is the last key to object-oriented programming that we’ll discuss. It corresponds to using virtual functions in C++, and it is best illustrated by an example. This example serves simply as an introduction to dynamic method binding. In the following section, you will see how it is applied in greater detail. Consider two classes, A and B, where A is a subclass of B. Class A is also a subtype of B. This means that any variable of type B can be assigned a value of type A. For example: B x; // x is a variable of type B A a = new A(); // a refers to an object of type A x = a; // Assigns x to a file:///D|/Downloads/Books/Computer/Java/Blac 20Java%20Game%20Programming/ch02/075-079.html (2 von 5) [13.03.2002 13:17:52] Black Art of Java Game Programming:Using Objects for Animations The last line assigns variable x, which is of type B, to a, which is type A. This assignment is legal because A is a subtype of B. Now let’s say that A overrides the method foo() in B, so that instances of A have a different foo() than instances of B, as you saw in the section on inheritance. Consider the following code: B x; // x is a variable of type B A a = new A(); // a refers to an object of type A B b = new B(); // b refers to an object of type B x = b; // assign b to x x.foo(); // which foo() method is called? x.foo() calls the foo() method of B, as you would expect. However, this code produces a different result: x = a; // assign a to x x.foo(); // which foo() method is called? In the last line, x.foo() calls the foo() method in A! So the method foo() isn’t bound until runtime, which is why this feature is called “dynamic” method binding. In Java, instance methods are bound dynamically by default. Final and static methods are not bound dynamically. This is all pretty abstract, and the next section shows how it’s used in practice. Putting It Together Let’s create an applet called Woogie that will extend the rebuilt Mondrian applet to animate multiple dancing rectangles. Woogie sets all three types of dancing rectangles on the screen. You’ll see how the investment that we made in the last few sections pays off in terms of clean, understandable, extensible code. Let’s discuss some highlights of Woogie. First, all the dancing rectangles are allocated in initRectangles(): public void initRectangles() { // allocate dancing rectangles r = new DancingRect[NUM_RECTS]; r[0] = new DancingRect(0,0,90,90,Color.yellow); r[1] = new BoogieRect(250,0,40,190,Color.yellow); r[2] = new WaltzRect(200,55,60,135,Color.yellow); r[3] = new BoogieRect(80,200,220,90,Color.blue); file:///D|/Downloads/Books/Computer/Java/Blac 20Java%20Game%20Programming/ch02/075-079.html (3 von 5) [13.03.2002 13:17:52] Black Art of Java Game Programming:Using Objects for Animations r[4] = new WaltzRect(100,10,90,80,Color.blue); r[5] = new BoogieRect(80,100,110,90,Color.lightGray); r[6] = new WaltzRect(200,0,45,45,Color.red); r[7] = new WaltzRect(0,100,70,200,Color.red); r[8] = new BoogieRect(200,55,60,135,Color.magenta); } The array r points to each rectangle. Since WaltzRect and BoogieRect are subtypes of DancingRect, the assignments don’t cause type errors. Next, the loop in run() is modified slightly, but it still resembles the Universal Animation Loop: public void run() { while (true) { repaint(); updateRectangles(); try { // pause for REFRESH_RATE ms Thread.sleep (REFRESH_RATE); } catch (Exception exc) { }; } } run() calls updateRectangles(), which tells each rectangle to dance. This is where dynamic method binding is used to provide the desired behavior for each rectangle: public void updateRectangles() { for (int i=0; i<NUM_RECTS; i++) { r[i].danceStep(); // each rectangles dance step } } Finally, the paint() method cycles through all the rectangles, telling each to draw itself. Double- buffering is implemented by passing the offscreen buffer to the paint() method of each rectangle. public void paint(Graphics g) { offscreen.setColor(Color.black); offscreen.fillRect(0,0,300,300); // clear buffer for (int i=0; i<NUM_RECTS; i++) { r[i].paint(offscreen); // paint each rectangle } g.drawImage(image,0,0,this); file:///D|/Downloads/Books/Computer/Java/Blac 20Java%20Game%20Programming/ch02/075-079.html (4 von 5) [13.03.2002 13:17:52] Black Art of Java Game Programming:Using Objects for Animations } Now take a look at the full listing of Woogie.java, shown in Listing 2-7. You’ll agree that it’s quite easy to understand and modify, which will be your homework assignment for tonight! Previous Table of Contents Next file:///D|/Downloads/Books/Computer/Java/Blac 20Java%20Game%20Programming/ch02/075-079.html (5 von 5) [13.03.2002 13:17:52] Black Art of Java Game Programming:Using Objects for Animations Black Art of Java Game Programming by Joel Fan Sams, Macmillan Computer Publishing ISBN: 1571690433 Pub Date: 11/01/96 Previous Table of Contents Next Listing 2-7 Woogie.java import java.applet.*; import java.awt.*; // run this applet with width=300 height=300 public class Woogie extends Applet implements Runnable { Thread animation; Graphics offscreen; Image image; static final int NUM_RECTS = 9; // in ms static final int REFRESH_RATE = 100; // in ms DancingRect r[]; public void init() { System.out.println(">> init <<"); setBackground(Color.black); initRectangles(); image = createImage(300,300); offscreen = image.getGraphics(); } public void initRectangles() { // allocate dancing rectangles r = new DancingRect[NUM_RECTS]; r[0] = new DancingRect(0,0,90,90,Color.yellow); r[1] = new BoogieRect(250,0,40,190,Color.yellow); r[2] = new WaltzRect(200,55,60,135,Color.yellow); r[3] = new BoogieRect(80,200,220,90,Color.blue); r[4] = new WaltzRect(100,10,90,80,Color.blue); file:///D|/Downloads/Books/Computer/Java/Blac 20Java%20Game%20Programming/ch02/079-082.html (1 von 4) [13.03.2002 13:17:53] Black Art of Java Game Programming:Using Objects for Animations r[5] = new BoogieRect(80,100,110,90,Color.lightGray); r[6] = new WaltzRect(200,0,45,45,Color.red); r[7] = new WaltzRect(0,100,70,200,Color.red); r[8] = new BoogieRect(200,55,60,135,Color.magenta); } public void start() { System.out.println(">> start <<"); animation = new Thread(this); if (animation != null) { animation.start(); } } // update each rectangle's position. // DYNAMIC METHOD BINDING OCCURS HERE! public void updateRectangles() { for (int i=0; i<NUM_RECTS; i++) { r[i].danceStep(); // each rectangles dance step } } // override update so it doesn't erase screen public void update(Graphics g) { paint(g); } public void paint(Graphics g) { offscreen.setColor(Color.black); offscreen.fillRect(0,0,300,300); // clear buffer for (int i=0; i<NUM_RECTS; i++) { r[i].paint(offscreen); // paint each rectangle } g.drawImage(image,0,0,this); } public void run() { while (true) { repaint(); updateRectangles(); try { Thread.sleep (REFRESH_RATE); } catch (Exception exc) { }; file:///D|/Downloads/Books/Computer/Java/Blac 20Java%20Game%20Programming/ch02/079-082.html (2 von 4) [13.03.2002 13:17:53] Black Art of Java Game Programming:Using Objects for Animations } } public void stop() { System.out.println(">> stop <<"); if (animation != null) { animation.stop(); animation = null; } } } Suggestion Box • Create new types of dancing rectangles, and add them to the Woogie applet. Try a ChaChaChaRect. How would you implement the delay between the dance steps? One solution is to bump an internal counter each time danceStep() is called; when the counter reaches a certain value, update the rectangle’s position. • Change the width and height of the rectangles as part of the danceStep(). • Add new shapes to Woogie, such as Ovals or Arcs. Can you think of a good way to alter the inheritance hierarchy to easily allow new shapes? The answer is in the next chapter, but here’s a hint: You might want to create a superclass of DancingRect, and move some functionality of DancingRect to the superclass. • Make a gravity simulation of bouncing rectangles. This will look cool, and it just takes a new formula in the danceStep() routine! • Right now, the coordinates used to define new rectangles are hardcoded into Woogie. Use the Applet method bounds() (which returns the dimensions of the applet) to compute the coordinates of the rectangles, so that they adjust automatically to the applet size. Summary As usual, this chapter’s chock-full of information that you’re going to need in writing a video game. You’ve learned how to create animations in Java by using the Universal Animation Loop, and that the applet methods you override execute in conjunction with the surrounding environment. You’ve seen how to use double-buffering to improve the quality and performance of your animations. Finally, you learned about three cornerstones of an object-oriented language such as Java: • Objects • Inheritance • Subtyping with dynamic method binding These are important keys to creating animations, games, and other applications in Java. file:///D|/Downloads/Books/Computer/Java/Blac 20Java%20Game%20Programming/ch02/079-082.html (3 von 4) [13.03.2002 13:17:53] Black Art of Java Game Programming:Using Objects for Animations In the following chapter, you’re going to learn about sprite and bitmap animation. Previous Table of Contents Next file:///D|/Downloads/Books/Computer/Java/Blac 20Java%20Game%20Programming/ch02/079-082.html (4 von 4) [13.03.2002 13:17:53] Black Art of Java Game Programming:Animating Sprites Black Art of Java Game Programming by Joel Fan Sams, Macmillan Computer Publishing ISBN: 1571690433 Pub Date: 11/01/96 Previous Table of Contents Next Chapter 3 Animating Sprites Joel Fan Goals: Understand sprites Use abstract classes and interfaces to design sprite hierarchy Use sound Create bitmap animation In this chapter, you will be introduced to sprites and begin constructing classes that you can reuse for your own graphics applications and games. You’ll learn how abstract classes and interfaces allow you to build understandable, modular Sprite classes, and how they work to give your objects conceptual unity. You will also see how to create all kinds of sprites—from rectangle sprites to bitmap sprites—that can animate at will. Finally, you will create an applet that bounces these sprites around! Let’s get started. What Are Sprites? Sprites are figures or elements on the screen that have the capability of moving independently of one another. These elements could be text, graphics, or bitmaps, which you might think of as preformed images that can be pasted on the screen. You’ve already seen an example of a sprite—the dancing rectangles from the last chapter. Sprites are commonly used in classic video games to provide screen representations for objects in the game world—for example, the classic game Galaxians, in which enemy ships fly toward you while file:///D|/Downloads/Books/Computer/Java/Blac 20Java%20Game%20Programming/ch03/083-087.html (1 von 3) [13.03.2002 13:17:53] Black Art of Java Game Programming:Animating Sprites unleashing a barrage of missiles. The elements of this game, such as the enemies, the missiles, and your ship, are represented by distinct sprites. In specialized game machines, like the ones you’ll find at arcades, the sprites are implemented by hardware to provide the best performance. Because we are programming for a multiplatform environment, we can’t rely on specialized hardware, so we will have to translate the functionality of the hardware sprites into Java code. To do this, let’s identify the fundamental properties that our Java sprites will have. These properties can be divided into two categories, states and behaviors. Sprite States • Internal representation of screen appearance. Sprites will be responsible for drawing themselves to the screen, which means they need an internal representation for how they should appear. • Screen location. In the case of a sprite that displays a rectangle, as you saw in the previous chapter, it might be sufficient to track the current screen location, as well as the width, height, and color. For a bitmap sprite, it’s necessary to store the current location, as well as the Image that makes up the bitmap. (You’ll learn all about bitmaps soon!) • Visibility. Sprites are either visible or invisible. For example, if you fire at an enemy ship and score a hit, it disappears. In other words, the sprite that displays the enemy changes from visible to invisible. • Priority. Sprites often have priority in relation to other sprites. A sprite of a certain priority appears in front of those sprites with lower priority. • Updateability. Some sprites need to be updateable. For example, one sprite may be moving to a new location on the screen, another sprite might change colors as time passes, and a third sprite may be expanding in size. Each sprite’s behavior might be different, but what unifies them is that their appearance on the screen changes with time. You’ve already seen an example of an update operation: danceStep() from the dancing rectangle classes of the previous chapter, which jiggles the rectangle in accordance with the rules of the particular dance. An updating sprite can be told to stop and stay frozen. In this case, we’ll say that the sprite moves from an active state to an inactive one. Sprite Behaviors • Painting. The sprite paints itself to the screen. The way it does this depends on its internal representation. If the sprite is invisible, painting does nothing. • Updating. The sprite computes how it will appear next, possibly depending on other sprites. A sprite that is inactive doesn’t update. Later in this chapter, you will learn to implement sprites with Java. By constructing sprite classes with these properties, you’ll have a layer on which you can write games and graphics applets. But first, let’s discuss abstract classes, which will provide a way of expressing essential sprite behaviors. file:///D|/Downloads/Books/Computer/Java/Blac 20Java%20Game%20Programming/ch03/083-087.html (2 von 3) [13.03.2002 13:17:53] [...].. .Black Art of Java Game Programming: Animating Sprites Previous Table of Contents Next file:///D|/Downloads/Books/Computer /Java/ Blac 2 0Java% 2 0Game% 2 0Programming/ ch03/083-087.html (3 von 3) [13.03 .20 02 13:17:53] Black Art of Java Game Programming: Animating Sprites Black Art of Java Game Programming by Joel Fan Sams, Macmillan Computer Publishing ISBN: 1571690433 Pub Date: 11/01/96 Previous Table of. .. file:///D|/Downloads/Books/Computer /Java/ Blac 2 0Java% 2 0Game% 2 0Programming/ ch03/097-100.html (3 von 4) [13.03 .20 02 13:17:56] Black Art of Java Game Programming: Animating Sprites independently of one another (for example, by different programmers) once the design of the classes is settled Previous Table of Contents Next file:///D|/Downloads/Books/Computer /Java/ Blac 2 0Java% 2 0Game% 2 0Programming/ ch03/097-100.html (4 von 4) [13.03 .20 02 13:17:56]... applet that bounces sprites off walls Previous Table of Contents Next file:///D|/Downloads/Books/Computer /Java/ Blac 2 0Java% 2 0Game% 2 0Programming/ ch03/100-1 02. html (4 von 4) [13.03 .20 02 13:17:57] Black Art of Java Game Programming: Animating Sprites Black Art of Java Game Programming by Joel Fan Sams, Macmillan Computer Publishing ISBN: 1571690433 Pub Date: 11/01/96 Previous Table of Contents Next Creating... defining the root of our sprite hierarchy Previous Table of Contents Next file:///D|/Downloads/Books/Computer /Java/ Blac 2 0Java% 2 0Game% 2 0Programming/ ch03/087-089.html (3 von 3) [13.03 .20 02 13:17:54] Black Art of Java Game Programming: Animating Sprites Black Art of Java Game Programming by Joel Fan Sams, Macmillan Computer Publishing ISBN: 1571690433 Pub Date: 11/01/96 Previous Table of Contents Next... animation = null; } } } Previous Table of Contents Next file:///D|/Downloads/Books/Computer /Java/ Blac 2 0Java% 2 0Game% 2 0Programming/ ch03/1 02- 107.html (5 von 5) [13.03 .20 02 13:17:58] Black Art of Java Game Programming: Animating Sprites Black Art of Java Game Programming by Joel Fan Sams, Macmillan Computer Publishing ISBN: 1571690433 Pub Date: 11/01/96 Previous Table of Contents Next This should look familiar,... shown in Listing 3-3 Previous Table of Contents Next file:///D|/Downloads/Books/Computer /Java/ Blac 2 0Java% 2 0Game% 2 0Programming/ ch03/093-097.html (4 von 4) [13.03 .20 02 13:17:55] Black Art of Java Game Programming: Animating Sprites Black Art of Java Game Programming by Joel Fan Sams, Macmillan Computer Publishing ISBN: 1571690433 Pub Date: 11/01/96 Previous Table of Contents Next Listing 3-3 RectSprite... than public variables Previous Table of Contents Next file:///D|/Downloads/Books/Computer /Java/ Blac 2 0Java% 2 0Game% 2 0Programming/ ch03/090-093.html (4 von 4) [13.03 .20 02 13:17:54] Black Art of Java Game Programming: Animating Sprites Black Art of Java Game Programming by Joel Fan Sams, Macmillan Computer Publishing ISBN: 1571690433 Pub Date: 11/01/96 Previous Table of Contents Next Protected Access The... file:///D|/Downloads/Books/Computer /Java/ Blac 2 0Java% 2 0Game% 2 0Programming/ ch03/1 02- 107.html (4 von 5) [13.03 .20 02 13:17:58] Black Art of Java Game Programming: Animating Sprites paint(g); } // public void paint(Graphics g) { offscreen.setColor(Color .black) ; offscreen.fillRect(0,0,width,height); // clear buffer for (int i=0; i . object of type A x = a; // Assigns x to a file:///D|/Downloads/Books/Computer /Java/ Blac 2 0Java% 2 0Game% 2 0Programming/ ch 02/ 075-079.html (2 von 5) [13.03 .20 02 13:17: 52] Black Art of Java Game Programming: Using. animations, games, and other applications in Java. file:///D|/Downloads/Books/Computer /Java/ Blac 2 0Java% 2 0Game% 2 0Programming/ ch 02/ 079-0 82. html (3 von 4) [13.03 .20 02 13:17:53] Black Art of Java Game Programming: Using. { }; file:///D|/Downloads/Books/Computer /Java/ Blac 2 0Java% 2 0Game% 2 0Programming/ ch 02/ 079-0 82. html (2 von 4) [13.03 .20 02 13:17:53] Black Art of Java Game Programming: Using Objects for Animations