advertisement
javaboutique
Search Tips
Articles  |   Tutorials  |   Reviews  |   Tools  |   by Category  |   by Date  |   by Name  |   Submit  |   Source  |   Forums  |  
javaboutique
Browse DevX


Partners & Affiliates











advertisement

Tutorials : The Java Game Development Tutorial :

Contents
Introduction
Basic structure of an applet
Move a ball
Double buffering
Ball bouncing and change the direction
Using sound in applets
Using pictures in applets
Mouse events
Keyboard events
The first complete game
Artificial intelligence for a pong like game
Generation of random 2D landscapes

Our first game

The game idea

In our game, the player has to shoot at two balls, (a red and a blue one), which are flying around in our applet. The direction and speed will be chosen at random; the user can hit a ball by clicking on it with the mouse pointer. If a ball reaches a border of the applet without being hit, the player looses one of his 10 lives. If the player loses all of his lives, the game is over.

Outline of classes and methods

The Main class

This class implements all methods concerning the animation of objects (balls) and "management" of the game. These are init(), start(), stop(), paint(), update(), run(), and mouseDown(), to handle mouse click events. The class also manages all objects, (two ball objects, the player object), and the thread in which the game is running!

  1. init(): Initializes all objects, gets audio data, sets mouse pointer and gets the game speed from a parameter in the HTML - file.
  2. start(): starts thread
  3. stop(): stops thread
  4. run(): moves the balls
  5. paint(...): calls paint methods of the both balls, paints score and life information to the screen. If the game is over it writes out an information text about how well the player has been playing (for example: "You are the champion")
  6. update(...): Implements double buffering
  7. mouseDown (...): Listens to mouse events. If the game is running it is watching out for "player hits ball"; if the game is stopped, (start or over), then it listens for a double click and starts the game (again).
The class Player

This class is very simple. It has two instance variables to store, the score and the lives of the player. There are also two methods to add score, (addScore(int plus)), loose lives, (looseLife) and two methods to transmit these values to the Main class (getScore(), getLifes()). As you see, a pretty simple class.

The class Ball

This class is the most complicated one in the game. It implements all of the important methods for a ball object including the following functions:

  1. Ball(...): Constructor, gets all important attributes of a ball object (color, speed, y - direction, ...) and initializes variables in the ball object.
  2. move(): Method moves the ball and tests by calling isOut() if ball is out which means, player loses one life.
  3. ballWasHit(): This method is called if the ball was hit by the player. Afterwards the new direction of the ball is set at random, and the ball is set back to the start position.
  4. userHit (int x, int y): This method tests with the help of vectors, if ball was hit or not (details later).
  5. isOut(): this method tests if the ball is out. The player loses one life if this is true.
  6. DrawBall(Graphics g): This method draws the ball and is called from the paint method of the Main - class.
How the methods work together:

Everytime we call the run - method in our Main class, we call the move - methods of the ball. This method moves the ball and tests if the ball left the applet area by calling isOut(). If the ball has left the applet area, isOut() calls the looseLife() method of the player object and the number of lives is decreased by one.

Everytime the user clicks in the applet area, the mouseDown method in the Main class is called. This method calls userHit(), which is testing if the ball was hit by the user and returns true if this is the case and returns false if the ball was not hit. If true is returned by userHit() ballWasHit() is called. This method adds the score to the player score, and resets the ball... .

One important thing before we start

It is essential, if you want to understand what I'm doing, that you download the sourcecode and read it while I'm explaining things. I won't explain every step in detail, instead you should read the sourcecode, try to understand those things I'm not talking about with help of the other chapters, and learn things by yourself that way.

Even more important might be that you begin to write your own little programs very soon and try to solve problems on your own. Because every game needs its own, very special solutions and mostly there will be no one to help you to find these. Use this little game and all the other applets and sourcecodes on these pages as blueprints and "dictionarys" which help you to implement your own games. You'll learn most if you try it by yourself!

How to Add Java Applets to Your Site

New on the Java Boutique:

New Review:

Time Management Made Easy with the Quartz Enterprise Job Scheduler
Why not just use the Java timer API? This open source scheduling API boasts simplicity, ease-of-integration, a well-rounded feature set, and it's free!

New Applet:

Reverse Complement
Reverse Complement is a simple applet that converts DNA or RNA sequences into three useful formats.

Elsewhere on internet.com:

WebDeveloper Java
Lots of Java information on webdeveloper.com

WDVL Java
Thorough Java resource at the Web Developer's Virtual Library.

ScriptSearch Java
Hundreds of free Java code files to download.

jGuru: Your View of the Java Universe
Customizable portal with online training, FAQs, regular news updates, and tutorials.

 Avaya DevConnect Center
 Service Component Architecture/Service Data Objects Solution Center
 Intel Go Parallel Portal
 Internet.com eBook Library
 IBM Software Construction Toolbox
 Microsoft RIA Development Center
 Destination .NET
