Beginning Java Game Programming

  • 94 1,518 1
  • Like this paper and download? You can publish your own PDF file online for free in a few minutes! Sign Up
File loading please wait...
Citation preview

BEGINNING JAVA™ GAME PROGRAMMING WzECOND EDITION

1-~l

ARBOUR

© 2008 Thomson Course Teclmology. a division of Thomson Learni ng Inc. All rights reserved. No pa rt of this book may be reproduced or transmitted in any form or by any means, electronic or mechanical. includi ng photocopying, record ing, or by any informa tion storage or retrieval system without written permission from Thomson Course Teclmology PTR, except for the inclusion of brief quotations in a review.

Publisher and General Manager) Thomson Course Technology PTR: Stacy L. Hiquet

The Thomson Course Technology PTR logo and related trade dress are trademarks of Thomson Course Technology. a div ision of Tho mso n Learning Inc., and may not be used without written permission.

Manager of Editorial Services: Heather Talbot

Java is a trademark of Sun Mic rosystems, Inc. in the Un ited States and olher countries. All other trademarks are the property of their respective ow ners. Jlllporfclllt: Thomson Course Techn ology PTR canno t provide sofhvare

support. Please co ntact the appropriate softwa re manufacturer's techni cal support lin e or Web site for assistance. Thomson Course Technology PTR and the author have attempted throughout this book to distinguish proprietary trademarks from descriptive terms by following the cap italization style used by the manufacturer. Information contained in this book has been obta ined by Thomson Co urse Technolo!:,'Y PTR from so urces believed to be reliable. However, because of the possibil ity of human or mecha nical error by our sources, Thomson Course Technology PTR, or othe rs, the Publisher does not guarantee the accuracy, adequacy, or completeness of any information and is not responsible for any erro rs Of omissions or the results obtained from use of such information. Readers should be particularly awafe of the fact that the Internet is an ever-cha nging entity. Some facts may have changed since this book went to press. Educatio nal facilities, compa nies, and organizations interested in multiple copies or licensing of this book should contact the Publisher for quantity discount information. Tra inin g ma nuals, CD-ROMs, and portions of this book are also available individua lly or can be tailored for spec ific needs. ISBN-l0: 1-59863-476-3 ISBN - 13: 978 - 1-59863-476-1 Library of Co ngress Catalog Card Number: 2007938236 Printed in the Un ited States of America 0809 10 II 12 TW 1098765432 1

Thomson Course Technology PTR, THOMSON a division of Thomson Le:uning Inc. • ,~ 25 Thomson Place COURSE TECHNOLOGY Boston, MA 022\0

Professional_ Technical. Reference

http://www.courseptr.com

Associate Director of Marketing: Sa rah O'Donnell

Marketing Manager: Jordan Casey Senior Acquisitions Editor: Emi Sm ith Project Editor/Copy Editor: Cath leen D. Small Technical Reviewer: Dusti n Clingman PTR Editorial Services Coordinator: Erin Johnson Interior Layout Tech: rcc Macm illan Inc. Cover Designer: Mike Ta namachi CD-ROM Producer: Brando n Penticuff Indexer: Katherine Stimson Proofreader: Kate Shoup

For Kaitlyn Faye

ACKNOWLEDGMENTS

