2 Replies - 21723 Views - Last Post: 24 May 2011 - 07:57 AM Rate Topic: -----

#1 768682   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 1
  • Joined: 24-May 11

Breakout game in java.

Posted 24 May 2011 - 07:30 AM

I've been working on this Breakout game in java and I've almost have it finished but I've run into one problem. Im trying to add a "kicker" to the game where the ball speeds up after hitting the seventh brick. The ball does speed up after it hits the seventh brick but it passes right through the paddle on its way down! Ive looked at the java api but have not found it to be helpful. Im sure its an easy fix but I'm really just lost. If anyone can point me in the right direction to what the error could be it would be appreciated!


import acm.graphics.*;
import acm.program.*;
import acm.util.*;

import java.applet.*;
import java.awt.*;
import java.awt.event.*;

public class Breakout extends GraphicsProgram 
{

	int score = 0;

	//width of game display
	private static final int WIDTH = 400; 
	
	//height of game display
	private static final int HEIGHT = 600; 
	
	//width of paddle
	private static final int PADDLE_WIDTH = 60; 
	
	//height of paddle
	private static final int PADDLE_HEIGHT = 10; 
	
	//offset of paddle up from the bottom
	private static final int PADDLE_Y_OFFSET = 560; 
	
	//number of bricks per row
	private static final int NBRICKS_PER_ROW = 10; 
	
	//number of rows of bricks
	private static final int NBRICK_ROWS = 10; 
	
	//separation between bricks
	private static final int BRICK_SEP = 4; 
	
	//width of each brick (based on the dimensions of the game display)
	private static final int BRICK_WIDTH = WIDTH / NBRICKS_PER_ROW - BRICK_SEP;
	
	//height of brick
	private static final int BRICK_HEIGHT = 8;
	
	//radius of ball in pixels
	private static final int BALL_RADIUS = 6; 
	
	//offset of the top brick row from top
	private static final int BRICK_Y_OFFSET = 70; 
	
	//number of turns
	private static final int NTURNS = 3;
	
	//the paddle
	private GRect paddle;
	
	//the ball
	private GOval ball;
	
	//the scorelabel
	GLabel scoreLabel = new GLabel("Score: " + score, 25,30);

	//ball velocity in both directions (x-direction, and y-direction)
	private double vx, vy;
	
	//records the last x position of the mouse (see mouseMoved method)
	private double lastX;
	
	//used for mouse events (only moves the paddle every 5th mouse move)
	private int toggle = 0;
	
	//main method -- called when the program is run
	public static void main(String[] args)
	{
		String[] sizeArgs = { "width=" + WIDTH, "height=" + HEIGHT };
		new Breakout().start(sizeArgs);
	}
	
	//run method -- called indirectly from the main method
	public void run()
	{
		setup();
		waitForClick();
		play();
		
	}
	
	//setup method -- called from the run method
	public void setup()
	{
		createBricks();
		createPaddle();
		createBall();
		addMouseListeners();
		add(scoreLabel);
		scoreLabel.setFont(new Font("Comic Sans",Font.BOLD,28));
	}
	
	
	//createBricks method -- called from the setup method
	public void createBricks()
	{
	
	GImage breakout = new GImage("breakout.png", 1,1);
	breakout.setSize(400,600);
		add(breakout);
		//make the bricks
		for(int x = 0; x < NBRICK_ROWS; x++)
		{
			for(int y = 0; y < NBRICKS_PER_ROW; y++)
			{
				GRect brick = new GRect((y * BRICK_WIDTH) + BRICK_SEP*y + BRICK_SEP/2, 
											BRICK_Y_OFFSET + (BRICK_HEIGHT * x) + BRICK_SEP*x, 
												BRICK_WIDTH, 
													BRICK_HEIGHT);
				brick.setFilled(true);

		if(x <= 0)
               {
                  brick.setFillColor(Color.BLACK);
               }
               else if(x <= 1)
               {
                  brick.setFillColor(Color.RED);
               }
               else if(x <= 2)
               {
                  brick.setFillColor(Color.RED);
               }
               else if(x <= 3)
               {
                  brick.setFillColor(Color.ORANGE);
               }
               else if(x <= 4)
               {
                  brick.setFillColor(Color.YELLOW);
               }
					else if(x <= 5)
               {
                  brick.setFillColor(Color.GREEN);
               }

					else if(x <=6)
               {
                  brick.setFillColor(Color.CYAN);
               }
					else if(x <= 7)
               {
                  brick.setFillColor(Color.BLUE);
               }
					else if(x <= 8)
               {
                  brick.setFillColor(Color.BLUE);
               }
					else if(x <= 9)
               {
                  brick.setFillColor(Color.MAGENTA);
               }
			
				add(brick);
			}
		}
	}
	
