Beginning Java Game Programming Second Edition
Beginning Java Game Programming Second Edition
JAVA GAME
PROGRAMMING
WzECOND EDITION
1-~l
ARBOUR
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.
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
,~ 25 Thomson Place
COURSE TECHNOLOGY
Boston, MA 022\0
http://www.courseptr.com
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
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.
CONTENTS
PART I
Chapter 1
Introduction ..
xiii
. . . . . . . . . . . . . . . .. 3
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
23
Java Applets . . .
24
24
. . . .. . . . . .. . .. . ... . . . . . . .. ..
27
37
39
Object-Oriented Programming
What You Have Learned . . . .
.
. . ...... . .
Review Questions.
On Your Own.
Exercise 1.
Exercise 2. .
Chapter 3
24
25
25
40
46
47
48
48
48
. 49
49
52
53
53
55
56
57
. ..... . .
. . . .. . . .... . . . ...
. ... . . . .
. . . .. . ..
58
59
60
61
61
62
63
63
64
65
65
66
68
69
71
vii
viii
Contents
73
73
74
74
74
. . . .. . .. .. . . . .
Exercise 1
Exercise 2.
PART II
Chapter 4
Vector-Based Graphics . . . . . . . . . . . . . . . . . . . . . . . . ..
Programming Vector Graphics
80
83
86
87
87
Exercise 1. .
Exercise 2
Chapter 5
87
88
89
89
90
92
94
9S
97
99
104
104
104
Bitmap-Based Graphics
. .... . . .... .. . . .
Opaque Images
............ .. ..
Transparent Images ............... .
Working Some Masking Magic .... . .. . . ...
What You Have Learned.
Review Questions .
On Your Own.
Chapter 6
77
78
77
Exe rcise 1.
lOS
Exercise 2.
lOS
Simple Sprites
107
107
109
110
111
114
Contents
Collision Testing. . . . . . . . . . . .
114
118
121
. . . . . . . . . . . . . . . . . . . . . . . ..
122
Review Questions. . .
121
On Your Own . .
Exercise 1. . . . . . . . . . .
Exercise 2.
Chapter 7
122
122
Sprite Animation
123
123
124
Animation Techniqu es
Drawing Individual Frames
124
126
Exercise 1..
Exercise 2.. ..
Chapter 8
127
132
13S
137
138
138
138
139
141
141
142
142
Keyboard Input...
Testing Keyboard Input . . .
Mouse Input ...
143
146
147
145
148
Review Questions . .
153
153
On Your Own . .
Exercise 1
153
154
152
Exercise 2...
Chapter 9
114
. . . . . . . . . . . . . . . . . ..
1SS
.
155
ix
Contents
157
Playing Sounds ..
164
166
166
167
Reusable Classes.
The SoundClip Class.
169
170
Exercise 2
Chapter 10
172
175
175
176
176
176
177
178
A Simple Loop . . .
..........
178
181
Feeling Loopy . . . . . . . . . . . . . . .
Recovering LongLost Applet Methods. . .
182
183
Stepping Up to Threads
184
184
Examining Multithreading
189
185
...........
Review Questions . . . .
189
........
190
........
On Your Own.
Exercise 1. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ..
Exercise 2. . . . . . . . . . . . . . . . . .
PART III
Chapter 11
...........
190
190
191
.
193
193
194
197
204
190
204
204
Contents
Chapter 12
.
. ... .. . . .
207
Chapter 13
208
210
224
Review Questions .
225
On Your Own . . . .
225
227
233
Review Questions.
233
On Your Own.
234
235
236
236
237
249
273
Review Questions. . . . . .
.
.
249
274
274
275
On Your Own..
Chapter 15
227
. ........
Chapter 14
207
. . . . ... .... .. . .
275
276
276
. . . . .. .. . . .. .. . . . .... .....
281
281
281
282
283
283
284
284
287
288
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 ..
Chapter 16
.
.
. ...... . .
.
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<"q) up.
This book rnds IiU a hobby book. with no pressu~ and limittd pis, btcausc tht
pri=ry purpose or this book is to hdp you have: fun learning how 10 progrnm wrobased games. Typing in long source code listings out of a book is not fun, so I don't
ask you 10 do Ihat in every single chapter in Ihis book-Inslead, you willieam to wrile
shor1 programs to demonstratc tht major topics, and Ol'n" tinx' you will get the- hang
of il ~ is no mrtl'lOr'Uation ~uirtd bm-. btcause I'm a firm bd~ that
n:pdition-praclia---is the best W3y to learn, 001 throry and rnanorlzation.
Note
lIva
1Jf'' '
~ wotS tu
tu mlI'lpilc a prllgrMn DIU and ' - it run on nwny ~ ~
syslemS. The JaQ ~ CINIeS a "l:Jorteoode- file tonIaIning W1ual m.xIlirw instJuctIarts that
tie lIl U- ~ ~ l tan cxecw (WI . " ~ S}W'II llpOll whidl it is
..
You will learn how 10 wr ile a simple la\"3 program in the first chapter. From
there, rou will Icam thc dClails or how 10 writc games that will run in a web
xiv
Introduction
browsc-r. WI" W\'l"r sourCl" code at a ~e that will nolll"3vl" you brilind. Aha- rou
havl" kamed enough, you will write your first ..d>-based g;lme. and you willihen
learn nl"W subjl"<:ts in each chapter to iru::rease your game programming skills. By
the end of this book, you will have learned to creale ~ complete web-based game
called Galactic War, and you will be able to deploy it to your website in a Ian
Archive (JAR) fill". And I'm not talking about some half-baked simulation posing
as a gamco I'm talking about a rmJ g;lmI'" that ill rdai] qlA.lity. suit:;lble for publishing in thl" castU1 gaml'" nurkl"t. Then att toous;rnds of casu<l1 gall'll"TS who att
paying to down]Nd g;lmd of this typl" from the many casual game sites on the
..,ro today-such as Rl"al Areadl" (...-.reala reade.com ). By learning how to
creale a casual game, you may even be preparing for a caret'r in the game
industry. developing gallll'S for Microsoft Xbox Live Arcade and other commercialendeavoT$.
gomtS _ widm ganws !IYI _ inWllfd on a
nI Ml in i Wfb ~ so
Ihil end usm do not need 10 ~tiI the gIflIe. Some giIlIe'i _
10 _
~(IIt lim; ;nf
pliyer dolt3 01\ th! Wfb - . n.. Im$t pcIIlUI.1r tn'I" III Wfb 9"""" is i casuil game:
While we're on the subjl"<:t of casual garnes, you can eVell program your own
Xbox 360 games, distributed on Xbox Livl" Arcade, using Microsoft's free: XNA
Game Studio bpre:ss softwue. Although this subject is beyond thl" scOpl" of this
book, I bring it up bromIC Microsoft's Cllanguagt' is unabuh~y similar 10
Java. Thomson published a book on this subject by Josq>h Hill. tilled XNA Gam..
51l1flio Express: Dn~lopiug Games for lViudo>o" (IUd the Xb<u 360 (Thomson
Course Technology PTR, 2007).
It all begins here! Are you serious aboul this subject and willing to learn? As a
senior instructor of game developmcnt, [ am scrutiniud daily by studcnts who
\":It, drink. and br\":ltM vidl game. I cannot CTI":Ite something that stinks. or I'll
neva- hear the end of it! So I am is motivated to teach you culling-edgt' game
de\'e1opment techniques here as I am in i real dassroom setting, by students who
are paying a lot more than the retail cost of this book to learn these concepts. I
have used this book in severnl Java courses already, so you arc guaranleed highquality material in lhese pages that will not be a waste of your time.
Introduction
and ~n writing graphia: code. You will lam how to get input from the user
and how to play sound efT~ts and music-all within the conteJ(t of an online
game. From there, the sky's the limit! Figure 1.1 shows the 8'lme you will !eMil to
create in this book. Starting with the basics (and I'm talking about eXlremebasics
here!), you will write a simple 2D game using Vlor graphics (using lines and
filled poIygolU).
You ..ill then learn new t~hniques ill each new chapter, such as how to load a
bitmap file and render it in the 20 applN window using the Graphics and
Graphies20 classes. You will eventually putlhc handful of game-related classes
together in an e'o'ent-dril'en game library. As you can see from Figure 1.1, the final
..
F"~1.1
xv
Kvi
Introduction
lPme uses some allradive arlwork and is ehlXk-full of small details! You will
learn aboul simple bitnl.;lpsand then sprites hefoR' getting into animation. Along
the w:ly, you will learn how to use Java's advall(ed 20 library to rotate and scale:
sprites. and I'll show you some interesting code tlu.t ITIOVd bulkts, powerups,
asteroids, and other game objects on 1M screen $IIlOOthly and rnIisticl1ly. The
end result is a profts.\ional sprile-based game mgine that pacb a serious punc:h!
By learning how to creale this rC'lail-qualily ra51111/ game, you will h.a\'e learned
enough to create your own games, suilable for sale in the casual game market.
No te
~ is a IWnfted type 01
reslricticJrrs, an appIel is
An
"""'d1
program
not"
III iless the
is installed like any other appIO:aliOll
~a
~ 10
",ftw~.
men
Introduction
Tip
n.. _
dII .. Ih5 boat _ COI'I'Ipifd n:l1MIN using 1wiI Sf: 6, buI: Illy Iat -.mm 01
Jav.lI Sf: wi! be ibIe 10 ooqJile n:I roolhe dIIlM 10 JrA's -*nt SlIpIlOI1Ior old dII (iIso
~ b.odwMds ~ , vitaIy irnportInt ...... in sottw..... dtwIopo.... n!hat Mi(ros,oh
_
to have abandoned with its products and languages-but that is' topic for another day),
While cowring some of Ihe basics over Ihe next th ree chapters, you'll create a
complete casual game in lava that runs in a web browser. which will be a
milestooe as well as a measure of your own skill kvd at thai poinL This book is
not a primer on the Java bnguage; ratber. it make$ llS(' oflhis verycapable. high
level bnguage to create games. You will lind the code in this book much easier to
understand if you have at least read a primer on th.. subject. We discuss gam..
programming, not basic Java progrornrning.
If this is your first experience with the lava language, then you may struggle with
the sourcecooe in this book. If you fed Ihat you are up to the chalJenge, th..n you
might be able 10 read th.. Jan cod.. and make sorn.. sense 01,11 of il. But I don't
$ptnd very much lime trying to leach anything about th.. Ian language beyond
the first thr<"(' chapt,"" b.allS(' game programming is a difficult sub;!, and ~
have a 101 of ground 10 cover.
All of th.. projn:ts in this book will com pile with the Jan Sf 6 development kil.
Although bter versions (such as lava Sf 7) will compile the code, older versions
of lava may complain about classes or methods thai are nol re<:ognize:d. I
recommend usi ng the v..rsion included on the book's CD ROM. (Look in th..
\jan fold..r.) You may also broWS<" 10 http://java..sun.comtosecwhelh..ran......
v,""ion of laV1ll is aV1llilabk. (As of tile writing of this book, Java SE 7 isdue out in
2008.) You will be able to rornpik the programs in this book using the javac.ex<"
program, and you will run the programs using appletviewcT.exe.
xvii
)(\Iiii Introduction
10
Tip
If yau ... famiiIr WIth . . ~1l<iDan 01_ book. yau....,. t.. ~ 10 INm N _.~ no
Ioogef using 80lland JBuiklH.1ns1Nd, _.~ WOIting WIlh lhr JOt( and a text editor lor ma>cimlKn
cr~l.patfOfTl1 wpport and tOE ~, Yoo will <Kwally giNn produttiYity as a fesUIt and
you will have mort o:onuol OV~ how Y"'I" Java applel$ behave.
Avoiding any single comp.mys IDE also aHo..., us 10 focus more on the Ja~"1l
codt'. and this helps with cross-platform dt'vdopmmt. Tht' code in this book ..iU
compilt' and run on Ihe foUo..ing syslems:
Windows XP (x86, x64)
Windows Server 2003 (x86, x64)
Windows 2000 (xS6)
Windows Vista (x86, x(4)
Linux (x86. x(4)
n-r
Introduction
Tip
oo will ~ using Java SE 6 On other wonh, Java Standard Edition 6). which is the IighlWei41t
version of Java best suited for ereat ng web-based games. Our text edilor of dloke is TextPad 5.0.
~ Lln (Offij'lile yoor Java SQu'te code fil~ with a maml key.
My favorite text editor. which I've been using for m3ny yeMs, is called Textl'ad
and is available on the CD-ROM in the lsoftware diredory, as well as at
www.lextpad.com. This very small and easy-to-uS<' source code editor recQgll;u$
the Java Development Kit and is abk to compile your JJVa code with a simpk
macro (Ctrl+I). By using Tcxtl'ad JS your IDE, you'll be working directly with
the file system on your hard drive rather thJn on a virtual projl.'Ct mmmger (su(h
:t.I the one in lBuilder). In TextPad, you'll see the 'tetual files on your drive, and
there is no concept of "adding" files to a "project." because you arc working with
your source files directly.
book.
Note
This is what a note looks like.
Not~
Tip
~
is what a tip looks like, Tips give you po<nlers about the mnen! tutorial being covered.
Caution
This Is what a ,"ulion looks li ke. Cautions provide you with guidance and whal1<.l do (or oot 1<.l
do) In a given situation.
Note
This is what a defin~ion looks like, Definitions el<,Olain the meaning behind a tedmKaI cOI'Kellt 01
"""
xix
PART
The first part of the book will get you started progr..mming in Jav;!. You wiHleam
how to install and configure the Java Development Kit from Java SE 6 and test
your Java installati(JlI on your PC by writing your first gallle-all Apple! version
of ASfrroids that runs in a web browser.
Chapter I: Getting Started with Java
Chapter 2: Java Programming Essentials
Chapter 3: C reating You r Firsl Jav;! Game
CHAPTER
la\'3 C1n 1)<' a complex progrnmming language and a challenge to learn in its
entirety, bllt it iseasy to get up and running with lava very quickly using freelyavaitable dc\'dopment tools and basic code, I~va is one of th e most rewarding progmnming languages I have uSll'd, ~nd I'm sure you will ~gr as rou gain
apcrimtt with the language that it's worth your iml$tment oftirne. This chapter
will help you to get Sl~rted with J~n ~nd will be espn;iaIly helpful if you ha\'t: had
00 prior apcricna with this language. It e:xplains wlu.t you nd, w~ to get it,
and how to configure your S)'Slem to pl"t:J'"lre it for building Ja....based g;iElK'S.
H~ are .some of the topics that will be COVft'ed in this chapter.
Understanding Java ~nd the Web
Undcrst~nding the casual gJrTlC$ market
Installing and configuring Java
Writing your first Jav3 program
game machines were at the top of their game. Many readers were probably bam
in the 1980s and have no recollC<tion of the games of that era, except perhaps
those games that were ported to the second-generation consoles of the early
1990s (Nintendo SNES, Sega Genesis., Atari Jaguar), You have, however, probably
seen the various anthology collections from Namco, Atari, Midway, and Taito,
featuring classics such as JOIISt, Dig Dug, Pllr-Matl, SP.lCC hWllders, Defem/er, and
others (some of which date back to even the 1970s).
Note
Ninteodo has given some 01 il'i <lassic g,lIT11" an OYe<haul alld rel~ them on the extraordinary
NinteOOo OS halldheld system. Good movel Not only are "'me da~cs. such as the original Slipet
Mario Brof., outsellir.g most other handheld 9'!mes, but rereleases, sl.'Ch as 1he legend of Zekh:
A link It> /he Past (lor the Game Boy Advance), have outsold most console and PC 9'!rnes,
Design Rules
[could go into other compal1ies with equally impressiv.... success stories, as well as
those that have been dismal failures. But my goal is to demonstrate to you that
the game industry is indeed a buyer's (gamer's) market. It's not dictated and
ruled by the board of directors of one company or another or by marketing
prople, who have been stymied by the reluctance of gamers to go along with
traditional promotional theories. In other words, gamers are a tough audience!
It's an empowering position to be in, knowing that your personal preferences and
tastes are shared by millions of others who demand excellence and innovative
gamepJay, and that these demands are met, more or less. Companies that produce excellent games are rewarded by garners, while those that faU short quickly
close up shop and move on.
Would you like another real-world example? A few years ago, a IKOW publisher
. . merged in the game industry by the name of Eidos. This company's bank
account was padded by millions of PlayStation owners who had all fallen in love
with Lara Croft. Eidos seems to have misinterpreted the market, believing that
gamers loved the image and motif of this Bond-esque heroine. Eidos <:reated a
new hotshot team in Texas made up of some industry veterans in an endeavor
calle-<! loti Storm. The belief was that marketing the "rock-n-roll" hype of these
vmes
games. This genre has been relegattd to secondhand status for many years. .....hil..
the numbers of ganxT$ has risen from the hardcor<' "gttk" fans to include more
and mort" prop"'. The averagl!' gamer pb)'"$ games for a few hours a wed;, while
1M hardwr<' gamn spends 20 or mort hour'S plajing pmcs I"\.tty "ttk (lik(' a
part-time job). Casual garners, on the other hand, will only spmd a few minutes
pbying a gamt r1(lW and thtn-ptmaps I"\.try day, but r1(lt al....';))'$. Tht casual
gamer doa not becolfl(' addicted to any gamt the way a hardoor<' gamer does.
with gaffi('S such as ''''orld of warCmft, StIlr Wnl'S Gnlnxies. Tire Matrix OtJlirrr,
E""rQ"est, and so on.
So, whal is a c"sual g;l1ne anyw;]y? A c;lsual game is any gaillc that can be playcd
in a shon timcframc and requires no instructions on how to play. In this context,
almost every classk arcad.. gamc ever made falls into this category. It is only
recently that publisher and game industry pundits have btgun to rtaliu that
The
Market
garners renlly don't want the long, drawnoul experience of instnlling a gnmc,
downloading ~ patch, ~nd spending eight hours karnillg how to play it. Sometimes it is rdreshing to just fire up n game nnd play for 10 or 20 minutes without
having to ,rrcw with il all evening! This was a gripe of mine for a long time. [t is
why 1spend far morc time playing console games than PC gnmes, and I'm sure
many readers share that scnliment.
No Manual Required
Yl'S, there are some PC games that are so compelling ()f innovative that they arc
worth the effort to gel them illstall~'" and running. The best ex.1mple of late is
WorM of lVarCraft. 1 have spoken to many gamers who dnim that if Blizurd's
games were not so darned much fun, they would boycott llli7.:t.Jrd altogether!
(How's that for a contradiction?) The impression I gel is that these gmners have a
lore/hale relationship with Bliz7.Jrd and many other !}1me publishers as well.
(Lest you suspe<:t that 1suffer from memory lapse over Blizza rd, let me dear up
one important point-l love their games, bill dislike their terrihle installersl).
CaS<' in point, [ could not inst all World of W",Cr<ift on my dently ~'(juipped
laptop (which has 1.2 Gll of RAM and a GeForce 6400 256-MB vidro card). First,
the installer lochxl up on a file ealled texture.mpq, and a subsequent install
attempt reported an error on disc two. 1 got around these issues by copying all
four discs to the hard drive and installed it from there with no more problems.
Howcvcr, as soon as [ fired up the game and logged in to my account, it dropped
out to download a 26O-MB update to the g.1me. When that was done, thrce more
small updates were installed just to bring the game up to the latest version. Arc
these problems tolerable! Yes and no. On the one h~nd, this is the most advanced
and complex MMORPG (massively IIWllipl"ycr Pliline role-playing gil"'C) ever
crealed, and Blizzard has a full-time team conl inually creating new content and
improving the game, which 1 appl~ud. Bll! on the other hand, thaI sure was a lot
of work just to get the game installed, and il took three hours of my time (which
is why hardenre gamers tend tn have more than one PC).
Would a casual gamer be willing to devote thatllluch time just to install a game
that will elld up requiring hundreds of hours of gameplay in order to rise through
the ranks within the game world? Most ca~ual gamers do not have the time or
patience to jump through so many hoops for Blizzard. Such is thc targel audience
for casual games! Have you ever given serious thuughtto this issue? If you are an
IT (i"for"'lIlio" ledlIIology) profe&Sional or a hardeore gamer, you are used to
dealing with computer problems .md coping with them without incidmt, But do
you t\'er wonder, if you-a smart, experienced, knowkdgeable computer
expert-;ln- having problems with a game, how on earth ...ill an .. \~ge user
figure out thl'Sl' problems! Wdl, the short answer is, they dOIl't, which accounts
for most game returns.
Casual Garners
Casual garners include professionals such as doctors and lawyers. business
eucutives, wftware developers. and, well, n>eryollr rls<-. Casual games aunCl
pcopk from all cultures, classes. genders. religions. ethnicities, and polilical
orienlatioll$. Given lhat lll(l5I pottlltiDl game playet'$ art' THlI willing or able to
cope ...ith the issues involved in PC games. is it any wonder that this burgtQning
markt'! has hem ilJe'\1table for Sl"\~1 years now? While casual games are cur
rently played mainly in a web browser using technology such as 1.1\';1 and Rash,
the console systems ate featuring online gameplay as well, and this trend will
continue to gain popularity.
Casual Games
The casual game market was limited a f~ years ago. Only recently has this
subject started 10 show up on the radar of publisher$, schools, and retail store;,
even though gamen ha,"<' hem playing casual games for two dtotdes. (I predicted
casual games would take off a f~ years ago, but my dog ate that article.) Casual
games are a win-"in situation because they are just as easy to create as they are to
play, so the developer iii able to create a casual game in a short timefrome, and the
gamer has an enjoyable experience with a 101 of choices. Casual games have a very
simple distribution model (most arc put up on a website for online pby), a
respectable compensation model (developers receive a percentage of net sales or
a single lump sum), an often meager development cycle measured in weeks or a
f~ months. and almost no testing required. As a casual gamedevelopcr, you can
come up with an innoY.ltive gamt idea, develop the gamt, and gt'! il onto store
shelves (that is, a website) all within the timeframe of just the concept-art stagt'of
a full-blown rebil gamt.
Jay Moore is an l"V3.ngelist for Garage GaIl1l'5 who promotes the Torque game
engine around the country at conferen,es and trade shows. He spoke at the 2005
Technology Forum at the University of Advancing Technology, where he
addressed the possibility of ea rning a living as a casll,l l g.1me developer. Garage
Games' Torque engine has been port ed to Xbox, and they have published two
1m.
[fyou feel as if I've been leading you along a train of thought, you would be right
to trust your feelings. The focus of this book is about programming games llsil1g
Java, and we willklrt1 to do just that shonly. Sincc Java is the pioneer language of
casual gamc development, I will be emphasizing this aspcct of gaming while
creating web-based projects in the chaptcrs to cOme.
10
Chapter 1
These typ<.-saf [,ragrams areealled fill... <lpplimtio",and require the Java Runtime
Environment ORE) to be inst~lIed. The web browser runtime is nat the .s.,~llle as
the desktop application runtime. which must be inst alled.
When you install Java Standard Editioll 6 (Java SE 6), the runtime indudes an
update for web browsers automatically. So if you write a lava game using features
from Java SE 6. the runtime might n......d to be upd'lted on an end uscr's 1'<: before
it will run the game properly. In some cascs. lhe compiled Ja'"3 progr;lm (which
ends up being a file with an extension af .d;lSS or .j;u) will run on older versions
of "lV'l, because some updates to the lava language have no impact on the
resulting compiled files.
... __. __
--_
. """,._-,
JaYa(TM)OC~
" I:U6~e2
...,.. ...
............
-"'II"-,,,-,_.,,~
Figure 1.1
Ir>stalliog /alia SE 6.
promp( 01'" sbdI window. The CUfmlt vasion at t!'lt time of this writing is Java SE 6
Configuring Java
lava will be installed by default in the f()lder C:IProgram Filesl)ava (on Ih~
Windows plalform; obviously, Ihis will be differen t depending on your system).
In this folder arc two folders ~alled jdkI.6.0_02 and jreI.6.0_02, containing Ihe
~eropment kil and runtime environment, respectively. We need to focus our
attention on the lirst foldCT ~omaining th~ 10K, in panicular. This fold~r contains a foldCTcallrd bin, in which)'O\l will find all of the Java programs ncedrd to
rompilC' and run Java rode. Th~ most imponant programs in this folder are
javac.C'Xe (the Java ~ompiICT) aDd appletviewer.C'Xe (theapplt! viewn utility). W~
nmi 10 add this folder 10 the system's environmenl ,.. riables so Ihat we can
im'Oke lhe Java compiler from any localion on the hard dri,'C'.
I'm going to focus my attention on Windows XP since il is the most widely used
operating system. IXpending on the system you're using, th~ steps will be differelll bm the concept will be similar. You need to add the jdkl.6.0_02/bin folder
l(l YUllr system path - the list of folders searched when YOIl invoke a program ;It
the command line. In Windows, open the Control Pand and run the System
utilily. ~[ect the Advanced tab, as shown in Figure 1.2. Her~ you will find a
button labeled Environmrnt Variables. Click on il.
Scroll down the liS! of syst~m variables until you find the Path variable. Select it,
then didr. the Edit button. Add the following to the end of the path variable:
(induding t!'lt snnioolon):
;{;:\Program Filcs\java\jd k 1.6.0_02\bin
If you have installed a differen t version. you will need 10 substitute the version
shown here with Ihe actual folder name representing the version you installed on
rour system. Click the OK button three times to back out oflhc dia logs and s<1VC
your scttings. Now let's vcrify that Ihe palh has h..-cn configured properly by
tesling the Java installation.
11
12
S_Fl... . .
G. ......I
__
u~
H.._
~N.....
~~ )
S!l\W'9
S....'4I"""R_
S_ _.tyIleIn l...... ,""" <loIiuggnp riormob>n
OK
Figure 1.2
The
S~lem
II e-
ilC(e-ssi~e
To 0pl?n a command prompt in Windows, open th~ Start menu, choosc Program
Files (or All Programs), and you will find it in Accessories. Thl? command
prompt should appear as shown in Figure 1.3.
If you arc using a systl?m like Linux, just open a shell if yOll don't have olle open
already, and the commands and parameters should oc the same. Now that yOIl
have a command prompt, type the following command and press Ellter:
javac -versioll
This will illvoke the Java cOlllpiler and instruct it to merely print out its vl?rsion
numocr, as shown in figure 1.4. The \'ersion reported here is just what rOll would
expect: 1.6.0_02 rcprescnts Java SE 1.6 UlXlate 2.
figure 1.]
A (~ prtIfTIpl window has
been
~.
Figure 1.4
TIle Jan oompilef printtd out its wmon numllef.
If you wtrt ablt 10 see lilt vt't'$ion number show up on your Sysltm, thtn you will
know that JaV;l has bn illSlalltd COlTtClly, and you'rt ready to slart writi ng and
compiling COOt! On tht othn hand, if you rectivtd an trror such as "Bad
comm;and or fik namc.o,n thtu your tuvironlll('Ilt ""ru.bk has not bttn set corrKtly, as expLainal pr~usIy. 11ltre is an alltmativt 10 tdiling tht syslnn's
13
14
C~apter
1 Gettiog Started
wit~
Java
mvirooment variable-yOll can iust modify the path (rom the command
prompt. However, whm yOll do this, the change is oot permanent, and you will
have to set the path every time )ou open a command prompt. But just for
reference. here is how you would do it:
set path=%pmh%;C:II'rogram Filcs\Javaljdkl.6.0_02
At this point, you are ready to start writ iog and compiliogjava code. So let's do
just that, 10 further test your Java installation. [n a mommt, we'll write a java
application that prints something out to the console (or shell). See the S<.,<:tion
Ixlow tilled "Your First lava Program."
,~,
'"'
'00'
,~
,~
,~
H~tory
Version
,..
"
U
,."
""
"
Marketed Name
Iav~
~"
lISE 1.3
!lSE ' .4
USE S.O
IavJ SE 6
Iav. SE 7
--..
Code Name
....
~
'"
M."",
"
When Sun released Java 2 as a trademarked name, the name caught on. and the
version we arc using now, Java SE 6, is still known internally as version 1.6.0. Java
funs love these quirks, which are not flalV5 but endearing traits, and it's not a
problem once you understand how it has evolved over the past decade.
Java Application
~ following program, shown in Figure 1.5, is calkd DrinkJava. Type it in and
save the file as DrinkJava.java.
p~bllc
Now let's compile the program. You'll need to open a Command Prompt
window ag<Jin, or you can continue using the one discussed earl ier if you still
have it open. Use the CD command to change to the folder where you savro. the
.java file-for instance, CD \chaptetOJ\OrinkJava. If you arc using the files on
the CD-ROM, you will need to mpy all of those files to your hard dri,'C first
be..:aUSoe you can't mmpile code on the CD. since the Java compiler ",,11 store the
rc:suIting .elass files in the same location as your source code fila..
1S
16
fI "., Jo_t_ S. _ _
II
""."""l_ .<__
U,,'....
ue e l _ D<.dJ..,.
_He nat'" YO.d _ IS ......... 111 l
Sn..... on ... '.I"" "","IDO <0 "" ... J""?-I,
Figure 1.5
The Drinl<Java program can be
fd i~ IIId
sawd wng
Nol~.
lI$C
J'.'c Orlnl:JU'.Ju,
lbc Java oompiJcr (ja\'a(.oc) should spend a (cw momcnls compiling )"Our
progr.un, and then mum thc command prompt cunor to you. If no ll1C$$lgc'
is displaycd, thai mcalU ('\crything wcnt ouy. You should then find a IlC'W
fill' in Ihc folder called DrinkJa\...c1ass.. You can scc thc list of filcs by typing
dir al thc command prompt, or just open Windows Explorcr to broW$(' thc
foldcr graphically.
To run the newly compilcd Drin k/ava.c1ass fiJc, you usc: the java.exc program:
J,.,OrlnkJH.
Note that I did not include the .class extension, which would have generaled an
error. Let Java worry about the extension on its own. By running this pmgrum,
you should see a linc OUlJlUl onlo the command prompt like this;
00 yOY 1He to drink J ,?
Perhaps without realizing it, wha t you navc done IKoIl' iscr....te a lava appllm/ion.
This is one of thc two t)'J1'eS of la'.. programs you can create. The otlKor type is
caJlcd an ppplcf, which describes a program that runs in a .....eb browser and is
Java Applet
Now let's create a lava applet and note how its code is different from a lava
application. This applet that you're about to write will run in a web browser, or
you can run it with the appletviewer.exe utility (which comes with Java). Open
}'our favorite text editor (Notepad, TextPad, Emacs, or whichever it may be) and
create a new file called FirstApplet.java with the following source code. TextPad is
shown in Figure 1.6. Before you try to run the program, though, we'll have to
create an HTML container, which we'll create shortly.
-'--
"""" """,.
oM>
:11:12 11 ~;,!,~<%q:.~
. r";',-"''''-=',,--~~-~---cr,-,--~-----o; l
"
, . ,,,,,, ,
,__
,,
w<
_1.,
', ~ '''''''l<''
""bl>
..
..,_. ....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
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:
<htN
<head)<t I t 1~>F I fS tApp 1~t<ft It Ie)< I h~ad)
<body)
<.ppln
codebilSe - ". "
code
- "flrstApplu.clilSS "
"ffrstApplet "
wldtb
- "640"
~lght
- "480"
u.
hspace
vspace
- "0"
- "0"
align
- ".1ddle"
>
<I.ppl et>
</ bodJ>< / ht_l)
This contai~r -b pa~ cock indudl'$ an C'tllbnkkd <appht> tag with paraII'I<tm that spify lhe: Java applet class file and the width and height of lhe:
........ r( ......
'. bill
..
--- ... ..
.....) \ ' - - -
,"..,
._,,,.1'1
-_
.
.1'1 .... _
__ .....
..
..
. _-"",';:l"'_
Figure 1.7
Compiling Java <ode is dndl in TelllPld.
"
19
20
---
_...
--
Figure 1.8
The fintApplft
pRlOpm
DOW
uriIiIy.
applrt,iewer FintApplet.html
The Apple! Viewer "indow appears with the FirslApplet program running, as
shown in Figul? 1.8.
You can also open the FirslApplrt.html file in your favorite web browser. Using
Windows Explorer, locate the folder containing your project and locate the
FiTStApplel.html file, then double-dick it to open it in the default web browser.
Figu re 1.9 shows the applet running in Internet Exp lorer.
goal
Review Questions
_... ...'- -
fIgure 1.9
RrstApp"t is IUlming .s an <.'flIbed<lro
,,~
, ~.
appI~t
in
Int~mel
ExPorer,
Review Questions
The following questions will help you [0 determine how well you have learned
the subjects discussed in this chapter.
l. What does the acronym ")DK" stand (or?
21
22
J. What is
th~ nam~
4. \\'her~ on th~ web ",ill )'OU lind Inc, lext nlilor c<lned TcxtPad~
sit~
for lal...?
7. Whal Iypot' of Ina program do you run wilh lhe ja\";l.Cl'C tool~
bro,,~r?
g. Whal is Ih~ name of the command-lin~ 1001 used 10 run a web-hJsW lal...
program?
10, What is lhe name Oflhc paramelCT IMssed 10 lhe paint!) el'elll mdhod in 3n
applel?
On Your Own
US('
Ih~
chapl~r,
Exercise 1
Modify th~ FirstAppltt program 50 thaI il displays your own nwssa&~ on Ihc
lo(:rC('n below Inc, CUrffnl message.
Exercise 2
See whether rou can figurc OUI "here System,oul.prinlln oUlput goes whcn run
from an applel project, SIllCC lhe It"xl is nOl displayed ill tht" applt"1 window.
CHAPTER
.JAVA PROGRAMMING
ESSENTIALS
/3V:l is a matuu programming 13ngu3ge thai offers many good features 3nd Q.pabilitiC$ that make it p<lpular on many computer systelTlli. Java is quite popubr
among Linux server programmcrs ;md adminislrators, as well as Windows application programmers. The key aspect of Java that makes it so appealing is its bu ilt-in
library support. The C++ language cannot even begin todo whal Java can do oll/of
1M box, so to speak. That is, you can't do any graphics programming in C++
wilhout an at .... 8"'phics libnary (5Ul:h <tS OpmGL or Dirt3D). Java, on the: Other
hand, has ~ing built in (while still supponing add-on libraries).
If you are jll5l getting S1aned as a java programmer. then this chapter will bdp you
gain some familiarilywith the Java bnguage. You wiD Ic:un most of the basics in this
chapter that you will need to wrile an applet-Ixucd wm game. There is a Jot more to
the lava language than what you willicam about in this sole ch,'ptcr, obviouslyl11,my entire books have been wrillen aboul java. This chapler will help give you a
jurnpstarl if you arc new to lava. If you have experience with java, you may find the
infonrultion to be: vague, bUl il is more importanl for a beginner 10 understand
ooncepts ralhcl"Ihan sundards. In addition. I will not deh~ into any features that are
new in Java SE 6. Herr is what you willlc:un in this chapter:
How to wrile Java code using appku
How to usc the java dala types
The basics of object-oriented programming
How to write java classes
23
24
Java Applets
Th~
are two dilT..rent types of prograll1$ you can coOlpi~ with Ja....: applications or applets. A Java UPtHicufion is a program compiled to run on a computer
asa sLllndaloTl<' application (hma the' naJ1l<'). A Java appl~. on the' othC'r hand, is
compiled specifically to run in a web browser. Java applicatiom are lm.llllly
written 10 run as ~'er programs, whilC' applm run as client prograll1$ in a
Tl<'tworkC'd environment. For enmple. Java Web Server (JWS) is a Java application that hosu wC'b pag.. fila to a .....tl browser (such as InterM1 Explorer or
Morilla Firefox). and it is comparable to Microsoft 's Internet Information Server
(115) web server and the open-source Apache' web scrv<:r.
25
26
Essential~
)~,........as based on C .,
by "borro"''ng" all of the best features of C~ + and
dropping the more difficult ~spects of the langu~ge. The Sun Microsplmls
progrJ.mmers who dewloped the 'a\d specifiCltion Crelted a langwge thai is
more of an evolution th~n something created. C ~ + is a powerful l~ngUilS<'
~ to build e'\'el),hing from cell phone g;t1l1e:$ to operating S~mlS to super
computeT simulations.. The poWeT of C+ ' makes it diffieull for ~nJ1('Q to
grasp, and ("\en profl$Sionals ....ho 1u\"C" spenl many vears "'orking with dJ.tabasn
and web applications rna)' be st)mied ....hen confronted by C.,.....-. It is a world
class l~nguage, and there 3re doz.em of compilers for it on ('\'ery computer
s)')u'm. Ilere is a list of software buill in C., ~:
Microsoft Windows
Microsoft Office
Microsoft Visu31 Studio
!.inux
Mac OS
Sobris
Mozilla Firefox
Star OprnOffice
I
~ould
Now consider )3va. lnere is jU5t one compiler for it, the lava Development Kit
(JDK), which;5 available f(lr the most popular c0111l'uler SyStenlS. Java is innovative enough to be calk'd a new languagc, but it was heavily innucllced by c ++.
Java is much easicr to program than C++. Java aUlomaticaHy handles memory
management for you-all )"OU do is allocate memory for new variables alld
objects, and thcn you don't reall)' need to wolT)' about freeing up the memory
afterward. ""':1 uses a thnology aIled garbou collrioll to remove unused
things from memory th,u }"Our program no ionS<"" ll<'OOs. To gh"C")"OU an analog)',
in the rnIm 0001\"3, )"ou don't e'\"m need 10 Cilrry lhe tr;lS/Kan out to lhe SIred for
The Jowa
LJngu~e
pickup beo!US(' the pro...ge colltclor just picks up all the trub thrown about in
your hoUS('. TIlt pro...y roIltcl.or is son oflike a link robot thaI seuma about
the hoUS(' st:It(hing for lrash to pick up. Whtn you an: done with your Chinest
takrout, just pilCh the container and your napkin, and the lillie trash robot will
find it and dean it up for you.
This co"ltIlead to sloppy progra mming if you spe nd many years programming in
Java and then swi tch to a more demandi ng language like C++, so Java makes it
possible for you to write solid rode Ihat dea ns up after itstlfif you wish to use il.
There is a dra~ck to garbay coUtion, though: You can't tdl it specifically
10m" to pick up the trash ( nriables and ob,itct.s that an: no longer used), only
that then: is trash 10 bt' pKbd up (as with the real-world ga.m.gt coIkctors J1lO$t
of the timt!).
Jan supports many data types. bUI probably the most basic data [)'pC is tM
illltgtT. Integers rtprtSol"nt wholt numbers, which an: numbt'rs thaI have no
dimal point. There are several types of integers that you may usc depending on
the size of number you need to store. Table 2.1 shows the types of integers you
can usc and their attributes.
Since Java programs alii run on a wide variety of computer systems (th is is called
cross-plnrfomr suppon), you might bt' wondering whether these data type values
...".
Sift in Bits
byte
~~ort
'"
10"9
32 bot>
64 bios
-12310121
-32.768 lO 3l.161
-2, W,483,64lIlO 2,141,483,647
-9,223,3n,036,~.I7';,808 lO 9,223,371,036,854,775.801
27
28
ChaplE'f 2
will b<.-Ih~ S3m~ on <:v~ry sysl~m. Aft~r all, a Java program can run on a litll~ c~ll
phone or it can run on a supe rcomputer, such as a Cray Red Storm system.
Tip
irlIomIilIon abouI ~ dled ad. _q600.arg Jar a ill: cI tht lOp SllO
on lhe ~ At Ihr tme 01 \hi. wntng. lhe net powerful a:np.rte" on tht
pIaIwt is IBM's B~"'" ~ a 1IWd-~ 280 lrillion apo<a~ ~ 1Qnll.
for
moll!
Java gelS around the dau type inconsiSlency in C++ by defining that data types
will be exactly the Arne. regardless of the compuler syMmI on which the Java
program is rulllling. Ifs lhe job of Ihe Java Runtime Environment ORE) 10
d~termjne at runtime how th~ current computeT syst~m will handl~ the data
types your Java program is trying to use, and it docs this scam lessly beh ind the
scenes.
Floating-Point Num~
There are t.....o da ta types available in Java for .....orking wilh f1oaling-poi nt
num bers. A floating-point r~'Prcsents a decimal value. 111e float data type stores a
32-bil single-precision number. Th~ doubl~ data type stores a M-bil doublepris.ion number. Table 2.2 shows th~ spOOfic.s of these two data types..
Th~ easicst .....ay to det~rrnine th~ rang~ for a numeric data type is to usc th~
MIN_VALUE and MAX_VALliE properties of the base da ta type classes. Alt ho ugh we
usc lowercase to specify Ih~ type of a nu m~fic vamble (byte, short, Int, long,
float, and double), these base numeric types arc aetu.ally instances of Java cla.sKs
(Byte, Short. Intl'ger, long, Flott, and Double). ThCTdore, .....~ can lake aped:
insid~ these base classes to find som~ goodics, Th~ MIIUAlUE and IlAX_VAlUE
properties will give you the range of values fo r a particular data type.
I have written a program caIIe1:I DataTypes Ihat displays these values in an appl~t
window. "Ilu.- output is sho.....n in Figure 2.1, and the source code listing follows..
This program is on Ihc CD-ROM in Ihe \sources\chaptcrll2\DauTypcs folder.
''''
.......
SizE' In Bits
,.-S
"l.4llllUSE~lI
UE-l24 10 1.7'I169ltl4a6lltS1E+lO!
1I _ _ r....l .....
-.
...
'n-_
"~,
...,
.-..-.....
.~
_
. . .1
.._>l
_ ._. . . -
_ - ,.
...-.
!'"ogure 2.1
The OiUTl'P!51'fOl.P'" lhpiIyI; ~ ~ for NdI....-ric d.wo IyJIt..
i_j)Ort Ju "t.:
i_port ju. applH .
publlC chss Da taTypu extends
~pplet
29
30
~.dra.Str1"qt Double
There are two data types in Java for working with character data; char and
String. Note that char i.s a base data type, while String is au tomatically r:Qgnizable u a class (due to the uppercase fiT5t ldtn-), JaV3 tries to make programming easy for C++ programmers by using many of the same basic data
types in order to make it easier to converl C and C++ programs to Java. So we
have a base char and a Strlnq class; of course, as you now know, every data type
in Java is a cl:lSS already.
You define a chu V3riable like this:
cll.. stude"tgrade;
chlr exa.score ' A';
Thc char data type can only handle a single cha racler, not an cntire stri ng. Note
that a character is idmtifi~ wim single quotes ( ' A') ramer than double quotes,
oecrssary for strings.
The String data type (or rather, class) i.s vny easy to uSC,' and is used by many of
the Java library methods. (Remember, a method is a (unction.) For instance, you
have seen a lot of the Graphics class $0 far in this chapter becau$C it is the main
way to display things (such as tal) in an apple! window. Here arc a couple of
differmt ways to crrate a string;
String fuorlte~a. - Sld Meier's CiYll1utlon IV;
String usernl.;
userMlit - 'Joh n"' R. .... OOe";
In addition to supponing the phu operator for combining strings (something
that C programmers look upon with mvy), the String class also comes rquipped
with numerous suppon methods for manipulating strings. I won't go over ~'ery
property and method in Ihe String class here because thai is the role of a Java
reference book-to cover every single detail.
linked
documenta~on
at iava.sun.coml,efereocelapi,
One good example of a function we've been using in this chapter is Graph; cs.
drawString. This function has many overloaded versions avaibble (overloading
is expbined later in this chapter, in the section entitled "Objeet.Oriented Progmmming") that give you a lot of options for printing text to the applet window,
but the main version I usc is this:
dra"String(String >tr,
Int x,
1nt,)
Note
We have just watched the surface of the Graphics class (and the Graphics2D inheritl'<!
class), This will be the focus of most of Part II. oovering Chapters 4 through 1D. Yoo willlea,n
about class inllel'itance later in this <:hap1e'.
Table 2.3 lists just wrueofthe useful methods in the String class. This is by no
means a complete list.
If you want to sec all of the properties and methods in a class (such as Stri ng ), the
easiest way to get a list, aside from using a reference book, is to create an instance
ofa class (such as Stri n9 s) and then usc the dot operator (,) to cause lBuilder to
bring up the contents of the class. This built-in "look" feature works with the
Java language classes as well as classes you have written yourself, as shown in
Figure 2.2.
Table 2.3 String Ck.;s Methods
Method
Description
contains
"odsWllh
"QU' 1S 19nOreC,se
Roltm< _
len~tn
replace
ld.
ReIlJms _
31
32
....... ,..._ ..
...---"..
...... ,..._"
_-_.
..
.N
:.:;- .....
.~':".:
,,--
.
~-~=--
.,.__.
'-,'__N_
'__h
'-'-'
'__N'
'____._'__
~
~,
.: =::::'::'~,
.__,
._,'. . . _.
._-
... _.
.__ ,~~:~:~_:..i''='"=''~~~~,-,-'''
~_._,._'----'~- - -_M,'---1
figure 2.2
JBuilde< displays the CO/lll'/ltl of a dass witI1 a I"'IH'P window.
Possibly lhe single greatest advantage to using an IDE is the built in help system.
whkh is available in tools such as lBuilder and Eclipse. If you aren'l using an IDE
that provides context-sensitive help and class member lists, then you will need a
good rderence book or website.
Tip
If you ilfe looking for help 00 a specifk )a"a language term or class, the easiest way to 100<. up
that inf<>rmation is by U'i ing Google. $earth ' java <keyword,.' to quid<1y locate the refe<en<:e. For
example, the firsl Google result for "java graphics1d' will most likely be a llRL to one of Sun's
own Java "rle<en<:e pages. Or you tan jUll go straight to the 50IIrcc and s.earcn through the dass
listings 3t java.sun.oomIreferencelapi.
Booleans
The Boolean data type (an be set to either true or false, and it is useful as a return
value for methods. For instance, in some of the example programs you've seen so
far, there have been methods thai returned a Boolean based on whether the code
succeeded. You can declare a bool can variable like so:
ehe
return true;
Here is an example of using the checkllollnds method 10 detmnine whether a
sprile's position on lhe scr~n (in the horizontal orienta tion) is within the
screen's boundary:
sprHeX spr1 leX + I;
H (eheekScunds(spritex . O. 639) -- true)
sp r HeX - 0;
This short e~ample assumes lhal the sprl te Xvariable has already been declared
eulier in lhe program. The spri te's X position on the screen will wrap around to
the left edge anyt ime Ihe spri te moves off the rig.ht edge of the screen. This
Boolean method an also be wnt1en like this, where lhe true is assumed in the
If S1alnnent:
If
Note that [havt: Id't out the -- trlle in this line of code. This is possible because
lavaevaJuates the Tl'Ium vaJueofthe ehe<:kSollnds method and replaces the method
call with the rdum value when the program is running. Thus if the chUOllnds
method Tttums lrue, the 1r S1alement becomes this:
HIV",t)
This is why we can leave the -- trlle oul of Ihe equation. On the converse, when
you want 10 tcst for a false relurn value, you can inserl h i se in the if
statelllent or you can usc Ihe logical nl'gativc operalor (!) in the statement;
1f (IcheckSounds(sprlteX. O. 639))
The result is that if cheekSounds returns false, lhe I f statemenl will exute
lhe code that follows; otherwise, lhe code is nOI exuted. Speaking of which.
you may include a single line of code after an 1r slalemenl, or you may
include a code block enclosed in curly br.KCS il$ follows. This is especially
))
34
The use of curly br,ICes in this new version of chedBounds might not change anything, but it docs allow you to add more lines of code before each of the return
statements. (For instance, you may want to display a llleSS<lge on the screen before
returniog.)
Arrays
All army is a collection of \';)riabJes ofa specific data lype that arc organized in a
managcab\e container. lin array is created usiog one of the base data types. a Java
libra!)' class, or one of your own classes. To tell Java that yOIi want an arra)',
allach brnckets to the dala type io your variable declaralion:
I nt[] hlghScoreL! st ;
But there are 1,,"0 steps to creating an array because an array must first be defined,
and IlleIl memory must be allocated for il. First, )'011 define the data type and
arra)' variable name, then you allocate the ana) by specifying the number of
elemcllls in the arl<l)' with the new operator:
Int{] studentGrades;
studentGrades - new Int{301;
Note that I have ;l!1ocak-d enough memory for lhis arra)' to hold 30 elements in
the stUdl'ntGr~des array. You can also define a new array with a single line of
code:
Int[J studentGrades - new Int(301;
I don't know about you, but! cnjo)' writing beautiful code like this. I get 3 chill
when writing code like this because my imagination slarts to take offwith visions
ofscrolling backgrounds and spaceships and llltlicrs and explosions, all of which
arc made possible with armys. But lhe real power of an army is made obvious
when you start iterating through an array with a loop. If you need 10 updale lhe
values of lhis army, you mighl access the array elements individually like this:
HudentGrades(O]
90:
HudentGrades(29] - 100:
If you truly need to set each element in ,m army individually, then an array can
still help to cut down on lhe clutter in your program. And an army will always
benefit from proct'SSing in a loop when it comes to things such as prinling out lhe
coments of the array or storing it in a data file, or for any other purpose you may
have for lhe array. leI'S sel all of lhe elements in an array to a slarling value of
zero (this is good programming pmclice);
long(] speed new )on9(100J:
for(lntl-0: t <100: !++) I
speed[l1- 0:
There is another way to creale an array by seuing the initial values oflhe array
righl al the definition. This army of five floals is defined and initialized in
memory with starting values al lhe same time.
float[ 1 rad1 oStattons - { sa. s. 91. 3. 97.7. 101. S. 103.0 ):
You can also creale multidimensional arrays. An array with more lhan one
dimension will have a multiplicative number of dements (based on the number
of elements in each dinl('nsion) becausc for every one dement in lhe firsl
dimension, there arc N e1emenls in the nexl dimension (based on the size of lhe
next dimension). In my own experience wriling games, I seldom usc more than
one dimension for an array because it is possible (and more efficient) 10 use a
single-dimellsioned array, and then index into it creatively to deal with multiple
dimensions.
Here is an example of a two-dimensional array that Slores lhe values for a game
level. The pound characlers (Il represent walls (or any olher object you want ill
your game) while lhe periods (.) represenl dirt, gmss, or any other type of image.
I presume that this is a level for a lile-baSl.-rl g.'me, where each character in the
army is drawn 10 lhe screen 'lS a tile from a bitmap file.
ChH[H] gaaeLevel - I
]S
36
Chilpler 2
{",
{.,
,. J.
,.J.
{.,............
'
{.,
[.,
,.
[.,
f ' .. ,
,.).
, .).
,.) .
,. I
Another common practice is to create a game level with just numbers (such as 0
to 9). Some programmers prefer to use character-based levels because they son of
look more like a game level. and arc. therefore. C<lSier to edit. I tend to prefer
integer-based game kvds because I am a big ran or a 1cvd ediling program called
Mappy, which aports k\'e1s as a comma-ddimited amJiY of numbers. Here is
how Milppy might aport the same level with numeric dilla:
n,
, t - induclfd ~ . . . . bcd's CD-ROM. Ltd ... m. ~ ~ You un Inl
""*
.,....
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.eLfyel1
{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.
Tip
Ooo't forget the semicolon at the end of an array dedaration, or yoo wi ll get some vel)' strange
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 .)
37
38
Chapter 1.
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++ lJause
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 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 reivtd "chicle tracking informa.ticm from a $CrYC'<,
and then displayed it in an apple!.
Caution
Jar<a applfts don't roeed a Hi n MlcIlOII beause thm
~ inswd (such ~ Intt nI paint).
1ft
in
Let's dissect the lWin funelion 10 help you better undCTStand what it does. The
term pub! ie specifies that this (unction is visible outside the class. (Remember,
every JaV,! program runs inside a class.) The static tcnn specifies that the
function definition never changes and is not to be inherited (borrowed for use in
another fUlletion). The stHle keyword is optional and 1I0t often used in an
applel. The void term means thatlhe function docs not return a value. Every Java
application you wrile will have a Hln funCiion, just like every C and C++
program. However, a lava applet, which runs in a web brOW5CT, conlains events
instl'ad and is not in complete control in the same way that a siandalolll' Java
application (...i th a main method) is..
39
40
Chapter 2
Ja~a
Programming Essentials
However, you eml write Java classes that dOII'1 have a m~1 n function. Why would
you want to do that? A class is usually created to perform a spedfk task, such as
the handling of sprites in a game. You might write a sprite class that knows how
to load a bitmap fik and draw a spri te on the screen; then the main Java program
(with the m~t n function) will COl/Slime or use the sprite class, which itself has no
"'ain function. A class has its own variables and functions, SQme of which are
hidden inside the class itself and invisible outside the class. What I'm describing
here are some of the key aspects of object-oriented programming, or OOP. In
some cases, as when developing an applet, you may just usc the pai nt event rather
than using a Ilain function. (More on that later.)
Object-Oriented Programming
There arc four main concepts involved in OOP, though you may not use all of
them in every class you write ,
Data hiding
Encapsulation
Inheritance
Polymorphism
I'll briefly talk about each of these concepts because you will bedealing with these
throughout the book. I don't spend a lot uft ime discussing advanced concepts
like these while writing lava games, and this book is not int....ndcd as a primer on
the Java language. Hundreds of books have been written about Java programming, includ ing some very complex textbooks on the subjed used in college
courses,
Data Hiding
Onta hidillg is a key concept of OOP because it provides a way to protect data
This way, the programmer can specify exactly what changes can be made to a
private variable through the built-in mutator functions and return customformatted data through the accessor functions. For instance, if you W'lnl to make
sure that a birth date is valid, the mutator function can restrict changes to a
certain range (such as 0 to 120). The following source code demonstrates the
concept of data hiding. [ have intentionally kept the code listing simpler by not
induding any comments.
publlc class vehlcle {
prtv~te Strln9 lI~ke:
prtnte lnt nUlIIWneels;
publlc String getM~ke() {
return . ~ke:
I
publIc boolun setM~ke(Strlng newake) I
if (newlOake. length() ) OJ I
luke - newm~ke:
return true:
I el,e {
retucn fa I se;
I
public boolean setNumWheelS(lnt count) I
If (count) 0 U count <20) I
nu....heeh - count:
return true;
) el se I
return false:
Encapsulation
IlCllpslIlllrioll is related to data hiding in that it describes how information and
proce&SCs are both handled internally by a class. These two concepts are often
Ilsed interchangeably, depending on the opinion of the programmer. (l prefer
41
42
Inheritance
Inheritance describes the ability to reuse dass definitions and to make changes 10
a subclass that relies on a base dass. For instance, the vehicle class might Ix used
as a basis for many subclasses covering a wide range of vehicles, from twowh~l
motorcydes to ISwheel semi trucks. When you are writing the code (or a dass, it
is best to pili each d;]ss inside its own wurce code file. Java allows yOll to inherit
from a single base dass.
Not .
A/though C++ ~ you III WlfriIIrom ~ ba5e dMses,. dlis leaun oftfll CiIMS_
problems tharl ~ soMs. so it IS wIdom tMd. ~1Nd 01 nUople inherilarn. J;wa * - you 10
1lIerf~_ ~ far thl' ~ and methods that shcUd be IoI.nI
WIIhin " partjaUr dtis.
.... nUupIe
A "O'lSlmClOr is a method that is called whenever you creatt> a new class in your
program. I'm nQt lalking about typing in a new claM, but when a class is instan
tiated into an object at runtime. When a new class is created (with the new
operator). the class dmnition is wed to construct an object, ~ where the keyword comes in herr. 111<' new object is "constructed" when it is being crated at
runtime; the class is a blueprint wcd to build or construct the ob:it at runtime.
When I click the OK button on the Class Wizard dialog box, a new file called
truck.java is added to my project, and it contains this source code:
pUb lIC chs, truck extends vehicle
I
public truck()
I
I
This is a nice, clean 'tarting point for a new class. Note that this class inherits
from the veMcle class (extends vehicle), and it include, a simple constructor
(pUblic truck()). Thi, constructor is called whenever you use new to create a new
truck obje<:t, using code like this:
tru ck silverado - nell truck():
The constructor i, ,pecified after the new operator in this line of code, and this is
called an emply COIlSlnlClor. If you want to pass parameters to a constructo r, you
can do so by defining another version of the constructor, which is a topic that
needs to be covered in the next section on polymorphism.
Polymorphism
Polymorphism is a complex word that, when broken down, equates to poly
(" many") and morpl! ("shape"); therefore, polymorphism refers to having
"many shape" or "many shapes." Java allows you to write many versions of a
function (or method) with different sets of parameters. When you write more
than one version ofa method, you have overloaded that method. Overloading is a
te<:hnical programming term that describes polymorphism at work.
Tip
I haw been Iffing tile terms fulKlioo and mell10d togetl1e( up to this point I wi~ refM to mell10d
ffom th i, point forward. Just note that a method i5 the same as a function. and thi5 applies to
accessor/mutator functions (terms that are used by C+ + programmers). Just r""",mber: A
property i5 a variable. while a method i5 a function.
43
44
Now Itt's make some changes to the main source code in the SimpleC1ass.java
file. This is the part of the program that consumes, o r uSC$, the vehicle and truck
classes. Here is the complete listing:
101portjna,lang,":
1.port java.a ppl et,";
1.port jiva,a"t. ";
publlc clUS SI~leChss utends ....pplet 1
vehlcle car;
truck llthtntng;
ptIbllC void InitO t
lIinl thl he i vehicle object
Cir - new vehiclel);
Clr.utMahl ford ):
clr.seU~heeh(4):
4S
46
What is the most significant part of this program lhal might seem unusual or
surprising? Well, take a look at those last fe'" lil1es of code where the lruck
information is displayed On the screen, The truck is using a method called
getHake() thai is 110t evell defin~xl in thl" trud class; lhis isa 11lelhod found only
in the vehiCle class, from whkh the truck class was inherited. Thai is the real
power of inheritanct'-tht' abilily to reuse fUl1clionalit}" while enh:mcing existing
c1a~.
I ha"e added the truck class to the Simpll"Class program, which is where the
vehtcle class may also be found. You can open the Simpll"Class project from
Ihe CD-HOM in the \sources\chapterQ2 folder. Figu re 2.3 shows the oulpul from
the current version of the program up to lhis point.
Re~jew
-..........
Questions
_,_..
c.......,. ...
~
' ..........."
".
'"
,''''''''_'',>0''''_
.....
,
,,_<_, "00
--
figure 2.3
tr"c~
(lass.
Review Questions
The following questions will help you to determine how well you
the subje<:ts discussed in this chapter.
ha~e
learned
I. What is the name of the JDK tool used to compile Java programs?
2. Which JDK command-line tool is used to run a Java application?
47
48
Chapt~
9. How many bits are thf're in a Java long in leger (th~ long <!ala type)?
On Your Own
Use Ih~ follo...;ng aercises to test your grasp of th~ material
chapter.
CO\~
in this
inh~rited class 10
try out
Exercise 1
Writt your own la"" class and then use it to almd an
tht concepts of inhC'ritana and mapsulllion.
Exercise 2
Modify your new dass by addingsomc methods Ihat dcmonstratc the concepl of
polymorphism by wriling sever-II versionsofth~ SOIm~ mdhod with different sets
of panmders.
CHAPTER 3
This chapter will give you a glimpse of whal's coming in the ne:xt few chapters
while teaching you some of the basia of game creation. The gam{'" featured here
was inspired by the classic Atari game of A5leroids. My first video game syslem
wa, an At ari 2600, and [spent many hours with il. In this chapter, you'll learn
how to creall' a varimion of this classic game, which will be th{'" basis of a more
advanced game later on when we get to Part 111. Here arc the key topia in this
chapter:
Creating an A5leroid5-slyle game
Writing key classes: BaseYectorShape, Ship, Asteroid, and Bull et
Writing Ihe main source code
Calculating velocilies on the fly
"
50
Ja~a
Game
figure 3,1
This Asteroids done is the basis for a much more .lITIbitious game.
understand e~erything in the soun:e code for the game at this point, but you will
learn how it works in time. Figure 3.1 shows the completed game you will build
in this chapter.
As mentioned, the game is cntirely based on vc<:;tor graphics. The player's ship,
the asteroids, and the bullets are all rendered as polygons, as shown in Figure 3.2.
Definition
Vector graphics dis.plays are diff~Nlt than ou, modem monitors in that t!Ie'I d,aw s~ based
OIl enlire lines. On the othe' llaod. 01"" mode,n displays (i"aw f35ler grifPhics based On pixels.
All of the objects in the game are moved using an algorithm that calculates the X
and Y velocity values, which are used to update the object's position on the
screen. All of these' values use tloating.point math, and the result is tluid 2D
rotation animation and realistic movement (see Figure 3.3).
Each of the vector shapes in the game has a built-in bounding reclangle that is used
to simplify collision testing, which is a crucial aspe<:t of the game (see Figure 3.4).
Without it, the bullets would not destroy the am'roids, and the ship would be
invulnerable! Collision testing is what makes gameplay possible in a game.
Fi'ilure 3.2
The objects in the
~ a'
all
Figure 3.3
FIOlIting-point IT\o1th algorithms give the gam.
~ 'f~l;sti<:
51
52
f igure 3.4
1lQurdnl.! reaangIes _
lMd lO delKl
when to/lisiclm
O((UI".
10
lueYectorSh.pe
S~lp
B\llin
53
54
f................
..........................................................
hse vector shape class for for pol)gonal shapes
nelper IIIl'thods
public voId setS h ~pe(Shape shape) 1 this . shapee shape ; l
pUblIc void setAllve(boolean alive) I this alive - al he ;
publ1t voi d setX(double xl \ thls. x - x; \
public void IncHdauble. j \ l ttlis ,J> .... j ', \
angle:
l
angle;
I
IldHault constructor
I
se t Shape(null ):
setAllve( fal se):
setx(O.Ol:
setYCO.Ol:
6He~ectorShape()
seUel~(O.O):
seUelHO.O):
setMOveAngle(O.O) :
setFaceAngle(O.O) :
I....
..........................................................I
55
Sf;
Fi~t
Java Game
Rectangle r;
- 6. (int) getr() - 6. 12.12);
r - neWRect~ngle((lnt)getX()
return r;
ShlpD (
sel5hape (new Polygon (Shi px. shl py. sh Ipx. Ieng th) ) ;
se tA1ive{ true) ;
.
.......................................................... ,
Bull et class - polygonal shape of a bull et
BulletO (
sh~pe
1);
jiIY
jiIY
t.'olygon;
t.Rectingle;
....
..........f
f ~
Aste ro1d c1lss . for polygonal asteroid snlpH
IIdeflul t constructor
AsteroldO I
setShlpe(new Polygonllstx. Isty. Ish. leng t h);
seUlhe(true);
SHRotat lon~e loc l tytO .0);
57
58
i..,or~ j . pplet.'
1..,ort j.v.wt.;
I~ort j.va . wt.event.,
laport j.va . wt.geoa.:
I.port j . wt . 1a.ge :
I.portj . utll. :
.
.....................................................
Prl .. ry chn for
t~e
gaat
l~plMeflts ~urnable.
bou~dlng
bOU$
bullet arr.y
Int 8lJUHS 10;
Blll1et{] bul1e~. _ Bu'let(BUltCS):
1nt clirrent8ll11 et 0;
flcrute the
Keyt'Hener I
appkt tnttO f'Vm l i$ run wbm the appkt fi rst sian s up and is us.ed 10
initialize the game. The code first crcatda double buffeT. upon which all gr.lphias
will be rendered in order 10 produce a smOOlh screen refresh WilhoUl flicker. The
player's ship and the asleroids are iniliali'Cd, and then the key listener is st:lrtcd.
.....................................................,
apple t Inlt nent
li ereate th e asteroids
for (lnl n - 0; n(ASTE ROIOS; n.... ) I
an[n)- ne. ASlerold();
as t [n). setRoUt IonYeloci t,( ralld. nutlnt (J)+I ) :
an{n). setl{ (double )rand. nut Int (600 )"20) :
as t{n). set'l (double )r and. nut Int (UOj .. 2ilj :
an{ nI. setltcveAngl e( r and. nut Int(31iO) ) :
double ang- asl[n] .getllcveAngle(} 90:
as t[n} .se t VI!! I X( ea \(Ang I e llc~el{ ang) ) ;
59
60
.
.....................................................
Ipplet updlle
t~tnt
.....................................................
publ1cyolddruShlp(11
g2d. set Trans for.( Ident I tyl ;
g2d. tr.nshte(shlp.geUI I. shlp.getll I);
gld. roUtelllulI. tllRlidl ans (5111 p. 911!tfaceMgl e( ) II ;
g2d. setCa Ior(Col or .OIWlIiE 1;
g2d . fill (sill p. getSII.pt!:( II ;
61
62
............................................1
public void
dr~1I6ul
lets() (
...................................._1
Screen Refresh
The p.intO lVent occurs when the applet window needs to be refreshM. This
mdhod is calkd by the: IIpditeO mdhod and simply serves the purpose of
drawing the back buffer to the: applet window.
I.... ~
.....................................................
Ipplet 1I1lldow ,elUlnt event -dr," tbe !lact buffer
I................
thrnd surt eYent . st.rt the VI. loop rllnn1ng
.....................................................,
rUltl~
IIpdltes
63
64
....1
I
~pillnt();
t....
thrUd $lap event
I............
Update the ship position bllsed on weloctty
**
publ1c void updHeShlpO r
f/update Ship'S X position
Ship. inCX(Shlp.get~el X( l);
65
66
(hilple, 3
I'
number of degrees cach frame, causing them to spin 011 thc sen."cn. Th is is a prrtly
nice effe.::t that adds to the quality of the game.
f
.....................................................
Update the asteroids based on velocity
67
68
...................
b~llets
,
public voId checkCol1islons() {
if
./
./
1f (a st [_l. getSounds ( ). intersects Cs hi p. getSou"ds ( ) )) 1
Keyboard Events
This game uses the keyPressed() evem to detect key presses. while keyReleased{)
and keyTyped() are ignored (although they must be in the source code listing
because of the KeyL 1stener interface). The most important parts of this method
are found in the code following the thrust and fire keys. which arc mappe-<! to
the up arrow and CIt! keys. (The Enter key and spacebar can also be used
to fire.) When the up arrow is pressed, this adds thrust to the ship, causing il to
move.
Definition
An algorithm is a mathematkal expression that causes one of the vanat>1'S ;n the expression to
dlange in a consistent w/tf. Amovement algorithm causes. for instance. the. vanat>e 00 a" x - ~
<;<,>ooj;nate plane to change SO mat it consistently ;ncreases in value, rnc.wing whatever object it
represents horizontally across the saeen.
69
70
.....................................................
key lIstener e ven t s
II
break ;
Sp~ce con be used t o fj re
KeyE yent . VICCOHTROL ;
KeyEvent. VICENHR ;
I /Ur I . Enter . or
c~se
c~se
lre~po"
The ea l eAngleMo~eX() method uses cosine 10 cakulate the update value for X,
returned as a double. The clleAngle"o~eY(l melhod uses sine 10 calculate the
update value for Y. also returned as a double. These small methods accept a single
pal1lmder (the angle IMt a game object is facing) and rdum an cstimalN X and
Yupdate value in pixels based on tlut angle. I can't S1rcss enough how wonderful
these two methods are! In the past, I M\"C miN mainly on the brute force (and
imprecise) method to move galm objects (usually called sprires) o n the SCrfl. I
would set the elocltyl to I and elocltyY to 0 to cause an object to mo\'e 10 the
right. Or, I would SCI ~elocltylloO and ~cloeltyY 10 -ilocause the game obje<:t
to mo\'c up on the screen. These veloci ty variables, along with an object's X and Y
values, would cause the objeclto move around on the S(rl'Cll in a certain way.
71
72
I........ ......
~
....1
Review QUf!Slions
...................................................../
p~bltc
~turn
Review Questions
The foJlowing qU~'StiOllS will help you to determille how well you have learned
the subjects discussed in lhis chapter. The answers arc provided in Appendix A,
"Chapter Quiz Answers."
I. What is tht
n.3IT1('
2. Wbat is the base class from which Ship, Asteroid, and Bullet are inherited?
3. Which dassic Alan gam.. inspired th.. gaITl(' df'VC'iopcd in this chapttr?
4. \\!him typt of collision testing does this samt ust?
5. Which method of th.. Shipe class does this game uSC for collision tesling?
73
74
On Your Own
Although this game will be enhanced in future chapters, you will learn a lot by
making changes to the source code to add some of your own ideas to the game
right now. Use the following exercises to test your grasp of the material covered
in this chapter.
Exercise 1
If you apply a lot of thrust to the ship so that it is moving very quickly across the
screen, and then rotate around backward and fire a bullet, that bullet will seem to
stand still or move very slowly. This is be<ause the bullet is based on the ship's
velocity. This isn't very realistic. Modify the weapon firing code in the keyPressed
event method to fire bullets at a fixed rate regardless of the ship's velocity.
Exercise 2
The ship tends to rotate rather slowly when you press the left or right arrow keys,
making it difficult to hit asteroids that are closing in on the ship from all
directions. The rotation angle is adjusted by 5 degrees each time the keys are
pressed. Modify the game so that the ship rotates much more quickly without
changing this 5-degree value. In other words, you want it to rotate by the same
value, but do these rotations more quickly.
PART"
This5ond pnt oftht book will cover the important lopia you need (0 know in
order to write an appln-based game in Java. including graphiC$, sound. music.
Uybo.:Ird and ffiOUSl' input, timing. and so 011. Hen: ne the chaplCTS in Pan II:
Clapler 4: Vector-Based Gnphics
Chapter 5: Bilmap-Rased Graphics
Chapter 6: Simpk Sprites
Chapler 7: Sprite Animalion
Chapler 8: Keyboard and MouS/: Input
Chapler 9: Sound Effects and Music
Chapter 10; Timing alld the Game Loop
CHAPTER
VECTOR-BASED GRAPHICS
The previous chapter really pushed the limits as far as the amount of information
cover! without thorough explanations beforehand. I wanted to immerse you
in the source code for a game right up front before fully explaining all of the
concepts to give you a feci for what is involved in cTt'llting a real game. The
Asleroidsdone was not a greal game, and nOI ewn vel)' good-looking, but it was
functional 'ava has a robUSI and feature-rich set of classes for working with 2D
V1or graphia and bitmaps (cxplaiDed in the naI cmplcr), making il pos.sible
to draw rectangles, polygons, and olhcr shapt:S very easily. Here are the key topia
in this chaplcr:
Drawing and manipulating vector graphics
Using the AfftneTnnsforll dus
Applying the lranslation, rotation, and scaling of shapt:S
78
ilrulgcs on 1M screen. But Java is wdl known for its ven;,atillty and wnvmitncc.
This class knows how to draw m:tangla and many othtr shapts. But it can do a
lot mort than just draw-it can abo 1l'lOVt. roUtt, and scalt shapes!
..
......................
tllpOrt jua ....t.;
tllpOrt jua . ppl~t.;
tllpOrt jua.a>lt.~.;
IlIpOrt jua.llttl. ;
public class
private
S~.pe lh.p~;
fi9ure 4.1
The
This program uSfil Ihe Grlphics20 class to translate. rOlate, and scale a Shape
object randomly. which retulu in the screen being filled with random rectangles
of v;lrying sizes and orientations. This simple program illustrates lhe basoe roncept bdtind lhe Asraoids-sty!e game from lhe previous chapter-dlat Java
79
80
Figure 4.2
The aste<oid sl'iapc,
...
e.
figure 4.3
pn:l!JiI!Il.
two arrays define the X and Y points for the polygon. We caD a point a
and the plural form is I'I'rtices. When you are creating a polygon in this
manner, keep in mind that the X and Y arrays must pair up, since every X must
go with a Y v'llne (0 make a vertex.
YCTtl'x,
..........................................................
Ran~olllPolY90ns progra ..
81
S2
lllp(lrt
ll1pOrt
111port
1.port
jau.a"t.:
jna.applet .
java .utl 1. ':
j ava.awt. geOll. :
e~tends
Applet (
O. -10. 7. 7. 10):
prlute lot[] )'polots (-10. -Z. 10. 10. -21:
prlvatelot[]~po1ots1
xpolnts.lengt~):
8l
84
Figu,. 4.5
TIlt P.olaIef'dItgon prow... _
,) Wr-Wpod
.
..........................................................,
RoUUPolJgon progra
l-slort
I.port
l-slcrt
illpOrt
ll1pOrt
java .awt .;
java,awt.event.
Jav a.a pplet.;
J av,) . ut 11 . ' ;
JaW,). , .. t. geOll, ;
I
prlutelnt[]xpolnU-{ 0,-10, -1, 1,101;
prlute lnt(] ypolnts - (-10, ,2, 10, 10. -21:
Ilhe r e 's the snape used for dralling
prlute Polnon poly;
/lt pp le t pt ln t eve nt
pu~1ic ~ol d pt l nUGr aph1cs g) I
/lcreUe an ins ta nce of Gnpll1cs2D
Grapll1cs2D gld. ( &rtpll1cslD ) 'I:
/lsue th e Iden t ity trans fo r.
AfflneTransfor1l Identity new AfflneTransfor.():
8S
rep.l ntO;
bre.k;
(lse le,E_ent. n ... RI6HT:
rOtitlolt++;
If ( rotitlOf1 ) 360) rot.tlon" O.
rep.lntO;
break;
On Your Own
Review Questions
The following questions will hdp you to determinr how ..'til you havc lcamnl
lhr subic'cts discussed ilt this chapler. n.c answers are provided in Apprndix A,
"Chapter QUil. Answers."
I. What is the primary class we'vc been using '0 manipulate vector gl"J phics
in this chapter~
2. Wha, is lhe name of the Appkt (''I'cnl Ibat rd"rrshcs 1M scrm?
J. W1I<1I is the name of the Gr3phialD mclhod lltat dm..s a filled
rungld
R~ndo.
On Your Own
U$C' thr following exercises to tesl your grasp of the malerial covered ilt 'his
chapter.
Exercise 1
ThC1C arc nu.ny cnmple progranl$ in Ibis chapter lhat could be modified and
aperimmted upon. Ld's tweak the RandornPolygons progr.lm-modify Inc
program 50 thaI it dr;lWll IWO different polygons instrad of jusl a singk onr.
87
88
Chapler 4
Vector-Based Graphics
Exercise 2
Modify the ROlalePol)'gon program .'iO Ihal it "'ill rotale based on mou5C.'
mo"enwnt instead of llUlIon clicks. You will rwed to implement the House
IIottonl1stener interface (and events) and call lhe addHouseHotlonltstener
method 10 gain access 10 lhe .ausel'\ll.ed evenl. In Ihise'enl, )'ou can lrad: mouse:
nto,ernenl and rolate lhe polygon accordingly.
CHAPTER
BITMAP-BASED GRAPHICS
Jan. has a robu5l aDd fature-rich 5d of ~ for working with 2D bitmap~ gnphics (also known u mstrr grtlphics), allowing you to load and draw
bitmaps vayeasily. Bitmaps are the k<ys to buildinga good 2D game with images
rather than vector shapes. Here are the key topics in Ihis chapler.
Loading and drawing bitmap images
Applying transfonnations to bitmap images
Drawing opaque and transparent images
.,
90
as you ha\~ manipuLltM \~or gl'ilphu thus far. This awaome functionality will
tnlllsble well into tM subsequent chapters on sprite and animation prognomming.
The real difference when working with images il; that you will ntoed to create a
separate AfnneTr~"~fo ... objcctto manipubte the INge objt, rather than going
directly through Graphlcs20.
Figure 5.1
The DrlWlmage progo-am loads a bitmap file and drirW$ it.
This ~ily castle image was rendtfed by Reiner "'olein using Caligari trueSiCe. He oIlm
a large amount of roya1ly.fref game artwor'<.. such as 1M ust\e, at tos website. www,rffierslileetde
~
.
,'
'
"
'
I
catch (Exception e) (l
return uri:
lIi1pplet Intt !Went
public .old Init() !
I.ilge - gUIr.age(getuRl("ciistle
png~)}:
91
92
Chapter S
Bitma~6ased
Graphics
Figulll S.2
The RaodomlmigfS program driJWS imigfS at laOOom Iotatioos. with random rotation and lUling.
,
.
......................................................f
I . r t J,v, .,lIt.;
j,.,
I
cnd lhceptlon e) ( I
return url ;
Iflpplet lnlt nent
public wold ln1tll (
Illage - oetillage (,nURl( -spa cnh1 p. pn,- l l:
IIlppl et pllnt u enl
pUbl1c wold pllnUGrlphlcs gl (
IIcrtite In Instince of Grapll1 cs2D
Graplll cs2D , 2d - (Graph lcs2D ) , :
llworkln, transfol'll object
Af11 neTrlns10r. trlns new Affl nelrlnlfor.( ) :
/I rlndOll nullber generltor
Rlndoe rand ~ new IlIndOll( I;
93
94
Transparency
Although you can load and draw a bitmap at this point, lhe code you've seen so
far is very limited. For one thing, the get Imilge(} method can't load a bitmap file
out of a Java Archive (JAR) file. JAR files will become very important later, in
Part Ill, when we build the Galactic War game. Since the game is so large, with so
many bitmap and sound files. it takes a Jong time for the game to load over the
web (unless you have a broadband connection). You'll learn how to create and
use a JAR file soon enough. All I'm concerned abou t right now is that we are
using code that will be compatible with a JAR, so that Java can read files out of the
JAR as easily as it reads the raw files from the web server (or the directory in
which your program is located if you are running it locally).
The Abstract Window Toolkit, known as AWT, provides a class caBed Toolkit
that knows how to load a bitmap file . It's smart enough to look in the current
URL path where the applet is located (something that you must pass to the
lleti llage{) method) . You can usc loo l~\t in your own programs or you can
instantiate a global 10011:.1t object and then Uf>C itthtoughoul Ihe game; there are
many options. Let's take a look at how this class works;
Toolkit tk - 100lkit .1letDefaultToolk lt() ;
I.~ge
First, I created a Toolkit object by returning the object passed l>3ck from
Too Hit.getOefau 1tToolkitO . This method returns a Toolkit object that
represents the state of the Java program or applet. You can then usc this Toolkit
object's getlm~ge() method to load a bitmap file . Since we want our applets to be
JAR-friendly so games will run on the web as efficiently as possible, I will use the
getURL() melhod again;
l.~ge
Traospareocy
Opaque Images
L.et'$ $Ian with what you have already ltamed up to this point-how to load and
draw a bilmap wilhout any tralUpolrmcy. At this poinl il doesn'l mailer whether
you use the Applet or the Tool kt t 10 load a bitfll<lp file beotuse!he end result will
be the $;lITle. I le:ive it 10 you 10 decide whkh method you prefer, and I will use
them bolh interchangt<tbly. L.et'$ wrile a $hon program to $tIVt as a ba5is for
discussing this topic. The output from the BitmapTest prognm is mown in
Figure S.). I ha~ highlighted the key ponions of code in bold in the Iisling thai
follows.
.....................................................
BltaapTeH progra_
lI.po rt
I_port
I_port
t.rt
java.allt, ,
java.applet,:
java. ut t I. ':
java ,net,';
9S
96
Chapter 5
Bilmap-Based Graphi(s
l..ge1..ge:
Thread g._loop:
RlOIdOli rind - new RaOldOll{):
prlute URl getURUStrlng fllenil ..) 1
URlurl-nul1:
try I
ur I - this .get(lus ( ) .9I!tlleslKlr(e( HI enil_) ;
I
ciltch (hcepUon e) I I
return uri:
public void Inl10 I
Tool kit Ik - Toolk1t.getDdilUltToolklt( ) ;
I .. ge - tk.geU..ge(gnURU-i1Suroldl.png-));
Ciltch (!fturruptedXception e) (
e.prlntStilctTrilce() ;
}
repillnt():
Tr(lnsp;trency
po,lbllc yotd INtnt(6r'llhtcs 9) t
6r.p~tes2D g2d
16uphtes2DI,:
tnt "tdtb - scrnnWtdt~ . tIlllge.getWidt~(thtsl - I;
jnt hetgM - serunHelg~t - j,qge .getHetght( U,lsl . I;
6
Q2d.dra"I~Qe(1.ge.rUd.nutlnt(.1dt~l. r.nd.nextlnt(he19~tl.
th1s):
This shon program loads the bitJrnlp image shown in Figure 5.4. In many pmgnmrning bngu;oges and gnphia; libraries, you must specify.ll transpamlt pil;d
ccMor to ~ uxd for tnll1SJQrmcy. In the aamplc shown here, the bld rqion
around the edges of the astm>id would ~ considered the Utranparmt ZO~" of the
image. This trnll$parmt color is black in the exampleshown here (with an RGB value
0(0,0,0), but other colors can be used (or the transparent color too-the color pink
(255,0,255) is often used for the transparent color b<.'cause it stands Out so well.
la.... uses a more advanced method to handle trall$parmcy, as the next section
apbins.
Transparent Images
Java is a sman language that handles a lot of things for the programmer automatically, including the drJwing of t ransparent images. This really makes life
easier for a Java game progmmmer because many game librJries use a transpuent pixel for transparency ill$tead of a mask layer. So instead of dealing with
transparency in code, it's handled in the source anwork.lf you supply lava with a
transparent bitmap file, it will draw that image transparently.
f igu re 5.4
This
op;>QOe
tr~~rl'l'q
i1tormation.
97
98
Most Jav;l progr<lms u.5<' the PNG foomt beau.5<' it offen deemt compression
and transp,areocy information without sacrificing image quality. You will need to
u.5<' a gr.lphics editor, such as Paint Shop Pro or GIMP, to con\"en images from
....hatever source format they are in (most likely the BMP format) to the PNG
format, along with the ma~k layer that makes tr.ln~parcncy possible.
Figure 5.5 shows the asteroid image loaded into Paint Shop Pro wilh a new
transparency layer. The checkerboard background behind the asteroid image
shows the transparent region.
Ti p
I " - lIlfd IIIiIly 9"Iftc: toiun,. iUdl is I'Iinl: Shop I'fQ. GIMP. -.I ftcIshcp. N\trlNlJI fty
... otammcaIy ciffe"ellc. fty shM' 1loe SII'Ie biSio: 1OOI5et. ondodlg 1loe dly III sel: a
~ . . . and ...... a file 0UI1ll a PNG WIth .. alpha dIameI. 1lle inslructJonl ~ ~
wi t.. SIII'IiI.- b other graphic eoitm; lOU siIr'9'Y _ ~ each mal in m. program'i _
i)'item.
..
_ _~
.. - - -- _.
~~~~
D"'.bY. 1 . _ _ '
'"I "' .
"
t~"',...
. '\
~.
,.
".
,
,
Figure S.S
1lle iSterold Image IIoJS been !to'tn a tr~1 mask t....
--_
Tranwarency
Figu.. S.6
An ilpha dwJnellayer
~ ~..xlIlO
d>r
~teroid
Ln'stau the same program you just typed in for BitrnapTesl and run it again.
Only this time, it will load up a new \'et"Sion ofthe asteroid I.png fik that has bttn
ediled to support lranspareocy. Figure 5.6 shows tht OIItput from Iht TranspartnlTest program. 1be soura rode has not ehanged (refer earlier 10 the
BitrnapTesl program listing), oollht PNG fill' has changed, which accounlS for
the difference!
99
100
Chapter 5
Bitmap-Ba'led Graphics
.... ~ w.
r
-
..-.
Figu re 5.1
A 3D rt/ldilion of a dumpy asteroid (coorlesy of Edgar Ibarra).
the game object). This should loom the edges orthe game object and highlight
everything around it (Stt Figure 5.8).
Now tha t you have a sdmion available, you need to inven it b<!use this
selediolJ wil1aClual1y exclude the image. In Paint Shop Pro, click on the SdKtions menu and choose [nverl (sec Figu re 5.9). Figure 5.10 shows the result orthe
inverted selecti on.
Tip
If YIlU ' - a ~
and -..Md lite 10 odIde - . , ~ 01 it in ordtr 10 ~_
bculcliq oI ... lNI
YIlU Qn Idd ~ h ~ by'" dilbIg: with ... Magic wad
tool imidr pclI'1ior6 01 thl'
10 add . - ~
The next step is to create a new mask Layer in the image to represent the transparent portion. You can tell Paint Shop Pro 10 generate a mask based on the
Trilnspilreocy
.'
,
Figure 5.8
- ....
.~
Figure 5.9
Pl'!piriog to inven Iht wlection.
101
102
"':'
. """
, ,;";,,,'~~~--- -- '''4
~ "
III
..
- .,-.
.~
'------~ " .~
.... _.
."'
Figure 5.10
- .....-
selection you've made in the image. To do this, open the Layers menu, select New
Mask L1yer, and then Show Selection, as shown in Figure 5.11.
>I,
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 ~
figure S.12
The flteroid image now lias a masffil
tr~ency
1Iy8.
103
104
Chapt~'
5 Bitmap-Based Graphics
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~
Ih~
n.an~
d~te(\s
<I
JAR!
key prtoSSes?
On Your Own
Usc the following exercises to test your grasp of the materi<ll w\'ered in this
chapter.
On Your Own
Exercise 1
ThcTc are IIklny example programs in this chapter thaI eQuid be modified and
expeOlTlt'ntM upon. TwtoIk tht Randomlllklges program. Modify the program
so lhat it !ooids and dnws two diffeTmt im.1ga nndomly instead of just a single
im.1ge.
Exercise 2
Modify the Dnwlmagt prognm so thaI it will scale the imagt largtr or smaller
with tht uS(' of the keyboard plus (+) and minus (- -) keys.
lOS
CHAPTER
SIMPLE SPRITES
Up to this point you have learned about a lot of jaVll classes that are useful for
m;lking a game, particularly the Graphl cs20 class. The previous two chapters
provided the groundwork for this chapter by showing you how to tap into the
Graphlcs20 class to draw vectors and bitmaps.. At this point, the source code for
evm a simple bitmap-based game will tend to be too compliated and too
difficuh to manag<- without a better way to ~ndle the objects in a game. What
you need at this point is a new class that knows how to work with gameobjectssomething known as an /ICt(Wor a spri'''. The goal ohhis chapter is to develop a
Wily to handle the game objec1s moving around on the sclftn. Here are the
specific topics:
Programming simple sprites
Creating a Sprite class
Learning about collision testing
'"
108
A spri te cannot draw itself without the Applet and Graphles2D objects in a main
program. Although the Sprl t e class could usc methods such as getGraphl cs() to
pull information from the main apple!, our examples use a double buffer (a back
b uffer image used to update graphics smoothly, without nickering the 5O:rn).
The 8iSeGa_Entit, class will handle aU of the position, vdocity, rotation, and
other 10gislkaI properties. while laageEnt I t, will mallt use o(them by providing
mrthods $\Ieb as tr.nsfo,..( J and 4rav( ). 1want to simplify the Sprl Ie cbs.s 5(l it
doesn't expose all oftbese propttties and methods., but provides a simpler means
to load and draw images. This simplification willlw especiaJIy helpful in the IJCl[t
chapter be<.:au.se animation tends to compliOlte things..
A useful sprite class should handle its own position and velocitydata, ralher than
individual X and Y vaJut$ (or these propttties. The sprite's position and velocity
will be handlfil by the 8iSeG._Entlty class. The Sprite class will not inherit
(rom llaageEnt I t,: instead, it will use this class internally, like a regular variable.
I also want the accessor methDds to resemble simple properties, while the llIutator
methods will be in th e usual "set" format. For in stan",~, I want the Sprite class
to have a position() method that returns the position of the Sprite obj ect,
bu t it will use a setPosltion{) melhod to change the X and Y values. For
instance, I want to lw able to access a sprite's posi tion and velocily by wriling
code like (hi$:
sprite. pes it i on( ) .Il )
sprlte.pesltion().l( I
AA Mcessor method is a method that returns a private variable in a das~ A mutator method is a
metllod that dlaoges a private variable in a dass.
1..
*0 . . . . . .
Point20 Cl ass
**......
..................1
Polnt20 utends Object l
private doubi e ~. y;
ChS5
lIint constructor
int y)
setX(x);
seU(y);
I
Ilfloat constructor
Point20(f1o~t x. flo~t y)
setX(x);
sety(y);
I
Iidouble constructor
Point20(doublex. doubley ) {
setX(x);
setY(y);
Polnt20{int~.
IIX property
double X() { return x;
109
110
Iidefault constructor
BaseGameEntlty() (
set~1 Ive{hl se);
setX(O.O) ;
setHO .Ol;
setVeIX(O.O);
setveIHO.O) ;
setHove~ngle(O.O)
setface~ngle(O.O)
;
;
10*................
..........................................................
ease galle I_age cl ass for bi t _apped game ent I ti es
111
112
pl'1ltecte<llllite lllige:
protected Applet applet:
protected Affll1l!TranHonl at:
protected Graphlcs2D t2d:
Ildefau I t cons tructor
l.ateEn t lt7(Applet a) I
applet-a :
setl.age{ nu1 1 l :
setA l 1ve{true):
\lllbilc lntw1dthO (
If (Illite I-null)
return lllige. tellli dth( applet) :
el se
return 0:
I
public lnt height( l {
If (1.age I-null)
return l.age.getHelght(app1etl :
else
return 0:
helgM0l21;
IIboundlng rectangle
publIc Rect~ngle gel8ounds() I
Rectl ng le r:
r ~ new Recling I e( (I ntlgeU (), (\ ntlgttY ( ), ,,1 dth() , hel ght ( ) ) :
return r;
113
114
Collision Testing
The Sprite class includes several methods for detecting collisions with other
sprites, and it also provides tests for collision with Rect~ng l e and Poi nt20 objects
as a convenience. Remember that I wanted this Sprt te class to be intuitive and
not cause the compiler to complain abou t silly things, such as data type con
versions? Well, the same is true of the collision testing code. There are three
versions of the CoIl i desW1 th() mcthod in the Spri te class, providing support for
three different parameters:
Rect~ngle
Sprite
Polnt2D
This should cover almost any game object that you would like to test for a
collision. Since these mcthods arc built into the Spri te class, you can call them
with a single parameter, and the internal data in the sprite itself is used for the
SKond parameter that would normally be passed to a collision routine.
C~
..........................................................
Sprite tIns
<_por t jUI .I Mt .:
IllPort JUI.applet.:
p~bllc
Ilconstructor
SprlteCAwlet a. Graphlcs20 g2dl [
entHy ~ new IflIgeEntltyCa):
ent 1t y .setGra ph Ics( g2d) :
enl1 t y. se Ul l .e( fa l se) ;
pos new POlnUDlD. OJ:
weI new Polnt20(D. 0):
rot~te ~ 0.0;
currentStateO;
115
116
liS
lIupd~te
II-el~ods
IItenerlc sprIte sUte url.ble (~1 he. 6ud. coil 'ded. et c.)
publIc Int sutel 1 I return currentStlte; I
pub1Ic ~oid setSUte( i nt s t~ te) ( currentSt~ t e - stl te ;
Ilreturns I bounding rectlngle
public Reclugle getBounds{)! return entlty.getBoundsll ;
I/sprlte posttlon
publlcPolnt211pos'tton lreh"'pos;!
publIc voId setPos; t iOllIPolntlll post I thl s.pos - pos;
II spr I Ie lIO.e.ent vel oc tty
I
public . oid setllo.e gle{float angle) I
ent Itl .seUlowe gle( (double I al\91 e):
I
public .oid setHoweAngle(lnt angle I I
ut I ty .setKo>eAn gIe ( (double) ang1 e) :
Ilt~eck
I
I fc ~ etk for coli i sion with another sprl te
pub11 c boo1e. n co1li des ll l Ul (Sprtte spd t e) I
return (getBou"lls( I. Intersects (sprl te. getBounds ( ) 11 :
I
IIcheek for coli h i OIl with a poi nt
publ ie boolean coil idnll HMPolntZO point) I
retu rn (getBo un d1( ). con t ai nl (poi n1. X( ). poi nt
Y()) 1:
118
Tip
6 II feJtI.ft nssing &om I!le Sprl te diss..: this pcwot we wiI 90 _lhil
next dIIpIer.
.........._
.. _
sW!ecl
r19uA! 6.1
1hlo SpitloTest
~ogram
Sp'H~
cliss.
kam more about threads and the pmt' loop. Sl:udy this short demo prosnm wdI,
bcaUK it ckmonstrates ~ps the lim high-speed enmplt you.~ $em thus far.
I
~
p rg gr~
Spr l teTnt
119
120
publicvoldstop(){
gall\l'loop - null;
I
cnch (JnterruptedE~ceptjO"e) (
e. prl ntStack Tracel ) ;
I
repalnt();
"e~tlnt(helght)l;
R~~iom
Review Questions
The following questions will help you to dctermine how well you have learned
the subjects discussed in this chapter.
I. What is the name of the suppo" class created in this chapler to hdp the
Sprl te elass manage position "nd ~Iocity?
2. During which keyboard event should you disable a key-press var iable when
variables~
4. Which Java class provides an alternate method for loading images that is not
tied to the applct~
S. Which Ian package do you need to impo" 10 use the GTlpll1cs20 class?
6. Which numeric data type ~ the POl nt20 class (creatoo in Ihis chapler) use
for internal storage of the X aud Y VOllues?
7. Which data typt$ can the Potnt20 class work with allhe constructor 1evel~
8. Which sprile property dC'lennines lhe angle at whieb the sprite will
mov~
III
122
On Your Own
Use the following exercises to te51 your understanding of the malcrial cO"erc<! in
this ch;Lpter.
Exercise 1
The SpriteTesl program demonslr:ues the usc of the Sprite dass. Modify the
program so thaI it draws multiple instances ofthe asteroid sprite on Ihe .screen,
each moving and animating differently.
Exercise 2
Modify the SprileTest program C'o'en further by adding collision testing, such Ihat
Ihe asteroids will rebound off one another when they collide.
CHAPTER
SPRITE ANIMATION
This chapttT adds a significant new feature to )'Qur box ofJa.... tools-the ability
to load and draw animat~ sprites and apply thai knowkdge to an rnhancrd new
sprite clau. You willieam about the different wa)'510 store a sprile animation
and how to acc~ a single frame in an animation strip, and you will s a new
class called Ani.atedSprite with some S('rious new functionality that greatly
extends the baS(' Sprite class. Here are the key topics:
Sprite animal ion techniques
Drawing individua.l sprite frames
Kccping track of animation frames
Encapsulating sprite animation in a class
Sprite Animation
the years I have seen many techniques for sprite animation. Of the many
algorithms and implementa tion$ I've sludird, I beliC'V(' there an: two CSSCTItial
ways to animate a graphic object on the screen-by loading individual frames,
each stored in its own bitmap lile. or by loading a single bitmap containing rows
and columns of animation frames.
()o,-er
124
Animation Techniques
First, there is the ~"or<t method. This type of animation involves loading a
bitmap image for each frame of the animuion in s.equmce, and Ibm animating
them on the scret'n by drawing each image in order. This technique tends to take
a long time to load all of the animation frames, especia lly in a large game with
many sprites. There is also the system overhead rfq uir.-d to maintain so many
images in memory, even if thq are unall. Figure 7.1 show, an enmplc.
Drawing an anillliltion sequence is somewhat of a cha1knge when loading individual fmmes because of the logistics of it. How should you store the images-in
an array or a linked list? I've.setn some implementations using both methods, and
ntithcT is very friendly, so to speak, becat= the code is so mmplialted.
The second sprite animation technique is the tiled method. This type of animation invol,cs storing an entire animation sequence inside a ~ingle bitmap file,
also known as an 1I11;rWI/;otl Slr;p. Inside this bi tma p file are the many frames of
the animation laid out in a single row or with manycolumllSaod rows.. Figure 7.2
shows an animation strip on a single row, while Figure 7.3 shows a larger animation with multiple columns and rows.
Figure 7.1
An ri'nation
~ wiIh
figure 7.2
An animation
~trip..,,;m
I t _ SlOItd ..
a 'iingit row.
~ bmnap
filrl.
Sprite Animation
Fi\Jure 7.3
No iIIIimatiotI 5ll1l.mh ..... cdurMi il'Id two rows.
thought of it gives me hives. Not only would it take houn to jot down t~ X,Y
position of every frame, but the bitmap file oould easily be modified, thus rendering the manually c:akulated poinl$ irrelevant. This is computeT scienc:e, alter
all, $0 theTe is an algorithm for almost everything.
You can eakulate the column (that is, the number of frames IlcrOS3) by dividing
the frJme number by the number of eolumns and multiplying that by the height
of each frame.
frllleYe (frllieHullber I colU1II15) helghl;
This will give you the correct
is located, but it wiD not provide you with the actual column, or X value. For that,
you need "similar solution. Il1$Iead of dividing me frame numoo by oolumns,
we will use modulus:
12S
126
if
Take a dose look at what's going on in lhe code here. First, the current frame is
incremented by all arbitrary value stored in a variable called anlJla t 10nOI reet Ion.
This will always be either -lor t to animate forward or backward. Then. the
next line ehed::s the upper boundary (tot a IFr allles J) and loops back to 0
if the boundary is crossed. Similarly, the lower boundary is checked, ~lting
Sprite Animation
currentrra-e to the upper boundary value if necessary. The end result is thaI
three VlIIriables are needed:
currentfra-e
totalfra-es
Int .. ttonOtrectton
You would WlInt 10 call this upcbte cod... from the Ihread's run( l ~t method.
But, speaking of th... thread, tMt does bring up an important issue-timing.
Obviously, you don't WlInt every sprite in the game to animate at exactly the same
rate! Som... sp rites will move very slowly, while olhers will have fast animations.
This is re;lllyan issue offine.tuning the gameplay, bUI you mllst have some sort of
nu:<:hanis1l1 in place for implementing liming (or each animated sprite st'pamtdy.
You can accomplish this by adding a couple more variables to the mix. First, you
will net<! to increment a co unter each time lhrough the game loop. If that
counta reaches a certai n threshold value, then you reset the counter and go
through the process of updating the ..ninution frame as before. Let's use v;ui
abies called fra-eCount and fra-eOelaJ. The frame dclay is usually a smalla
value lhan you would expecl-sudt as 5 to 10, but usually not mudt more. A
ddayof JO in a game loop running at 50 Cps means that the object only animates
at S fps, which is "ery slow indeed. I often use values of 1 to S for the frame delay.
Here is the updated animation code with a dclay in place:
fra..co.nt++:
1f (frCount) fr._OellJ) (
fra..count.o(l;
127
128
Figu re 1.4
All animated blIII with 64 11"-.
.
.....................................................
/
I.port
jIVII . awt
. I.age
l..,l_~ts
RuMilble I
_,
_.
....
figure 1.S
1hlo AAunationTel program.
stattc tM SCR[[NHElGHT - 480;
Thrud gllle1 oop;
Rando. rand new Randall();
IIdoubh buffer objects
Buffered I.age blckbuffer;
Graphtcs2D g2d ;
I/background tllolge
lllolge background;
IIsprtte nrllbles
IlIolge blIll:
1nt balll 300. blIllY" 200:
1nt speedl. spHdY:
lIutllolttOll nr11bhs
1nt currentfrl." D:
tnt totalfr. .I" 54:
tnt u1l1olt1onD1rKttOll- I:
tnt fr..count .. 0:
tnt fra.tlell, .. 5:
Sprite Animation
129
130
Rlget"Rl(Str;~g fllen,W)
~rl a n~ll;
'" urI -
t~h.gftCllSsl)
.9ftllesourcelfl 1e<lilw):
J
Cilte~ l{lceptton el /I
return ~rl;
f ~ntfrrUjlad.cept len
el I
~.[ I G~l .
Sprite Animation
e.prlntStacHrace() ;
I
glieUpd.tet);
fellllntl);
J
.1st If (currentFre. (Ol (
current Fr totll frl.S );
131
132
Now, after reviewing this code, you mighl be wonderi ng why we aren't using lhe
lU!ileEntHy and Sprite cluscs from lhe previous chapler, since they would WI
down on so much oflhis code. That's a good question! The reason is this: I don 't
like 10 build 100 m3ny dependencies into class definitions. As I explained in lhe
previous chapter, 100 many links in an inheritance chain om lead to problems,
This progr:am is completely Idf-contained, withoul nd of any atra classes.. A
single, self-conlained example is far more educalional than a short program filled
Wilh object variables dl'Clared from (Uslom classes. Al a certain po inl, we wi ll do
thaI. BUI righl now, let's focus on just one subject withoul any dependencies.
Sprite Animation
great thing about moving drnFrllle{) inlo a class is thaI moSI of the paramelers
can be eliminated. as they will be pulled out of Ihe class in lernally. Selting up an
animation will require a few steps up fronl when the game Slarts up. but aflet
lhat. drawing an animaled sprile will be an automatK process with just one or
IWO melhod ails. Note. also. that we're inheriting from the basic Sprite class
from the pl'n'iow chaplet! I'D highlighl the important code in bold.
,
.
.....................................................,
AlilutedSprl te ellss
l-.or,
l-.oH
111ll0rl
laporl
Jan.awt. ;
Jan.applet .;
java.avl.luge .';
Jan.net. ;
pu~lle
133
134
citch (Exceptlc.n e) II
return uri ;
p~bllc
p~bll
Sprite Animation
public Int fra~eDelay() I return frOehy; I
public vOid setFra~eDe1aY(Int delay) {frOehy - delay;
public 1nt columns() I return cols. I
public void setColwllns(1nt IIU ~ ) {cols - nu...
pub1Ic vol d updateAn lll~ t Ion(} I
frCount++;
I f (frameCountl) ) fr~IIleOel ~y()}
setFrallleCounHO) ;
Ilupdate the ~nl.~tfon fraille
setCurren tF rame( currentF rame () + anlllM t Ion01 rect Ion ( ) )
if (currentfr~IIleO ) toUlFramesO - 1) I
setCurrentF rame (0)
I
else if (currentFrameO (0) (
setCurrentFrame(to t~ IFraooes() - 1);
i~age
O. O. fraIleWldth()-l.
fr n eHelght( )'1. fralleX. fralleY. fUIleX+fraIleWldth().
fraIleY+fr neHel ght(). applet() 1:
te_pSurflce.drawlnge(an\.1~ege.
13S
136
ChapI~r
7 a
Spril~
Animation
_.
-'.'.
figure 7.6
Testing lht AntalttdSprite daiS.
inheriling from Sprite, the Anl ..tedSprlte class allows yo u 10 rolatc Ihe animated sprileS ...itik Ihq arc drawing! This is duc to thc functionalily provided by
l..geEnt 1t)', a core support d~ for sprite drawing. I will show you the key
portion of lhe program that differs from the AnirrulllionTCSI program (covered
cartier in the chapter). Figure 7.6 shows the output of the pr~m. which you
can open up and run from the CD-ROM if you wish.
Hcre is a list ofall the dasses used in the AnimationClass program. You can copy
theSt: files from the previous chapter. The new projttt is called AnimationClass.
Anl.. t ionClns.java
Basee;..Entt t)'.jeva
'..geEnl II)' .Java
PoinllO.Jau
Sprl Ie . java
137
138
Review Questions
The following questions will hdp you to detnmine how well you h<a~ lc-amed
th~ subjts discIWe'd in Ibis chaptet.".
I. Wh<al is th~ n.aJ1ll' ofth~ animation class created in Ihis chapl~r?
3. How many frames of animalion were Ihere in Ihe animated ball sprile!
4. \\Ihm do you call an animation thaI is stored inside many files?
fram~'s X
9. What is a good class to use when you need 10 creale a bitmap in memory!
10. Which Anl.atedSprl te method dr.lws Ihe cu rrent frame of animation!
On Your Own
l1lC: following exncises will hdp you 10 det.ennine how well you h<a~ undn'Aood
lhe new material introduced in this chaptet.".
Exercise 1
The AnimalionTesl program is really LaJ1ll'. I ml'3n, whit.. balls paslw wilh a
red X, being drawn ov..r a strange W<Xld -grain background! Locale a really
great image Ihal you can use for the background, and loo k through Ihe
\Media folder on the CD-ROM to find a better animat ion sequence to usc in
place of the whit.. balls.
On Your Own
Exercise 2
Now that you Cln do fuU-biown animllkm. it's timt 10 rombint thai awtSOmt
Clp,ibility wilh timt-provm rollisian dC1td.ian in ordtr 10 add SOmt aaual
functionality to tIM: AnimationTm pmjtct_ Modify 11M: program and Clust tht
animalro sprite 10 dt$troy each othtr whtn thq rollidt.
ntW
139
CHAPTER
1lJe ktyboard and mo~ are tM only rWistic devices for usn input in a wdr
based game developed as a Java appkt. But even when oonsidcring a standard
Windows-based game developed in DirKtX or another library, the keyboard and
mouse are by fu r the most oommon forms of user interaction in a game. This
chapter covers the important subject of handling user input. lll.'rc arc the key
topics you will learn in this chapter:
listening for keyboard events
Testing keyboard input
Displaying ke'y presses
Reading mouse motion
IXtecting mo~ bUllons
Testing moux input
'"
142
Keyboard Input
Th, KeyL1 stener intl.'rface Iis\('ns for l.'Vl.'llIS gl.'llcrated by the keyboard and sends
those events to the callback methods implemented ill your progr;lI\l, Th~ methods
are called keyPressed, keyRel eased, and keyTyped, and these thn"C ml.'thods all haw
a singlc parametercall&l KeyE~ent. When wriling a program to uS!' the Keyll stener,
you modify the class definition of your prognml Il.ing the l..plelllents keyword:
public class KeyboardTest extends Applet 111l11e.ents KeyLlstener
Tip
The interesting thing about the Implements feature of lava dasses i,!hal you
(3/\ implMlenl
multiple interlaces in yoor program by sepa<ating the interlace dal5 names wil!l rommas.
You may rC'C31l seeing thl.' l oplements kl.'yword used before wit h the Runnab1e
il\lerface (which added threading support). When you need 10 add more than
onl.' in\l'rfacl.' class, you can separate Ihem with commas.
Keybwrd Input
KIr)' Code
,~
(IT
'tLRIGII"
p
' ....U
''-'"''
IV... 'U
Y(.fl .. U..Fll
ItL(P_lFT
I(.~P_RIGHT
v(.xp..up
VUP_OOWN
VtLnrR
~(.8ACtLSPAC(
V(.TAB
.......----.--...............
Description
_\:I!ypodlefl
H.-.ic 'ooypocl riottl
H......nc I:e,pad""
H......nc kfWild dowrl
......
. '" '"
[nm key
Thert' art' two ways to drtenni~ thr kry that has brrn p~ or rdused using
the KtyEnnt paramdrr. If you want 10 ck1:rrminr thr charact.... codrofa key, you
can usr thr gtUtyChu mrthod. which mums a char. If you want 10 know
whrthrr a key has brrn prrssrd t-rd on rnr key codr irutrad of thr charad.....
you an usr thr gttKtyCodt mrthod irullrad. If your program is listrning to
thl' krybo;trd and you press the A kry. thrn geUtyChlT will mum "a" (or "A" if
you arr holding down Shift), while getKeyCode will return a virtual key code
called VK.....A. AJI of the virtual key codes are wntained in a class called KeyEYent.
Table 8.\ shows a partial list of virtual key cooes for the most commonly used
keys for a game.
Not.
WIlen roo want 10 get the 1leys beill\l!ypo'd for "", ;n. chat mes~. lor insl<lnce. \lIeo you wi ll
wanlto 1M the keyTyped eYenllOoflich Il!lInS ASCii charilCtefS. Most of your lJol"",,, input wil l
come from 1he keyPressed h'tnt, which prtMdes tty codes.
143
144
-.
Koy.- 81
...
111
ltytKl,rdl
~t
utend, AW1et
I~l.ents
llQ'Llstetter I
nt ItyCOdt;
char ktyChar;
p~bl
IC YOld In1t!) 1
addleyL1ltener( this) ;
Mouse Input
klJ'Cocle e .,etKerCode() ;
klJ'Chr
r tp4lnt{);
This is the bare-minimum corle you need to provide k~ybo;lrd support to yOllr
Java programs. so you might want to jot down this page number for future
reference (or save the code in a file that you can easily find).
Ti p
A VIItUII Ry o:ode is plttIoo:m-nMrai . . . b Ry. Whfn you wnte <oct. 10 work with
~ W1UtI Ry o:ode (wdllllo Yl;..LErn you (In be ~ 1het lhe Ry wiJ be deIemd on
.., pltllorm (WJncloM,. liu. Mec. SoIW" tnd KI 011).
Tip
The I nl t() IIItlh<xl is 'PfrltI1IItlhod .. til ~ m. you willlOI find ... sttndtloni! JtA
~trn (in 0IIlef words,. tIl~. The In I t () medlod is lhe rnt big m. IIrIS when til
fIlPIel surts up.. n- Ire _a1 other twIllS in til fIlPlet wdllllo p.1 nt( I, m. I will bpltin
llIo ' " 90 along. 5uIl'a it 10 SIJ!he p,lnt(' t'IftIl ~ lhe lIPPeI wn;Iow. K1lhis is ot\efl
whm progIilIlIflItfS wiI write II oIlhe code lor game..
Mouse Input
Tapping into the mouse handler in lava is similar to the process or programming
the keyboard. as you might have suspa;ted. Java handles mouse input using
evenlS that arc generated by the Java Runtime Environment ORE) and passed to
your program when you implement a mouse listener,
Tip
Tht ~ Runt-nr Uh.'..'...... or . . IS Sllbsef 0/1Ile .... ~ l(jt (D::J 1het 1$
~ to iImt you 10 IItw ~ to .. ~ wi 0/ dllIo.ses 1htl you (In l6l! to lUll ......
~
Ire
inducled in ...... V. 6,
Jlr1l"'ided on 1ht ~
145
146
"fhc,
Tip
No abjKt is nat I d8s; il: is tlw rtSWl 011 dIss. Thri 011 dMs IS I bloepllII: b' I procMt. ifd
., abjKt IS tlw product itself lhal !'IS bftn oonsIrIICIed.
-ouseEntered(HouseE ~ent
eJ
Mouse Input
There is another, completely different interface class for mouse mo~'emem.
You can read the mouse's position during a bullon or enter/leave event with a
HouseListener, but re<:eiving events for actual mOllse morioll on the window
requires another interface. To receive events for the mouse's movement across
the applet window, you must use the HouseHotionL1stener interface. There are
two events in this interface:
public void llO useOraqqed(HouseEvent e)
publie void
mo~seHoved(HouseEvent
e)
The getButton() method b lIS<:fUJ if you unly care about detecting a single bUllon
press. If, for whatever reason, you need to know when two or three mouse
buttons are being pressed at the same time, you can use a different method in the
147
148
8UTTOMUUS~
6UTTON2_NAS~
8UTTON3.J\ASk
Thtrt art I1Uny mor~ 1ll<lSkC'd ,..... ues (that is. ,,,lues that are bit-packed
into a singl~ ...riabk) in t~ Houn(went class that you can cx:amill(' u.ing tM
ge\.ModltlefS(1 method. But i( all rou care about art tht usual It(t-<!i,k and righl~
dick C"tnts' you can mak~ u~ o( get8utton(:
packl~
Mouse Input
:::=";:~m
_ _ II:lllO,301
_lftOOOd
_ _ 1I11:'1.156
II: J ICI,.Z)l
_ < t__
II:'I~
_ _ 4l161.Z!17
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
149
ISO
Chapter 8
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
repli ntO:
The ncxl two mous.e event methods, mIlseEnteredO and 8lluseJ.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
ehtekButton(e):
replht(}:
I
pybllt vOId llOuseRelused(llouseE.ent el I
rellun - e.geU( I:
relnuj' -1.geUO:
clllckBulton(e) :
rlpahtO:
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~
key~
key~
5. Which ke}-board event wiD tdl you when a key has been
rdeased~
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
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 rtangle ..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
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
,ss
156
..
,
..._----_
,..,.-=
.... .-
. ..
'.".:
- -, ' ~- - ~
I:
Figure 9.1
Audacity is ~n ex<ellem freeware ""'00 editi",! program with many advarlCed features.
AU
WAY
The digital sample files can be 8-bit or 16-bit, with sample rates from 8 kH:t to
48 kHz (which is CD quality). Java's Sound API includes a software sound mixer
that supports up to 64 channels for both sound effeds and background music for
a Java applet.
Tip
for tile latest information about the Java SOOOO API, poinl\'O"r web br0WS8 10 java.sun.com!
produttsljavamedW"",OO.
II"');
Could you imagine: what it would look like if you h<Jd 10 write aIlof your code like
this? It would be illegible for I~ ITlOSI pan. Here is wtull~ code looks like after
you have imported javaLSOund.sampltd ',
AudfOl~ll\It5trei.sillllle Aud lo51~tel.getAudlol~
putStrU.(lIew
Filet _hoo.
1I. . " l} :
10 be well
157
158
r_._
_
---...
,,--_._1._-
_~I_
"'-1-1- _1_1_1
3
f---r---'
~ .
Figure 9.2
~
!he IligiqII
file format. The other, more obvious, problt:m is truu the lile it~lf might ~
mis.sing.
You em dlt<:kand oonvtrl audio fiks using the fn.tw;tre Audacity program that I
mentioned earlier. Just load up an audio filt !lut you suspt<:t is mc:oded in a
weird format, and then savr the lilt to a new format. Figure 9.2 shows the File
Formats tab in the Audacity ~ diaJog box. Here you can dwJgt the dt6.u1t
lilt fornut for aponing audio lilrs from the Filt: mtnu. If you choo5l:' the Other
option from the drop-down list, you will ~ presc:nted with evell more audio
formats, but most of them are obsolete. ( For instance, you can save to Creative
l.abs' old VOC format, which was popular in MS DOS games many years ago.)
Some of the custom formats require an additional download of a plug-in for that
panicu lar sound forma\.
The key to sound prog~mming is a class called .I.udlolnputStrea.. This class is
used to load a sound lile (which can be an AIFF, AU, or WAY lile) from either a
local file on the current ~ ~n~, ....' htre the applC1 is located, or from a remote
URi U1ywbere on the InttmC1. An input stl'Cillm is a source of data. You can
cl'Cillte a new iruilanCt' of the cbss like so:
.I.udlolnputStru. UlllP1t:
1e - Audi oSn tell. getAud i 0I"putSt re~lI ( new Fil e( numbug. wav" )) ;
Note that the return value of this method is an AudiolnputStrealll. Also, since
getAudiolnputStrNfII does not offer an overloaded version that just accepts a
String for a filename, you must pass a Fi 1e object to it instead. This is easy enough
using a ne... File object, passing the filename to the File's constructor method. If
you want to grab a file from a URi., your code might look something like this;
URl url new un ( "http; I /W>N. j ha rbour . comItes t. wa v' ) ;
s~ ..pIe - Aud ioSys tem. getAudi 0 lnputStrealll( ur 1 ) ;
Either way, you thell have access to a sound file that will be loaded when needed.
However, you can't just use an AudiolnputStream to playa sound; as the class
name implies, this is just a source ofsample data without the ability to play itself.
To playa sample, you use another class called CI i P (ja~ax.sound. sampl cd .CI jp).
This class is the return value of an AUdl oSystem method calk-d getCI ip:
Cl i P cl i P - AudioSyste... getCl lp();
lOild ing Resources
The code "",-"",nte<! he> will load a sound file correct!y when your Javil program is running either
00 y<IU( 10<iII PC Of in iI web bro\vse(, floweve<, we nCO'd to u..... a slightly different method to load
~ file oot of a Java archive This wbjecr is oovered in Chapter 16. ' Ga lactic Wil'; web Deoploy.
ment ' which cOYm web ~oymeot
But I want to prepare you IOf distributing your Java programs 00 the web IIOW; 50 thilt your
p>gJilms will afrl'adr be ready tOf <ieploymeot. To that end, you mUsT repla<e the ne... File ( )
and new URL ( ) meltlods to load a resource (sudl as iII1 imiIQC Of sound file) wiltl the following
(Ode instead; th is .getCla ss( ) .getResourceO. The getResource( ) method is tound
in 1Ile CUll'e!1t class instionce. this.getClass(). Yoo will rrnd it most u.....ful if you use
1S9
160
roe
...,.;., INI
""*
Since we don't need. to pass a par:am\"ler to getCI t p, you might be wondering how
this objt knows whal to play. Thne:'s aetuaUy one: mor\" step involvtd becaU5C
al this point, aU you have: is a sound dip objt wilh the: cllJHIbility to Iood and
play an audio file: or S1r1"am. This method actually rdurns a sound dip objt
from the: default s~lc:'m milCT.
Loading
th~
Sound Clip
At this point, you have an AudtolnputStre and a Cll p, so you just need to open
the audio file and play it. These steps;\rC bo th performed by Ihe CI 1p class. First,
let's open the sound file;
cllp.open( ullple);
Fil~
On the other hand, the loop method provides an option that lets you spedfy how
many times the dip will repeat, either with a specific number of repeats or
continuously. Here is how you might playa dip Drre rime using the loop method;
exploston. l oop<Ol;
Rememher, the pammeter specifies the number of times it will replay, as it's a
given that the dip will always play at least once IIsing the loop method. Here's
how you can playa dip continuously:
thrus lers . loo p(C I ; p. LOOP_CONT [HUOUSL Y) ;
You might use this option if you have a music track that you would like to play
repeatedly for the soundtrack of the gmne. Keep in mind, though, that sample
files (AIFF, AU, and W AV) are quite large, so you wouldn't want the userto wait
five minutes or longer (especially on dial-up) while the sound file is downloaded
by your apple!. This happens when you call the open() method, so if you try to
open a huge sound file it will force the user to sit there and wait for an indeterminate length of time while the dip downloads. This is why I recommend
using a MIDI sequence rather than a digital soundtrack for your game's background music.
Tip
MIDt i51he acronym for MusKallnSlruflK'nf Digirallnterfau. MIDI i5 a synt~i,ed music forma~
not a Sdnljlled fOlTl1a~ meaning that MtDI musk was not recorded using an aoalogto-digital
oonverte< (whkh i5 built into your computer's SOIJrldcard). Professional musical instrumems use
the MIDI format to record ootes rather than samples.
You may feci free to use the ClIp class' starl() method to playa sound dip, but I
recommend using 10op(O) instead. This type of call will give you the same result,
and it will be easy to modify the method call if you ~'Ver want to repeat a sound
dip once or Sl.'Vcral times. For instance, you might use this technique to save
some bandwidth. Instead of downloading a two-second explosion sound crfect,
go for a one-half-second clip, and then repeat it four times. Always keep your
mind open to different ways to accomplish a task, and look for ways to optimize
your game.
Tip
As you willle.lm in Cl1ap\e( 16. the Ja~a Rumime Environment (IRE) provides an attraetM! applet
Ja~a
161
162
One interesting upect of the sound cb= is that they reqUiR that n-ror5 be
a ught. The rompi ler will refu50e to build a program using some of the sound
classes without appropriate try. catch error.handling blocks. Since this is a new
concept, ['lJ quickly explain it.
Java errors are handled with a spial error-handling feature called a try..(;Itch
block. This featun: w;I$ simply borro.... ed from the C++ bnguage. on which Java
w;I$ based. Here is the basic syntax of a try..cnch block.:
try (
I
I
\hen you add error handling to )"Our program. you an: "wrapping" an error
halldkr around your cod e by literall y wrapping a try. ,catch block around a
section of code that you need to track for errors. The Java sound classes require
try. ,cltch blocks with specific ~ of error checks. The generic [_cepllon class
is us.ed to catch most errors that ace not aught by a more specific type: of error
handler. You can ha''(' llIany catch blocks in you r n-ror handln-, from the more
specific down to Ihe llIore generic in nature.
Ti p
In some casH, I try .catch _
hardtr i ~!II tade -:eptian _
INt a
part;cuI rrleIhod Ilwoows (on pwposeI. In d\ose C3I5oI!:I" yow PJ09'3IIl _
~ !hi
110
errors.
For instance, if you are load ing a file, you will firSl check for an IOElcept 1on
bdou providing a gnxric Exceptton handlcl". The A~dioS,ste-, A~dtolnp~t
Stru.. and Clip cbsses requiu the following CTTOr haodkn:
IOE~ception
UnS~PJlOrtedA~dl
about to write for lhe PLaySouod program. The following cooe is found in the
Applet. tni t( I evenl:
publ Ie ~old tnH() 1
tr, I
Ifsource code lines cl ipped
I CI tch (Ill I forwedURlExcept Ion ell
I cltch (IOEaceptlon e) I
I cltch (L jneUnOallibleE~ceptlonel I
I ca tch (UnsupportedAud IoFl1 cExcept Ion c) I
I
111 be the first pfSOll to admit that this is some ugly COOl.'. Error handling is
notoriously ugly ~ust it adds all kinds of unplrasant-looking mal1;Ig~ment
melhoosand f'Venls around your beautifullywriucn sou rce COOl.'. However, CTTOr
handling is necessary and prevenlS your program from crashing and burning. I
like to think of aIry ...cltch block as a rev limiter thaI prevents n cnr engine from
blowing itsdf up when a foolish driver hilS lhe accel~rator too hard.
163
164
Chapter 9
. - 1'1'..,-
__
-_.
I !I-'" Ik _ _ _
I
PCN~22ll5OD"'l6l11,_1~
__
I - . . , - 22ll5O
__
.I'Ol~
_ _ '6-bl
"'-_:
"'9u '.9.)
The !'IIySc:uld prt9_
cIfmonsIr~ how
to lDl ind
own melh0d5 10 load and pL.\" .. sound file or URI..I...tcr in Ihis dupter)'OU '.,,11
find source code for a class nlln! SoIl~dCllp thu does just that.
Playing Sounds
lbe Java sound classes are not quill.' a "turnkey" programming solution, because
)'011 muSI perform several sleps to load and playa sou nd file. I think it wo uld be
convenient to wrile a c1as~ lhat has a collection of sound clips you can load and
pby at any lime from thaI single class. bUI I hesit ate to "wrap" any la\'" code
inside another class when il is such a heavily ob;ect-oricnk'd language in the first
place. let's just wrile an example program to Set' how to put all th is code to work.
Tht resulting program, called 1>l.a)"Sound, is shown in Figure 9.3. The rt"IC"oanl
code 10 Ihis chapter is highlighled in bold
IIIJI'O't java.awt. :
'.'t jJYa.applH. :
.'tjua.lo. :
I
/finltlal1le th eapplet
pub lic void in1t() 1
t ry I
sa.p Ie _ Audi OSyst N .geUudl olnputSt ru.( getURL( fi 1enae) ) ;
lIerute ~ sound buffer
Cl1p el ip - AudioSyst N .getCI ip();
fl1o~d t he audio flle
cl ip.open(ulIPle);
flphy the sound clip
clip.start();
I catc h (M~ I forRledURLXcept i on el
I catc h (toXceptlo n e) 1
t catc h (l i neUnava il ableXception e) I
t ca tch lU nsupp or tedAudi of 11 eExcept I on e) t
t catch (Exce ption e) ( t
16S
166
MIDI Type I
MIDI Type 2
Rich Music Formal (RMF)
At lhis poinl, 1M MIDI sequence.should Slart playing when the apple! 'Hindow
comes up.
Playing Music
The following program listing demonstrales how to load and playa MIDI file in a
Java apple! window. The PlayMusic prognlm is shown in Figure 9.4. As you can
sec, there are some minor details about the MIDI file thaI are displayed in the
applet window, which is basically just an easy way to determine that the MIDI file
has bttn loaded correctly. The key portions of code are highlighled in bold.
__
__
Mif~'
_M
'w
,,--=1
_,0
F"'5Iu", 9..
1llt ~ pnqim d<ornonslrMK how III kwd ond pi.,- a MIll
167
168
Mu~k
jl......t.;
jln. 'PIll et. ;
jln. Io. ;
jl".net.;
jnu.sound ldi. *;
cltch lhceptloo e) r I
returo url;
Reusable (laue
g.drnStrlll9( "!rror
lo.dj~g
stquetlCe file""
flle~.
10. IS);
Reusable Classes
Now that you understand how to lood and play sound clips and sequence files,
leI'S pUl aU of this useful (but SC3tlered) code inlo two r~sable classes that can be
easily dropped into a project and used. Insle;Jd of d~ing with all of Ihe Java
sound c~ and packages, you will be able to simply create a new object from
11K- SO~ndCllp and Mtdtseq~e~ce classes, and thm load up and play ri~ a
sample or sequence with a couple lines of code.
r should
disclaim the userulllC$S of the:\(' c!uses for you, so you will know
",hat to expect. Java's Sound API has a sound mixer lhal works very well, bUl
we can't tal' il1to the mixer directly using the Cltp class that I've shown you
in lhis chapler. The sound fi les thaI you load using lhe Clip class do support
mixing, but a single clip will inlerrupt iudf if played repealedly. So, in the
case of Galactic War. whm your ship fires a we;Jpon , the we;Jpon sound is
restarted every time you play the sound. Howt'VCl". if you Iuve anolher dip for
explosions (or any other sound), then it will be mixed with any other sound
dips currently playing.
In Olher words, a single (1 ip object cannot mu wi,II it~l[. only with otMr- $(lurid$.
This process works quite well if you usc short sound effeds, but can sound odd if
your sound clips are one second or more in lenglh. (They sound fine at up 10
about half a second, which is typical for arcade"g.lme sound effects.) If yOIl want
to repeatedly mix a single clip, there are two significant options (and one other
unlikely option):
Load the sound file into multiple (I tp objects (such as an array), and then
play each one in order. Whml'Ver you need to play this specific sound,
JUS( ilerale through the array and locate a clip that has finished playing. and
then start playing it apin.
Load the sound fi le into a single (lIp objl, then copy lhe sample bytes inlo
mulliple C1 t II objecls in an array, and lhen follow the general lechnique
Mscribed in the first option for playb;lck. This saves l ime from loading the
clip multiple times.
169
110
Reusable ClaSSl!'l
1I100p1ng property for cont1nuou$pllyllict
prhitt boolun 1000plng hi se:
public .old setlooplnglbooltlln _looplngl I looping - _Iooplng;
public boOleu getlOOlllngCl I return looping: I
IIrel"!ll1 prOl"!rt, U5e<! to plly $(\IInd ..ltlple tl.u
prl.ltt Int repe.! -0:
public .old setRepelltllnt jePflltl I ~Pfit - jePfu;
public Int getRepelltO I return rtPfit: I
Ilfl ItIlI.,. properl,
Ilconstructor
public SoundCllpO I
try I
IIcrult i 50und buffer
cllp - 1.IlcI10S,ltell.getCl Ipl I.
I c.tch lliMtJnn.II.lIle[ueptlon eJ I
II
Illlrllltter
171
172
utFllena.(alldlofil.) ;
I/set the ...dlo strea. source
u~le 1.lId10Systl!ll.getAudloln""tStr.... (~tUIl{fllena.;
I/Ioad the aadl0 file
cllp.opH(sallJl l el:
return !rue;
I catch (IOExceptlCHI el I
return false;
I catch (UnsupporttdAudloFllebceptlon el I
return false;
I catch (LlneUnnallablehcept Ion el I
return false;
Reusable Classes
~uenct
classes, making it much tuie:r to load and playa MIDI file withjusl lwo
IiI'lC$ or code inslead of many. Take nole of the: kc:y portions or code:. which ha~
bc:c:n highlightN in bold_
--
Tip
_100pln9;
173
174
I
((over 1olded constructor accept s al dl fl1 enallf
public MldISequence(Str1n'l aldl file) I
thls(): f/cill debult constrlOctor first
10ld(aldlfl1e): f/load thealdl file
I seqllence
public boolean 10adlStrlnll .ldlfl1e) 1
try (
Ilioad the.l dl file Into the seq~encer
filenaltf .idl file;
sonll IIi dl Systfll.lIttSequenct( lIetURl( fil enaltf I ) ;
stq ~ encer . setSeq~enc e (song) ;
seq~encer open ( ) ;
r etur n t rue ;
I catch (lnvalldllidlDahhceptlon ell
r eturn hhe:
I catch (1I1diUn"ulhbleE:<ceptlon ell
retu rn hhe;
I clltch llDE:<ception el I
return hhe:
Review Questions
sequencer. utLoopCount( repnt) ;
sequencer. start( ) ;
Review Questions
The following questions win help you to determine now wdI you have learned
the subjects discussed in this chapter. The answ=; are providw in Appendu A,
"Chapter Qui:t Answers. "
I. What is the Il3me of Java's digital sound system dass~
file~
file'!
6. Which method of the MIDI system returns the sequencer object?
7. ''!hat is lhe main Jan class Menrchy for the audio system
class~
175
176
Chapt~
SOund Effects
~nd
Music:
8. What is the main Java class hierarchy for the MIDI system class?
9. What three digital sound file formats docs JaV<l support~
10. What rare exception error wiD occur when no MIDI sequencer is aYi.ilabl~
On Your Own
Use lhe following exercisc:s to Icst your g:rup of the mat~al oovcrC'd in this
chapter. Are you ready to put sound and music to the test in a real game yea
These exercises will challenge your ullde~tanding of th is chapter.
Exercise 1
Write your own sound-effects generating program to try out a large list of sound
fi les. You can acquire sound files of various types by searching the web. Have the
program playa specific sound file by pressing kC)'5 on the keyboard.
Exercise 2
Wrile a similar progrom for playing back muhiple MID I music sequence files by
pressing various kC)'$ on the keyboard. For an even greater challenge. try combining this program with the one in Exercise I so that you can try out playing
music and sound effects at the same time!
CHAPTER
10
You havc learned how 10 uSC' thc Graph1cs2D class to program graphics using
ve<lor shapes and bitmap images, and you have even seen a nearly complele
game wrillcn from scnuch. YOli ha\c lcarnffi how 10 load and play SOllnd files
and MID I mllsic files, and how to program lhe keyboud and mouSC'. By all
aCCOllnls, you have the 10015 to create many different games already. Bllt there are
some tricks of the lrade-srets of the craft-thou will help you to make your
games stand out in the crowd and impress. This chapler discusses the game loop
and ilS vilal importance 10 a smoothrunning game. You willleam aboulthrea.ds
and timing. :uld you willtUe the Asreroifis..-styk game crealed in Chapter S inlO
completely IKW terrilory, as it is modified extensively in Ihe follo""ng pages.
Here are the specific topics you willleam about:
Overriding defauh appll'! methods
Using timing melhods
Starting and Slopping a lhrcad
Using a thread for lhe game loop
Iluilding the Galactic War game
178
An inttrff am ~ "" <>b5tr"" dM5 wn!I propenies and meIhods lhM 3Il! definfd but I'lOl . . .
mJIfd. A P'O!1'" thM """ an inIfff~ dM5 ;.; ~ 10 aIflSOfIlf it. and must i~ lIlI of !he
pobIic rnttf>o(t in !he inlerfKe. lypciI namples indu:le [fyL t s tener aod Runn,b 1e.
A Simple Loop
~
Runn.ble interlace gives your program its own awareness. I realize lhis
concept sounds a lot like anifida.l inleUigmu, but the term <IW<lrmdS is a good
description oflhe Runnable interf.lce. Before Runuble, you r lava programs have
been somewhat naive, capable of only processing during the screen refresh. Let's
take a look at an example. Figure 10.1 shows the SimpleLoop program. As you
f;9U~
10.1
The~propn.
this program doesn', do aonylhing in ruJ time; it waits until you press a
key or dick the IDOliSe' bero~ d"'wing a rlangk.
.
f
.............
lllpOrt JUt
lllpOrt j
lllpOrtj
l.po r tj
aollt.:
aollt.nent.:
app lu .:
utl1 .:
pu blI CChH SlaplHoop extends Applu lapleMents Key U stener, MouseU stener I
R.ndo- rand
new RalldOll():
179
180
Tip
The Ra ndom dass ;\ loeatt<! in the j ava alit, ut j I 005 aloog with many other lIIihly OOses
that provide common~ oeeclfd tools to yoor program, To use Rando_ in your program, you must
~ this dim with ~ followi"!lt .port ltateme<lt:
l"POrt jua ,'111. utll.:
Not .
I've t-n thinUng about. w~ to use;ll 01 thew interiiKe OOses (such ill Runnable and l!le
input listeners} by lUCking tIlrm MIl into a class ~ of tIlII' main~. This 5I4'POfI class
-..:I pn:I'Iide ""f main progfanl wilh rY lMIIlS when IIWlgs ~ sudl as bJ fft15eS,
fI'IOtM ll'ICIWlI'I!I'I II'Id CIlher _
~ this is dle biIdl 01 an idN lIwl wiI beame some
SO"! 01 game ensJilIel l.e'I's wait II'Id see wIIat Part .. "The Galactic war 1'nljKt,. has in S'n.
18\
182
Figure 10.2
The SimpleI.oop progrilm now dlaws rna." ~Ifs.
As you can 5C'C, the: upchte ( 1 mdhod is bearing a single: line: of cOOc:, a call to the:
pal nt ( 1 mc:thod. This giVt:$ you compk1e: control over the: scrttn rdroll bc:causc:
the default updH ell would root just rqxtint the: scrttn, it woukl abo dmr 1M
scrn. Now you can run the: SimpleLoop program and Stt a bunch of rectangles
as originally expected, as shown in Figure 10.2.
I think this example makes it pretty ckar that any serious game ...~1l nte:'d to
override the update() method as wdlas paint( 1. But that doesn't rally address
the subject at hand- what about the loop? I've been calling this program
SimpleLoop when no loop is even being used. Let's gettD that now.
Feeling loopy
There are quite a few Applet methods available that we haven't implemented yet,
in addi tion to the standard methods you've snon.so far. I'll go over the remaini ng
kq Appl et methods at the end of this Stion to make you aware of them, For
now, I'd like to introduce you to the: next Appl e t mdhod: stutO , The sUrt( I
mdhod is invoked in your Java appltt by the web browser right after calling
in1t( l. So, you can use in1t() to get the game ready to go, and then use Hart()
to get thing!i moving.
Now you finally haY< an opportunily to add a real loop to this progr.tm. BUI just
for kicks, what do you think would happm if you added a III1i le() loop to the
In1tD method? I tried it, so you should try it too. Doing this will lock up
the applet, which will not evcn be disp layed. Why! Ik<:ausc inl t( l is ealled before
the applet has evcn brought up thc web browser or applet viewer, so putting a
loop he-re preve-nl$ the- apple! from drawing. Howeve-r, this is not the- case with
the stutl) method, which is calkd afte-r the applet has hem initialiud and is
ready to go. lbe engine has hem started and is just waiting for you to press theaccde-rator at this point.
You can build on this game loop, too. The-caUto re-pa int the-window isonly the last
in a gaml". Firs!:, you move your game objects around on 1M SOttIl, pttform
collision testing. and so forth. You can ptrform all of these steps in the- start()
event and then call re-paintl) at the very end. Here- is a suggestion. This is 1I0t
actual code that you should add to the- Simpld.oop program-it's just an eltample.
.st~
void stJrtO I
lithe 91. loop
vIIlh(trlle) I
II.,;).., the 9111e objects
upd~ teObJ ects( l ;
p~bl1c
183
184
The IsActi Yet 1 method delermines whether the applet is a'tive, which is marked
just before the stut() event method is ailed:
boolun isAtthel)
Tbe st.rt() method is called after InttO arK! il; often usN to resume the apple!
after the usn Iw; b ~ away from the applet page and then returned.
YOld sUrtO
Tbe stopl I method is called by the web brows.er when the web
signifying that the applet is about to be destroy!.
pa~
changes,
Yold stop()
The destroy( 1 method is <:ailed by the browser when the applet is about to be
destroyed (removed from memory).
void destroy()
Stepping Up to Threads
We use the Runn.ble interface class to add threading support to a game. This
inttrface has a single tvent method called rill'll) lhat represents the lhread's
functionality. We can cmllle this rune 1 method in a game, and thaI will act like
the game loop. Tbe thread just calls rill'll) once, $0 you must add a willie loop to
this method. Tbe"hlle loop will be running inside a thread t.ha.l il; 5CpaTllle from
the main program. By implemenling Runn.ble, a game bKomes multithreaded.
In that sense, it will su pport multiple processors or processor,ores! For instance,
if you have an Intel Core2 Duo or another multi-core processor, you should be
able to $Ct' the applet running in a thread thai is 5CpaTllte from theweb browser or
appltt viewer program.
Stepping Up to Threllds
thrUd
ThrudCtll1s);
thrud.SllrtC);
&
Then you an write the "ode for the thread's loop in the run() n't'nt method (pan
ofRunn~bh).We'll take a look at what goes inside runC) in a moment. First, let's
take a look at the stop() event. This method is provided by the Applet dass and
can be overridden. It has no functionality bydcfaull. This is a convenient place to
killthc thread, so let's do that:
public woid stop() (
thrud-n~ll:
ThrudedLoop progr
....
l-eMlrt j.n.'wt.:
lllpOrt j.n.I.,..,. ;
l-eMlrt j.YI"wltt.:
IlI(IOrt j.n.utl1.;
18S
186
utcll1lnhrruptedExuptlon d (
e.prlntStadTra,,() ;
IIdrlw s_th1ng
repl1ntO;
Ilflgure aut hOll fnt 1t's rUll/l1ng
1f (start + 1000 <Systell.,urrentTl-eMlllls( II (
stut - Syste_.,urrentT1-eHlll II( I;
shOllStatus("R"tanglts potr le-eolld, + count),
,GlInt - 0;
JlapplUIlpc!lte eyent
publl, void upc!lte(GraphlCI gl I
pllnt/g);
Stepping Up to Threads
II'W1et p.lnt elent
pI.Ibllc lold p.lnt(Gr.p~IU g) I
Gr.p~IU20 g2d (Gr.phtu2DI g:
IIcreHe' r.ndOil rectangle
1M II qnd .nextlntOODI :
lnt h r.nd.nutlnt{lODI:
tnt ~ r.nd.nutlnt{gHSlu() .lIldth . ,:
tnt J . f'nd.nntlnUgHStu( l.~etght . h):
Rectangle rea new Rectangle( . J .1I.h):
IIgeMute I r.nda. color
tnt red rlnd.nutlnt(256):
tnt IIreen r.nd. nutlnt(2561:
int blue rand . nutlnt(256):
g2d. setCo l or( nell Cclcr(red.green .bl ue)):
IIdr.1I the rectangle
92d. ftlll rect):
lI.tid .noUer to
count... :
t~e
counter
Now let's eX3mine this ru MI event that is called by the Run nab l e interface.
There's a lot going on in this method. First, a variable calle<! start gelS the
current time in milliSC'Conds (Systell.currentilIleMlll t $( I). This \'alue is w.ed to
pauseOIKC per second 10 print out lhe total number of rect.. ngles th..1h..ve bttn
dnwn (5 Figure 10.]).
Next, a local variable is set to the currenllhread, and then a IIhlle loop iscreate<!.
Thrud current - thread.currentThread():
This local thread makes sure thm our loop only processes thread events intended
for the game loop because you can use multiple threads in a program.
IIh lle (current thrudl
lbe core of the threld loop includes a call to Tllrud.sIHp(OJ, whkh is a place-holder for slowing the game down 10 a consistent frame n le. Righi now it's running
as fasl as pos.sibk because the sleep( ) method is bting passed a O. This single method
call requires an ClTor handler because: it throws an [nterruptedE.cepticn if the
187
188
fi9ure 10.3
tr, 1
TMud.sleepIOl;
I
l:
After this call 10 sleep (which will slow 1M g.t1Tle 10 a consistenl frame rate), Ihm
we can call game-rebttd methods to updatt ob;tcts on the Krn, perform
collision taling, perform g.tme logic 10 interact wilh enemies, and $0 on. In the
block of code thai follows, you can ~ $Ome liming code inside an If stalemenl.
This code prints OUI the number of rectangles thai have been drawn by the
pll nt() event during the pasl 1,000 milliseconds (which equals 1 second).
IIdrill
s_thtng
rep~tnt(l:
What You
I/fl9~r~ o~t
I t (su rt .. 1000
Ha~
Learned
<S,SUII.currentfllltl\! llls( l)
I
sUrt e S,5ttll. current TlIlelli111 S( ) :
sh""Status( R~ctan91 u per second: . .. count):
counteO:
The single call to repaint() aClually makes this program do soml'/hilrg; all of the
rest of th~ code helJl5 this ml'1hod all to do its job cfl"a:tilely. Here inside the
run() event, whkh houses the: new thrnded game !oop.l've used one of the: new
.&.pplet ITIl'1hods. 1lIe shCStatus() ITIl'1hod printsoul a string 10 tbe status har at
the: bottom of the Web broW$l"T or appld viewer.
Examining Multithreading
Aside from the sample g;une in Chapter J, this program might h~ve been your
first exposure to multithreaded programming. Java makes the process very easy
wmp;lred to other languag('S. I've used a Ihread library cilled pthread to add
thread support in my C++ programs in unux and Windows. and it's not very
taS)' to USoC at aU wmp;lral to Java's built-in support for threads.. We will wntinue to USoC Ihreads in every subsequent cbapter, 50 you will bave had a lot of
exposure to this subjt by Ihe lime you complde Ihe book.
Nole
~ Third Edirion (Thomson (oorse PHI. 2006l 00YefS the pthread
and rnatl'f other ouss1Ntform game ~ \Opics. and is bawd .-.::I the AIltgro
IiiInry and the ( ...... ~
~brary
189
190
Review Questions
The foUowing qUe$lions will help you to determine how wdJ. you have learned
the subjt.s discussed in this chapter. 1be answers are providM in Appendix A,
"Chapter Quiz Answers.."
I. What is the name of lhe inlerface c1as5 lhat provides thread support!
2. What is the name of the thread execution method thai you can
code inside the separate thread~
3. Whal is the name of the class that handles vec10rba5ed
U$e
to run
graphics~
4. What Thread mdho<! causes the thread to pause execution for aspecified time?
5. What Syste. method returns the current time in milliseconds?
6. What is the name of the met hod that returns lhe di rectory containing the
applet (or HTML container) file?
7. What is the name of the method that returns the entire URi string induding
Ihe applet (or HTML container) file?
8. What c1ass do you
U$e
On Your Own
The following exercises will test you r comprehension of the topics covered in this
chapter by making some important ch.anges to the projects.
Exercise 1
The l breadedLoop program runs at br....akneck speed with no dday. Modify the
th read delay value to see whether you OIn slow down lhe numbl.'"r of rectangles
being drawn to just 1,000 rectangles per second.
Exercise 2
The ThreadedLoop program jusl draws V!or graphics. Modify the program so
that it draws animated sprites instead.
PART III
CHAPTER
11
The G~I~ctic War proiect will demonstrJte just one type of game that can be
created in Java. This game is compln, but that complexity is hidden inside a
game engine that, once written, does not n~'\'d to be opened again. You will write
an al'pkt that will inherit from the game engine, and then the vast majority of
the core code for the game will be handled behind the scenes. We'll build the
game step by step, beginning with the simplistic Asteroids-style game from
Chapter 3, gradually improving the game until it is finished and ready to be put
up on your website. The first step to building Galactic War is to begin converting
the original project from an entirely vector-based game into a bitmap-based
game. We'll start with a partial conversion in this chapter, retaining some of the
vector shapes but replacing the player's ship with a bitmap.
Here are the key topics:
Improving the game
Generalizing the vector classes
'"
194
',,",pter 11
GiI~k
all of the properties needed to manipulate game obje'C1s on the scm:n (the
asteroids, bullets, and ship). In this chapter, we'll make a few changes to add
sprite support, and in the next chapter we'll move the game entirely over to
bitmaps.
By upgrading t~ spaceship to an illl<lgt' and doing away with t~ Vtor ship
(which was liule mon: than a filled triangle), the pme is rally starting to look
mon: playable. Then: is no substitute for bitmapped graphics. But ooe of t~
gools I set out to achieve for this game is adding the ability to use an image
instead of a shape, while still retaining the existing tra nsformation features (most
importantly, real-time rotation).
You an open up the: project from Chapter 5 and continue using it or you an
just copy the .jav.ll files from t~ old project to t~ new project. Here an: the
source (Ode files you will ....-ant to bring over to the new game from prC'Yious
chapters;
&seVectorShape.java
Asteroid.jav.ll
Bullet.jav.ll
Ship.jaV1l
SoundClip.java
MidiScquence.jaV1l
Note that I did not include the main source code file, Asteroids.java. There an: a
few changes needed to add image support to the game, so [ will just give you
the complete sou rce code listing for the main code file, which is IlOW called
GalacticWar.java.
Holt
..........................................................
l"IlOrt
JIY~.i.. t.;
The Asteroid class will be modilil now to use YectorEntity as a base class. This
fred up a lot of code that was previously dupliGitoo in Asteroid and the olher
classes. The Aneroid class inherits from YettorEntlty, which in turn inherits
from BaseGallleEntlt)'. You eun open up the Asteroid.java file that you copied
over from th{'" projfft in Chapter 3, or you can just add this as a HeW dass to the
Galactic War project.
I......
Asteroid chss derlYes trOll hseYectorShipe
......................................................1
195
196
Vt~
to Bitmaps
lldefault COflHructor
AHeroldO I
setShapelnew PolnonlulJ:.. aHy. un_length):
setA11we{ true) :
set Rotat1 cnVe l ocl trIO . 0):
B.aseYeetorShape
..........................................................
f~
BulletOI
IIcrute the bullet
l~.Pt
letStl~PtlfN!'ll~cu",le(O.0.1.1));
letAlhelhhel:
figu.. 11. 1
n.. plIyfr's spI'Ship ii ..- I bitmap II'N9l' ..n.. Ih.1n
palypL
197
198
Chapter 11
Figure 11.2
on and off by pressing the B key. Figure 11.2 shows the rtangle around the
player's ship. The collision code is a little too strict for a truly enjoyable game
be<:ause the bounding rectangles are slightly too big. We'll corrt th is by finetuning the collision code in the next two chapters.
The majority of the code remains ullchang~-d from the Asteroids.java file b.lck in
Chapter 3, so you may just open that file and modify it as indicated. But I'm
going to list the emire program again because it's been a long time since we went
over that code. I have highlighted in bold att of the lines of code that have
changed. If the source code for a particular method has nol changed at all, I
simply commented out Ihe code and inserted Ihe statement linD changes needed,
so keep an eye out for this comment and then reuse th:l! code from the Chapter 3
projl. II is a beallliful testament 10 object-oriented programming that so few
changes arc needed to this source code file!
/
.
.....................................................
GAlACTIC WAR.
Ch~pter
II
IlIIlCrt
I.rt
IlIPCrt
llIIPOrt
llIIPOrt
/
jUI.IlIt. ;
jUI.IlIt.Uent. ;
jUI.IlIt.g_. ;
jUI.IIILluge.
jUl. ut 11 . ' ;
.
..................................................... ,
Prlurr ellss for tl\e gl
~ull\lc
I,
.
..................................................... ,
Ipplet \nit eyent
199
200
Chapt er 11
pub l lcvo1dlnit()I
/I c reate the back buffer for smoo th graphi cs
backbuffer new Bufferedllllage( 640. 480, Buffered Image. TYPE..I NT.JlGB) :
g2d - ba ckbuff er . c rea teGNpht cs () :
({set up t he shl p
sh1 p. setX( 320) ;
sh1 p. setH 240) :
sh1 p. 1oad( "spacesh1 pi png " ) ;
sh1 p. setGraph1 cs (g2d) ;
{Iset up the bul lets
for (lnt n 0; n<BULLETS: n+-+)
bull et[n] - new BUll et();
I .. .. .. .. .. ..
Improvin g t he Game
.....................................................
drawShip called by applet update e_ent
There are no changes beyond (his point. Please double-check the source code
listing in yOuT new Galactic War project to ensure that all of the methods following this point are included (from the project in Chapter 3). If you prefer,
you may open the completed project on the CD-ROM in the folder \sources\
chapterll\GalacticWar.
/
.
.....................................................
drawBull ets ca 11 ed by
~pp 1et
update event
.
.....................................................
drawAs tero i ds ca 11 ed by aPO) et update event
..
.....................................................,
applet window repaint e_ent 'draw the
bac~
buffer
201
202
o..pttr 11
.
.....................................................
thrud sttrt
tf~nt
.. .. .. ....f
thrud $t0)9
tf~nt
.....................................................
.
.....................................................
..we al'd ani ute the ObJKts In the ga
.....................................................
UpdHe the $hlp posit Ion bHK on .eloclty
..
.....................................................
Update tilt bullets based on welocltr
.
..................................................... ,
UlXIUe the asteroids bastel on velocity
.....................................................
I .. .. .. ..
.....................................................,
hyllstener elt1lU
I NO
I
cilculate X-o.elltnt "lue based on d1rectlon Int1e
..1
I..
.....................................................
Cllcullte y ..,uent IIlue bned on dIrection Intle
203
204
Chapter
11
Review Questions
The following quest ions will help you to determine how welJ you have learned
the subjects discussed in this chapter. The answers arc provided in Appendix A,
"Chapter Quiz Answers."
1. What is the name of the class that handles bitmaps?
2. Which class in Galactic War detects when bullets hit the asteroids?
3. What is the maximum number ofsprites that can be supPQrted by the game?
4. Which method in the Graphics2D class aClua lly draws the image of a sprite?
5. What is the name of the Appl et method that redraws the window?
6. How llJany key presses can the game detect at a single time?
7. Wha t method do you use to track the mouse's movement?
8. Whattypc of graphics entity docs the game IISC for the astero ids?
9. Regarding ship rotation, by how many angles can the ship be rotated?
10. What method prov ides the game with support for collision detection?
On Your Own
The following exercise will test your comprehension of the topics cover~-d in this
chapler by mak ing some important changes to the projects.
On Your Own
The Galactic War game is much more playable now than it was back in Chapter 3,
thanks in part to the new keyboard handler. But we are completely ignoring a
perfectly valid altemative to the keyboard-your trusty mouse. Devise a way to
add mouse support to the game. You could rotate the ship when the mouse is
moved left or right, apply thrust when the monse wheel is used, and fire when the
button is pressed.
205
CHAPTER
12
The goal o f this chapteT is to develop a way to handle the game objects moving
around on the scr~n and to enhance the Galactic War game with some significant new gameplay features using sprites rather than just images and vectors.
Here are the $pific 10piQ you wililcam aboul:
Upgrading Galaclic War to a sprite-~ game
Adding new artwork to the game
Adding new functionali ty to the g.1meplay
208
Figure 12.1
The new ol'l'Siorl ot Galactic War.
As you can sec in Figure 12.1, the game has been completely converted to bilmapped graphics, finally doing away with the vestiges of its vector-graphics
ancestry.
f igure 12.2
The badgroood image used in Galactic War.
209
210
,-
_------ ..
. "' .....l;I""
ll". b
Sprit~
~;::=
1'"
.... _
_j["ijr__
!iI._.
---....,
_.
.
~ "-f""'=":J
.~
.,
~iI
. _._........... _-
--"'._-~
...... ......
--~
animation coming out of the engine nozzles when you press the Up arrow key to
apply thrust (fulUre enhancement!).
5tt
8a5cG<lmeEnlily.jaVll
GabetkWor.java
IJllogeEntity.j.wa
Sprite.java
Point2D.java
Tip
n-
The first (ode li5ting here indudes the main d:us definition for the game, along
with the global variables. r have highlighted key (hanges to the 1}1111e in bold tex!.
{
.....................................................
jUI.lpplet. :
jIU.I"t. :
jIWl.I"t.nent
JUI.I"t ,1"'ge
JIU . ~t 11. ':
I~ort JIVI. lang. 5Y51C11 :
l-.ort
l"POrt
l"POrt
IlIllOrt
IlIllOrt
......
..
211
212
Ch~ptt r
12 Ga lactic
W~r :
80~ts
Figure 12.5
80lIlding boxe and mIisions are IoggIfd with Ihr Band C keys.
.
.....................................................
/
213
214
Ch apl~
8o~es
II set up t he I steroids
fo r (lnt n - 0: n<ASTEROIOS: 11++1 I
ut[n] - new Sprlte(tM s . g2d):
ut[n]. seUllveltrue1:
IIlold t ne asteroi d l..ge
int I- rlnd.lteJU.t(S )+l:
ut[n]. lod l -asterold" + I + . pd'- ) :
Ils et to I rlndOOl position on th e scree n
l"t J - rand .neJ tln t (SC REE HW IOTH) :
int, - r and.nut1nt<SUEEH~EIGHTl:
ut[n].setPositionlnew Polnt211(K, y):
IIs et .0Ution angles to I rlndOOl ' I lue
ast [n) . set rIc eAng1e( ri nd. next Int< 360) ) :
u t [n). setllOveAn, le( rand .next [nt (360) ) :
1St [n}. setRottt i onRi tel rUd .nutOoub Ie( II :
IIset velocity bued on -a.eaent di .ection
double I ng - H t[ n} .-a. eAng leD gO :
doubl, veh ClltAnglellcl.el(lng):
dOubl, vel, - uIW,ltMov'Ylangl:
ut[n), set Yel oci tr(nell Point20(ve lx, vely)) :
, applet
~p'Sate
.....................................................
/
.01d updlte(Grlphlu gIl
IIcalculate frlM rHe
frIMCount++:
1f (SystM.currentT1MHll1 1$0 >stlrt1,.. + 1000) {
stutT1M - Systee.currentT11ol!111111s0:
fUMbte frllltCouot:
frl.counto:
p~bllc
215
.216
Gal~
War.
5pril~
if (tolll$lOl1Testlngll
IIr~p~lnt
tM
~pplU
.lndow
p~lnt(gl :
dr~wSh 1p C~ 11 ~ d
by
" ' 1
publlc void dr~wShlp(J (
II let the tr ~nsfOrll for the lnlge
shl p. t rlns fOrll( ) :
ship.dr~w(J:
If (showBounds) I
1f (5hi p. stltt( ) SPRITl..COLlIOEo )
s hi p. drlw8ounds ( Co lor. REO ) :
else
shi p. drllf80unds (Co I or . 8LUE I :
.
.....................................................
drlwhllets ulled bYlpplet updlte ewent
..................................................... ,
dr~wAsterojds c~lled
by
~ppltt
updUe event
.
.....................................................,
~pp)tl
window
rep~lnt evenl-dr~ w
or
The next section code updates the gamc via thc g~lIIel oop thread, which calls
g~IleUpdate( l. Th is method, in turn, calls methods to process user input; update
the ship. bullets, and asteroids; and perform oollis.ion testing.
.....................................................,
tbrud sun event - stlrt tbt g,llt loop rUMlng
public void sllrt() l
g'lltloop - _ Tbrud( t hls);
gult 100ll. stirt( );
I
.....................................................,
publtc .01d run() I
211
218
Ch.Jptl!'l" 12
Ga~ic
.....................................................
........f
..
.....................................................
public void updl teShlp() I
aM p.llpdltePos Itlon ( I :
doubl e lIevlt sM p. pos ltl OII( I .X( I ;
doub11 newr. ship. posl tl OII( I. Y( ) :
" " riP Hound leftlrlght
If (shlp.poslt l on(). XO < ' 10)
>SCIEElllllOTH + 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
219
220
,
.
.....................................................,
UpdUe the nterolds t>.sed on .elocHy
public .01d
~pdntAsterolds() I
1I~.e
< '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);
b~ llets
.....................................................,
(i~1p.collldeIW\th(i1St[_j)l(
iI i
The next SKlion of rode processes keyboard input. The game has prog=sed to the
poinl where lhe limp li~ic keyboard input from earli~ chapters was insufficient, so
I've added support (0 the game for multiple key presstS now. This works through
the use of 5e\lef3l global variables: key Left, keyRight, and so on. 'These boolun
variables are set to true during the keyPressedl) event and set 10 false during the
keyReleilsed( l event method This provides support for multiple keys at the same
time in a given frame of the game loop. 1lIcre is a practical limit 10 the number of
keys you will be able to pres at a time, but this code makes the game fluid-looking.
and tbe input is smoother than lbe jerky input in the IasI: chapter.
/
process keys tllilt line been pressed
.....................................................
221
222
ChiJpter 12
s~lp
8o~es
left 5 dlgrHS
5):
shlp.utFaclMgle(s~I,.faceAngle
O
If
(s~I,.faclAngh()
<0) s~lp.setflclMgh(360- 5) :
I
e1le11 (h,R1ght) (
IIright urow ralites ship right 5 dl9rlls
shlp.utFaceMgle(shlp. flceAngle() + 5):
11 (shlp.flceAngle() 360) shlp.setFlCeAngle{5):
I
11 (ke,Up) (
lI~p arrow applles
applyThrutfJ :
thr~st
to shlp
I....
.....................................................
ke, 1 I stiner nlllu
SJll!~)
223
224
Chapter 12
**..............
I
public double ca1cAngleHo~eY(double angle) (
double llO~ey - Hath. sin( angl e' Hath. PI 1 180):
return llO~ey:
On Your OWn
Review Questions
The following queslions will help you to determine how wdl you h~ve kamM
the subjecls discussed in litis chapter. The answns are provided in Ap~ndiJ: A,
"Chapter Quit Answen."
I. Which support cbss helps maragt' the position and velocity of sprites~
2. During which keyboard ~t should you disable a ky.pras variable when
ddling multiple ky presses wilh global variables~
3. What is the IlOlInt oflhesprite: collision detection routine: used in Galactic War?
4. Which method in the App1et class provides a way to loo.d images from a JAR fila
5. Which Java package do yOll need to imllQrt to use the Gr.phics2D class?
6. What numeric dat a type docs the Polnt2D cbss (created in this chapter) usc
for internal storage of the X and Y values?
7. How does the usc of a class such as POintlD improve a game's source code.
\'CT5US using simple variabla?
8. Which pro~ny in the Sprite class determines the angle at whKh the sprile
will mova
9. Which property in the Sprite class de'lermincs the angle at which a sprite is
pointed?
10. How many milliseconds must the game usc as a deby in order to achieve a
frame rate of 60 frames per second?
On Your Own
TheGalaetic War game is in a transition at this llQint, after having bemllpgraded
significmtly from vector-based graphics. At present, it does not perform any
action due to coll isions other than to rCllQrt that a collision has occurred. We
want to separate the roJJjJjoll ICJlillg code from the {olliJioll rCJpo"J(" code. Add a
mdhod that is called from g.-eUpdau( l that displays the position (x,y) of any
object thaI has collided with another objecl, for debugging purposes. You can do
this by looking al.ll sprite's state properly.
225
CHAPTER
13
228
Figure 13.1
The ll;frame an imaled explosion (courtesy of Re<rler ProkeinJ.
Figure 13.2
Colli~ion~
l.cl's lake a look al Ihe changes required 10 update lhe game 10 supporl explosions. There's more involved here than just loading up the animalion and
drawing il because we have to accoun l for timing and Sprile Slaw values. The firSI
change is in the globol se<:tion at the lOp ofl he cbss-notc lhc changes in bold.
Tip
!hi' s Uti c keyword defines a variable thai does nOi change.
pJbl Ie closs Gol act Ic'o'ar extends Applet l",ple..ent~ Runnoble, KeyLI stener I
Ilglobol constants
stotic Int SCREEH'o'IDTH - 800:
stotie Int SCRHHHEIGHT - 600:
stotle lnt CENHRX - SCREENWIDTH I 2:
stotte Int CENTERY - SCREENHEIGHT I 2:
stotle Int ASTEROIDS 10:
stot Ie int BULLETS - 10:
stotle int BULLECSPEEO - 4:
stot Ie double ACCtLEJU..TlD~ 0.05:
Ilsprite state nlues
statle lnt STATE.-HDOOL - 0:
stltle lnt STATE.-CDLLlOEO - l:
stl tl e I nt STATE.-EXPLDOIHG - 2:
/ltne ",ol n t~reod beco"'es
Thrud gOJIICloop:
t~e
gaM loop
229
230
eftech
sa~nd(llp s~oot;
saO/ndCI Ip fXplOCle:
Is111ple "Iy to ~irdle ..,ltlple ~eyprnses
bOOlun keyllo1o key",. <eyu~ft. keyRlgM. keyflre:
I l f u . rite CO<lnters.n4 ot~er thing ur1lblel
1"1 fr .co~"t - O. fr Rate - 0:
10"~sUrtTl.-Sy$t..... eurrentT ... 111s1
Makc thc following changes ncar the top of the lnltl f'\ent method to s"itch
the background ob;e.::t from an l.. ~e to an 1... ~e(nt1ty.
pubHc wold ,nit I
IlcreHe Ve back buffer for slIOoth graph1 cs
baekbuff er - ntll Bu ffered [",age( SCR[[~ W! OTH.
Bufferedl",age . HPCINCRGB):
g2d - backbuffer .creHeGraphl cs[) :
SCR[[ ~~[
IGHI
1\ext, scroll down inside the Inl t() l"'o'cnt mctbod a bit more until you ha"e
found the call to iddl(eyllstenerl thl s) and insert thc follo"ing code in bold.
This code lQ;lds a 16frame explosion animation.
1110.d the upTosloo
uploslOll" net' MI ..tedSprlte(thh. 92d):
uploslon.lo.d(~e.lflToslon9'x9hl'.JMlg~.i. I. H. HI:
upl ollon. utFrI.rN!117(2):
upl 011011. uU Tl.tl It I se) :
IsUrt Iheustr input listener
Iddlcyl Istener ( th \
the
boc ~ ground
this) ;
!ldrawthe gUM! gr ophlCS
drawAsterolds() ;
dr awShi p() ;
draw6ul l ets() ;
drawhploslons() ;
Now, while you're still in the update() method, scroll down a few lines to the part
of the method that draws stalUS information on the screen and add the following
code to display the ship's current stale.
tf (shtp . SUH( )- . STATLNORlV.L)
g2d .drawStrlng("Sute : NOll.MAl", 5, 70);
else t f (shlp .sute( )"STATLCOLLIDEO)
g2d .drawStrtng("Sute : COLLlOEO", 5. 70);
else If (shlp .stlteO"STATLEXPLODING)
g2d .dro wSt r lng("Sute: EXPLODING", 5, 70) ;
Now, scroll down past the three dra w methods and add lhe following O1<,thod
after drawAs l erold s(}. This is just IIII' first version of the explosion code, and it
only draws a single animated explosion. later, the game will need to supporl
several explosions al a time .
pJbHc void dr awEx plosiollSO 1
If expIos Ions don't need sepHa t e updne llC thod
i f (expl os ion ,a l l ve( }) I
exp 1os Ion ,updateAn I-at Ion{ ) ;
If (expl osion . cu r rentfr~ me() -- nplos Ion. tot al Frames( )1) 1
expI os Ion. se t Cu rren t Fr ame( 0) ;
explos 10n .set AI I _c( fal sc) ;
I
else {
explos lon.draw() :
231
232
prlv~te
Scroll down just past the checkCol1 i si ons() method and add the following new
methods to lhe game. The two collision handler rOlllines for asteroids and hullets
are not implemented yet, as the goal is first to get a response for ship-asteroid
collisions along with an animated explosion. The handl eSh1 pCol11 s1 ons()
melhod uses the ship sprite's Slate property extensively to monitor the current
state of a collision, and il adds a thr~-sccond delay after a collision has occurred
so Ihe player can get out of the way before collisions slart 10 occur aga in.
public v01d handl eSh1 pCol115ions() 1
1f (ship. state() ~ ~ STATCCOLLIOEO) (
1'0111 slonTllM!r - Systelll.current11aeMll l l.1():
ship . setYeloci ty( new Polnt20(O ,0)):
shl p. setS tate (S1ATCEXPLOO IKG) ;
startExpl oslon(5hi p):
I
else if (sMp.st~te() -- STATE_EXPLODING) {
if (coll1s10nTiaer'" 3000 <Systell.currentTi . eMl1lls{)) {
sM p. setSu te (STATLNORMAL) :
Review Questions
sprl te . getBounds ( ) . heigh I f 2,
explosion .setPosl t lon(new Polnt2D(x. y));
exp1os 1on .setCu rrentf rame( 0) ,
explosion .setAII ve(true l,
Review Questions
The following questions will help you 10 determine how well you have learned
the subjects discussed in this chapter. The answers arc provided in Appendix A,
"Chapter Qui? Answers."
1. What is the name of the mcthod thm makes collision detcction possible?
2. How many collisions can the game detect within a single update of the game
loop?
233
234
On Your Own
Since we are constantly improving the game with each new chapter, there is little
you can do now that will nOI be addressed in the next chapter. However, some
improvements can be made now that arc not added in future chapters. Here is
one such example: Add another explosion to Galactic War so that the asteroids
blow up like the player's ship when they collide with the ship.
CHAPTER 14
You have le;mlCd lhe basics of web game programming in previolls chapters, ;lIld
you have bem building the Galactic War game here in ParI Ill. The source wde
for an applet-based game is becom ing a bi l ledious at this poim. You've seen that
there is a lot of code lhat does not change very much from one game 10 lhe next,
now thaI you know how 10 write a typical game in Java. Arm'l you gelling tired
of steing the kqand mouse handlers io I:'Icrycode listing? [sure am! I don't want
to enfolU' too much structure for your own game projects. but I think it will ~
hdpfulto add some organization 10 Inc code.
lkre arc a lot of e--ents and methods that mUSl: ~ caIJed and monilored nogubrly,
and sina this code doesn't change very often (if C\o~). it woukI clean up the sourcc
~ considerably if we could move reusable code inlo a separate class. This
chapter shows you how to create a base dass for an applet-based framework-or
r:lther. a gailit' mgine. You win ~ able to writea game very easily by inheriting from
the new-G' 1Ie class. and your game won'l nred to implemenlthe interfaces (such as
Runnlble) any longer. Instead, you will be able to focus 00 high-level game design
and gameplay. Hcre are the specific topics you will learn about:
236
Image Entity
-
--
---
..... _- ~~~~-
-::":"_!~=;,=-=--
FisJure 14.1
Sprite
--,--
AnimatedSprite
giIllt ~
AdjlMing to
~venH)fMen Progr/lmmlng
class nlled Sprite was dtveloped. Now, Sprite does not inheril from llUgeEntity, but r~ther, it uses th is core class to store its internal image used for
drawing sprites. That is why the link from I.age[nt I ty 10 Sprite is a doned line.
Nat we h:n~ Anh.,tedSprl teo which is the core of the game engine due to iu
support for animation.
When you look at this diagram and resoIwo the connec:tiol1$ in the l"CVC'l'Se dirtion.
you find that AnllUtedSprl te inherits (rom Spd t e several key properties: an image,
width, and height. AnlllltedSprl te also makes usc of an IIlIQeEntity to handle the
brge, tiled images containing frames of animation. The Sprite class li~
looking backward, ronsumes an image and its oridth and height propmies. You
can use this diagram if you ever stan 10 feel over-..iIrimed while perusing the
Gillactic War souoce oodc: ill these: final chapters, because the game is becoming
lighter. When an AnllutedSprlte loads its souoce billn~p, that is passed up to
the "supeT" or "parent" class (Sprite), which handles the image. This is inherilance
at WOl'k. bcause the AnINtedSprite cbss doesn't actually need to handk iu image
...11
[ use the word "tight" to dl'$CribC' the situation in which the source code is not
becoming blQtlted, as is often the case when ~ game becomes more advanced .
Instead, Galactic War will evolve from a d irect. actively coded model 10 an
indirect, passively coded model using the game engine dtveloped in this chapter.
The source code listing for the game isabout the Arne length as il was befOrt, but
the game has ~n comp/tlely rt:Writtnr. The Ga. ctass is quite complex, but the
"front end" or "user" source code file, GalacticWar.java, is much, nIl/ch simpl",.
That is the benefit of a game engine-it handles all of the messy details for you,
UIowing you to focus on building gameplay. From the engine's point of view,
"You art too skilled to be hotherftI wilh $UCh minutiae as sprill' IN.nagement.
le1 me take care of that for you, while you focus on making this game u fun u
possible!"
231
238
as our programs have fOt the last 13 chapters. This new dass will nd to
implmlent the Uybnard and mouse listener intedac:n. 11 wiD also neal to handle
the game loop thread on its own, so the derived game will not need to be
bothered with mcll details (or rather, logistia, sinee we'n: trying to INmige the
Iogistia of an app~).
Enapsulating a StiJndatd Java Applet
Hen: arc the lNin events that you'n: aCCU$tome(! to stang in a Java app~-bastd
program up to this point. I'm including the mouse events because they are going
to b< part of the engine, even if we haven't used them very much in Gala(!ic: War.
You arc wekome to add mouse support if you wish; I'm iust not sure how you
would control the ship with a mouse.
pubHc
pubHc
public
llubHe
pubHe
p~bllc
/lIIblle
publlc
public
IWbllc
public
jlIIbllc
jlIIbllC
publ Ie
public
publ Ie
void
void
void
void
void
void
wold
wold
fold
fold
wold
wold
wold
wold
wold
wold
l nlt()
V)
palnt lGraphl" Vl
sUrt( )
run O
stOlID
h,.T,.p.e4lke,.Ewtnt k)
hJ'PrtnedClt,.Eftnt kl
kQ~ltued(lt,.Ef~t kl
updlte(Gr~ph lcs
.,usePrtnedlllo~seh~ttl
"osf~l.utdlllo\lseEw~t
"us.wedlllo~stE
..nt
e)
e)
.,oseDralNedlllousth~t tl
.,ustEnttttdlllOusthent tl
.,ustExlttd(l!oustEwtnt tl
lIOuscClltktd (Househtnt tl
Even if you ignore the mouse listrner events, there are a lot of raw evenls in th is
listing Ihat every applet-I);lsw game must implement at a minimum. As for
Ihings such as k...'Y events, we wanlto completely repktc:e the stock events with a
keyboard handler that supports multiple key pres~ and releases. I experimented
with quite a few different ways to do this, and I came up with a solution that is
veTS3tile but not totally internal to the Ga.e class. The key events arc passed on to
the game, which can then usc a few global boolean variablC$to keep track ofkC)'S
needed by the game, The mouse events :;lte parsed, and sever.tl mouse prOllC'rties
are made available to provide your game with mouse button and movement
infonrnttion.
239
240
n.
1hr iI"'=ed IisI hi hinlIes ip'IIl!S in lilt gnr I'IlginI! iI aglabll di5S ~ calIod Sl'rttes( I.
'bl CMI ~ . . d'I'IC! ~ II,.... ~ when. n - hm &._.
Here arc the ncwC'\~nts introduced in ttH, sprite cngiIY. These C'\'enlsare declared
as aDmact hccaus-e the inheriting class must implement them. Thq do not
contain any source code in the Ga.e class, ahhough Ga.e does callihem. This i~
what gives the sprite engine the ability to pass events on to the game while still
handling all thc rcal work behind the scenes.
VOId ga.eStarhp( )
voId gaeTl.edUpdatl()
vol d gaeRefresbScreen()
voId gaeSbutdown()
voId gaekeyOown(tnt \eyCode)
vOId ga-eke}'1Jp(lnt keyCode)
voId ,a-ellouseOownO
voId ,a.ellousel/ll
voId ,a.ellousellove
vOId sprl tellpdate lAttlNledSprlte sprJte)
voId sprltrilnw(Att1 ..te<lSprlte ~pri Ie)
vol d sprl teO:tlllt I .....1.. tellSprl te sprl te J
void Sl'rlteColl1stOll( .....1..tedSprHe sprJ. ..... 1.. lelISprlte spr2)
Know what's really great ahaut these events? lbcydescrihc t=dlywhat you need
to know in your game. What does spriteOyl ng mean? This is called just before a
sprite is removl-d from the linked li~t! What about Sl'rl telll)date and sprlteOra..'!
These two work hand in hand to give yalrr rode an opportunity to monilor a
sprite as it is updated and drawn (both of them are handled for you). For
instance, you use Sl'rlteOr~.. to draw the bounding box around a sprite if you
turn on the bounding box display option (8 key). The sprites are already drawn
by the time spriteOra.. is called. This just gives you notiC<" that the spritt has bttn
drawn, and you can do whatevtr you want with it. Likewise:, wben sprttellpdate
is called, the sprite will have already movecI (hued on vclocity). II'S up to you to
keep the spritt from going out of ttH, .scrCll:n bounds or ptrfonning any othtr
hchavior you want.
Here is lhe complete source code listing for the Ga lile class, which I have been
describing 10 you thus far. 1\luch of thi s code should be fa mili ar to r Oil ba use
we've used it extensively in previous chapters. I will highligh t ill bold the crl/ci,,1
code th at is not directJr related to the apple!. While perusing the source code for
thl' Ga lle class, pay close atte",ion to all bold lines of code, and then take note of
the rest of the code. This should help yOIl 10 grasp exactl y what this class docs.
I
.
........1
Applet
G~tIe
l .. portJ~ Vl
FrallCllork class
~p pl el .;
alit .';
j ava. awl . event
java .allt . 11IIage
java . lang .System;
jaVl . lltll .;
'!II,ortj~va
Iliporl
IfIlport
Ilport
I.port
p rl~ at e
~ey l1
st ener .
241
242
constructor
............. ......... ...............................f
public
Polnt2DIC~sePosltlon(11 returnlCusePos;
I..
.
1
~
I....
1
pplet update event -e th od
243
244
.
.....................................................,
applet windOW
pl~nt
evenl
~lhoo
p~bllc
void pJIAl(GrilpMcs 9) I
g.dr ... lllilge(biI'~b~ffer.O. O. thiS):
r~nnlng
vold lti1rtl I
9i111e1oop ~ new lhreild Ith I):
gille1oop. ~ tnUI:
p~bllc
thrud
p~bliC
r~n
void
r~n()'
lIi1cq~lre
Thread t
Thrud.c~rrentThrud() :
v,
~prttes
Adjusting to
e~nt-Oriven Programming
thrud
Sl~
ennt
~'*
I
.
.....................................................
,
r
I
publlt wold keyllelened(Keyhent 1'.)
gl.KeJtl!l( t. getke,y(ode( I) ;
.
.....................................................
245
246
Chapter 14
WluseSuttons[J] - filse;
brUk:
elSe llouseEvenLBUTTON3:
WluseButtons[l] ~ filse:
WluseButtOlls[2] ~ f.lse:
WluseButtons[J) ~ true;
bruk:
,
.
.....................................................,
",use 1t stener events
I
Ilthl $ uent Is not netded
p~blle
I .. .. ..
X al'ld Yweloelt)' eale~htlon f~netlOfls
..................................................1
I
pro t ected dO\lble uleAngleJlOweYldolible anglel I
retu .... 160llblel (Math.$lnlan,le ItHh.PI / l80ll;
241
248
s~re
if (fIrst I second) (
u.
sprite
I
else
sprl setColl1dedlfahe);
I
drall all actloe sprltes h the sprlte 11st
spritE's IQfier (n the Iht He drun on top
....1
.....................................................,
prl VI te vold pur<~eSflrl tes () I
for (Int lI'"O; n <_sprltes.slze(); n )
Anl .... tedSprl te spr (An' .... tedSpri tel _sprltes.getln):
if (!spr.,lhe()) I
_spr1 tes. re.Gveln);
249
250
Chapter 14
LC't's gel st.. rted with the opening atdilS for tht' gamt, where ..JI the initi:l1
variablts ..nd objtcts Ut dmned. 1M most signiflant thing .. boul this code is the
short cbss definition! Tht 6I.lIct1cll,. dass just ottnds 6i-e-..nd th<lt's it!
Ikyond th<lt, the initwiz.uion o(the gamt'S graphics is.U done bcn:. The images
defined and loaded at the beginning are used ....mnl"Ver a new sprite needs to be
added to the internal sprite list.
..
.....................................................
GALACTIC liAR.
Ch~pter
IlIp<.Irtj,,,,,"t. ,
IlIp<.Irtj.~,.utll.:
IlIp<.Irt ju'.lIng.Systell:
l..-ort jU, . vt.uent.:
publIc clln Gahctlcllir extellds G,. I
If then ...n be stattc btc~use they Ire passe<! to . constructor
~Utlc Int FRAHERAl[ 60:
stHlc Int SCRHNIIJOTH 600:
600;
251
252
........................
..,
publiC (>,l.cticll.r() I
IIcal1 b.se G ,1 us' con~tructor
iUper(fRAllHATE, SCREEHIIIDTH, SCREEHHEIGHT);
...
yold ,1.Startup()
111 old the b.ckground lalge
blckground new laigeEntlty(thl~);
blc kground. 1Old( ' b1uesp.ee. pn9 ' ) ;
/lerute the ship sprite- f irst in the sprite list
~hiplalge[D] new laigeEntlty(this);
shi plalge(D]. 1old ("Sill cuM p. png-);
sMlllalge(l] .. new laigeEntlty (th1s);
sh1 Illalge( I]. 1old( "sh1 p_thrust. png") ;
Now let's tak~a look at some keyNents passed here from the Game c1ao;s. Remember,
these methods were defined as ,,jl$lr(l(/ in Galle so that they would be implcmentl'tl
here in th~ ckrh'ed sourc~ code fijI'. ~ ga1leTI-el!Uplllte() method is called from
..ithin the timed game loop thrad. ~ qI1leItefresh:Kreen() melhod is called
from the appln updat~l) ('Vmt. I'm 1101 currmdy using gShutdownl), but it is
a,~ if you IlffiIto dwl ~ befo~ the progr.am tOOs.
Now let's take a look at figure 14.3. which shOW'S the game fairly early on in
the run. The :wIme toggle'S a~ still available in the game, including collision
253
254
Chapter 14
figure 14.3
The largeastereMds brtoak "" intosmallef ones. either when 1heyhit your shipOl'when \'OJ fire a plasma bolt.
.
.....................................................,
ga~eTjlledUpdate
.old9a.Tlwdllpditt~()1
chKUnput();
' ga.Refr~shScreenevent
.... ",
.., , ..
"
..
" /
256
1-*..-*................
..1
gameShutdown event passed by
void
g~lIeSnutdown(} I
lion well, let the
g~rbage
ga~e
eng; ne
Figure 14.4
The \h,p
257
2S8
"
.....................................................,
, sprltelJpd.te en"t p.ssed by til. e"tlne
lsprlte_eur~trril.O
sprlte_ toUlFrsO- l 1 (
brut:
Cil se SPRI n StEROI O_BIG:
cilse SPRiTE STEROIOJlEOIUM'
cilse SPRln STE ROIO_SIlALL:
Cil se SP RIn STERO I 0_T I HY :
wilrp(sprlte):
bruk:
f "
.....................................................,
public yold sprlteOrilW(A"lai1tedSpr!te sp r ite)l
if (s~owBou"ds) I
1f (sprHe,collided{)
sp r i t e, drilwBou"d s (Co Ior , REO) :
else
spri t e, dr ilwBou~ d s{ Co Ior ,BLUE) :
.....................................................
Tah a look at figure 14.5, which shows the ship firing several volleys of flaming
plasma bolts toward asteroids. There are several bolts traveling away from the
F;gur. I ..,S
I"rojKliIes fired from the Vip ~ get pmed!llrol.9h the ~ __ wIwn they a6
...........
259
260
I hold down the kft or right arrow kty to spin while hitting bolh fire buttons (the
Ctrl keys). This launches twice- as many volleys of plasma bolts, as Figure- 14.6
shows.
{
.
.....................................................
~prl
p~ssed
F;gu.. 1.6
~ IN>d> lwice
YlIU
a5
bru t;
CHe SPRllLSHIP:
IIdld Harold crHh 1nto the ship?
If (l sJ.ste~l d ( lpr2.lpr1hTYPt()1l {
If (spr I . IUh( I -- STATLlIOftIlAll {
call1slonTl _r - SystIM.earrffttTllldtlll1l( I ;
sprl. seth I11(:1 t1lftew Polnt20 (0. 01 1;
doubl e x - Iprl.pollt1on O .Ill 10;
double y - Iprl.poslt1on O .YO 10;
stirtBlgEll.plos1on(new Polnt20 (x. y)l ;
sprl. set5u1l (STATLEIP LOOI ~Gl ;
sp r2.set.i.lln(hlse) :
brukAste rold(spr2) :
)
261
262
I
brnk:
The keyboard and mouS(' handlers are not always used, but you must still
implement them in your program. You might wonder, then. how is this allY
better than just using the li$tenen d irectly in the game's source code file~ That's a
good quation! Basically, we want to homogenize the ~cnts as much as possible.
Note that the keyboard ~enu pas.s nothing but the key scan code, and the mouse
evenu pas.s nothing at all- you must access the mouse infom\;ltion through the
musePos and .auseButtons variables (wi th their associated acCes.llOr methods).
Simply k,no",ing about a ke}t>o;.rd or mouse e-'enl isenough; we don't nd all of
the a1ra information that Java sends the program.
..
.....................................................
;uleKey[)()Wn eoent passel! by gall! \,n;ln\,
bruk;
.....................................................,
publi c veld g ~ meXeyUp(lnt keyCodel I
swltc Mk eyCodel I
cHe h yEvenLVlLlEFT :
keyleft fi15e;
bruk :
cue Ke,Ev ent. WK.-RIGIH:
h,RIgbt fi15e;
bruk:
cue hlE ven t. VK.-UP:
k.,Upfi15e:
bruk:
USI tlyEven t. VK.-CONTROl:
k" Flr e.filu:
f1re8ullet{):
br ei k:
.....................................................,
",bile void g.~ou$elloom() I I
",bIle void g.-eHou$eUpl I I I
public void g. _ l\I)u$ellO'l( I I 1
263
264
figure 14.1
Tht bculding bcae5 MIll JIIi5oon
CIt
sevenl methods for working with asteroid$, mainly calJed from !he collision
~u thoot occur. The brgtt asteroids an: ~royd and replad by SmallCT
asteroids, while iIIl apJOSKln is animated over !he old asteroid.
Figure 14.7 shows the game with bounding boxe$turned on so you can s the
dimensions of each sprite in the game. Note how even the explosions have a
bounding box-they an: included in collision testing as well, even though the
game ignores them. All of the or iginal asteroids have been destroyed and
replaced with increasingly smaller ones. If you wanl to grab wme powerups
(so mething thaI will be added in the next cha pter ), you will have to be careful
not to destroy all of the brger asteroids-the smaller ones are next to
impossible to get around, and your shi p will get hosed by them in short order if
you let the guns go carelessly. As a result of this gameplay factor, this gamt'
involves somt' strategy.
This section of cOlk marks t~ end of the gaITIt' t'ngine events. From this point
forward, all of tht' rrK'Ihods an: custom progn.mmed and provKle tht' real
g;tmqIby in Galactic War.
.....................................................
bru t up In IS t erold In t o slNller pieces
sprit e ) I
sll ltch(sprHt.sprlttTlI.eOII
cue SPRITLASTEROI(UIG ,
'sp."", .-dhll u tero14s o~er t he old one
sp'vnAsteroldlliprlh l i
sp'vnAsUr01 d( spr1 tel i
sp'vnAster01 d( sprl te l ;
Idr," bl~ up10si0ll
surUl9UpIos I OII( sprl te. pos Itl one I',
brut:
cue SPRITE..ASTEROIO_" EO Il.lH ,
lisp' ,," $all i l .sterOl4s over t he ol d one
sp.vnAsterol d( sprl tel;
sp'lII\A.s urold( sprl te) :
spllIMsterold(sprlte) :
II dr," sIN11 explosion
s U rtSIH 11 Exp1osl one sprite. posl t Ion ( 1) :
bruk;
ci se S PRIT USTE ROI D_ SII~ ll ,
II s p.~n ti ny Ht er01ds over the ol d one
splllnAs terotd (sprl te) :
5pllln~s terol d(5prl te) :
5plllnAs terold (5prl te) :
IIdr lll slNll expl osion
5tartSIN11xplos lone sprl te. pos I tl on( II :
bru lr.;
tlse $PRlTE..A$TE RDID_Tl NY,
ISp.,,", r.nda. paver"p
SpllmPOIIl!rllp(sprl te I:
'dn ll sull uploslon
starts..11 Up1oil 0111iprl te. poil t I011 I I1:
brelt:
. .....................................................
.....................................................,
sp..... 1 SIlIlle r ISterold bHe<I on p'sse<l sp r ite
265
266
Chapter 14
us~
SIIMI Tl.ASHll:OIO_SIIAll :
I5t. setSprltfTJ~lSUI Tl.ASTEIlOI O_T i Iff I :
Ipic~ on~ of t ~. rarnlo.,ltuold i... g~s
t r. nd.nutlntU):
Ist.s~tl.. g~(tnJAst~rolds(11.getlug~())
:
1St. s~tFrl-elfldth( tnJAst~rol ds[ 1] .wt dtM ) ) :
ut. s~tFrlMHelght (tnyAstuol ds(l] h~t ght( ) ) :
b r ~ak:
t~~
sprt t~ lIst
.....................................................
crute a und~ poIlerup.t th~ supplied sprt te loutton
( t hls will be tllPle-e nted tn t ~ ~ n ~ xt chapter)
.....................................................,
~rt
.....................................................,
Il'obl
flcrelt~'
267
268
Chapter 14
.....................................................
returns true H
p~ssed
Presses
I spent a lot of time trying to incorporate a multiple key-press syslem into the game
engine itself, but this proved to be too troublesome. N, a result, the main game
keeps track of key presses and releases using global boolean variables. Since only a
handful of keys are ever used in an arcade-style game like this, a more complex form
of key handler is not necessary. As il is implemented here, the engine calls a few
even!S and passes the key code when a key is pressed or released so thaI you don'l
have 10 bother decoding the KeyEvent, MouseEvent, or MooseMotlonEvent class.
.....................................................
process keys that
h~ve
been pressed
c~ectlnput()
I
else If (keyRight) (
Il r ig~t arrow rlltates th fp right S degrees
shlp.setflceAngle(shi p. hceAngle( ) SHIPROTATlON);
11 (ship.flceAngle(l >36(})
shl p. setFlceMg1e( SHI PROfAT 10.) ;
11 Ue)'llp) (
lup Irrow Ipplles t~ ..... st til ship
dt p. set 'lIge( lhl pl..,e[l).,etlllge( II ;
IpplyThrustll;
I
else
Iiset s~ip iatge to noratl non-t~rU~I iatge
shl p. set IlIge( shl pllNge[O]. get I., ge( I) ;
The sp.1uship in Gabelie War is rol3lffi usi ng the lrit and righl Jrrow keys, and
thrusl is appliffi by pressing 1M up arrow by_ The IpplyThrust( Illt1.hod
handle$
I~
,docilY threshold
...........
269
210
Firing Weapons
The mOSl signifkanl area of improvement for Ihe game is in the weaponry
dep.1Ttment, so some lime will be spent in Ihe ne~l ehapler adding powerups 10
the game. You will be able 10 grab powerup icons lhal arc dropped by exploding
asteroids, which will Ihen enhaoce the ship in various ways. The (lIfTenl version
of the game here has ll(){ changed from the previous chapter, except lhal il now
fuJlctlons with the game engine. The Orl key is ~ to fire weapons, bul you
can change this 10 ;lll(){!ler key if you want by eumining the key handlers.
uuu
"
u ,
Giv~ M~
There 3re two main methods for sta rling explosions. 1could hnve come up with a
craftier way to do this, but I decidcd 10 just write two similar methods: one for
initiating large explosions and another for smaller explosions. They usc images
stored in the explosions array (of '_lgeEntlt1 objeclJl ). There are currently only
two explosion animalio ns. The large explosion is used when you hit a large
asltroid. The smaU explosion is drawn when you hil smallCT a5leroids.1 think the
result looks prdty good.
Because 1!lCTe are Q lot of mWI asteroids and bullets flying evay whidl .... y. you
don'l ....nl too oomplex of an explO$ion sucking up lhe game's resources ..nrn
Ibm: oould be a couple dottn such explosions animaling at a lime. QIeck out
Figure .4.8. The large explosion's frames are 96)( 96 pixels in size and 1!lCTe are
LARGE EXPUlSION
SMALl. EXPLOSION
ftgure 1....
br -.
271
272
Chapter 1<1
16 frames; the small explosion has 8 frames, and each one is only40 x 40 pixels in
size. The big explosion is used for the ship and large asteroids. This should be
used sparingly because it is such a large image.
I
........................
,
hynch, big uploston It the PIssed loc,tlon
~
I
Ilunch, s.,11 uploslon.t the PIssed locltlon
.....................................................
What You
Ha ~e
Learned
lut method in the gaIl'll' iscalkd warp{ l,and it has l~ duty of making Spriles
wnp around the edges of the screen (right, left, top, and bottom). This is kind of
a slrange occurrence if you think about ii, but a lot of gal1le$ llSof' this technique.
The iOO is that this makes an otherwise Slrnlll playing fidd appe;;tr larger because
objects can just travel through etha-J/K'U behind t~ monitor and magically
rnppe;;tron t~ Ol~rside, othelWUc' Ul1$Cl.thed. It helps to cont;Iin Ihe pmeplay
when a scrolling pme world is not a gool for the gilme.
f ..
.....................................................
cause sprite to IlIrp around the edges of the serren
llSof' t~
273
274
Chapter 14
Review Questions
The following questions will help you to determine how well you have learned
the subjects dis<:ussro in this chapter. The answers are provided in Appendi~ A,
"Chapter Quiz Answers."
I . What is the name of the new game engine class developed in this chapter?
2. How many sprites can the new engine handle on the screen simultan~"Ously?
3. Which of the four key classes in the game engine handles image loading?
4. How many different asteroid sizes does the game use?
5. True or False: Collisions are handled inside the game engine.
6. What type of object is ani .. I..age, a private variable in ~nl l1atedSprite?
7. Which class is responsible for rendering a single frame of an animation in
Ani Ilia tedSpr 1te?
8. What is the maximum velocity value for the player's spaceship?
9. Which class does the game/sprite engine pass in some of its events?
10. Wha t is the name of the support method in An1mHedSprite that returns a
properly formed URL for a file to be loaded?
On Your Own
The following exercise will help you to see how well you have integrated the
new materia! in this chapter with your existing knowledge of Java game
programming.
There are curreotly two methods used to sta rt an o:plosion-a custom method
for large explosions and another one for small explosions. lbese methods do the
same thing, but they use a few different properties. How could yOIl revise one of
them to handle both cases for a large or sma ll explosion with a si ngle method?
CHAPTER
15
The lhings you have learned in this book all culminate in lhis lasl chapter
involving Galactic War. The game will be enhanced, polished, and ready for a
production environmenl althe end of this chapter. A111hat will remain to do is 10
package up the entire game, rl"SOUrCCS and all, into a JAR file for dislribulion on
lhe web (which is covered in the neXl and final ch'lpler of the book). Here are lhe
key topics of inlerest in this chapler:
Adding powerups to the game
Implemenling a global game state wilh a slarl and end screen
Polishing the game and preparing il for production
276
Chapter 1S
--
_.
'*
'"
F;gu~ 1S.1
GilacIic Wl1f hilS
Figure 15.I.shows the six po.....erup$ that will beaddi to tlte PI1\(' in this chapter.
Tip
Weapon Upgrades
The .....eapon upgrade poowerup is by far the most interesting new feature of the
game, and il is very .....e1come given how difficult it is 10 stay alive in this game!
Yo u ca n earn up 10 fivc levels of weapon upgrades in this game. I had my son,
. ,, ,
F"lgun! 15.2
~ au now Ihrte modts tor lht ship: llOfII\lII, lhR5tels, ind shields.
,
{;!
...
"
{;!
00.
0' 0
000
..
;; ; ;
Vu
{;!
- - {;! - -
{;!
)'0'.1"
ship.
p;1t1fT1\$
for each
upgrad~, and
the result is
Th~
upgrades w~r~ implemented a little di!Tn"Cntly than our design h~re, bUllh~
result i~ unmistakable. The biggest difft'rcnce i~ upgradt' level fiv~: Rather than
firing ~id~ to side, the twO addilionalshot5 go upward at a slight ;lllgle. I made
this adjustment whilt' playing th~ gamt' wh~n it seemed to be morc cffelivt' than
firing thcm at 9O-<Icgr~ angles. Let's take a tour of the fi,'c weapon upgrades a.s
!My werc impkmenled in th~ gam~.
Standard WHpon
Thestandard weapon is shown being fired in Figure 15.4. NOle lhesingle bullet kon
in the upper-right cortlt'r of the scrl'en, ~howing the current weapon upgrade level.
first wtlIpon upg.rack allows th~ ship to lir~ two shots at the Rme time, as
shown in Figure 15.5. There aer now IWO bullet icol1$ al the upperrighl. After
277
278
Figu.. 15.4
The standanI wupon is J WIgle bulK.
Figure 15.5
Two bullets clefinilety 00
101 men
~l
~rups
play testing the g~me for a while, I decided to m~ke this the starting weafXln level.
You can stilllo~ this by ge1t ing hit and then drop down to the standard weapon
if you aren't careful
Weapon Level Three
WeafXln upgrade level three allows the ship to fire three shots at the same time, as
shown in Figure 15.6. There are now three bullet icons at the upper~righl.
Weapon Level Four
The fourth weapon upgrade gives you four shots at a time, spreading out at
slightly wider angles than the previous level, meting out ma"ive damage to the
horde of asteroids, as shown in Figure 15.7.
Weapon Level Five
Heavy gunner! Weapon levd five is truly ltaggering. delil'ering massive amounts
of firepower to the ship. Take care, though-if you get hit, your ship is taken
down a notch to level four again. The angles of spread at level five are slightly
I'<ider than 1.....e1 four, and two additional shots fire out roughly sideways from the
ship (sa: Figure 15.8).
279
280
Figure 15.7
ro.. shots at a time is good for 'tOO' SfIf-<OlllidMcf.
,.
.. , '
..-,.,' ,,
,
,
fjgure 15.8
,.,.
'""
, ,.
,
..... -.'~
En~rxing
Galactic War
yau
ope1\lP
.".
tlle
flnll
flnll
flnll
flnll
28\
282
I""ogu.. 15.9
11ll' bile
KIftI'I
fln.11nt IWlUlUnlllltl:
fln.11nt &o\IIE....OJEa!:
/furjous toggles
boolun showBounds hlse:
boolun coil islonTest lng - true:
When Iheg:une first starts up. youSttthe titlcscrecn, which ilimown in Figure IS.9.
This screen shows 1M kys you pre:lli to conlrolIM ship.
284
Chaptff 1S
The collision toggle and bounding box loggle are both still active in the game.
Although they were use4 for test ing, they are now known as undocumented
hidden CMtlI$ in the game!
~ey8, ~eyC.
hJSbleld;
~eJ
boDlun
tnput
trllc~lng url.bte~
~eyLeft. ~eyRIgbt.
~eyC.
hyShleld;
600 KB.
lc1's add all of the new code to garttSUrtuptl to load all of the new images.
sounds, and music in tM game. lbcn arealso.some gamcpby-rdated changt$ in
Ihis method that you should look out for. All new code and du:nges are high"
Hghted in bold,
void ga-eStartupO (
I/load sounds and ....Ile
.,slc.l0.dl-..slc .ld-);
shoot.lold(-sboot.n-) ;
exp I osl on. 1oldl "explode .IU-) ;
l/lold the hnlth/sht.ld bars
birfr " new 'aageEnt1t,lthh );
birfr. loIdC-barfrl png-);
blrhMge[OJ new 'aageEntlt,Cthls);
barl..ge[O].lo.dl-barJlnlth.png-);
barl.age[!)" new l.. geEntl t,lth15);
hrl..gt[l]. loadl"bar_shield. png-I;
III o.d powel1olPS
powen,pShleld" new 'aaIlIEnt1t,(thh);
J/OVtrupShl11 d. load{ "powlrup_shl e I d2. png-) ;
powerup~ell th .. new ' ..gentlt,(thls);
J/OVerupllnl tho loadl-llO"lrup_coh .pnll");
powerup250 " new 'aagIEnt1tJlthh);
powerup2SO. loadl "POOlfl1olp_2SO .jlllg-) ;
jIOWlrupSOO" _'aageEnt1t,lthh);
powerup500. I oadl "poIffrup_500. png-);
poweruplOOO" new l..geEntl t,lthls);
powerup l OOO. lOld("powerup_lOOO.png");
powerupGun" new 'aalleEntlt,(thl s);
,-np&un. load( ",-I1oIP-llun. jlIIf-) ;
Il~t
285
286
-"til INge~nt1t,{th1s):
"til
Jlde lete th Is lIIod of code. wlt lch h, s beetl .,red to , notller -ethod
, .,.ed to resetG, -e
/lcrelle the rlnda.l5l erold spdtes
far lint n -0; n(ASTROIOS; nH! (
Crelle,(slerold( !,
./
281
288
IIreset variables
health - 20:
sh1eld - 20:
score - 0:
flrepower - 2:
Figure 15.10
II )'our f1ealrl1 drops to zero. tile game is r:NeI-YOU lose!
If
ga.Refres~Screen()
Grap~lcs20
I '"
g2d -
grap~lcs():
1l000~f OR
......,
11 '''llfH()~f
I'
n.
289
290
~me
i
If (collfsfonr..HfngJ I
'12d . seUolorlColor .GRUN);
'12d. drawStrln'1( ' COLLIS/OIf TESTING', SCRfClfIiIOTH/50, 25J;
......
I
else 11 (ga.State &.IJt.ll:Unlll6) (
IIdraw Maltlllsbleld bars and .ters
g2d,drawl.ge(bifFra.,getl.. ~(). SCREflllIDTlt - 132. 18. this):
for (Int n D: n < health; n++l (
gld. dr,,, I.age( b' rFrue. get luge( ), SCREENVIOTH - 132. 33. th1 s );
for lint n _ 0, n <sh i eld; nH) {
Tnt dx SCREEIIVI OTH 130 ... n" 5;
gld.d.."llUge(blrllUge[l].getlIUgeO. dx. 35. this);
Preparing to End
The galileShutdo"n() event comes next. As you'll recull. this method was left
empty in Ihe previous chapter, but now we need 10 IISC it properly. A wellbehaved la\"a program will free up resources before the program .-nds. In the casc
of Galactic War, I pmer to rely on/av:l's buill-in g;tr'Ngc colltelor to free up
I'OOUrccs automatically. HowcvfT, it is necessary 10 shut off I~ music and any
SOIInd ril'tctscurrmlly playing before the applet ends becaliSC' sorndimes a MIDI
sequence will keep playing after the game has ended.
291
292
Figure 15.11
The<e arc a klt of sprites In arr; normal game. but thi' ;s 0011' 1/4 of the
SCfet'O.
The
cases to the
293
294
brelt;
Grabbing Powerups
Ncxl in the source code listing is the sprl teCo 11 I Slon() event. All we need to do
here is handle all the new powerups that are in the game; this means that only the
ship should collide with the powerups. I've moved the test for the collision
testing toggle to the top of this method, out of the keyboard handling code,
lx.'Cause it belongs here instead. Some new lines have been added to increase the
score whenever a bullet hits an asteroid aJld to deal with collisions when the
shield is up. Note the changes in bold, as usual.
pub11 e vo1 d sprl teCo 11 is i on (An hila tedSpr I te spr1. An1 lIa tedSpr1 te spr2) l
Iljullp out qu1ckly if eoll islons are off
if (lcollhionTest1ng) return;
I Ifi gu re out
bruk:
case SPRIH_SHiP,
IIdld asteroid crash 1nto the ship?
I f (I sAsterol d{ spr2. spri teType( ) )) I
if (sprl.stateO STATLNORIIAU {
1f (keyShieldl {
shield -1:
}
el se {
colI ls i onTjIller - Systell. current HlleH1 11 j s (1:
flrepower-;
11 (ffreJlllftr (1) f1rej)Olf1!r - I;
I
spr2 . setAl heC h l se} :
b rea kA5tero i dC sp r2}:
I
bre~k:
cue SPRITU'OMERU'_SIIIELO:
1f (spr2.sprlteTJpeC )--SPRITE...SIIIP I I
shield"- S;
If Cshield) to ) shield - to;
sprl. setAl I u Cfa I $II;
)
break;
clle SPRI TE.,POWERUP~HEAL TH:
1f Csprt.sprltlTJpeC)--SPRITLSHIP) (
hulth"-S;
If C/Iotalth) to) hulth - to;
sprl.$ItAI1u(flhal;
)
break:
295
296
break;
cue SPR ITE...POWERUP_500;
If (spr2.spr\teT~pe()--SPRITE...SHIP) {
bu . pScore (500) ;
sprl. setA1he(hl se}:
)
brfGk:
case SPRITLPOWERUP_1000:
lf (spr2.sprlteType(J --SPRITE...SHIP) {
bu.pScore< 1000};
sprl. seUI he<h1se}:
)
break:
case SPRITLPOWERUP_GUN:
1f (spr2.spr1teT~pe(}--SPRITE...SHIP) {
flrepower++;
1f (fl repower ) 5) fl repower - 5;
sprl.setAll ve(false);
)
break:
sw it cn ( ke ~ Code)
F"ogUnI! 15.12
The bupf ~ ... end the game immediatfly and . . . you to
keyleft - true ;
break;
cue keyEven t. VK.JIGHT,
keyRlght - true;
br eak ;
cue keyEvenLVICUP:
keyUp - true;
break;
cue keyEnnLVICCONlROL;
keyFlre-true;
brUk;
cue keyhenLICB;
II toggle boundlnll rKUnll1es
$horiounds - ! sllowllounds;
bruk;
cue hyEwent. 'ICC;
IIt0ll91e col11s1on testllll1
(011 hlonTestlnll - !collls1onTest 11ll1:
break;
CUI keJ'Eunt.VK..SHIFT:
11 (( l tlYUp) &I (sh1e l d ) 0))
hJ'Shfeld true;
$~ - .
297
298
I
lin 11 (gl_sutt! ... W...OVU) {
rentGl_Cl:
res~_Cl:
gl_SUte WLRUUII6:
}
(1$1
brelk,
Klybent. VIl.ESUJ'E:
11 (gl_Stlte &AHE.JtuNMI16l I
PIUse61_Cl:
gl_Stlte &AHLOVER:
I
break:
Now leCs add a single new case 10 the gaJlleKeyUp() even t as well.
pUb lIc void g~-eKeyUp(1nt keyCode) {
switch(keyCode) (
cue KeyE_ent. YK..LEfT:
keyLeft hlse:
brett:
clse Key[ _ent. VIl.RIGIlT :
teyRigkt - false:
brUk:
CiSe Keyhent. VIl.UP:
keyUp - false:
brUk:
CiSe leyE_ent. VK..COI'lROL:
kerFlre - false:
flrehlletll:
bre.k:
cue ltYhtnt.fk....SHIFT:
kerShl,ld" false:
Spawning Powerups
In the pr~ious chapter _ adckd a ~ method 10 the game ailed SlltlfllPover",pt I.
which was kft empty at ttJ.c, lime. Due to that foresighl, _ do not havt to mak any
dlangt:5to the brea kAsterot d( I mdhod that makt:5thisaillnsltad, here is the fully
functional sp,lInPover\lpt I. Attbe lOP of tht codt, a random ptrttnlage: dettnnilltS
whether the powerup is act",altyCTtaltd. 1havt it cumondy S('tiO 12 ptTctnt, which
providts somt fair gameplay.lf)'Qu want to make Iht game mort difficult, reduce
this value. To make il easier, increase it.
Even though 12 percent dotsn't sound like very many powerups, keep in mind
lh~l every I:lrge asteroid produces three "mediums," each of which products
threc "smalls," t~ch of which produces threc "tinys" (see Figure 15.13). That's a
whopping 27 tiny asteroids forevcry I:trge one, and since the game starts out with
10 large ones-well, you can do that kind of math. In a single game session,
12 percrnt will grnmlfe about 30 powerops! I think this value should be rtductd
10 about 20 to make the game a bi l more challrnging, but t<lCh powerep tw a
limited lifetime, so it's possible in tbe htat of battle that tbe player will only
manage: to grab a few of them.
The sllallnPOIIerupl I method creates a singk PO"'"CT1lp sprite with 5011'It standard
properties Ihat all powerups share, and thrn it $tIS the specilk properties Wiing a
random number. Since there are six powerops, this random number determines
the type of po_rup.
299
300
Chapter 15
Galactic War:
F;ni~hin9
the Game
Figure 15. 14
Thi' doloe'up view shows multi~ a'teroids impac1ing the ship', shields (aM bfeaking aparI iOlQ small
asteroids Of jusl blowing up).
301
302
Fini~hing
the Game
input changes when in lhe G.o.HE_MENU or GAME_OVER stale. The new code is shown
in bold.
publ ie void eheeklnput() {
if (galleState I- WE.....RUNNINGl return;
lIthe ship is always the first ~prite in the linked list
Ani lila tedSp rite s hi p - (An i la tedspri te) spri tes ( ) . get (0) ;
if (~eyleft) (
Illeft arrow rotates ship left 5 degree~
s hi p. seO' aceAng I e( shi p. faceAng 1e() SH I PROTATI ON) ;
if (shIp . hceAngleO <0)
ship.setfaceAng l e060SHIPROTATIONl ;
I else If (hyRlght) {
Ilright arrow rotates ship right 5 degree~
shi p.setfaceAngl e( shi p. faceAng I e (l + SH IPROTA Tl ON 1;
if (ship. hceAngleO >360)
shl P. setFaceAng 1e( SH I PROTATION) ;
I
ifUeyUp) (
Ilup arrow applies thrust to ship
shlp.setlmage( shipllllage[11. getlll~ge());
~pplyThrust() ;
I
else if (keyShleld) {
shi p, seUlllage (shl plnge[Z]. get Inge( ) ) ;
I
else
Ilset ship illlage to norlllal non-thtu$! IlIIage
s hi p, seUlllage (shl pl.age[O). getl.age ( 1) ;
-4);
4};
- 5) :
5):
- 10} ;
303
304
shoot.pli1(I:
Hen's the new .djllslOlrectlonO support I1ldhod. which basically just cuts
down on the amount of codc in ftreBul leU) becaU5C this code is repeated for
~ry single bullet launched. This method is new, so you should add it ~low the
ftreBullet(} method in your code listing for GalaeticWar.java.
prIvate voId adjustOlreetlo n{AnlaatedSprlte sprlU, double Inglt) {
.ngle - spr Ite. flceAngle() + Ingle:
11 {.nllle (01 In91e +- 360.
11 se 11 (Inlll' >360) In91 I' - .. 3fiO:
sprl te. setF.ewgle( IIIg1 e):
sprl te. seUlovWllle(sprl te. f.(Wlll el) -110) :
.nllle - sprlte ..auM9le( I:
double SYJl" calcAnllleltoveI(.nglel - BULLET_SPHO:
double sv)' - ealeAnllleltouHlnglel- BULLECSPEEIl:
grap~lts(:
305
306
Review Questions
The following questions will help you to determine how well you have learned
the subjects dUcus.sed in this chapter. The answns are provided in AppendiX A,
" Chapter Qu~ Answen."
I. What method in GalacticWar.jaVlll makes il possible 10 add powerups to the
dGtroyed~
2. What construct does lhe sprile engine (in Game.java) use 10 manage the
sprites~
On Your Own
6. How many different asteroid images are there in Galactic War?
7. If you wanted to add another weapon upgrade to the game, which method
would you need to modify?
8. How many sprites is the sprite engine capable of handling at a time1
9. How many bullets are fired at a time with the fifth-level weapon upgrade?
10. What is the name of the static j nt that represents the game state when the
game is running normally?
On Your Own
There are so many possibilities with this game that I hardly know where to start.
Since 1 consider the game finished in the sense that it is sufficiently stocked with
featur~'S and gameplay elemellls to meet the goals I laid out for this book, I will
just make some suggestions for the game.
I would like to add a black hole that randomly crosses the screen from time to
time, sucking in everything it touches. Wouldn't that be cool?
Another great feature would be to have an alien spacecraft come onto the screen
from time to time and shoot at the player. To keep the alien ship from getting hit
by asteroids, the ship would engage a shield whenever it collides with an asteroid;
otherwise, it would have to navigate through the asteroid field, and that's some
code I would not care to write!
Here is yet another idea to improve gameplay, since the game is really hard. The
game could start off with a single big asteroid for L<..>vel I, and then add an
additional big asteroid to each level the player completes. Although the game can
handle an unlimited numocr of sprites, I would end the game at level 10 to keep it
reasonable. Since the game currently just throws 10 asteroids at the player from
the start, switching to a level-based system would greatly improve the fun factor!
For the ultimate version of Galactic War, I refer you to a derivative applet
available at www.starnightgame.com. where the team has posted a "space
combat demo" of the gameplay in Swrflight: TIle Lost CO/OilY using the source
code for Galactic War as a basis. You will find many aspects of this game that are
1miliar after working through the Galactic War project.
307
CHAPTER 16
GALACTIC WAR:
WEB DEPLOYMENT
This chapter finishes the book by explaining the all-importan t subje<:t of how to
deploy your Java applet~based games to the web. I aSSllllle you already have some
knowledge about how to usc FTPtocopyyourgame to a web server. I will show
you how to prepare the applet so that it will TUn from your own web page! (Evcn
if you use a free hosting service, if you can upload till.' files to your website, then
very likely the game will run from your site.) You will also learn how to usc the
Java Archi,'e 1001 to bundle your entire game (with class files and all media files
together) in a lava Arch ive file.
Here are the key topics in this chapter:
Packaging an applet in a Java Archive (JAR)
Using the JAR command-line program
Packaging Galactic War into a JAR file
Creating a hoSI HTf.,lllile for the applet
""
310
The parameters in this Help listing are de<:eptive. Not only should you llpt use the
dash (-), bUi these parameters must be spe<:ified in a spedfic order. For instance,
we use the c parameter to tclllAR to creatc a new JAR file. Bm this parameler
I1u,SI be used along wilh f 10 specify Ihe file name. I can'l imagine a situ'ltion
where you would want to use the JAR tool without using a IAR file, bUl I guess
that's just me. After the cf parameters, you specify the JAR file name, and then
the files you want to add. Here is an example:
jar cf test.jar '.class
This command will create a new JAR file called test jar and add all .class files
found in Ihe current folder to the JAR file. Aft er doing so, if Ihe JAR 1001
successfully created the new JAR file, il will simply exit and not print anything
oul. (So remember, no display equals no problems.)
Fi\lllre 16.1
\lerifyirlg mat the JAR program
liSt
jar tf test.jlr
You an also include the option to display the contents of the JAR filt with
dtuils. This option also works when creating a new JAR file. hUI you mUSI he
artful 10 include tht v option afttr tht c or t paramtltr. Here's an example of
bot h cases:
Jar c, f tesLjar '.class
Jar tv f tesLjar
EJrtr.tctjng Files
from
a JAR
Fi~
You an extract a single filt or all lilts from a JAR filt using the ... option, like this:
Jar xvf test. Jar ',.
You can update a JAR file using the II parameter, Any files you specify will replace
existing files in the archive, and any new files will be added.
311
312
Chapter t6
J ar
C~ f.
Hou
~ . . J.w.J cormtI.nIY's ~ WIth didlk rm ~!he JAR proopm _1lOt t*d
MUG mINd, Un Oflf clol!S IlOt usuaIy drri: a hot be!fage ~ JAR.
wi~
a JAR file when you have drployed the apple! to a ~ite. Ioe s~ you a couple of diffe<ent
ways to load im.>gl'S and other media files in th;s book.
The method you must use when a game is deoployed in ~ JAIl uses the J~va. net. URL dass and
!he getResource() method to aute a URl that \'011 can pass to !he appropiaIe .... <;f
sound loader. The getResou rce ( ) method is available from thi s. getel a55 (J. This mtthod
wiI Cll're(tIy puI a rnetilo hom ttw loaI fiI. 'Y'~ or from ;I JAR fiI. whrn leCUl'Ce5 ;Ire
sand wilhin a JAR. 11M is an eumpIe:
~Rl
urI- thls.getClanlJ.j)etResouru{fl1el\;l.);
313
314
.. , _
l.t - . . .. to _
-.
~'"
>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 nCl 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 nClass
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<:.lUse that will add .Iprojeclto the internal structure of
the JAR file. Instead, you want to grab all the files inside of .Iprojecl, bUI not
include the folder name. The option is C (uppercase is important). Here's the
command to create the GalaclicWar.jar file:
ja r cvflll Ga I ac t I cllar . jar 'un1f es I . tx I . C proj eCI
This line tells JAR to create a new java archive called GalacticWar.jar, to include
the manifest informalion stored in manifest.txt, to use the projeCI subfolder, and
Figure 16.3
Cn>.~ng
to add all files in Ihat subfolder to the JAR file. Figure \6.3 shows the output of
the command.
If thes<' additional steps get on your nerves, just lump everything together in a
single folder and fun the JAR program in the same folder as all your Java projcrt's
files, without using the Coption, like so:
j ar c.fll
G~l acticWar
315
316
Chapter 16 Galae;t;c
cht.lll)(hU4>
ctHle>Thl$ 1$ ., giwclt HIe>
clMid>
(bod,)
The key to running an applet inside a Java archive is 10 add anolheroplion within
the <applet) tag called archive.
(apple t tode-gaw.clus
Irthtve-gI .Jar
wldtll-800 helght.ofiOO>
(/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.
~
~~
>
_.<1>
U.I~>G.oh.tl
-.
. ... ~ loy
<~.<I>
,_.tt....
$ . . . .. -......U.ln
wi....."I....,.
<l,""'"..."'"h" .t1c...
....
<"!'Plet>
~ .J U
0600>
~~:l;
figure 16."
CRating
II
---........-~_
.~
j)
--
Java
---
.-
down~i"ll
317
318
When me applet ha$ compl~dy down1Dackd 10 )'OUr local ~m1, il Will access tn.:files in the JAR locally rllther than tuning Ilk- web.serwT for e'Vl"rf fi~. Rrmnnbn
tlk- list of 42 rMdia files in Galactic Wa~ If Ilk- game ""ere deployed to the web
server wilh all of those individual files, tlk- app~ would have to downlood C\1:ry
single file individually over Ilk- Internet. ThaI's a lot offik transfers! But when your
applet is stored in a JAR, that single JAR file is downloaded to your PC. and the
applct runs from there. All media files are drawn directly from lhe JAR file instead
offrom the web server. If all goes wen during the downloading of lhe JAR file, the
game should wme up as shown in Figu re 16.6.
.....
-_.
..
-.
_---
.-
III
Review Questions
~ppkts
I~rg<"
J;lVil Archive (JAR) li.Ic. you dranu.tically impro\'e th.. lilTl<" il uk.-s to download
game' from ~ web SC1'V<"r. You a1so cut down on the: number of
tnnsfen that must be mad.. whc:n individual filesaT<"stor<"d dirt.ly on th.- SC1'V<"r
inst....d of iruid.. m ;m:hive filt.
Review Questions
The following questions will hel p you to delermine how well you have learned
the subjects discussed in this chapter.
I. What does lhe: acronym JAR stand for?
2. What is the: name of the: program used to work ",ith JAR files?
3. What types of files can be stored inside a JAR file?
4. What compression method does the: JAR format us.c?
5. What mrthod must you ~ in conjunction with the J'YiI. net.URL class for
loading m<"dia files when an applet has bttn deployed in a JAR file?
6. What command would you enter to create a new JAR file, called test.ja r, that
con tains all files in the current folder?
7. What command would you enter to creat e the same archive bu t also include
a m anifest file called manifesuxt?
8. What command would you enl CT to list the contents of a file Gllled MyGam...jar ",ith verbose list ing t'nabled?
9.
Wh~t JAR parnmetCT option Gluses files to bc added from a djff..rmt fold..r
without adding tht' folder name to tlK files stored in the: archive?
10. What
t~
319
320
Chapter 16
Epilogue
This concludes the final chapter of the book! I hope you have enjoyed reading
this book as much as I enjoyed working 011 it. I'll admit that it was quite a
challenge! For a while I didn't think this Galactic War game would ever sec the
light of day. There are so many advanced topics that we didn't have time to cover
in this book, the likes of which a diehard Java programmer would have liked to
sec. However, I believe a completely functional game, created from scratch and
actllally finished within the pages of a book, is c'u more educational than any socalled "advanced" material we might have looked at instead.
The game engine developed in the previous chapter, which was based on all the
material in this book, is a viable game engine that can be used for many difTerent
types of games. To see one example ofa game created using this engine, check out
the Space Combat mini-game at """,,.starfiightgame.com. This applet is a demo
of the ship-to-ship combat that takes place in Srarjligllt; TIle Lost CoI,my.
My hope is that you have learned enough from this book to build your own Java
applet-bascd games and that you will create the next blockbuster game for the
online casual g<Jme market. Good luck!
APPENDIX
Chapter 1
l. Whal dOt$ tht acronym JDK stand for!
322
Appendix A
p~t
Chapter 2
I. What is the name of the JDK tool used to compile lava programs?
Answer: javac.exe
2. Which JDK command-line tool is used to run a lava application1
Answer: java.exe
3. Which IDK command-line tool is used to run a lava applet?
Answer: applctviewer.exe
4. What arc two good, free lava IDEs recommended in this chapter?
Answer: Eclipse, Net Beans, or TextPad
5. Encapsulation, polymorphism, and inheritance are the keys to what
programming methodology?
Answer: OOP: Object-Oriented Programming
6. What's the main difference between a lava application and an applet?
Answer: Applets run in a web browser.
7. Which method of the Gr~ph! cs class can you use to print a text message on
the screen?
Answer: drawStr! ng()
8. How many bits make up a lava integer (the j nt data type)?
Answer: 32
9. How many bits are there in a java long integer (the long data type)?
Answer: 64
Ch<lpter 4
Chapter 3
I. What is the name of the method Ihat calculales the velocily for X!
2. What is the base class from which Ship,Asterold, and Bullet are lnherittd!
Answrr. BHeYectorShape
3. Which classic Atari game inspired the game de\'ffiped in this ,hapter?
Answer: Asluoids
4. Wltich type of collision testing does this game use?
Answer. Bounding Redangle
5. Which method of the Shape class doc this game use for ,ollision testing!
Answer: contaln${)
6. Which geometric shape class do the Ship and Asteroid classes use?
Answer. Po I ,gon
7. Whkh geome1rK: sha~ class does the Bullet 'lass use?
Ans...." t:r. RecUngle (Phel
:aceept;Wle)
:loo
game!
Answer: Runnable
10. What math function does ulwglellovd use 10 calculate the X "ekx:ity?
Answer: KoIth.cos( )
Chapter 4
1. What is the primary class we've been using to manipulate Vedor graphics in
this chapter!
Answer: GraphlcsZO
323
324
scrttll~
3. WI.... t ill Ihe name: of the Gr.phlC$20 method tholt draws, filled reaangle?
Answer: 1'111 Rect! I
4. Define the words comprising the acronym AWl'.
Answer. Abstract Window Toolkit
a polygon?
Chapter 5
I. WhoIl ill t~ primary class we've ~ using to manipuble bit mapped
Ch~PIe<
S.
Wh~t
melhod~
lmages~
Ans....er.
"nntrra~sfp...
8. What is \he name of the "tn1l5p,armcy" chanDd in <lI 3!-bn PNG image?
Answer: alpha chanDd
9. What is the "-pplet class method u5Cd to lO.:Id a resource from a JAR?
Answer: getRuQurce()
Chapter 6
l. Whal is the name of the support class created ill this dwpter to hdp the
Sorlte class m.lIlage position and velocily?
Answer: Polnt2D
2. During which keyboard evenl should you di",blc a key-press \"ri:,ble when
deteaing multiple key presses with global variables?
Answer.
key~elused()
4. Which Ja~a daM pro~ides an alternate method for lO.:Iding images that is nol
lied to the applee
Answer: TOQlklt
32S
326
ima~
i$ pointed,
10. Which AfftneTransforll methods allow you to tranSlale, rotale, and scale a
sprile?
Answer: trans 1ateC I, rotate( 1. and scalel 1
Cha pte r 7
I. Whal is the name of Ihe animation class created in lh is chapter?
Answer. AnlaatedSprlte
2. From which class does tM nnY animation class inMritr
Answer. Sprt U
3. How many frames of animation were there in the animaled ball sprile!
Answer: 64
4. Whal do you call an animation lhat is slored insi<:k many fib?
Answer. stquertU
Chapter 8
7. What arithmetic opel'31ion
poliition!
Amwer. division
10. Which
A.~1I1:HedSprite
Answer: drawl l
Chapter 8
I. Whm is lhe name of the method used to enable keyboard events in your
progrom!
Answer: .dd~eyL i
ste~er(
Answer. (eytlstener
J. Whal is the 'inual k~ code for lhe Enter ~
Answer: Y(..EntR
4. Which keyboard ",,'ent ..ill ldl you lhe code of.t pressed
key!
5. Which keyboard event willlell you when a key h"s been relcaS!!
Answer: keyPressed( l or keyTyped( l
6, Which keyboard eve nt will tdl you the character of" preSSl...d key!
Answer: Techn ically, any of lhe following three (keyPreuell{ l,
keyReleasell{), and keyTypedl) )
~ts?
327
328
Appendix A
pa~mtter
methods~
Answtt HousH_tnt
10. Which mouse event reports the actual movancnt of the
Aru;wer: -.;!ustOr.ggtd() or -.;!us~_td()
Chapter 9
l. What is the name of Java's digital sound S)'$tem class?
Answer: AudloSyS!tll
2. What is the name of lava's MIDI music system class?
Answer: HI dl System (Sequencer also acceptable)
3. Which Java class handles the loading of a sample file?
Answer: Audl olnputStrea_ (AudloSysttll also acceptable)
4. Which Java class handles the loading of a MIDI file?
Answer: Sequence (HtdtSyS!e. also acceptable)
5. What type of exception error will Java generate when it cannot ~ a 5(ltInd
''''
class~
8. What is the main Java class hiera rchy for the M IDI system class?
Answer: javax.sound .tdt
9. What three digital sound file formats does lava suppo rt~
Answer: AIFF, AU, and WAY
10. What rare aception elT(lT will occur ...men no MIDI sequencer is ava.ilable?
Answtt MidlUnn.ll.bleuception
Chapt~r
\1
Chapter 10
L What is the name of thc inlerface class that provides lhread support?
Answcr: Runnable
2. "'lut is the IUme of the thrnd encution method tlut
)'()U
an usc to run
Answer: sleep( I
5. Whal Syste.. method n!Urns the current time in milliseconds!
Answer: current TilieHi 1\ 1$( l
6. \\''}ut is the IUme of the: method tlut refums tlK' dirtctory containing the
applet (or HTML contail"lC"l'l lilt?
Answer: getCode8ase( I
7. What i~ lhe name of the method that returns thlentire UR Lstring including
the applet (or IITM L colllainl'r) file?
Answer: getGoc\llIentBase( J
8, Wlu.t class do you use to store a bitmap inuge?
Answer: [lUge or BufferedllUge
9. Which Graphlcs20 mel hod is used 10 draw a bi tmap!
Answer. drawllllge(}
10. Which class hclps to improve g;lJTKpby by proriding random numbc'T'$?
Answn: R,,~do.
Chapter 11
L W}ut is the rurnt of the class tlut lundks bitmaps!
Answn: h ...ge or Buffe'edllUge
329
330
Appeodil A
Chapt~
Quiz Amwers
2. Which
3. What is the maximum number of spritCS that can be supponed by the game?
AI1$W('r: virtually unlimited (based on avaibble mmlOry)
4. Which method in the 6riphlu2D class aetually dr;lws the image: of a sprite?
Answer: driw[lIIgel)
5. Whal is the name of the Applet ml.'1hod that rcdra ....'S the window?
Answer: pitntO
6. How many key presses can the game dett at a single tilm'?
Answer: virtually unlimited (limited only by the oper'1lting system)
Answer: Shipe
9. Regarding ship rotalion, by how many anglcs can the ship be rota led?
Answer: 360
10. What lm'thod provides the game ..ith RIppon for conision detection?
Answer: Rectingle.contalnsl 1
Chapter 12
1. Which RIppon c!ass helps manage: the position and velocity of spritt:S?
Answer: Point2D
2. During which kryboard f,"\'enl should you disable a key-press variable when
detecting multiple key presses with global variables?
Answer: keyRelused
3. What is the lWTll' ofttK- sprite collision detection routine used in Galactic Warl
Answer: Rectlngle.contiins( l
4. Which method in the Appl et class provides a way to load images from a JAR
file?
Answer: getRnollrce()
(hapter 13
5.
Which '~\'~ (QCbge do you need to impon to U5t the Grlllhlcs2D class~
Ans",1'I": j;I\'1I.~",'.Graphics..!D
6. What numeric dau typt' docs the Po!nt2D class (created in this chaptCfl
for internal storage: of the X and Y v.t.lues!
Answer. do~blt
U5t
7. How docs Ihe liS(' ofa closs such as Point2D improve a g;ulle's source code,
,'er$us using simple variables?
An5\\o1'l": A single I"'rameter handlts t....o \'ariablcs (,; :;md yl.
8. Which propcrty in the Spri tf class detennincs the angle at ....hich the: sprite....ill mo,e?
Answer. ..,.tAngle
9. Which property in the Spr! te class determincs the angle at which a sprite is
poink-d?
AII,wer: faceAngle
10. How many milliSI.'Conds must lhe game uS(' as a delay in order 10
fr.mle rate of 60 frames pcr S('("ond?
Answer. 1000 J 60 - 16.67 ms
achic,",~ ~
Chapter 13
I. What is the name of the mc:lhod thai makes collision lktcttion possible?
Answer. Rectangll".cnntalnsO
2. Ilow many collisions c.m the g;lllle dcl~'<:t within a single update of the g.1111C
loop?
Answer. the ;quare of the number of spritcs
3. Woot would happen ifthc: ship ..-m: to firu projectile that ~warps" around the
SCrrl:;md tlv:n hi~ the shiiY. Would ~ collmn taU place? Why or ",f,y OOI?
Answn: 1\;0 collision i:s handkd brt~ the ship:;md buIJcu.
4. What should happen 10 the pl~YCf's ship ~ftC'r it has bct'n dcstrortd by a
collision with aJl asteroid? DCS(ribc a beller way to "rcspawn" the ship than
whal is currently being done.
Answer: II should hed<:stroycd and respawned. A better way might be to give
the plarer some "invulncrabk" time aft~.,. rcspawn to improve gameplay.
]]1
332
s. What typeof lransform could you apply to the explosion sprite to change its
size?
Answer. scaling
6. How does 1M ship's vclocity afft 1M result of a collision ,,-ben the ship is
deslro~~ Should lhe ship continue to am momentum rven while
blowing up~
Answer: ~ ship culTently slOPS when il explodes. A more realistic
aplosion would conlinuc 10 move a little ways along the ship's trajectory.
7. How can the collision routine be impro\'! upon,.so that collisions are more
prKise?
Answer: Either smaller bounding boxes can !x used, or every pixel of two
sprites can be compared (which is usually overkill),
8. What is the name of the constant appli!lo the ship when a collision has
taken place?
Answer. $TATLHPlOOING
9. What is the nameohhe method that updates a sprite's animation sequence?
Answer: updateAntllitton()
10. What is 1M name of the method that handles the game loop for Gabelic
Warr
Answer: qaIlO!Update('
Chapter 14
I. What is the name of the new game engilM' dass developed in this chapter!
Answer: Galle
2, How many sprites can the new engine handle on the screen
Answer: unlimited (with available memory)
simuhancollsly~
3. Which of the four key dasses in the gilme engine ha ndles image load ing?
Answer: '.aqcEntity
4. How many different asteroid sizes does the game
Answer. four
use-r
Chapter IS
S. True or False: Coll~ions are handled inside the game engine.
Answer: nlse (collisions are only detected, not handled)
6. What type of object IS .nl.l.. ge, a private "aliable
Answer: [..geEM 1~7
In
Ml.. tedSprite~
An,.. tedSprite?
Answer: Sprite (which, inlum, uses l .. ge(ntity)
8. What is the maximum velocity value for the player's spaceship?
Answer: 10
9. What class docs the pmdsprite I"nginl" pass in some of its evel1ls?
Answer. Arli.. tedSprlte
10. What is the rwne ohhc wpport method in A1II.. te<lSprlte that returns a
properly formed URL for a file to be ~~
Answer. get~Rl
Chapter 15
I. What method in G:I\acticWar.java makes it possible to add powerups to the
2. What construct docs the sprite engine (in Game.java) uS(' to managl" the
spril cs~
Answt'r. Unkellllst
3. How nuny ,,tapon
Answer: 1i,,1"
u ~ are
333
334
Appendix A
Chapter 16
I. What does the acronym JAR stand for?
Answer: la,,, Archi\"(.'
2. What is the name of the program used to work with JAR files?
Answ....r: jar.e:'(e
3. Whal types of files <:an he stored inside a JAR file?
Answer. anr t)l'C of file
4. What eomrrC'Mion m....thod does the JAR format use!
Answer: ZIP compr....ssion
5. What method must you usc in conjunction with the jawa .net .URL class for
deplo~
in a JAR file?
6. Whal command .....ould you ....nter to create a new tAR file, called tcst.jar, thaI
contains all files in the current (tllder?
Answer: jar cf test.jar "."
Chapter t6
7. What command woukl you entn 10 ont~ 1M SUlK' archivt' bUI also ilKlud~
a manifest file called manikst.txt?
Answer: jar ct_ test .jar ..,nlfest. txt '.'
8. What command would you enter to list the contents of a file called
MyGame.jar with verbose listing enabled?
AnS\'<'er: Jar hf MyGa-e.jlr
9. What JAR paramctn option ClIuse5 files to be added from a diffnent fokln
without adding tlK' fokln lW1K' 10 tlK' files sto~ in 1M archivr?
Answer. C
10. What type o( web server do you need to host a Java applel-bascd gam~?
Answer: Any server will do; applel$ are client-side programs.
335
INDEX
Sw<
-"iIT IAS"ETl ...... l4
ooIdJ(qoU
O _ - . 142_IU
....,...*J1
......
A
_ _. _ - . . . . . .... u
lor If"*'. ' __
'M
<l,ffi...T",nsfot'"
"ad.
I'h~.x
_o>r,.
A.....
_t.
A.J~
:!!
lJ
121
.r
!.
.....riOIint ddI....
'r~"" 1'fOV''''' II
111-181
~J
ss
dnt""" '"'._
...>11
< "RJ. S3
d"wA"mRd,{l n,,,,It.>d kor. ~
d"wRnll.{j """"'nl ~". 61-61
d"w<;b;p;J.,.,ht>d for,61
..,.....t'pdaI<l) ......hod. 6k>4
......
b,_
-_
....--......I.r
''Pb'> of.
_\"'k>f5hartdooo .....
...... d-. Sl>-S1
~.
.......... ! ...
! m l l _ .... la-I.
~
7J.s..-.'",~
1'0..........
" _ _ a,S7
&Dod.
--._m
-,,"no.-, I
<nt;l..., 9
Oftl_';". ....... lU
"",-iono;m:h_1l
1_"""_1'>-17
Actiq
to9>-.,
-.0< COok
fiI< b . 0;\1
~1.-b.6J
............ ',-)
\l>ip_b,~lo6
Ihrnd.-. b. 6J
"I'dooe<' m<lIIoW.._7
At.... ,~ JI<roid.. 4'J
33B
Index
Atori l'g,w\4
AU fil.., 155--1S6. Su ~I.o sound di[>l
Aud.o<i'y,IS5--156
'h.nging digital ,,011'1, fom"t
...,ln8' in. 158
.ndi... Su rnu. i<; _nds
Au,HolnputS',..m d _ IS7. 1S8-1S9
<fro, "'ndl<,.. 163
Soun<lClip d... 'n<'l"ul1'ing, 17Il-171
AndioSyot<rn .l_ IS'
ro, ~,ndl= 163
Ioodi"tl ",und.. 1S9
Sonn<lClip d ... 'n<'p"'I"ing,
170-172
A....II"
(io"..
Conft"n, 2005. 9
c
c provom.. )7-.38
C++.1.l, )II
;n.... ri'."'" in, 42
po,....-of.l6
w<b """'" wri"<o in. 24
CI,24
a.kAngI'Mo~J m<thods..
7l_n
pro;ro
)(jl-JOI
lib,,'Y. H6_H7
<h
l.!~__ I
-
~. ..
~~ ~~
2.
~!"~~rl
~
i'
<
~
~
~t
~;"
~ ~
~ c> pwrprp
HlI~
~~~~ c
i -
~'I'"""'i'l-".
,="
~~] ~
! ;"0:;;
~.
"
HmUifI
PHf!UUJiHUHh
rt~
Wl,j~~ fi ~ HE! - HnH! I
-1,J'd
i . . ~ '1iI~..
~ ~~ r._
I 'H
,,"
". "
.,
~ P'f
'Ht"
O'
] i' ii
jj.q.[
!I i
~!:
r.
J
~
11lll~,.~fllt'~.r.lll!11!!!,j!,~IIJII'lttl[II'il I1
1IIIt'~!11 ErllJlfll' Ij " ! I!I,~tl!I!ljjl_ r 1111
~~~
I~[r
~~
i~t
~rr
!~l~flt~f~!
~t~!,j~~fltillt~1'1 fl~t~l~
;l;JI;~;~f!
Jilt!
.,'}."
.'"'
J"
-.
.
""_."t~"
".~ (-. ,;:'1, ",'f -" ~~,.;:.
~ ~t ~" """'1
-~1:n.~=
.F-
t'~ ~ 1~
~ .~
>;:r".'
'f
.. Q"'S
Ig~
"HI
'"'1'11;
~..!
"
It
J ~I; ! j'
rn
t
~ ~!
i
.
"~
~
-t'
~1 "-~~ ~"~.
~ ~
'j;
e-
r~
I.
!:!
~f~~~
;-
lnde~
~~I""'11Il
....,I_...
IU-IIJ
~,-
no.... n...,,~Il5--I"
Gobct>.
e - ~io:rllll;"0...
ni", ,lir;..
"'.I"""i<a."-" r..r.1Il-11~
I"
GMltJoIENU . - . 2f7
G M!....OVER mod<, U7~l"
G MI!...PUYING mod., lS7
_.R<f~(J
IBM', 81l1<G<DCfL. lS
III ....yo, )7
IIle. (In' .... '1 dcY<IOpm.. ,
"''''ronm<nto), n
m.. hood,
"'~
..-st>IMcIowu() - - . U),
~ I ~~l
1. . . .1!n';lf - . IDS
Aftimo~
-"..-..0 "'-'~217~1l1
-'-~
d-.
:Je-:27
r..r~III_IU
...... ~-l7
..... ~\\'.~~I-]9l
I_Eatitr.jna.211
~"'W~,
~krr-d.I'l
.._""'0
Ibr .....<roid ,
57
. .B"01....0 _
ptCnphio()
, 141_148
hood, 1011
"'''''"pO'-bo4, _ I
... fo'_"""'111
~""".I......h'ml.l,.
""""'""""
........
""
w.
... MJO-"'-'I4,J
ptURL() - - . 1M
TIo< GII>1P, 'J'S, 101
--
~,
J'"
;mo
GPS (pokI
;1
~--'I'"
..It-...Q...-. ,ID
. . _IionV<locity,57
_.-
p<Ojo<cI.lIl-U4
.. III
'
Dr
9-11
io........ -.14l,17lI
en,wa'-'ll
,-~
s..../ooo .....
""m>fI'<d~_
_b RoNIomSIu.... 1'fOv.'m. 7'J-8O
H
h.n,JJ<ShipColli'iono() method. l.ll-llJ
1~
l'i lJ of W.,cll>/l. 7
i...'"n'i.'in" 4)
in' in'
'l"J'<'. 27
in'
br.
.16-';
in'
!7-U
1.1<1 eo.,,: 0-. 134
pool
.,. OJOl.-). l'J
~ Sn--."...t~_
............... "...l.l
Cnploia.W - . n.
:27
P-l "'-
Boo--,.
.,.-Wl.... I.
1. . . . . ~,.,l4
1,:,,-':0-
__""Ion.n
In'
341
342
Index
J
JAil. Sn J..... A",hi.. UAR)
jac."". prognom, u';ng. J08-.ll0
/a"",
[diri"" (S<hild'I,.ll
J"" 2.
J
Ja
I~
Appl;c.,;"ns, 10
A",hi... (jAR),?-l
<<>fI'm" of JAR fik. li"iog,)OII
..1ra<1iog fik> from JAR filt,)OII
Gai><1ic W" pro;.c, in IAR fik. I",bging.
.llo--ll)
;O r.,x< Prosn>"'. u""&- J08-.!IO
",. nif<>! fi...
fo' Galactic W.. proj<ct. 1I1
wmking wilh. llO
!KW IAR fik. ","'ing..108-)OII
pxuging 'prkt. in. )07-liO
l"'h 1o IAR. ><t'ing, lO8
updaling JAR fil.... J(l9-l10
J...
l
Thr lIgrnd 01 Zrida: A Link '0
rhr Pa.., 4
LEeO,6
I<nglh mnhod, II
Bb...ri<s
Alkgtn libt. <y. 189
""t.
b",h-;" ,"ppor1
2.1
pthrndlibrat)'. 189
lib....,. d
fa, ....Y" l4
li"<Una i1.bkEx<<rtion <tTO, !>andl, lfiJ
linkodl;". In _
<agin<, 239-240
,,,"'p;!,,,. II
un"x, 2J
C ++ . nd. U.
<,,"figuring I, ... fat. 12
li>l<o.,. ....'hods, 141_1<2
1"5i"i<& ~fappl .... lllI
10"5 in'<!Iff 'lJ'<" 27
loopL Sn also gam. loop
i'",,';ng 'hrongh. lS
GoIo<1;< 1'1'" pro;.c,. urJ'" for,
lSJ-lS6
"",nd dips. pl,oying. 161
""ys,
'~7
M'rrr, .!6-37
M~riJlr
.i"....
Bla,t, 9
Index
-"-'--
.. OOP,......--.:t ..""
........:rtl'-.,
.""'""""'"
~s....J..,I
C~.
-'
.... ~
~",""711
_ _ .1_14
'-_~71_7}
_bln'o.lS
1 _ ~ S<rwr ,115.2)
1<. _ _
Ian .... II_lZ
,.14
_r-
~I...-tI ~ ~
II'
_
5.u..._.....
i==' _ ' -
]I
...
-)6
1"1.... 1"
M"',..........~-.17!_I.~
~liI<o.l6f>
_,/.,.a.,
14~ 141
-....14i-1l,2
,"_I -.
N<lll. .n.. lS
Ninl<od", 4
No'q>oH!
lIU-JlU
~1-'147
_.,.........---.'47
.... '"
-....I~I
M......E
t.a.;.a......... ,....
I~I
l4li-l.7
......... IS2
.........1' 0 M<thod, 261_U3
_l'rfto<dIl-.tlood, 1.7
,-.ISI
~1"'-'147
I<M1JII. lSI
_ 1... _141.--1502
Ii
w;.m.. S.IM""- ~
.......
,*
lell;o---,............,,_
<lOP
..... hO:loIrog._I
.....pq4_ 41 .... 2
~.42 ....J
................ 1
~4l- ...
I~I
Mo~..lh...... ;n,<rfK~.
..
eII;o-,-I , . . . . _. . Sn 00f'
_Emft!ll - - . 147
_,
C.,
"""i_
...... ,'~5-ln
-tlr\S--.
N."""",.
.NET 'Iu>olotl'. 14
","",'"
<>Y<rloodi"" U
p
"o <-Mon,~,
6
poin'O ",~,hod,
lOt Au""",._ .. y\< IOn><. 100. 6.l
to<
("...lo<1"
It,
""I'I<mml'... 1'1
"'-"'P"'.I,".I~
--
............,1 '
343
344
_.
Inde~
......... _ - . - . . . . 1
l1oy"'_ _ 161_1"
1'\orSoo-oI,.....-.
I'NG
liIot."
... GoIarn<
. . .... ,. _IJ)-Il
Sl(;11 (Rt<I, G"""," 11I...1.
,.,
R.ahoBIi':. ,
~_(UGoI..
1.......1..
w. ~ ztt
-'P
~ I'NG . . . . ~ "'-Ill..!
~ia6x--."
_v.;o-m
....... n
IWIdomNrpu
1M
l O r _ & . - . . 127
_~~II5
-~
1I-aJ
~"l!wi""80-13
polym<>tvhum, ~
pooltlotl. opri1< cl....... ndll~.. lot
I'Tok.I~.
oo:oIi",1II._ 1)-16
Scl>ildI.. H......... 31
GoIo<tic: Wu
-....... s..
I'f"iect
StpGt-n. 4
~wll!l....,..l1
--...-_71-10
~
do., 1
167
_ _;.;.
R
....... <1-.1.
.......1. . . .
_':-94
......."-'7P- _
.I-aJ
,
9p_"""
...... .,.....oa.50
......u- .. ~(n5)_.
~n.s...a1s<>-"~
.....p"" md, 10
~pnt<
1'<1"....."""""""
...,.a.no -'-L II
-~)
-'-L 2II1-la
lOr. 2JS
......... 1_171)
..... .-..~II.
_V<ioociry()
--
.a-l...-
II
liIll_
"
11Zo-11S
51
5'
JI"'IIcd
.;........................ ....,..l1
- , 0 -.hood, IV-I.
SSE$, 4
Selorio, C
-...l
s....
Inde~
- - ' dIvo.
110
~ I_I~I
....... ,..... 01
~"""'I"""'I7\l
......
~I<>':
....0...-.
.,..,.....
"""""'' ' _)(11
'l'ril<
.n,,,,,',,,,, (
sm.cc:lo-.,-JZ
-..."
S - M ~............
P...... II
T
T.i,
,...j
~h<
........,
.uo--n
,10K _
....... ll
,'l
,.,
.."....-
~1~160
"fM I~"""""
t.-Mna."
~U9
>vrit<
Sp<iI. dooo, 1I
_
i
ZlI
T
117
1l1
ZlI
~1'~"
.,.il<{Ae;.....O . . . - . lS6., m-l6.l
opplco.. . - - . I"
~I"'-'Z"
fot \
1'0. P"*"- ~ _ ~
Spril<.jo
III
.,n.... fiN .1... GooIo<ti< W.-pnoj<; .....
HZ-It)
'hrad
II~
..
phl&'.,nm,"S
,IJ7-I..
'1...., _
1Il-1II9
"""" " II
duoo,---.,
cnlI_ do1,,"'
..
.-.<l
fnr~-
.....
_\'''-'"
u:
1171
Iii, )7
.......
T.... ""
.
T_c:Io-.,94
,17
345
346
Indt~
T"""",_._
..... F ~ ......... U7
.... ,.
....U7
~...-en-n
. . - . 0 _willi
...
~_eL,-,n
,.,...aulI_
.......... IU-ltJ
..,........Id>....'-Dy _ _ lU-ltJ
~
"-,,,,71-71
Goio<b<
r. -.ppm ~ M, '1-"
r.._lo.l
amp. ls-31
I~IlI6
-~
.....
"
~"""''''''''n-M
t~~'"
~W_
..-
.,.....
__
ll-ll
tOl
. . 14--1}
...m.-. II
YIrtoool kq....D, In
ploriomo- ...........
I'~
IluI<, U
V'
u
lIft....l
... l. 9
U,,"'., To"'''~,,,,,,, 1/1. ,
~ftBi
...
~ 0<IftII .......
Sompl<I.<>op _ _
_7
odd.Ic ....
_
......c5IoirO
- . t6
UaL.o (\1
"",,0 ,_hod. 1M
W
W.rCN" Mrico,
-..0 .-tloo<I,
... _-
4-}
III
........-..0
void
Ilt_tll
.-s)
- . m-
s..-./so ..........
..... ..,,114
...u"'
........
"'..._ n
I\
'I\'.,c../f. <-5,.
r..IHJ
7
_ _ .16.)-160
v
...riabI<o, 40.
Sn .,"" ..... ~
~1'
"""yo,
Z
.......,...lty _tloft......ti" l0 10
license
n.. mdoJcd ~ is copyrichlCd"" tit< coprtichl hoIdttfl' indial...J on 1M fIOI'tw= due.
"""""ttr
'rtm
limited liability
ruE SOLE REMEDY FOR 8REAOl OF nilS UMfTED WAIUlAt\'TY SHAll CONSIST
F.N11RELY OF REPl.ACL\IE..>n' OF mE DEfECllVE DIsc. IN NO EVL'lT SHAll
TIIOMSON rouRSE TECIlNOLOGY I'TR OR mE AtmlOR a UAIIlE fOR ANY onlER
DAMAGES, INCLUDING LOSS OR CORRUYnOS OF DATA. OIANGES IN THE
FUNCI'IONAL OiARACTEIUS11CS OF ruE HAKDWARE OR OI'EJlATTh:G SYSTEM,
DELTUUOUS IN'Tl:RAcnON Wmi OTlfER SOFTWARE, OR,.u..", OTllER SPECIAL,
INQDEZ-1'AL OR COSSQUll."'AL DAMAGES THAT MAY ARISE, EVEN IF TliOMSOS
rouRSE TEOISOLOGY I'TR AND/OR mE Al1T1iOR lIAS PREVIOUSLY BEEN SOTlAED
niAT TIlE POSSI81LITY OF SUCH DAMAGlS EXISf"S.
Disclaimer of Warranties
THOMSON COURSE TFOfNOUX;Y I'TR ASD TIlE AIJl'HOR SPEClFlCAllY DISCLAIM
ANY AND ALL OTHER WARRAJ'l'm:s. EITHER EXPRFSS OR IMPLIED. INCLUDlNG
WARRA~1'IFS OF MERCIlA~1'AIlILlTY, SUITABILITY TO A PARTICULAR TASI( OR
I'URI'OSE. OR FREEDOM FROM ERRORS. SOME STATFS 1)0 NOT ALLOW FOR
EXCLUSION OF IMPLIED WARRANTIES OR UMITATION OF II':CtDENTAL OR
CONSEQUENTIAL DAMAGFS. SO TIlFSE LIMITATIONS MIGHT SOT APPLY TO YOU,
Other
Thit Ap'mmt is .,...,.....J br thclowJ 0( lho SUte 0( M-.chllM11O wil"""l reprd l<l dooice of
bw prilIo<ipI<a.
U",ud Coafttllion 0( Contr:octs for the 1.o,cnwi(>Qol ~ of Goods it
>pifiaIy tIixIwn<d. T'hio ............... OOftAilul<S the alii............. bcIwccn l"-"" and
Thn.oIov PTR nopnti"l"" of It.. ""'-ro.
n..
n.c-- e-.....