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


Partners & Affiliates











advertisement

BreakOut


Java Source:

//
// Breakout game
//
// (C)2000
// Brian Postma
// b.postma@hetnet.nl
//

import java.awt.*;
import java.applet.Applet;

public class Breakout extends Applet implements Runnable
{
  Dimension	d;
  Font 		largefont = new Font("Helvetica", Font.BOLD, 24);
  Font		smallfont = new Font("Helvetica", Font.BOLD, 14);

  FontMetrics	fmsmall, fmlarge;
  Graphics	goff;
  Image		ii;
  Thread	thethread;

  boolean	ingame=false;

  int		player1score;
  int		ballx,bally;
  int		batpos;
  int		batdpos=0;
  int		balldx=0, balldy=0;
  int		dxval;
  int		ballsleft;
  int		count;
  boolean	showtitle=true;
  boolean[]	showbrick;
  int		bricksperline;

  final int	borderwidth=5;
  final int	batwidth=20;
  final int	ballsize=5;
  final int	batheight=5;
  final int	scoreheight=20;
  final int	screendelay=300;
  final int	brickwidth=15;
  final int     brickheight=8;
  final int	brickspace=2;
  final int	backcol=0x102040;
  final int	numlines=4;
  final int     startline=32;

  public String getAppletInfo()
  {
    return("Breakout - by Brian Postma");
  }

  public void init()
  {
    Graphics g;
    d = size();
    setBackground(new Color(backcol));
    bricksperline=(d.width-2*borderwidth)/(brickwidth+brickspace);
    d.width=bricksperline*(brickwidth+brickspace)+(2*borderwidth);
    g=getGraphics();
    g.setFont(smallfont);
    fmsmall = g.getFontMetrics();
    g.setFont(largefont);
    fmlarge = g.getFontMetrics();

    showbrick=new boolean[bricksperline*numlines];
    GameInit();
  }

  public void GameInit()
  {
    batpos=(d.width-batwidth)/2;
    ballx=(d.width-ballsize)/2;
    bally=(d.height-ballsize-scoreheight-2*borderwidth);
    player1score=0;
    ballsleft=3;
    dxval=2;
    if (Math.random()<0.5)
      balldx=dxval;
    else
      balldx=-dxval;
    balldy=-dxval;
    count=screendelay;
    batdpos=0;
    InitBricks();
  }

  public void InitBricks()
  {
    int i;
    for (i=0; i0 && d.height>0)
    {
      ii = createImage(d.width, d.height);
      goff = ii.getGraphics();
    }
    if (goff==null || ii==null)
      return;

    goff.setColor(new Color(backcol));
    goff.fillRect(0, 0, d.width, d.height);
    if (ingame)
      PlayGame();
    else
      ShowIntroScreen();
    g.drawImage(ii, 0, 0, this);
  }


  public void PlayGame()
  {
    MoveBall();
    CheckBat();
    CheckBricks();
    DrawPlayField();
    DrawBricks();
    ShowScore();
  }

  public void ShowIntroScreen()
  {
    String s;

    MoveBall();
    CheckBat();
    CheckBricks();
    BatDummyMove();
    DrawPlayField();
    DrawBricks();
    ShowScore();
    goff.setFont(largefont);
    goff.setColor(new Color(96,128,255));

    if (showtitle)
    {
      s="Java Breakout";
      goff.drawString(s,(d.width-fmlarge.stringWidth(s)) / 2, (d.height-scoreheight-borderwidth)/2 - 20);
      s="(c)2000 by Brian Postma";
      goff.setFont(smallfont);
      goff.setColor(new Color(255,160,64));
      goff.drawString(s,(d.width-fmsmall.stringWidth(s))/2,(d.height-scoreheight-borderwidth)/2 + 10);
      s="b.postma@hetnet.nl";
      goff.drawString(s,(d.width-fmsmall.stringWidth(s))/2,(d.height-scoreheight-borderwidth)/2 + 30);
    }
    else
    {
      goff.setFont(smallfont);
      goff.setColor(new Color(96,128,255));
      s="'S' to start game";
      goff.drawString(s,(d.width-fmsmall.stringWidth(s))/2,(d.height-scoreheight-borderwidth)/2 - 10);
      goff.setColor(new Color(255,160,64));
      s="Use cursor left and right to move";
      goff.drawString(s,(d.width-fmsmall.stringWidth(s))/2,(d.height-scoreheight-borderwidth)/2 + 20);
    }
    count--;
    if (count<=0)
    { count=screendelay; showtitle=!showtitle; }
  }


  public void DrawBricks()
  {
    int i,j;
    boolean nobricks=true;
    int colordelta=255/(numlines-1);

    for (j=0; j=(d.height-ballsize-scoreheight))
    {
      if (ingame)
      {
        ballsleft--;
        if (ballsleft<=0)
          ingame=false;
      }
      ballx=batpos+(batwidth-ballsize)/2;
      bally=startline+numlines*(brickheight+brickspace);
      balldy=dxval;
      balldx=0;
    }
    if (ballx>=(d.width-borderwidth-ballsize))
    {
      balldx=-balldx;
      ballx=d.width-borderwidth-ballsize;
    }
    if (ballx<=borderwidth)
    {
      balldx=-balldx;
      ballx=borderwidth;
    }
  }

  public void BatDummyMove()
  {
    if (ballx<(batpos+2))
      batpos-=3;
    else if (ballx>(batpos+batwidth-3))
      batpos+=3;
  }