XML error: not well-formed (invalid token) at line 53
advertisement
Receive Articles via our XML/RSS feed
Receive Articles via our XML/RSS feed

JavaBytes
Internet Cyclone
This powerful, easy-to-use, internet optimizer is for Windows 95, 98, ME, NT, 2000 and XP. It's designed to automatically optimize your Windows settings, boosting your Internet connection up to 200%.

Cisco Romancing Linux Developers
MobiUI Snares ActionEngine in iPhone/Mobile Push
Windows 7: It's Not Just a Codename Anymore
Microsoft Shines Silverlight on Eclipse
OpenOffice Hits 3.0: Can It Challenge Microsoft?
Get Ready for Microsoft's 'Oslo' Modeling Tool
Latest Linux Hits Networking Flaws
Metasploit 3.2 Offers More 'Evil Deeds'
'Thank You Apple. Seriously.'
The Buzz: BlackBerry App Store Seen Next

Intel Sees Fewer Power Cords in Your Future
F# 101
Use Explicit Conversion Functions to Avert Reckless Implicit Conversions
Polyglot Programming: Building Solutions by Composing Languages
Automated testing for .NET by Ben Hall
"Supply Chain" SOA with SKOS
Service Component Architecture in Real Life
C++Ox: The Dawning of a New Standard
Getting Started with Virtualization
Master Complex Builds with MSBuild

Advertising Info  |   Member Services  |   Contact Us  |   Help  |   Feedback  |   Site Map  |   Network Map  |   About



JupiterOnlineMedia

internet.comearthweb.comDevx.commediabistro.comGraphics.com

Search:

Jupitermedia Corporation has two divisions: Jupiterimages and JupiterOnlineMedia

Jupitermedia Corporate Info


Legal Notices, Licensing, Reprints, & Permissions, Privacy Policy.

Advertise | Newsletters | Tech Jobs | Shopping | E-mail Offers

Solutions
Whitepapers and eBooks
Microsoft Article: Will Hyper-V Make VMware This Decade's Netscape?
Microsoft Article: BitLocker Encryption on Windows Server 2008
Go Parallel Article: Intel Thread Checker, Meet 20 Million LOC
IBM Whitepaper: Innovative Collaboration to Advance Your Business
Internet.com eBook: Real Life Rails
Avaya Article: Call Control XML - Powerful, Standards-Based Call Control
Tripwire Whitepaper: Seven Practical Steps to Mitigate Virtualization Security Risks
Internet.com eBook: The Pros and Cons of Outsourcing
Internet.com eBook: Best Practices for Developing a Web Site
IBM CXO Whitepaper: The 2008 Global CEO Study "The Enterprise of the Future"
Avaya Article: Call Control XML in Action - A CCXML Auto Attendant
Go Parallel Article: James Reinders on the Intel Parallel Studio Beta Program
IBM CXO Whitepaper: Unlocking the DNA of the Adaptable Workforce--The Global Human Capital Study 2008
Adobe Acrobat Connect Pro: Web Conferencing and eLearning Whitepapers
Go Parallel Article: Getting Started with TBB on Windows
HP eBook: Storage Networking , Part 1
MORE WHITEPAPERS, EBOOKS, AND ARTICLES
Webcasts
Go Parallel Video: Intel(R) Threading Building Blocks: A New Method for Threading in C++
HP Video: Is Your Data Center Ready for a Real World Disaster?
Microsoft Partner Portal Video: Microsoft Gold Certified Partners Build Successful Practices
HP On Demand Webcast: Virtualization in Action
Go Parallel Video: Performance and Threading Tools for Game Developers
Rackspace Hosting Center: Customer Videos
Intel vPro Developer Virtual Bootcamp
HP Disaster-Proof Solutions eSeminar
HP On Demand Webcast: Discover the Benefits of Virtualization
MORE WEBCASTS, PODCASTS, AND VIDEOS
Downloads and eKits
Amyuni Download: PDF & XPS Engine for Your .NET and ActiveX Applications
Microsoft Download: Silverlight 2 Software Development Kit Beta 2
30-Day Trial: SPAMfighter Exchange Module
Red Gate Download: SQL Toolbelt
Iron Speed Designer Application Generator
Microsoft Download: Silverlight 2 Beta 2 Runtime
MORE DOWNLOADS, EKITS, AND FREE TRIALS
Tutorials and Demos
IBM IT Innovation Article: Green Servers Provide a Competitive Advantage
Microsoft Article: Expression Web 2 for PHP Developers--Simplify Your PHP Applications
MORE TUTORIALS, DEMOS AND STEP-BY-STEP GUIDES