I thank God for the many opportunities that have come my way this year, such as the chance to write this book, and for the apparent talent needed to make something tangible of these opportunities. I am grateful to my family for their ongoing encouragement: Jennifer, Jeremiah, Kayleigh, Kaitlyn, Kourtney, Mom and Dad, Grandma Cremeen, Dave and Barbara, my extended family at Vision Baptist Church, and Pastor Michael Perham and his family-Jennifer, Ashley, Bryce, and Sage-who have been such a blessing this past year. Thank you to the students, faculty, and staff at UAT for contributing to such a wonderfully creative environment for learning. I would like to thank the Alpha Squad team, who had some influence on this book (and even helped to solve a few coding problems with Galactic War): Roy Evans, Stewart Johnston, Peter Pascoal, Travis Eddlemon, Daniel Muller, Daniel Stirk, Patrick Cissarz, David Coddington, Marc Kirschner, Jeffrey Woodard, Jonathan Allmen, Levi Bath, Douglas Cannon, Joshua Gertz, Justin Hair, Adam Knight, Eric Lacerna, Daryl Lynch, and Kevin McCusker; and the faculty sponsors: Rebecca Whitehead, Michael Eilers, and Arnaud Ehgner. I also owe my thanks to students Mark Walker and Andrew Hawken for introducing me to the angular velocity code used in Galactic War. I am also very thankful for the artwork featured in this book, provided by Ari Feldman (www.flyingyogi.com) and Reiner Prokein (www.reinerstiJeset.de). Without their wonderful graphics, Galactic War would have featured programmer art (cringen. I offer my sincere thanks to the editors at Course Technology PTR and the freelance editors who put this book together: Emi Smith, Cathleen Small, Dustin Clingman, and Kate Shoup.

ABOUT THE AUTHOR

Jonathan S. Harbour is an Associate Professor of Game Development at the University of Advancing Technology in Tempe, Arizona. His current game project, Starflight: The Lost Colony (www.starflightgame.com). will be released in late 2007. He lives in Arizona with his wife, Jennifer, and four children: Jeremiah, Kayleigh, Kaitlyn, and Kourtney. He can be reached at www.jharbouLcom.

CONTENTS

PART I Chapter 1

Introduction ..

xiii

JAVA FOR BEGINNERS

.

Getting Started with Java

. . . . . . . . . . . . . . . .. 3

Java and the Web . . Studying the Market . . Design Rules. . . . . . . . •. . . . . . . •. . . . . . . •. . . . . . . •. The Casual Games Market.

3 4

5 6 No Manual Required . . .. . ..•.. . .. .••.. . . 7 Casual Garners. . .. ... .. . ... ••. .. ... .. .. . ... .. . 8 Casual Games. 8 Installing and Configuring Java. .. ...••.. 9 Installing Java . . . . . . . . . . • • .. 10 Configuring Java 11 Java Version Numbers ........ . 14 Your Fi rst Java Program . . . . . . . . • .. 1S Java Application. . . . . 15 Java Applet . . . . . . .. .. .••. . 17 What You Have Learned. ......•.. 20 Rev iew Questions . 21 On Your Own. 22 22 Exercise 1 . . Exercise 2 .... . .. . ... . . .. . .... .• •. . . . .. . . . .. .. . . . 22

vi

Contents

Chapter 2

Java Programming Essentials . . . . . . . . . . . . . . . . . . . ..

23

Java Applets . . .

24

.

.

Web Server Technology Explained Hosting Java Applets . .

24

. ... . ... .. . .• .. ... . • . .. . . .

The Java Language .. Java Data Types. . . .

. . . .. . . . • . .. . .. . ... . . . . . . .. ..

The Essence of Class. The rnain Function . .

27

37

39

Object-Oriented Programming What You Have Learned . . . .

. . . ...... • • . .

Review Questions.

On Your Own. Exercise 1. Exercise 2. .

Chapter 3

24

25 25

Compiling Java Code . .

40 46 47 48 48 48

. 49

Creating Your First Java Game About the Game Project.

49

Creating the Game . ..

52

Creating the Project ..

53

The BaseVectorshape Class.

53 55

The Ship Class The Bullet Class

.

56

The Asteroid Class ................... • .

57

The Main Source Code File Applet initO Event. . ..... . . • . Applet updateO Event . . .

.

. ..... . •.

Drawing the Player's Ship . ... . . .• • . ... . .... .. . . • . . . .. Draw ing the Bullets. Draw ing the Asteroids. Screen Refresh. . . . . . .

. . . .. . •. • .... . • • . . ...

Thread Events and the Game Loop Game Loop Update ... . . ..• .

.

Updating the Ship. . . . . . . . . . . • • . . . . . . . . .. Updating the Bullets . .

. ... . • •. . .

Updating the Asteroids Testing for Collisions. Keyboard Events Calculating Realistic Motion .

. . • . .. . ..

58 59 60 61 61 62 63 63 64 65 65 66 68 69 71

vii

viii

Contents

What You Have Learned. Review Questions On You r Own.

73 73 74 74 74

. . . .. . • .. .. . . . .

Exercise 1

.

Exercise 2.

PART II

Java Game Programming .. . . . . . . . . . . . . . . . . . . . . .. 75

Chapter 4

Vector-Based Graphics . . . . . . . . . . . . . . . . . . . . . . . . .. Programming Vector Graphics

.

Working w ith Shapes ..

80 83 86

.

What You Have Learned. . . . • . ..... . .•... . ... .

87 87

Exercise 1. . Exercise 2

Chapter 5

87

.

88

.

89

Programming Bitmapped Graphics ... . ..... . .... .• .. . .. . . Load ing and Drawing Images. . .

89 90 92 94 9S 97 99 104 104 104

Bitmap-Based Graphics

Applying Transforms to Images. Transparency. . . . .

. ....• . . .... .•. • . . .

Opaque Images ......••...... .. .. Transparent Images ............... •• . Working Some Masking Magic .... . .. . .• ... What You Have Learned. Review Questions . On Your Own.

Chapter 6

77 78

Working w ith Polygons Rotating and Scaling Shapes Review Questions. On Your Own.

77

Exe rcise 1.

lOS

Exercise 2.

lOS

Simple Sprites

.

Programm ing Simple Sprites. . . . . . . . . The Point2D Class. Basic Game Entities The ImageEntity Class Creating a Reusable Sprite Class

.

.

.

107 107 109 110 111 114

Contents

Collision Testing. . . . . . . . . . . • .

114

Sprite Class Source Code . . . . . . • . . . . . . . . . . . . . • • . . . . . . . Testing the Sprite Class. What You Have Learned.

118 121

. . . . . . . •. . . . . . •• . . . . . •• . . . . . ..

122

Review Questions. . .

121

On Your Own . .

Exercise 1. . . . . . . . . . . Exercise 2.

Chapter 7

122 122

Sprite Animation

.

123

Sprite Animation ...

123 124

Animation Techniqu es Drawing Individual Frames

124 126

Keeping Track of Animation Frames. Testing Sprite Animation Encapsulating Sprite An imation in a Class ..... .. .•. . . . . .. Testing the AnimatedSprite Class. What You Have Learned . . Review Questions. . . On Your Own.

.

.

Exercise 1..

Exercise 2.. ..

Chapter 8

Keyboard and Mouse Input Listening to the User

.

127 132 13S 137 138 138 138 139

141

.

141 142

Listening for Keyboard Events

142

Keyboard Input... Testing Keyboard Input . . . Mouse Input ...

143

Reading Mouse Motion

146 147

145

Detecting Mouse Buttons. Testing Mouse Input What You Have Learned . .. ... . . ... .. . . ..•. ... ... . . . . .

148

Review Questions . .

153 153

On Your Own . . Exercise 1

153

154

Sound Effects and Music Playing Digital Sample Files

152

.

Exercise 2...

Chapter 9

114

. . . . . . • • . . . . . . • • . . . . . ..

1SS .

155

ix

x

Contents

Getting Started with Java Sound ... . . .•.... . .• .

157

Playing Sounds ..

164 166

Playing MIDI Sequence Files .. Loading a MIDI File

.

166

Playing Music. ....... . .. ....•..... •. ......•.. .

167

Reusable Classes. The SoundClip Class.

169 170

The MidiSequence Class ......•• . . .. .•.. . ... .•....... What You Have Learned ... Review Questions. On Your Own. Exercise 1

.

Exercise 2

Chapter 10

.

172 175 175 176 176 176

Timing and the Game loop. . . . . . . . . . . . . . . . . . . . .

177

The Potency of a Game Loop . .

178

A Simple Loop . . .

..........

178

Overriding Some Default Applet Behaviors. . . . . . . . • . . . . ..

181

Feeling Loopy . . . . . . . . . . . . . . . Recovering Long·Lost Applet Methods. . .

182 183

Stepping Up to Threads

184

Starting and Stopping the Thread. . The ThreadedLoop Program. .

184

Examining Multithreading

189

What You Have Learned.

185

........•...

... ...•.. .. .. ... .. .. .• • .. ..

Review Questions . . . .

189

.......•.

190

.......•. On Your Own. Exercise 1. . . . . . . . . . . . . . . . . • . . . . . . . . . . . . . . . . . . . . .. Exercise 2. . . . . . . . • • . . . . . . . . . .

PART III

THE GALAalC WAR PROJEa

Chapter 11

Galactic War: From Vectors to Bitmaps

.......•....

190 190

191 .

Improving the Game

.

Generalizing the Vector Classes

193 193 194

The Main Source Code File: GalacticWar.java

197

What You Have Learned .

204

Review Questions .......... .. . •• ... . ... On Your Own. . .

190

.

.

204 204

Contents

Chapter 12

Galactic War: Sprites and Collision Boxes Creating the Project. . . . . . . . . . . . . .

. . ... .. . . •.

207

The Galactic War Bitmaps. The New and Improved Source Code

Chapter 13

208 210

What You Have Learned.

224

Review Questions .

225

On Your Own . . . .

225

Galactic War: Squashed by Space Rocks

.

227

What You Have Learned . ......... . •. . . . . . •. . . .. ... . ..

233

Review Questions.

233

On Your Own.

234

Galactic War: Entity Management

.

Adjusting to Event-Driven Programming

235 236

Exp loring the Class Library . .

236

Building the New Game Class .............. ...... •. ..

237

Enhancing Galactic War. .... .. •.•.. .. Exploring the New Galactic War Source Code ...

249

What You Have Learned

273

Review Questions. . . . . .

. .

Galactic War: Finishing the Game Let's Talk about Powerups . Ship and Bonus-Point Powerups . . Weapon Upgrades. Enhancing Galactic War.

249

.

274 274

.

275

. . •.. ... . ••... .. .• . . . . ..•. . .

On Your Own..

Chapter 15

227

. ....•....

Being Civilized about Collisions.

Chapter 14

207

. . . . ..•. .... .. . .

275 276 276

. . . . .. .. . . .•. .. . . .• .... ..•...

281

New Sprite Types ...

281

New Game States.

281

New Sprite Images. . . . . . . . . . . . . Health/Shield Meters, Score, Firepower, and

.

282

Game State Variables.

283

New Input Keys . . ..

283

Sound and Music Objects . . .. . . . . . . . . . .. •• .... ....... Loading Media Files. . . ... ... . ... . • . ..

284 284

Game State Issue-Resetting the Game.

287

Detecting the Game-Over State .... . . . . .. • . . . .. .•. . .

288

Screen Refresh Updates. .

289

. ....• .. . . ..

xi

xii

Contents

Preparing to End .. Updating New Sprites. Grabbing Powerups. . .. . . . .. .... ... ..• . . ... ...... New Input Keys. Spawning Powerups . . . Making the Shield Work. . Making Use of Weapon Upgrade Powerups ..

.

Ta llying the Score What You Have Learned . . .. . .... . .• . . .. ... . .. . . . .• . .. Review Questions On Your Own

Chapter 16

. .

Galactic War: Web Deployment

.

Packaging an Applet in a Java Archive (JAR) Using the jar.exe Program Packag ing Galactic War in a Java Archive . . Creating an HTML Host File for Your Applet ... . . . • . . A Simple HTML File. .

. ... ..... . . ..•.

Testing the Deployed Applet Game . What You Have Learned. . ........ ... . . .• • . . .. ... Review Questions. Epilogue

. ...... . •. .

Appendix A: Chapter Quiz Answers Index

291 292 294 296 299 301 302 30S 306 306 307

309 309 310 312 315 315 317 319 3 19 320

321 337

INTRODUCTION

This book willicach you how to write JaVil games that will run as applcts in a wcb bT'mt..a. l"hc goal is to &vriop gal"l'lCS ror the casual gal'DC market. Gal'DC pro· gramming is a challmging subject that is not jusl difficult 10 IfU.SItt-it is difficuh just to get started. This book takes aW3Y somc or thc m)')tc-ry or gamc prog11lmming by expbining each step along the w~y, rrom one chapler to the next I assume Ihat you havea litlle la\"a programming experience, but c\"en ir you hal'C I"IeI'tt usal )aVil herorc. you should Ix- ablc 10 k ~ Oue 10 secunl\' lie system on a user's PC Iibo a J.wa applic.allOn,