  public void CheckBat()
  {
    batpos+=batdpos;

    if (batpos(d.width-borderwidth-batwidth))
      batpos=(d.width-borderwidth-batwidth);

    if (bally>=(d.height-scoreheight-2*borderwidth-ballsize) &&
        bally<(d.height-scoreheight-2*borderwidth) &&
        (ballx+ballsize)>=batpos && ballx<=(batpos+batwidth))
    {
      bally=d.height-scoreheight-ballsize-borderwidth*2;
      balldy=-dxval;
      balldx=CheckBatBounce(balldx,ballx-batpos);
    }
  }

  public int CheckBatBounce(int dy, int delta)
  {
    int sign;
    int stepsize, i=-ballsize, j=0;
    stepsize=(ballsize+batwidth)/8;

    if (dy>0)
      sign=1;
    else
      sign=-1;

    while(ii)
    {
      i+=stepsize;
      j++;
    }
    switch(j)
    {
      case 0:
      case 1:
        return -4;
      case 2:
	return -3;
      case 7:
        return 3;
      case 3:
      case 6:
        return sign*2;
      case 4:
      case 5:
        return sign*1;
      default:
        return 4;
    }
  }

  public void CheckBricks()
  {
    int i,j,x,y;
    int xspeed=balldx;
    if (xspeed<0) xspeed=-xspeed;
    int ydir=balldy;

    if (bally<(startline-ballsize) || bally>(startline+numlines*(brickspace+brickheight)))
      return;
    for (j=0; j=(y-ballsize) && bally<(y+brickheight) &&
              ballx>=(x-ballsize) && ballx<(x+brickwidth))
          {
            showbrick[j*bricksperline+i]=false;
            if (ingame)
              player1score+=(numlines-j);
            // Where did we hit the brick
            if (ballx>=(x-ballsize) && ballx<=(x-ballsize+3))
            { // leftside
              balldx=-xspeed;
            }
            else if (ballx<=(x+brickwidth-1) && ballx>=(x+brickwidth-4))
            { // rightside
              balldx=xspeed;
            }
            balldy=-ydir;
          }
        }
      }
    }
  }

  public void run()
  {
    long  starttime;
    Graphics g;

    Thread.currentThread().setPriority(Thread.MAX_PRIORITY);
    g=getGraphics();

    while(true)
    {
      starttime=System.currentTimeMillis();
      try
      {
        paint(g);
        starttime += 20;
        Thread.sleep(Math.max(0, starttime-System.currentTimeMillis()));
      }
      catch (InterruptedException e)
      {
        break;
      }
    }
  }

  public void start()
  {
    if (thethread == null) {
      thethread = new Thread(this);
      thethread.start();
    }
  }

  public void stop()
  {
    if (thethread != null) {
      thethread.stop();
      thethread = null;
    }
  }
}

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.

 Microsoft RIA Development Center
 IBM Rational Resource Center
 Destination .NET
XML error: not well-formed (invalid token) at line 33
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%.

Free VMware Server 2.0 Now Release Candidate
Linux Player Xandros Grabs Storied Rival Linspire
Hey Enterprise: Here Comes the 3G iPhone
MySpace Opens Profile Portability API
Microsoft Jumps Into Virtualization Fray
Eclipse Ganymede Makes It Easier for Devs
Open Source Nokia a Threat to Microsoft, Google?
Salesforce, Google Head for 2nd on Apps
HP Open Sources Unix File System for Linux
Red Hat Opens Its Network to Space

Build a Generic Histogram Generator for SQL Server
Beyond XML and JSON: YAML for Java Developers
Mastering the Windows Mobile Emulators
Avaya AE Services Provide Rapid Telephony Integration with Facebook
Featured Algorithm: Intel Threading Building Blocks: parallel_reduce
Getting Started with Windows Live Admin Center
Eight Key Practices for ASP.NET Deployment
Java ME User Interfaces: Do It with LWUIT!
Talking VPro: Transcript
Bringing Semantic Technology to the Enterprise

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
IBM eBook: Planning a Service Oriented Architecture
IBM eBook: Choosing the Right Architecture--What It Means for You and Your Business
Microsoft Article: Will Hyper-V Make VMware This Decade's Netscape?
Avaya Article: Using Intelligent Presence to Create Smarter Business Applications
Intel Go Parallel Article: Getting Started with TBB on Windows
Microsoft Article: 7.0, Microsoft's Lucky Version?
Avaya Article: How to Feed Data into the Avaya Event Processor
IBM Article: Developing a Software Policy for Your Organization
Microsoft Article: Managing Virtual Machines with Microsoft System Center
Intel Go Parallel Article: Intel Threading Tools and OpenMP
HP eBook: Storage Networking , Part 1
Microsoft Article: Solving Data Center Complexity with Microsoft System Center Configuration Manager 2007
MORE WHITEPAPERS, EBOOKS, AND ARTICLES
Webcasts
HP Video: StorageWorks EVA4400 and Oracle
HP Webcast: Storage Is Changing Fast - Be Ready or Be Left Behind
Microsoft Silverlight Video: Creating Fading Controls with Expression Design and Expression Blend 2
MORE WEBCASTS, PODCASTS, AND VIDEOS
Downloads and eKits
Red Gate Download: SQL Toolbelt and free High-Performance SQL Code eBook
Iron Speed Designer Application Generator
MORE DOWNLOADS, EKITS, AND FREE TRIALS
Tutorials and Demos
Silverlight 2 App and Walkthrough: Leverage Silverlight 2 with SQL Server and XML
IBM Article: Enterprise Search--Do You Know What's Out There?
HP Demo: StorageWorks EVA4400
Microsoft Article: The Progress and Promise of Deep Zoom
Microsoft How-to Article: Get Going with Silverlight and Windows Live
MORE TUTORIALS, DEMOS AND STEP-BY-STEP GUIDES