	//createPaddle method -- called from the setup method
	public void createPaddle()
	{
		paddle = new GRect(0,560,PADDLE_WIDTH,PADDLE_HEIGHT);
		paddle.setFilled(true);
		paddle.setFillColor(Color.BLACK);
		add(paddle);

	}
	
	//createBall method -- called from the setup method
	public void createBall()
	{
			ball = new GOval(175, 375, 10, 10);
			ball.setFilled(true);
			ball.setFillColor(Color.WHITE);
			add(ball);
	}
	
	//play method -- called from the run method after setup
	public void play()
	{
		startTheBall();
		playBall();
	}
	
	//startTheBall method -- called from the play method
	public void startTheBall()
	{
		RandomGenerator rgen = new RandomGenerator();
		vx = rgen.nextDouble(1.0, 3.0);
         if (rgen.nextBoolean(0.5)) vx = -vx;
         vy = 4.0;

		
	}
	
	//Counts the score. 10 points per brick. :]
	 public void getScore()
      {
         scoreLabel.setLabel("Score: " + score);
		if(score == 70)
		{
			vy = 5.0;
		}
		if(score == 100)
		{
			ball.setFillColor(Color.MAGENTA);
		}
				if(score == 200)
		{
			ball.setFillColor(Color.BLUE);
		}
				if(score == 300)
		{
			ball.setFillColor(Color.BLUE);
		}
				if(score == 400)
		{
			ball.setFillColor(Color.CYAN);
		}
				if(score == 500)
		{
			ball.setFillColor(Color.GREEN);
		}
				if(score == 600)
		{
			ball.setFillColor(Color.YELLOW);
		}
				if(score == 700)
		{
			ball.setFillColor(Color.ORANGE);
		}
				if(score == 800)
		{
			ball.setFillColor(Color.RED);
		}
				if(score == 900)
		{
			ball.setFillColor(Color.BLACK);
		}

		if(score == 1000)
		{
			GLabel winner = new GLabel("", 25, 390);
			winner.setFont(new Font("Comic Sans",Font.BOLD,28));
			winner.setLabel("GAME OVER: YOU WIN!");
			add(winner);
		}

	}

	
	//playBall method -- called from the play method
	public void playBall()
	{
		//continuous loop
		while(true)
		{
			getScore();
			//move the ball
			ball.move(vx, vy);
			//pause
			pause(15);
			
			//check for contact along the outer walls
			
			/**********************************************/
        	/*                       			          */
        	/* if ball contacts the floor,		          */
        	/* reverse the y velocity 				      */
        	/*                      				      */
        	/* otherwise, if ball contacts the ceiling,	  */
        	/* reverse the y velocity 				      */
        	/*                      				      */
        	/* otherwise, if ball contacts the left wall, */
        	/* reverse the x velocity 				      */
        	/*                      				      */
        	/* otherwise, if ball contacts the right wall,*/
        	/* reverse the x velocity 				      */
        	/*                      				      */
        	/**********************************************/
		
				if(ball.getX() <= 0)
            {
               vx = -vx;
            }
            if(ball.getX() >= 400)
            {
               vx = -vx; 
            }
            if(ball.getY() <= 0)
            {
               vy = -vy;
            }
			if(ball.getY() >= 600)
			{
				GLabel loser = new GLabel("", 5, 380);
				loser.setFont(new Font("Comic Sans",Font.BOLD,22));
				loser.setLabel("GAME OVER! CLICK TO PLAY AGAIN.");
				add(loser);
				remove(ball);	
				waitForClick();
				score = 0;
				setup();
				waitForClick();
				play();

				
			}


			
			//check for collisions with bricks or paddle
			GObject collider = getCollidingObject();
			
			//if the ball collided with the paddle 
			if(collider == paddle)
			{
				//reverse the y velocity
				vy = -vy;
				
			}
			//otherwise if the ball collided with a brick
			else if(collider instanceof GRect) 
			{
				//reverse y velocity
				vy = -vy;
				//remove the brick
				remove(collider);
				score = score + 10;
				
			}
		}
	}
	
