A trading approach based on RSI oscillatorFull description
Full description
Java Programming Assignment Documentation
Introduction to Java ProgrammingIntroduction to Java ProgrammingIntroduction to Java ProgrammingIntroduction to Java ProgrammingFull description
Full description
Full description
Master in Computer Application from Guru Gobind Singh Indraprastha University (www.ipu.ac.in) by Ketan Rajpal (www.ketanrajpal.com)Full description
Java Programming Question BankFull description
This assignment has been assigned to analyze and implement the solution for the given problem and to understand the concepts of java. It states the differences between best searching and sorting al...
JAVA Server Programming Java EE7 Black Book
Curriculum Guide 2016
Descripción: programming
See also: http://www.scribd.com/doc/14227525/Python-Calendar-Program, http://www.scribd.com/doc/14143029/Comparison-of-Java-and-Python.Full description
Java 8 Programming Black Book encompasses syntax to declare variables, as well as advanced object-oriented concepts. The book also deals with the programming implementation of the concepts explain...
This is a details tutorial about java programming. At least, any java programmer needs those skills to develop an application in java platform. However, I didn’t write this tutorial. I’d like to sh...
Exercise for OOP javaFull description
BioDesign : The Process of Innovating Medical Technologies 2nd EditionDescripción completa
APQP reference manual from aiagFull description
BioDesign : The Process of Innovating Medical Technologies 2nd Edition
Java 8 Programming Black BookFull description
Удобный бизнес-курс для взрослых, способствует развитию разговорных навыковDescrição completa
Publisher and General Manager) Thomson Course Technology PTR: Stacy L. Hiquet
The Thomson Course Technology PTR logo and related trade dress are trademarks of Thomson Course Technology. a div ision of Tho mso n Learning Inc., and may not be used without written permission.
Manager of Editorial Services: Heather Talbot
Java is a trademark of Sun Mic rosystems, Inc. in the Un ited States and olher countries. All other trademarks are the property of their respective ow ners. Jlllporfclllt: Thomson Course Techn ology PTR canno t provide sofhvare
support. Please co ntact the appropriate softwa re manufacturer's techni cal support lin e or Web site for assistance. Thomson Course Technology PTR and the author have attempted throughout this book to distinguish proprietary trademarks from descriptive terms by following the cap italization style used by the manufacturer. Information contained in this book has been obta ined by Thomson Co urse Technolo!:,'Y PTR from so urces believed to be reliable. However, because of the possibil ity of human or mecha nical error by our sources, Thomson Course Technology PTR, or othe rs, the Publisher does not guarantee the accuracy, adequacy, or completeness of any information and is not responsible for any erro rs Of omissions or the results obtained from use of such information. Readers should be particularly awafe of the fact that the Internet is an ever-cha nging entity. Some facts may have changed since this book went to press. Educatio nal facilities, compa nies, and organizations interested in multiple copies or licensing of this book should contact the Publisher for quantity discount information. Tra inin g ma nuals, CD-ROMs, and portions of this book are also available individua lly or can be tailored for spec ific needs. ISBN-l0: 1-59863-476-3 ISBN - 13: 978 - 1-59863-476-1 Library of Co ngress Catalog Card Number: 2007938236 Printed in the Un ited States of America 0809 10 II 12 TW 1098765432 1
Thomson Course Technology PTR, THOMSON a division of Thomson Le:uning Inc. • ,~ 25 Thomson Place COURSE TECHNOLOGY Boston, MA 022\0
Professional_ Technical. Reference
http://www.courseptr.com
Associate Director of Marketing: Sa rah O'Donnell
Marketing Manager: Jordan Casey Senior Acquisitions Editor: Emi Sm ith Project Editor/Copy Editor: Cath leen D. Small Technical Reviewer: Dusti n Clingman PTR Editorial Services Coordinator: Erin Johnson Interior Layout Tech: rcc Macm illan Inc. Cover Designer: Mike Ta namachi CD-ROM Producer: Brando n Penticuff Indexer: Katherine Stimson Proofreader: Kate Shoup
For Kaitlyn Faye
ACKNOWLEDGMENTS
I thank God for the many opportunities that have come my way this year, such as the chance to write this book, and for the apparent talent needed to make something tangible of these opportunities. I am grateful to my family for their ongoing encouragement: Jennifer, Jeremiah, Kayleigh, Kaitlyn, Kourtney, Mom and Dad, Grandma Cremeen, Dave and Barbara, my extended family at Vision Baptist Church, and Pastor Michael Perham and his family-Jennifer, Ashley, Bryce, and Sage-who have been such a blessing this past year. Thank you to the students, faculty, and staff at UAT for contributing to such a wonderfully creative environment for learning. I would like to thank the Alpha Squad team, who had some influence on this book (and even helped to solve a few coding problems with Galactic War): Roy Evans, Stewart Johnston, Peter Pascoal, Travis Eddlemon, Daniel Muller, Daniel Stirk, Patrick Cissarz, David Coddington, Marc Kirschner, Jeffrey Woodard, Jonathan Allmen, Levi Bath, Douglas Cannon, Joshua Gertz, Justin Hair, Adam Knight, Eric Lacerna, Daryl Lynch, and Kevin McCusker; and the faculty sponsors: Rebecca Whitehead, Michael Eilers, and Arnaud Ehgner. I also owe my thanks to students Mark Walker and Andrew Hawken for introducing me to the angular velocity code used in Galactic War. I am also very thankful for the artwork featured in this book, provided by Ari Feldman (www.flyingyogi.com) and Reiner Prokein (www.reinerstiJeset.de). Without their wonderful graphics, Galactic War would have featured programmer art (cringen. I offer my sincere thanks to the editors at Course Technology PTR and the freelance editors who put this book together: Emi Smith, Cathleen Small, Dustin Clingman, and Kate Shoup.
ABOUT THE AUTHOR
Jonathan S. Harbour is an Associate Professor of Game Development at the University of Advancing Technology in Tempe, Arizona. His current game project, Starflight: The Lost Colony (www.starflightgame.com). will be released in late 2007. He lives in Arizona with his wife, Jennifer, and four children: Jeremiah, Kayleigh, Kaitlyn, and Kourtney. He can be reached at www.jharbouLcom.
CONTENTS
PART I Chapter 1
Introduction ..
xiii
JAVA FOR BEGINNERS
.
Getting Started with Java
. . . . . . . . . . . . . . . .. 3
Java and the Web . . Studying the Market . . Design Rules. . . . . . . . •. . . . . . . •. . . . . . . •. . . . . . . •. The Casual Games Market.
Applying Transforms to Images. Transparency. . . . .
. ....• . . .... .•. • . . .
Opaque Images ......••...... .. .. Transparent Images ............... •• . Working Some Masking Magic .... . .. . .• ... What You Have Learned. Review Questions . On Your Own.
Chapter 6
77 78
Working w ith Polygons Rotating and Scaling Shapes Review Questions. On Your Own.
77
Exe rcise 1.
lOS
Exercise 2.
lOS
Simple Sprites
.
Programm ing Simple Sprites. . . . . . . . . The Point2D Class. Basic Game Entities The ImageEntity Class Creating a Reusable Sprite Class
.
.
.
107 107 109 110 111 114
Contents
Collision Testing. . . . . . . . . . . • .
114
Sprite Class Source Code . . . . . . • . . . . . . . . . . . . . • • . . . . . . . Testing the Sprite Class. What You Have Learned.
Keeping Track of Animation Frames. Testing Sprite Animation Encapsulating Sprite An imation in a Class ..... .. .•. . . . . .. Testing the AnimatedSprite Class. What You Have Learned . . Review Questions. . . On Your Own.
Detecting the Game-Over State .... . . . . .. • . . . .. .•. . .
288
Screen Refresh Updates. .
289
. ....• .. . . ..
xi
xii
Contents
Preparing to End .. Updating New Sprites. Grabbing Powerups. . .. . . . .. .... ... ..• . . ... ...... New Input Keys. Spawning Powerups . . . Making the Shield Work. . Making Use of Weapon Upgrade Powerups ..
.
Ta llying the Score What You Have Learned . . .. . .... . .• . . .. ... . .. . . . .• . .. Review Questions On Your Own
Chapter 16
. .
Galactic War: Web Deployment
.
Packaging an Applet in a Java Archive (JAR) Using the jar.exe Program Packag ing Galactic War in a Java Archive . . Creating an HTML Host File for Your Applet ... . . . • . . A Simple HTML File. .
. ... ..... . . ..•.
Testing the Deployed Applet Game . What You Have Learned. . ........ ... . . .• • . . .. ... Review Questions. Epilogue
. ...... . •. .
Appendix A: Chapter Quiz Answers Index
291 292 294 296 299 301 302 30S 306 306 307
309 309 310 312 315 315 317 319 3 19 320
321 337
INTRODUCTION
This book willicach you how to write JaVil games that will run as applcts in a wcb bT'mt..a. l"hc goal is to &vriop gal"l'lCS ror the casual gal'DC market. Gal'DC pro· gramming is a challmging subject that is not jusl difficult 10 IfU.SItt-it is difficuh just to get started. This book takes aW3Y somc or thc m)')tc-ry or gamc prog11lmming by expbining each step along the w~y, rrom one chapler to the next I assume Ihat you havea litlle la\"a programming experience, but c\"en ir you hal'C I"IeI'tt usal )aVil herorc. you should Ix- ablc 10 k<"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
~
• programming language ilwented by Sun Microsystt'lllS. The primal)' goal of Java's
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
~
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
What Will You Learn in This Book? This book will leach you thl" difference between Java applkations ind applets (which run in a web browsc-r). You will thcnleam about Java's graphics classes
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 V«lor 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
YoIt willNm hgw 10 0Nte fils 'Ji"ll! torn wMdlI
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 il«ess the is installed like any other appIO:aliOll ~a
run in a -t> ~ Oue 10 secunl\' lie system on a user's PC Iibo a J.wa applic.allOn,
~ 10
",ftw~.
Becaust this book is dedicale
men
What about the Programming language? This book is about g;.mc programming, and il assumcs thai you alre~dy know ~t least somc J~va. r rc<:ommend thm you acquire a Java primer to read ~forc delving ill10 this book, or to keep handy for those parls that may confuse you. For starters, you can pick up John Flynt's Java Progmmmiltgfor tlleAbsolutc &gilmer. 5«otld &ii/jOlt (Thomson Cou rse Technology PTR, 2006). If I lose you halfway through Ihis book, I apologiuo in advance, because we jusl don'l have enough pages to ltach Ja~d and build a complete game. I do not utiliu any advanced features of lava SE 6, ('Ven though this is the btest version of Java.
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.
What IDE Should You Use7 The first v..rsion of this book focused on a professional IDE (Integrated {)e•.c/. orman Environment) to help organize: JaV1ll game projects.. However, much has changed in Ihe IWO years silK<" the first edition came OUi. Borland JBuilder Foundation was a free trial version of lBuilder. and we were able to supPOr1the 200S and 2006 versions al the time. BUI Borland is no longer making ~ versions available, and the only option now is tQ llS(' the 3O-day trial ofJBuilder 2007 Enterpris.- Edition, which is not ideal and is quite large.
xvii
)(\Iiii Introduction
I RaV'l: decided 10 Iry sonx1hing dilTt'renllhis lilTl(' around. If a revision is mnnt updJ.tt' a book. Ihen it may seem odd 10 S1ql away from using a professional IDE. But thai is exactly what many professional Java programmers art' doingutili7.ing a simple text edilor and the Java SE 6 Development Kit directly. There are In,my reasons why this is preferable, and the best explanation may Ix: a desire to al'(lid Ihe adoption of any single IDE, since there are no Slandard project files in the industry. and each one is dr.uNtically dilTerent.
10
Tip If yau ... famiiIr WIth . . ~1lcimlKn cr~l.patfOfTl1 wpport and tOE ~, Yoo will
Avoiding any single comp.my·s 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)
• Solaris (Sparc 32, 64) • Solaris (x86, x(4)
n-r
Cttm-pUrbm ............" is . . abiiIy WI ~ and IIrI lhr SMIlf a:dt on cifIemtI ~ ~ ~ oxIt M>d fllIel1f.lIllIt 8es f t ~ 00 ...., plalbms. You do lOX need WI IfCOOlIile .,.:u J.wa oxIt for - , sy;Ifm. Ilt
Due to this extensive list of supportc:d operating systems, it is obvious why we would not want to limit oUfS('lves to a singlt' IDE, but would prefer 10 support aU of tht'st' syslems. M a conSt'q~t', 00n(' of tilt' source code on tilt' CD-RO:\1 includd any projn;t fila; il merdy includa SOUIU codt' files and galTl(' ~s ( image and sound files).
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.
Conventions Used in This Book The following styles Jre used in this book to highlight portions of text that are important. You will find these highlighted boxes here and there throughout the
book. Note This is what a note looks like.
Not~
provide you with additional Information related 1<.l the lex!.
Tip ~
is what a tip looks like, Tips give you po
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
I
JAVA FOR BEGINNERS
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
1
GETTING STARTED W ITH .JAVA
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 im·l$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 n«d, 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
Java and the Web let's take a look at game design for a moment and see how Java fits in, because this is the cort" subject of the book. What truly has changed in the world of gaming since the "good old days"? By that lenn, I am referring to the infancy of the game industry that entertains the world today, back in the 1980s when arcade
,
4
Chapter 1 • Getting Started with Java
game machines were at the top of their game. Many readers were probably bam in the 1980s and have no recollC
Ninteodo has given some 01 il'i /he Past (lor the Game Boy Advance), have outsold most console and PC 9'!rnes,
Studying the Market The game industry is pushed forward by garners, not by marketing and business executives, which makes this industry somewhat unique in the world of entertainment. Isn't it obvious that professional sp
Java and the Web Can you think of a game that Blizzard has published that does not fit into theso:: two g....nres? Blizzard has consistently hit the mark dead cent....r with thdr gam . . s in terms of target audience, quality, polish, and subsequ....nt mass appeaL World of W
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-
S
6
Chapter 1 • Getting Stane
vmes
I n my experience, the fun factor of vidto has risen exponentially in the Lut two dec:ldes. along with the compleJ:ity of modem garlle$. Le'l's face it; you nn only play Pnc-Aftm for an hour or 50 umil it becomes tedious. 1lJe Slim applies to ITlOSt oftM dassjc arcade gal11('$. At o~ time, you wuld 6tl"\'ery vidto game in existence in a single room, and those quarter-fueled machines were housed in stand-up cabinets. Sincl!' that tilm, thl!'rt" have been about a half miUion gamts created, though we might narrow down that figure to a few thousand good games, out of which we find a fcw hundred "Hall of Famc" grl!'3tS.
The Casual Games Market In the last two yea rs a new genre has arisen in the game industry calltd msulll
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
C3~ ...al Game~
Market
garners renlly don't want the long, drawn·oul 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
7
8
Chilpter 1 • Getting St,rted with Jav,
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
Installing and Configuring Java games on Xbox Live Arcade that you can download and play if you are a Live user. Marblf' Blilst is one such game, and Garage has m,my more games planned for release on Live and through relail channels. In fact, when you purchase the entire Torque game engine for SIOO, you have the option of publishing through Garage Games, which does the contractual work and provides you with a contract (subject to quality considerations, of course}. Microsoft has really embraced casual games by making it possible for independent developers to publish games directly on Xbox Live Arcade without going through retail channels. Xbox 360 is the first con:;ole video game system in history to provide downloadable games right out of the box without first purchasing retail software. If you arc interested in casual games, you can enjoy playing on Xbox Live Arcade without buying a retail gmne at all, because many games arc available for free trial and purchase on Xbox Live Arcade (with a membership account, that is). I attended the Austin Game Conference in 2005, and the focus of the show was casual games. Microsoft's booth w;lS titled "Microsoft C1sual Games," and they were giving away USB nash drives with the MSN Messenger SDK and showcasing some of their Xbox Live Arcade games, as just one example. One of the most impressive games available on Live Arcade is RoboBlilz. This S'ulle was built using the Unreal Engine 3 (which Epic GanK'S developed for U"rrlll TOllrtJllmcut Ro/JpRljtz also makes usc of the impressive Ageia PhysX physics engine to produce realistic gameplay. Another innovative g.1me 011 Xbox Live Arcade frOm the creators of Projur Gothllm Rilcillg is Geometry W,lrS. This game is unique and compelling, with gameplay thar involves gravity and weapons that resemble geometric shapes.
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.
Installing and Configuring Java As you might have gueSS«!, Java applet games run in a web browser-Internet Explorer and Mozitla ['irefox work equally well for running Java games. Java programs can also TUn on a deskrop system locally without going to a website.
9
10
Chapter 1 •
Getting Stilrted with Java
These typ<.-saf [,ragrams areealled fill·...
Inst alling Java Java SE 6 is anibble an the CD-ROl\l accompanying this book in the \IavJ folder. You may also ,isit the fa\"J home Pilge al jJ'":J.sun.oom todownJoad the latest ,'ersion of the JOK {s<''C Figure 1.1}. When you install the JDK, the installer will not automatiolly moditY your ~)'Stem's environment variables, which is something we will
... __. __ --_ . """,._-,
"'........ 10 "'" ~,,'_
JaYa(TM)OC~ " I:U6~e2
...,.. ...
............
-"'II"-,,,-,_.,,~
Figure 1.1 Ir>stalliog /alia SE 6.
IrlStalling and Configuring Java
n«d to do so that you can run
w
Jay.l CQIllpiIeT (javac.aL") using a CQIllmand
promp( 01'" sbdI window. The CUfmlt vasion at t!'lt time of this writing is Java SE 6
w install fik is calkdjdk-6u2-windows-i586-p.aL". [f you aR using a othtr than Winc\olo'$ you will nM;I to visit w Java website to do-.nIood the arrropriate ~ lOr )
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
Chapter 1 • Getting Sta rted with lilvil
S_Fl... . . G. ......I
__
u~
••
H.._
~N.....
.
You """ be lowed M '" .... - . . . . _ 10 moI
v...ae/ltlCl•. proce.... ~_utOlIO."""~c>IIi_
I
~~ )
S!l\W'9
I
S....'4I"""R_ S_ _.tyIleIn l...... ,""" n
OK
Figure 1.2 The
S~lem
Propertie-s dialog box.
II e-
ilC(e-ssi~e
from Windows Cootroll'anel.
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.
Installing lind Configuring Java
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 b«n 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."
Java Version Numbers lava's versioning can be confusing, hut it's something you might want to understand. The officiallatcst version of lava at the time of this writing is lava Standard Edition 6 Update 2, or java SE 6. However, the actual version numocr is 1.6.0. Th.. computer industry is an)1hing but consis tent, given the cxtraordinary changes thm have ta ken place on the Internet and in softw'lre development in general. liut one thing has oc'Cn agrCl-d upon in lhe compll1cr industry rega rd ing I'ersioning. The first release of a software product is version 1.0. Often a revision or build number will Ix appended. such as 1.0.8392, which helps technical support or caU ccnter personnel identify the version or sub-revision of software that a customer is using wheo a problem arises. The revisioll lJumber is, in every case. not part of the retail packaging and prod uct name, but rather a tracking tool. Table 1 1 lists the ja\'3 "ersion history.
Table 1.1 mva Version Year , ~
,~,
'"'
'00' ,~
,~ ,~
H~tory
Version
,.. " U
,." "" "
Marketed Name Iav~
1.0 I JOI: 1.0 Iav. 1.1 I J[)I( l.l
~"
lISE 1.3 !lSE ' .4 USE S.O IavJ SE 6 Iav. SE 7
--..
Code Name
.... ~
'"
M."",
~
"
Your First Java Program ~ inlCfl.'Sting thing aoout this table is that it is very '()Jlsistent in the S('(Qnd column (VeTSion), but there are a lot of inmnsisteneies in the third column (Marketed Name). which is not a gnat surp~ sina marketing campaigns sddom makes sense. If you were to follow the progression from Olle' '"CTSion to the nat and tally them, you might note that then have hem K'VCIl major versions of Java (while the eighth veTSioJl is 1.1, and not yet rclcascd). Produa branding is a very C'Xpm.sive and time-
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.
Your First Java Program I walll to take you through the steps of creating a new Java program (0 test the JOK and a Java appld project to ttst web-browser integration before moving on to the next chapteT_ Let's start at the very beginning so thaI when you ha"e wrinen a full-featured game down the road, you'll be able to look ba,k and see where you started.
Java Application ~ following program, shown in Figure 1.5, is calkd DrinkJava. Type it in and save the file as DrinkJava.java.
illllO rtJ UI. tO .·; cllss Or l nkJna I p ~ b ltc static wo t d .. t nl Str i ng Irgs()J I Sys te•. out. prj nt1n( • [)o you IlkI' to dr t nk Jua 1" ) ;
p~bllc
Now let's compile the program. You'll need to open a Command Prompt window ag
1S
ue e l _ D<.dJ..,. _He nat'" YO.d _ •• IS« ......... 111 l Sn..... o••••n ... '.I·"" "","IDO <0 "" ... J""?-I,
Figure 1.5 The Drinl
fd i~ IIId
sawd wng
Once in the oorr«1 foldcr, you can Ihen your program:
Nol~.
lI$C
thc javac.oe program to cornpilc
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
Your First Java Program rcally what we want to do in order to create Java games. YOIl Qln certainly write a la"a g.lme as an application and run it on a local syst"m, but the real point of this book is to cr"ate lava applets that run in a web browser.
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.
is provided on the CD-ROM, Yoo can optionally download il from
I~port java.allt. ", Illport java.applet.', public chss FI rsUppi et extends Applet I public voId palnt«(;raphlcs 9) l 9.draIlStr1ng( "Thls Is lIy first Java Appletj", 20, 30),
The applet code is a lill1c different from the application-based code in the DrinkJava program. Note the extends Applet code in the class definition and the lack of a static main method. An applel program extends;1 class called Applet, which mcans the applet will receive all of the features of the ApplH class (which has tI\(" ability to run in a w!.'b hrowser). Essentially, all ofth{· complexity of tying in your program with the web browser has been done for you through c1'lss inhcritance (you r program inherits the (eatures of th" Appl et class). You C:ln compile the program with this (Onlnland, javac FirstApplet.java Now, if you happen to be using TextPad, as I am (refer to l'igurel.6), you can compile the program from within TextPad without having to drop to the command prompt to compile it manually, As Figllre 1.7 shows, Textl'ad has a macro that will launch the lava compil!.'r for you and r"port th" results of the compil!.'. If there arc no ",rrors in the Java code, it will report "Tool completed successfully." In order to run an applet, you must provide an IlTMl.container. This is a basic HTt.11. web page containing the code to eml>l.'d an applet on th", page. We'l! be creating one of these containers for every program in the book. But don't worry, it's easy to create an I-lTML container, and the eml~'dded arrlet COOl." is shon and sweet. Create a new file called !'irstApplel,htrnl and enter the following code into this file: F I fS tApp 1~t
Your First Java Progrllm
This contai~r -b pa~ cock indudl'$ an C'tllbnkkd tag with paraII'I
'".IK".......... "~ .......~ ......,01v."..p,... v,, ... p.... j.>~1
'. bill
..
--- ... ..
.....) \ ' - - -
~
,"..,
._,,,.1'1 -_ . .1'1 .... _ __ .....
• •
.. ..
. _-"",';:l"'_
Figure 1.7 Compiling Java
"
19
20
Chapter 1 • Getling Stfrted with Jav
---
_...
--
Figure 1.8
The fintApplft
pRlOpm
is nftIing iMidt lh. Appet
appltt, among other propmics. You can liUso:
~
DOW
uriIiIy.
opm this file with Applet V~
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.
What You Have learned Well, this has been a pmty htavy chapter thai covered a lot of material, but my was to get the Nsics covered so that we can jump right into jaVil game programming in the nat chapter. You learned about:
goal
• Casual gam($, what tl\(y arc, and their importance
Review Questions
_... ...'- -
-
fIgure 1.9 RrstApp"t is IUlming .s an <.'flIbed
,,~
•
, ~.
appI~t
in
Int~mel
ExPorer,
• The Java Development Kit (lDK) and lava versions • Editing and compiling Java code • Standalone Java applications and Java applels
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?
2. What version of Java arc we focusing on in this book?
21
22
Chapler I • Getting Started wilh Java
J. What is
th~ nam~
of lh~ compa.ny lhal cr~aled la,'a?
4. \\'her~ on th~ web ",ill )'OU lind Inc, lext nlilor c
5, In ",'hal '"Car "''as la"a first rckased? 6. Where on 1M ",-dl is lhe primary download
sit~
for lal...?
7. Whal Iypot' of Ina program do you run wilh lhe ja\";l.Cl'C tool~
8. Whal lypc of Java program runs in a wdJ
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~
foUo..ing ~nrci~ 10 lesl mur grasp of Ihe mJ.l~ co,'cre
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
2
.JAVA PROGRAMMING ESSENTIALS
/3V:l is a matuu programming 13ngu3ge thai offers many good features 3nd Q.pabilitiC$ that make it p
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
Chapter". Java Programming Eswntia!s
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.
Web Server Technology Explained The main d ilTerence is lhat Microsoft's web :server (115) and the Apache web :server were wrilten in C++, while JWS was wrillen in Java./WS can host regul;IT HTML web paga and custom Java Server I'ages (151'), which are custom web server programs written in Java. A Java applet is difTerent: An applet is a "dientside" program that runs entirely in the web browser, not on the web server. A Java Ser...er Pages application literally runs on th.. web server and sends contC'TIt to th.. web browser, whi~ an appl~ runs only in the web browser. For this reason, we say thai SCf\'C!" progranu run on the' "back end," while applm run on the' "front end." Microsoft's 115 web SCf\'C!" has gained in popularity and marUt share in rcce'nt yt'ars, thanks in pan to the' new .NET (prollOUlKC'd "dot n~") technology. The latest ...ersion of 115 hosls Acti...e Ser.....r Pages .NET (ASP.NET) pages. which are similar to Java ServCT Pages (lSP) in concept, but ASP.N~" pages are written in Visual Basic or C# (pronounced uSC<'_sharp"). If you don't know much about web servers and web applications, don't worry- we will only be wTiting web diem programs, not :server programs.
Hosting Java Appfets If you really find that you enjoy Java, then you may W;lnt to consider creating or enhancing your own website' with Java applets. You can build an entire website as one large appl~ or you can embed many different apple'lS inside a standard HTML page to enhance your website. One ofthe' st rong suilS of Java is that you don't need any special t)'p<' of web snver in order to use Java on your wrllsite'. Java has been around since 1995. and web browsers h.a...e supported Java since
The Java language I;l\'a 1.1. Microsoft InteTn.... Explol"eT and Morilla Firefox support lhe blesl version ofJava. To update your browser, simply install Java SE 6, and lhe installer will add a plug-in 10 your web browser aUlomatically. This is nc<:essary if you wanl 10 run the exa mples in lhis book-mosl web browsers come wilh an older \·crsion of Java, such as 1.4.
Compiling Java Code The e;\sicst way 10 compile a lava progrJm is by using lhe command-line compiler. A5 you may recall from the previous chapler, you usc the javac.cxe progrnm 10 compile a .java file inlo a .class file. You lhen usc IheappletviCW(:r.cxe program in conjunaion with an .htm! conlainer file with;lJ\ embedded applct tag to run your Java applet in I~ applct viewer program. ¥ou an also open this HTML lcsl file in a web browser to run the applet. Rather lhan using a complex and large Inlegraled Development Environmen t (JOE) 10 build and compile your Java code, I recommend using a simple leXI edilor and t~ command-line tools instead. In l~ previous edition, we' used Borland IBuilder as our IDE of choice. This lime around, we're using just simple lext editors (with TcxtPad bring my cboice in WindoW$). This will impm~ your programming skills and make you a more useful progrnmmeT, since you will nOI be lied 10 any specifi( platform or IDE (such as JBl.lilder). A good texl editor thai I recommend is TcxlPad because il is small and hus the abili ty 10 (ompile (Ctrl+I):;Inc! run (Orl+3) your lava programs. The cost oflhe fuUy regislered version of TcxlPad is II pallry sum compared to the (ost of a full IDE sudl as lBuilder. Of counoe you can also usc any frtt lext edilor as wdl, lbough most do not ha~ Ihe nice buill-in support for lava that TexlPad has. Anolher pair of ahemalives thaI you may (onsider is Net Beans (www.nelbeans. org) and Eclipse (www.cclipse.org). Bolh arc free IDEs wilh varying levels of complexity :;Ind fcaluTC$ Ihal you may want to upgrade 10 whm your Java projects become too brgc to manage wilh a simple file system.
The Java Language There arc lhousands of classes in Java, bUl we will only be using a few oflhem 10 build web :;Ipplets. Now then, I suppose el'en a word like "class" might be a mysteT)' if you arc new to programming. A <:bss is a Klrt of container thai holds both dal:;l and funaions. Do you ha~ any experience with the C++ bnguagrl
25
26
Chapter 2 • Java Programming
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 •
Microsoft Internet Explorer
• !.inux • Mac OS •
Sobris
• Mozilla Firefox • Star OprnOffice I
~ould
go on and on, listing thOUSillJds of operating systetm, producli\ity Cimf d('\'ice dri\ers. compilers. .....semh!ers. interprel...rs. and on and on. ~ppli,at;ons, ,ideo
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 t«hnology aIled garbou coll«rioll 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 coU«tion, 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!).
Java Data Types Let's now learn about the basic data types avaiklblc in Java, because you will be using these data types throughout the book (and presumably for the rtSt of your programming ca re-er). Int~Numben
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 d«imal 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
Table 2.1 kttegel' Oata T)'Ill'S
...".
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 •
Java Programming Essenlials
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
for