~ 10

",ftw~.

Becaust this book is dedicale

..

..,_. ....1• •

, 4 .. ,. , ... . "._

.

,,,

......wi'" ..

••

..

'0. "

--'-'----------------------------_.~. Too' _01.,,,,, ,..-0'.'"

" Figure 1.6 The firstApplet soorce code if,

Te~tPad.

17

18

Ch~pter

1 • Getting

St~rted

with

J~v~

Tip The 11';"1 edilion 01 www.textpad.com.

Te~IPad

is provided on the CD-ROM, Yoo can optionally download il from

I~port java.allt. ", Illport java.applet.', public chss FI rsUppi et extends Applet I public voId palnt«(;raphlcs 9) l 9.draIlStr1ng( "Thls Is lIy first Java Appletj", 20, 30),

The applet code is a lill1c different from the application-based code in the DrinkJava program. Note the extends Applet code in the class definition and the lack of a static main method. An applel program extends;1 class called Applet, which mcans the applet will receive all of the features of the ApplH class (which has tI\(" ability to run in a w!.'b hrowser). Essentially, all ofth{· complexity of tying in your program with the web browser has been done for you through c1'lss inhcritance (you r program inherits the (eatures of th" Appl et class). You C:ln compile the program with this (Onlnland, javac FirstApplet.java Now, if you happen to be using TextPad, as I am (refer to l'igurel.6), you can compile the program from within TextPad without having to drop to the command prompt to compile it manually, As Figllre 1.7 shows, Textl'ad has a macro that will launch the lava compil!.'r for you and r"port th" results of the compil!.'. If there arc no ",rrors in the Java code, it will report "Tool completed successfully." In order to run an applet, you must provide an IlTMl.container. This is a basic HTt.11. web page containing the code to eml>l.'d an applet on th", page. We'l! be creating one of these containers for every program in the book. But don't worry, it's easy to create an I-lTML container, and the eml~'dded arrlet COOl." is shon and sweet. Create a new file called !'irstApplel,htrnl and enter the following code into this file: rdogy PHI, 2(06), Although this book fOCl/l.tS on \l8.NH it is one ot the ttw bookl that fJqllairtl how to build a tilf. biill!d ~ from watth, and the concepts can be lIpplird to JiNa, should you wish to o:mte such

""*

.,....

Un you I11ake out the simibrity bctwcm the two game Icvds shown hen? It's all the same data, just rcpresmlN differmtly. When Mappy aports a 1n-e: Iikc this, il sends !he dau 10 a text file that )'OU can then opm and pute into )'OUr game's source cOOe. To make it work. )"Ou would dd1nc an array 10 handk the d.lla Iik£ this: tnt{][) gl.eLfyel·1

{2.2.2.2.2.2.2.2.2.21. 12. I. I. I. I. 1. 1. 1. 1.21. 12. I. I. I. I. 1. 1. 1. 1.21.

The Java Language 12,1. I. I. I. l. 1. 1. I. 2l. 12,1.1.1.1. I. l. 1,1. 2l. 12,1.1.1,1. I. 1. 1. 1. 2), 12,2,2,2.2.2.2,2.2.2) I,