	//getCollidingObject -- called from the playBall method
	//discovers and returns the object that the ball collided with
	private GObject getCollidingObject()
	{
		if(getElementAt(ball.getX(), ball.getY()) != null)
			return getElementAt(ball.getX(), ball.getY());
		else if(getElementAt(ball.getX()+BALL_RADIUS*2, ball.getY()) != null)
			return getElementAt(ball.getX()+BALL_RADIUS*2, ball.getY());
		else if(getElementAt(ball.getX()+BALL_RADIUS*2, ball.getY()+BALL_RADIUS*2) != null)
			return getElementAt(ball.getX()+BALL_RADIUS*2, ball.getY()+BALL_RADIUS*2);
		else if(getElementAt(ball.getX(), ball.getY()+BALL_RADIUS*2) != null)
			return getElementAt(ball.getX(), ball.getY()+BALL_RADIUS*2);
		else	
			return null;
	}
		
	//mouseMoved method -- called by the mouseListener when the mouse is moved
	//anywhere within the boundaries of the run window
	public void mouseMoved(MouseEvent e)
	{
		//only move the paddle every 5th mouse event 
		//otherwise the play slows every time the mouse moves
		if(toggle == 5)
		{
			//get the x-coordinate of the mouse
			double eX = e.getX();
			
			//if the mouse moved to the right
	        if(eX - lastX > 0)
	        {
	        	//if paddle is not already at the right wall
	        	if(paddle.getX() < WIDTH - PADDLE_WIDTH)
	        	{
	        		//move to the right
	        		paddle.move(eX - lastX, 0);
	        	}
	        }
	        else //(if the mouse moved to the left)
	        {
	        	//if paddle is not already at the left wall
	        	if(paddle.getX() > 0)
	        	{
	        		//move to the left
	        		paddle.move(eX - lastX, 0);
	        	}
	        }
	        	
	        //record this mouse x position for next mouse event         	
	        GPoint last = new GPoint(e.getPoint());
			lastX = last.getX();
			
			//reset toggle to 1 
			toggle = 1;
		}
		else
		{
			//increment toggle by 1
			//(when toggle gets to 5 the code will move the paddle 
			// and reset toggle back to 1)
			toggle++;
		}
		

		
	}

}



Is This A Good Question/Topic? 0
  • +

Replies To: Breakout game in java.

#2 pbl   User is offline

  • There is nothing you can't do with a JTable
  • member icon

Reputation: 8381
  • View blog
  • Posts: 31,956
  • Joined: 06-March 08

Re: Breakout game in java.

Posted 24 May 2011 - 07:35 AM

This is a pure vanilla Java forum for people using Java and its API
I doubt you will have support for and external library like acm... anyhow may be a member of our group is familiar with it

In any cases pleae :code:Which you did... sorry

This post has been edited by pbl: 24 May 2011 - 07:38 AM
Reason for edit:: Apologise

Was This Post Helpful? 0
  • +
  • -

#3 LakeTahoe   User is offline

  • New D.I.C Head

Reputation: 5
  • View blog
  • Posts: 14
  • Joined: 18-May 11

Re: Breakout game in java.

Posted 24 May 2011 - 07:57 AM

Most likely the ball's movement path has a Y value just before and just after the paddle, so the collision never really happens. A probable fix for this is to check to see if the ball and paddle's X bounds match each other, and if the ball's Y is below the paddles, it rebounds it. Something else that might work is checking if the ball is inside the paddle's bounds, assuming the getElementAt() doesn't already handle this.

End result is that the ball is never actually on the paddle, and can't rebound because it never collides mathematically. If nothing I mentioned above works, I suggest at least trying to have the ball update twice as fast, and halve movement distance so it might actually come into contact.
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1