Tip Ooo't forget the semicolon at the end of an array dedaration, or yoo wi ll get some vel)' strange

errorl f,om the Java compiler. However, I prefer 10 treat a game level (or other array-based da ta .sequence) as a single-dimensional array because data like this is easier to work with as a onedimensional array. Here is how J would define it: lnt[] gameLevel - 1

2. 2.2.2,2,2 . 2. 2.2,2, 2,1.1.1.1.1.1.1.1. 2, 2. 1.1.1.1.1.1.1.1. 2. 2. 1.1.1.1.1.1.1.1. 2, 2,1.1.1.1.1.1.1.1. 2, 2.1.1.1.1.1.1.1.1. 2, 2. 2.2.2,2.2 . 2. 2.2.2 I,

Do you see the subt le difference between this lD array and the 2D array defined before? AliI need to know are the width and height of the array data, and then I don't need multiple dimensions. In this example, this game level is 10 tiles wide and 10 tiles deep, for a total of 100 tiles. (A tile is a small bitmap used to build a game world in a 2D scrolling game, and it very closely resembles the analogy of noor tiles in the way it is used .)

The Essence of Class In case you haven't noticed, I've been talking about classes a lot. That's because you can't really get around the subject when writing a Java program. The main part of a Java source code file itself is a class. You might have seen a C program before and you might already be familiar with the maln() function. Here is a simpleC program: intlllain{1nt argc, char argv[]) { printf("1 alll a C progralll . In ' ): return 0:

37

38

Chapter 1. •

Java Programm ing Essentials

Let's take a look at the same program written in pure C-t + : 'I nclUde 1ntru in (int argc, char argv{]) l std , :co ut "I a. a C++ prog ra ll. " c: s td: :end l : return I : Now take a look a\ the same program written in Java: importj ~ v a. io .·: p~b l ic C\HS S~lIp le Java

r

public st atic void m~jn(Strin g ar gs[lll Systell .out. pr int In("1 all a Jav a program ") :

lXl you Sff any simibrities among these programs? You should, because they are listed in C"o]ut;on;uy order. Now, I don't want to get into an argument with anyone about whether Java is truly an evolutionary leap ahead of C++ lJ«ause I'm not sure if I believe that in the strictest sense (with a feature comparison). Hut I do like to think ofjal'a as the next logical step above C++; it is easier, less prone to error, but not as powerful. I)ocsn't that describe ;lny system that tends to evolve ov{'"r timd Take the compuwr industry itself, for instance. The earliest computers were built with thousands of vacuum tubes, which were difficult to maintain 'lnd very prone to error; and as far as power consumption goes, 1think the computers of old definitely usro more power than the computers we commonly usc today- but let's not talk about performanc{'", which is no contest. The C program is quite simple and llIaybe even readable by a non-programmer (who may nOI underst,md anything other than the pr l ntf linc, alld even then with much confusion ). Thl' C++ program is so much gobbll'dygook to anyonl' but a programmer. But those of us with a C++ background often describe C+ + code as beautiful and elegant, with a powerful, perhaps even imimidmillg, lure. The Java program is very similar to the C and C++ programs. Likl' the C+ -t program, the Java program must ·'gt"t solllething" frolll "solllewhere else" in the form of the illport j ava, 10,' statement. This java.io is a library that provides access to the Sys tem. Qu t class, which is uscJ for printing out text (as you probably guessed ). But the biggest difference is thatlhe java program is located inside a cl"sl. This class is called SaJlpl eJa va, and inside this class ('nclosed with

The Java laonguage curly brace$) i$ a main function very similar 10 the main funclions found in the C and C++ programs. Whal is this SallplNan class, you may a.sk~ The troth is. n'e?1hing in la\1I is a class, and it is not possible todo anything usdUl in Java withoul using a class. AU source code that you write in Java will be enclosed inside a class definition.

The .a1n Function The core of a Java application is Ihe Hin function. (Note Ihat applrts typically don't have a lWin funclion, as I'll explain shortly.) The lWln function has this basic format: pUblIc Hltle voId -.aln(Strlng i1rgs[]l 1 I

The parameter (String ugs[]) allows yOll to pass information to the Java program and is only practical when devclopinga Java application (rather than an applet) to which you can pass paramel('rs, pre$umably from a command prompt or shell. You alii pass parametCTS 10 a Java applel, but that is not done very often. I once worked for a company that built vchicle tracking systems using GPS (globlll posi/ioning ~mn), and my job was 10 maintain the: la'.. progra.m that displayed a map with all the vchicks in the Slate of Arizona n'l()\"ing along their routes. This Java program r«eivtd "chicle tracking informa.ticm from a $CrYC' .... j ', \

/

Creating the Game publ i c void setY(doub l e y} I thl S.1· y: I publ i c void lncYCdoubl e i) I thl S.1 1'S ;n the expression to dlange in a consistent w/tf. Amovement algorithm causes. for instance. the. vanat>e 00 a" x - ~ oid palnt(Grlphles gl I Ifereate In instlnee of Grlphits20 &rlphles20 g2d - (&rlphle s20Ig: lisave the Identity tr~n$for. Aff1neTrinsfol'llldent1t1 - new Affindrlnsfol'll(); Ilcreite I rlndo- n~r gen.eutor Rlnda. rind - nl!W R.l1\dooI1 I: IIsue the window wldthlheight lnt width · ge tS lu( l. wl dth: i nt hel ght • getS he ( ) . hei ght : IfUll the background with blld ,2d.utColor(Color.Iucrl: ,2d.f111It1ctlO. O. wI4th. lltl,htl: for(lntn-O:nI, Although I am basing mis Morial on the ex(ellent grapl1k ed~or, Paint Silop ~ most professional graphic editors support layers and prol'icle similar fcatur,..; to mose found in PSP. The GIMP, for instance, is a freeware griljlhk editor wim (omjlilrable features and is available on many platforms (Windows, linux, and 50 on). Download The GIMP (GNU Image Manipulation Program) from www.gimp.org.

In Figure 5.12, the transparency has been created based 011 the masked selection, The result looks very nice; this asteroid is ready for primetime! You can load this image into your Java applet and draw it, and it will automatically be drawn with transparency so the outer edges of the image (where the black pixels used to be) will not overwrite the background of the screen.

Trarnparency

.....

.



. .. •

f igure S.11 CrNting ~

new mom IIy8 out of !he wIection.

figure S.12 The flteroid image now lias a masffil

tr~ency

1Iy8.

103

104

Chapt~'

5 • Bitmap-Based Graphics

What You Have learned W~ \'Iill wnlinue to \'I~rl \'lith tr;lIlspu~nt imagu from this point fO""'3rd. so you ha\'~ Ieuncd a \Try irnponant tool in thisdupterthat will make it pol&ibl~ 10 crC'at~ utrmlely atll'3eti\'~ pffieS. Spt'CifiooIl\'. you kamed:

• How to dl'3w bitmap images • How to trJnsJal~, rotal~, and scale bitmap imagl!S • How to draw bitmaps with transparency

Review Questions Th~

following questions will MIl' you 10 determin~ how well }~U ha\'e Ie:lrned subjccu discussed in this chapter. n.e answ~rs u~ provided in Ap~ndil[ A. "Q,..aptCT QUil AIlSI'I'CTS." th~

I. What is the primary clus. wc'\'~ bttn using to manipulate bitmappcd graphics in this chapt~ 2. What method initializes

Ih~

keybo;!rd listener interface?

3. What Graphics20 method is used to draw an image? 4. Which Ja\'a cia$:> contains the get!luge() metho·d? 5. What cia" makes it possible to perform translation. rotation, Jnd SClling of imagesl 6. Whil.1ced with tht (ollo..ing rod~ listing inst~ad. This program uses the Graphics dass' d'''wStrlng method alld a bunch of variables to dispkly the status of all the mouse ~"Ven(s individually. Figure 8.2 shows what the program output looks like. Note the important p.arts of the code listing in bold. Tht first part of tht program includes the applet's dass ddinition (with the needed int~rfaces (ollowing tm, 1..,Ie.ents keyword) and ... riabl~ dfdaratiol1$. -ousttest: IlIPOrt JUI.awt.": l.,mrt JUI.awt.event.", I_port Ja... applet.":

packl~

publiC cl iSS HouseTut utends Apple! IlIIll_nts MouseLhtlMr. MousiYlDtlonltstener I l6echre s.-e a:l~se e,ent v..hotes lnt el1cb'.. cllck:f: lnt presu. pren:!,: lnt relusu. releuey: Int enurx. entery:

Mouse Input

:::=";:~m _ _ II:lllO,301 _lftOOOd _ _ 1I11:'1.156 II: J ICI,.Z)l _ < t__

II:'I~

_ _ 4l161.Z!17

lftt ultJ'. exltJ';

tnt drlgJ'. drlQJ'; lnt ... vex. -ov.,; lnt llOustbutton;

The lnl t( 1 ('Vent method is the first method that gelS run in an applel. So .his is where)'Ou would initialize )'Our game objectsand variables, and this isalso where )'Ou add !he listeners lOr any input devicf$ 1M prog.ram ~ to ~. If your program f:¥er seems to be ignoring the ~rd or moUK, check 1nIt( 1 10 make sure you have added the appropriate listener. III.HIlllle the applet pUbl1c voId lnHO I

IddMoueLlstener(th1s) ; IcldJIoIIselkltl onL1stener ( UIs):

The pllntO

~t method is CotIled whrnevCT the appkt needs to refresh the window. Since pllnt() comes with a parametCT ( Grlphics gl, we can usc this

149

ISO

Chapter 8 •

Keyboard and Mouw Input

Objecl 10 draw onto the screen. 'Ibis program uses the Graphics dr!wStrlnli() melhod 10 display texl on lhe applet window. IIrednw t~e applet wlr>dow wotd Pllnt(GTlp~ics g) t 9.drnStrtn'l( "House clicked " • -ousebutton .. . at " • c)tckx. ". ·.clicky. 10. 10}; 9 d.. "Strtng("Ilo~se entered It ... enten. ".· .. enter)'. 10. 251; g.drlwStrtl\9( "House exited It " .. exlh .. "." . exit)', 10 . 401; g.drawStrtng(·IIO~le pressed". -ousebutton •• at •• pressx. ".•• press)'. 10. 551; g.drlwStrtng( "House relelSed " • -ousebutton" " at ... relelSu" ".... relelSe)', 10. 70); g.d.."Strtng("House dragged at ... d..gx . ". · .. drag)'. 10. 8S); g.dra"String( ·House -owed at . .. -owex .. . ... -owe)'. 10.1001;

p~b1ic

The next portion of code includes the checkButton() method, which I have wriuen 10 support lhe mouse event handler in lhe program. This c~eckButton() method chcclu lhe current button that is being pressed and KlS a variable (-o~sebutton) to a V;t.1ue representing the pressed button. IlcustOll .ethod called b)' -ouse ewents to report but ton status private wotd checkButton(MouseEvent e) ( lichee! the -ouse buttons swttch(e. get8uttOllO) { Clse HouseEwent.BUnOMI: -ousebutton -I; bruk; Clse lIouseEwent. BUTTON2: ..unbutton - 2: bruk; CI se lIouseEwent. BUTTON3: lIOusebutton - 3; brUk; default: ..llSebuttool - 0:

Moose Input The -ouseCl icked() event is part of the ~ouseLtstener interface. When you implement this inlerface, you must include all of the mouse events defined in the interface. or the compiler will generate some errors about the missing events. This evenl is called whelK'VeT you click the mouse bUllon on the applel window-in which case both a press and rdease ha.s OCCUfTed. This event is nol usually needed when you program -ousePreued() and -ouseRelused() yoursel f. publ ie yoid 8OusC'Cllcked(lIousehent el { IIsne the 80ua position y'luu el1eu. - e.getI() : el1ekJ- e .geU(): Ilget ,n updlte on buttons

e!IKkButtOll(e): IIrefrUh the

5cr~n

(call the paint eyent)

repli ntO: The ncxl two mous.e event methods, mIlseEnteredO and 8lluse£J.ltedO. an" called whenever the mouse (Ul'$Or f'rlteTS or leaves the apple! window. Th~ events arc nol often needed in a game. public votd

8Ou5eEntered(~euseEYent

e) (

- e.geUO: entery - e.getnl: relNl1ntO: enter~

I publ ic Yeld lIIOuseE~lted(~euseE.enl e) I ulh-e.gelX(l; ulty-e.9ttY(l; reINl1nt/): The lIOusePressed() and lIlQuseRelused(} evenl methods are called whenever you cl ick and release the mouse bulton, respectively. When these (vents occur. you can get the CUlTf'rlt position of tile mouse a.s well a.s the bullon being prascd or released. publ1c Yeid 8OusePrused(lIousehent el I pruu-e.geU(); pressy - e.getYO:

151

152

Chapter 8 •

Keyboard and Mouse Input

ehtekButton(e): replht(}: I pybllt vOId llOuseRelused(llouseE.ent el I rellun - e.geU( I: relnuj' -1.geUO: clllckBulton(e) : rlpahtO:

1hcl'lousdiot lonllstener inlerf.1a defines the next lwocvcnes-useClugged() and lIOuseKoved( l. 'These ...·mtsan helpful when you just want to know when the mouse: is moving o"cr the apple! window (and when it is moving while the bUllon is being MId dmo.n). public void llOuuClriqqedlMotlseE.ent el I drag.- e.geU(}: dragy-e.getY(): repaht(}: I p~b 11 e vol d llOuseHored(ll(lu~eE.e"t e I I llO.u-e .geU(): IlOvey- • .geU(); repalntO:

What You Have learned This ehapterexplaincd how to lap inlO the keyboard and mouse listeners in order to add user input 10 )"Our Java programs. • You lC'arncd how 10 detect key prascs.

• You learned about kcy cod~ and character values. • You lC'arned how 10 mid the mouse's motion and buttons.

On Your Own

Review Questions The following questions will help you to doetermine how wt'll you have learnM the subje.;ts d iscussed in this chapter. The answers are provided in Appendix A, "Chapler Q uit Answers." I. What is the name of the method us.ed to enable keyboard events in your prognm~

2. What is the name of the keyboard event interbee? 3. What is the virtual key code for the Enter

key~

4. Wh ich keyboard event willldl yOIl Ihe code of a pressed

key~

5. Which ke}-board event wiD tdl you when a key has been

rdeased~

6. Which keyboard event will tell you the dW'2CtCl" of a p~ key? 7. Which XeyEyent method returns a key code value? 8. Whal is the name of the method used to enable mouse motion

events~

9. Whal is the name of the d;lS$ used as a parameter for all mousc event methods~

10. Which mouse event reporu the actual movement of the mouse?

On Your Own Use the following exercises to test your grasp of the material covered in this chapter. Arc you rearlylO put mouse and keyboard input to the test in a real game yd~ These exercises will dWlenge your understanding of this chapter.

Exercise 1 Modify the KeyboardTcst program so that pressing numeric keys I to 9 will change the font site used to display the key code and character values. To do this,

IS3

154

Ch3pter 8 •

Keybo3rd lind Mou~ Input

U5e the Gr.phlcs class in the plint event, which has a method called sttFont that you can impltmmt like thi$: g. $etFont( new Font( · Ar leI'. Font. NOJlllAl. iiI ue II , I will gi\'e you a hint: The ktyoode for I i$49, so you can subtrac! 40 from tht" k~ coot" to arrive at a good font site.

Exercise 2 Mooify tht" MOUKTest program so thaI a point is drawn whenever the user presK$ a lllOU5e button. You can U5e tht" Grlphics e!au's ftll Reet Jm1.hod and tht" lllOU5e position ",n..bles. (Just draw a r«tangle ..ith four oomtl'S that au one pixel aran.) If you au {ming confidml with your llC'W }a", programming skills. try using the setColor method to change the oolor of the points.

CHAPTER

9

SaUNa EFFECTS AND MUSIC

java has a rich sct of features for recording, mixing, and pbying sound sampk-s and MIDI sequences using a variety of classes that you will learn about in this chapter. You will learn about Java's rich set of sound support classes for loading and playing audio files in a variety of formats through Java's sound mixer. You will then learn about MIDI files and how to load and play them through Java's MIDI sequencer. Here is a rundown of the key topics in this chapter: • Loading and playing digital files • Loading and playing MIDI files • Writing some reusable audio classes

Playing Digital Sample Files Java's Sound API provides a package for working Wilh digital sample files, which has methods for loading a sample file (AIFF, AU, or WAY) and playing it through the sound mixer. The package is called javax.sound.sampled and includes numerous classes, most of which we will ignore. Some of these classes provide support for recording sound and manipulating samples, so you could write a complete sound editing program in Java that is similar to full-blown sound editing programs. One good ex-lmple is Audacity-a freeware, open-source

,ss

156

Chapter 9 • Sound EHeSCIEElllllOTH + 10)

top/bott~

< -10) nellY" SCRHMHEIGilT + 10: else 11 (shlp.pOlltl0n(). YO >SCREEMHEIGilT + 10} ntlf)''' -10:

if (lhlp.pos1tlon().YO

s1l1p.let'011t\ontHW '0Int2D(HWlt. ship. utStlte( S.IITEJIOIIIo\L):

1lfW)'J):

I····················································· ....................................................., • Update the bullets blled on veloclly

public Yold updHeBullets() I IIWlYe tile bill I ets for (lnt n -0: n (&uUETS: rt++) I If (bul1et[n!.llhe()}I lIupdate bullet' I x PQs It Ion bull et En]. up.:IItePos1t 1on ( ) : IIbullet dhlppurs at leftlright edge 11 (bullet[n].polltlonl).It) < 0 II bullet [n]. posl tl on I ) .It I >SCREElIVl DTH) bullet[n).uUl1wetfilse) :

lIupdate bullet's y position bull et[n] . up4ttePol 1tl one ) : IIbullet diupptars It topfbottol edge If (bullet [n].pos ltlon ( ).YO SClEEIlKEl6HTl bul let(n].seUlln{fllse) :

bu I \ et[n] .s'tSti let SPRITUORHAL l :

219

220

Chapter 12 • Galactic Wilr: Sprites and Collision Bo~es

, . ....................................................., • UpdUe the nterolds t>.sed on .elocHy

public .01d

~pdntAsterolds() I

1I~.e

,ncr route the nterolds for (lilt n - 0: n < ASTEflOIOS: tt+ +) I if hst(nl.JlheO) I lI~pdne the n t erald's position Jncr rau l 10n ISt[n]. opdettPos It 1on e); ISt(n). apdlteRout ton ( J :

1nt II· ut(n] .1MgellldtMJ- l; tnt h - ut(n] .IMgtHelghUJ - l; do~ble ntwX· ut{n] .poslt10n( I.I( I: do~ble n~ - ut{n] ./lOsl t10n(). Y(): I/•.,ep t he ~st e r old ~ ro~n d the sc reen edges if (ISt[ n] .poslt l onf).If)

< '11 )

newx· SCRHHWIOTM + w: else if (lSt{n].pos1tionf).X{) >SCRHHIIIOTK+II) newx· ow; 1f (ut[ n].poslt10n O .YO (-h) newy- SCREEWKEI&HT + h: else 1f (ut(n] . poslt1onO. YO > SCREENKEIGKT + II) newy· -h: ut{n].setPosltlon(new PolntlO{ntwX.n~): ut(n] •setSute( SPIIT[JIORlIAL);

I···································

• Test ut'ralds for co III s 1OfIS with shl p or

b~ llets

.

.....................................................,

pobll c .olel checkeo III s Ions Cl I IIcheck fo r coll 1$100 bet ~e n nteral ds end bulle ts for (Int _ · 0: -BULUTS - I ) currentlul1et - 0; bullet[ currenUullet]. setAll ve( true );

IIset bull et •s start lng pot nl lnt . - bullet[currenUullet].lugelltdth(); lnt h - bull et[currentBullet].lugeHetght(): ~oub lex - sht p. centerO •Xll - ./2: doubley-shtp.centerO.YO - h/2: bul l et[currentBull etl. setpos t t lon( new Pot nt20(x ,y) ) ; llpotnt bullel tn u. dt r«tton shtp t s faclng

223

224

Chapter 12 •

Galactic War: SpriteeW items shown in bold tUI. IIsprtte t ypes tnt SHlTE.5WIP -I: tnt SP.IH....ASHROIO_RI6 -10, tnt SP.ITE",lSHItOIOJlEDlLAt-ll, tnt SPRlTEJ.SJEIlOIO_SllAtl -12, fl~11 tnt SPRlTEJoSTEROIO_TlNY - 13: fl~ll tnt SHlTL8ULLET - 100: flnll tnt SPRITLEXPlOSION· 200: flnll tnt SnITLPOIfEIW'_SHIELD - 300: fhal In! S'UTLI'OIIEIWPJjUlTM· 301; flulln! snlTLPOVuuPJSO-302: ftnll tnt SPR ITE..-POIfERU L SOO· 303; flul t nt SPR ITLPOIIERUP_1000 _ 304: flul In! SPIITLJ'(lII(lU' _6UN _ 305 :

flnll flnll flnll flnll

New Game States To give Ihe g~ ll1 e Ihe ab ilily to start, play, and cnd (with the option 10 restart), we need 10 add some cond itional gameplay stales and make usc of Ihe pau$C pro~rty in the sprite engiDe (found in the 61.... class). Add the following lines jusl below the J>eW sprile definitions, above tnc toggle V;lI.ubles. ~ J>eW code is shown in bold. Jlgl.... I tltu

fl nil tnt lWlEJtENU• 0;

28\

282

Chapter IS • Galaaic War: finishing the l_• • •• • •

~:::l;;:; .,'1 _ ,,,,,..

_

0;,

....

",

.. r'-' . -____ . ._.r

• m"o>

".'.'

".,... ...,"

-~

.

,-

_~

figure 16.2 Listiog the contents of the GaladicWar Iokle,. files are located. I've copied all of Ihe class and media files to a subfolder called project to keep things tidy. So, all I h~ve in this m~in G~laclicWar folder are index.htm!, manifesuxt. and the projecl subfolder (see Figure 16.2). The manifesl.lxt file for Galaclic War conlains this line: Mal n·Cl ass, G!la el i cWH This tells the jRE which of the .class files 10 open up and start runn ing after opening the JAR file. (Ik sure to include a blank line after the Mai n·Class property line.) You will need to use an optional parameter of the JAR program that lets you specify a subfolder where the actual files are located. You don't want to just tell it to include .Iprojectl·.· bc.~ng

the deployable JAR role

to add all files in Ihat subfolder to the JAR file. Figure \6.3 shows the output of the command. If thes ctHle>Thl$ 1$ ., giwclt HIe> clMid> (bod,)

(ipplu tode e glw.cl.lSS wldtll-flOO helght.ofiOO) (1Ippltt> (lbod,)(lht.l)

The key to running an applet inside a Java archive is 10 add anolheroplion within the

(/Ipplet>

1be wdlpa~ file is usualIyCl1kd inda..html ~\l.S(' that is w roune-of a 6.~ that wdl .sc.-rven will send the: wdl broWStt autolNtically if you don't specify the: HTML file directly. For inslalKe, when you go to www.jharbour.tom, W ..-cb ~r...er deli...ers index.html automat ically. You ClIn create Ihis simple HTML 6.~ using a text editor such as Notepad (as shown in Figure 16.4). If you want your applet to IX' stored with your other web files, induding your already existing index file, then just use a different name, suth as GalaclicWar.hlml.

~ ~~

>

_.

U.I~>G.oh.tl

-.

. ... ~ loy

of.

_\"'k>f5hartdooo ..... ...... d-. Sl>-S1

~

~.

.......... ! ... ! m l l _ .... la-I. ~

7J.s..-.'",~

1'0..........

" _ _ a,S7

_ _ _ s... 01.., " ' " " _....

«&Dod.

--._m

1IfdIj... " " )1.

............ s... "'",.......... . - : G.laip_b,~lo6

Ihrnd.-. b. 6J "I'dooe.1 ..ri.ble> for lll_llI

--

~,

J'"

;mo

Golo ScfY, 169-170 .\(;. 2&9-191

urkulo"ng fram••• l1S ,....i.,J""1 t...",... d""'ing, 1:4-115 I«h"'qu.. 1'.", l:~ lIin(l. lZ' 111 I,",Lng n, 120- III Spril< do>&. 101. S« .1 ~1010

.n,,,,,',,,,, (

sm.cc:lo-.,»-JZ

-..."

S - M ~............

P...... II

T T.i,

~

s.... al... colli.ion ckt",,'inn

,...j

~h
I"" •.1Il-Jlb 1411-1~Z

........,

.uo--n·

,10K _

....... ll

Svrit< Sp