I'm trying to learn java by following the cs106a course online.
Currently I've arrived at the breakout exersize and I'm having some trouble with bugs
I haven't finished it completely but I want to solves these issues first before I go further.
Problem 1:
when the ball collides with the bricks they don't always seem to be removed from the canvas.
sometimes the brick will be removed on a second time it collides. But there is one row (of yellow bricks) that doesn't respond at all to the ball collisions.
Problem 2:
my paddle can be moved by dragging the mouse. the only problem is. the bricks can also be moved like the paddle.
I know it has something to do with this piece of code
gobj = getElementAt(lastX, lastY);
If I remove it altogether the bricks aren't moveable anymore. which is good. but I'm still
able to move the paddle no matter where I click and drag.
can anyone give me a hint so I can correct the mistakes?
Here's my code below.
Thanks
/*
* File: Breakout.java
* -------------------
* This file will eventually implement the game of Breakout.
*/
import acm.graphics.*;
import acm.program.*;
import acm.util.*;
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
import org.omg.CORBA.PUBLIC_MEMBER;
public class breakout extends GraphicsProgram {
/** Width and height of application window in pixels */
public static final int APPLICATION_WIDTH = 400;
public static final int APPLICATION_HEIGHT = 600;
/** Dimensions of game board (usually the same) */
private static final int WIDTH = APPLICATION_WIDTH;
private static final int HEIGHT = APPLICATION_HEIGHT;
/** Dimensions of the paddle */
private static final int PADDLE_WIDTH = 60;
private static final int PADDLE_HEIGHT = 10;
/** Offset of the paddle up from the bottom */
private static final int PADDLE_Y_OFFSET = 30;
/** Number of bricks per row */
private static final int NBRICKS_PER_ROW = 10;
/** Number of rows of bricks */
private static final int NBRICK_ROWS = 8;
/** Separation between bricks */
private static final int BRICK_SEP = 4;
/** Width of a brick */
private static final int BRICK_WIDTH = (WIDTH - (NBRICKS_PER_ROW - 1)* BRICK_SEP)/ NBRICKS_PER_ROW;
/** Height of a brick */
private static final int BRICK_HEIGHT = 8;
/** Radius of the ball in pixels */
private static final int BALL_RADIUS = 10;
/** Offset of the top brick row from the top */
private static final int BRICK_Y_OFFSET = 70;
/** Number of turns */
private static final int NTURNS = 3;
private static final int DELAY = 50;
private static final double X_START = WIDTH / 2;
private static final double Y_START = 450;
public void run() {
world();
play();
}
private void ball() {
ball = new GOval(X_START, Y_START, BALL_RADIUS, BALL_RADIUS);
ball.setFillColor(Color.BLACK);
ball.setFilled(true);
add(ball);
}
private void paddle() {
paddle = new GRect(100, 500, PADDLE_WIDTH, PADDLE_HEIGHT);
paddle.setColor(Color.BLACK);
paddle.setFilled(true);
add(paddle);
}
private void brick(int x, int y, Color c) {
GRect brick = new GRect(x, y, BRICK_WIDTH, BRICK_HEIGHT);
brick.setColor(getBackground());
brick.setFillColor(c);
brick.setFilled(true);
add(brick);
}
private void brickRow(int x, int y, Color c) {
x = BRICK_SEP / 2;
y += BRICK_Y_OFFSET;
for (int i = 0; i < NBRICKS_PER_ROW; i++) {
brick(x, y, c);
x += BRICK_WIDTH + BRICK_SEP;
}
}
private void world() {
//initialize x and y position for the rows of bricks
int x = 0;
int y = 0;
// set starting color for first row
Color c = Color.red;
paddle();
//create 2 rows of bricks and switch colors
for (int i = 0; i < NBRICK_ROWS; i++) {
if (i <= 1) {
c = Color.ORANGE;
} else if (i > 1 && i <= 3) {
c = Color.YELLOW;
} else if (i > 3 && i <= 5) {
c = Color.GREEN;
} else if (i > 5 && i <= 7) {
c = Color.CYAN;
}
brickRow(x, y, c);
y += BRICK_HEIGHT + BRICK_SEP;
}
}
private void moveBall() {
ball.move(xVel, yVel);
}
public void mousePressed(MouseEvent e) {
lastX = e.getX();
lastY = e.getY();
gobj = getElementAt(lastX, lastY);
}
public void mouseDragged(MouseEvent e) {
if (paddle != null) {
paddle.move(e.getX() - lastX, getY());
lastX = e.getX();
lastY = e.getY();
}
//constrain paddle movement
if (paddle.getX() < 0){
paddle.setLocation(0, 500);
}else if (paddle.getX()+BRICK_WIDTH > WIDTH ){
paddle.setLocation(WIDTH-BRICK_WIDTH, 500);
}
}
private void checkForCollision() {
// ball collission with walls
if (ball.getY() > getHeight() - BALL_RADIUS
|| ball.getY() < 0 + BALL_RADIUS) {
yVel = -yVel;
} else if (ball.getX() > getWidth() - BALL_RADIUS
|| ball.getX() < 1 + BALL_RADIUS) {
xVel = -xVel;
// ball collission with paddle
} else if (getElementAt(ball.getX() + BALL_RADIUS, ball.getY()
+ BALL_RADIUS) == paddle) {
yVel = -yVel;
// check for collision with bricks to remove them but ignore collision with paddle
} else if (getElementAt(ball.getX(), ball.getY()) != null
&& getElementAt(ball.getX(), ball.getY()) != paddle) {
remove(getCollidingObject(ball.getX(), ball.getY()));
yVel = -yVel;
} else if (getElementAt(ball.getX() + BALL_RADIUS, ball.getY()
+ BALL_RADIUS) != null
&& getElementAt(ball.getX() + BALL_RADIUS, ball.getY()
+ BALL_RADIUS) != paddle) {
remove(getCollidingObject(ball.getX() + BALL_RADIUS, ball.getY()
+ BALL_RADIUS));
yVel = -yVel;
} else if (getElementAt(ball.getX() + BALL_RADIUS, ball.getY()
+ BALL_RADIUS) != null
&& getElementAt(ball.getX() + BALL_RADIUS, ball.getY()
+ BALL_RADIUS) != paddle) {
remove(getCollidingObject(ball.getX() + BALL_RADIUS, ball.getY()
+ BALL_RADIUS));
yVel = -yVel;
} else if (getElementAt(ball.getX(), ball.getY() + BALL_RADIUS) != null
&& getElementAt(ball.getX(), ball.getY() + BALL_RADIUS) != paddle) {
remove(getCollidingObject(ball.getX(), ball.getY() + BALL_RADIUS));
yVel = -yVel;
}
}
private void play() {
addMouseListeners();
ball();
while (true) {
checkForCollision();
moveBall();
pause(DELAY);
}
}
private GObject getCollidingObject(double x, double y) {
return getElementAt(x, y);
}
private double lastX;
private double lastY;
private double xVel = 5;
private double yVel = 15;
private GOval ball;
private GRect paddle;
private GObject gobj;
}
Why don't you use suggested method in handout 19:
private GObject getCollidingObject()
use also collider:
GObject collider = getCollidingObject();
First of all separate your conditions with walls collisions and (paddle with bricks) game elements collisions into two separate methods cause to simplify else if cascading (decomposition I think you know what it means). You have only two objects what you should worry about paddle and bricks, so you need to compare only on (collider == paddle) and collider != null. Also you use only radius in comparisons but should use diameter (2 * radius). Have fun :)
You're y step for each movement of the ball is too large at 15. Since each brick is only 8 in height, at times you're bypassing the brick before evaluating whether that location contained an object or not. E.g. Lets assume you're last evaluation left you're ball with a Y location of 20 and the closest brick is only length of 2 away. You're next evaluation will not include this brick since you move 15 and the height of the brick is 8, meaning range of y values 22 to 30. You'll be out by 5 away from this brick in you're next evaluation. I know the values should be inverted considering the location of the bricks, but you get the point...
With smaller steps in y values collisions will be checked more regularly and provided you make the step small enough, remove this problem.
Related
I'm trying to create a Roomba program with a ball that bounces around the screen that cleans the tiles that it passes over. The program should start with all grey tiles and when the ball passes over them then the tiles turn white. Currently I have the ball that bounces around everywhere and a grid method which creates a 5x5 grid.
I have encountered two problems:
I cannot make the grid and the ball appear in the same simulation while running the program, it's either one or the other.
I'm having trouble with finding a way to analyze if the ball has passed over certain squares in the grid, perhaps I need to create an object for the grid/ball?
My code:
import edu.princeton.cs.introcs.StdDraw;
public class Roomba {
private static int windowWidth = 200;
private static int windowHeight = 200;
private static double x = 100;
private static double y = 100;
private static double vx = 2;
private static double vy = 4;
private static int radius = 5;
private static boolean inGame = true;
public static void updateLocations() {
x += vx;
y += vy;
}
public static void drawGrid() {
StdDraw.setScale(0, 5);
int[][] grid = new int[5][5];
for (int x = 0; x < grid.length; x++) {
for (int y = 0; y < grid.length; y++) {
grid[x][y] = 255;
}
}
for (int x = 0; x < grid.length; x++) {
for (int y = 0; y < grid.length; y++) {
StdDraw.square(x, y, 1);
}
}
}
public static void updateVelocities() {
if (y + radius >= windowHeight) {
vy = -vy;
} else if (y - radius <= 0) {
vy = -vy;
}
if (x >= 194 || x <= 6) {
vx = -vx;
}
}
public static void setBackground() {
StdDraw.clear(StdDraw.GRAY);
// drawGrid();
}
public static void drawBall() {
StdDraw.setPenColor(StdDraw.BLACK);
StdDraw.filledCircle(x, y, radius);
// StdDraw.setPenColor(StdDraw.RED);
// StdDraw.filledSquare(x + 3, y + 3, 1);
StdDraw.setPenColor(StdDraw.BLACK);
StdDraw.text(100, 70, "x is: " + x + " y is: " + y);
}
public static void draw() {
setBackground();
drawBall();
}
public static void main(String[] args) {
StdDraw.setCanvasSize(800, 800);
StdDraw.setXscale(0, windowWidth);
StdDraw.setYscale(0, windowHeight);
while (true) {
if (inGame) {
draw();
updateVelocities();
updateLocations();
} else {
StdDraw.text(100, 100, "Game Over");
}
// change to if all tiles have been cleaned
// if (x + radius > windowWidth || x - radius < 0) {
// inGame = false;
// }
StdDraw.show(20);
}
}
}
Maybe the background is being drawn over the ball or vice verse? Try to draw the ball first then the background? Make sure the ball is actually being rendered at the correct size and not as the entire screen. I'm not to familiar with 2D graphics but maybe there is some z fighting?
I am studying java with the book "The Art and Science of Java: An Introduction to Computer Science". One of the practice programs is to create a simple clone of the Breakout game.
I am currently able to load the game, but am having issues with the ball physics. I'm using the simplest physics possible, and can't see why it isn't working.
When the ball hits a wall, it bounces normally, but when it hits the paddle or a brick, it doesn't. I'm using the same code in the collision detection to change the direction that I used with the walls. The collisions are detected, I added a println and watched the console as it went through the collision events, but the direction change is not happening.
package chapter10;
/*
* This program creates a clone of the classic Breakout Game,
* where a player bounces a ball with a paddle to "break" bricks
* along the top of the screen.
*
* Controls: Left: left button, Right: right button
*/
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.RepaintManager;
import javax.swing.Timer;
import acm.program.*;
import acm.graphics.*;
public class BreakoutClone extends GraphicsProgram {
/* components */
private GRect paddle;
private GRect brick;
private GOval ball;
/* static variables */
private static final double PADDLE_HEIGHT = 5;
private static final double BALL_SPEED = 2;
private static final double PADDLE_SPEED = 2;
private static final double ROWS_BRICKS = 6;
private static final double COLUMNS_BRICKS = 10;
private static final double TOP_GAP = 50;
/* variables */
private int numTurns = 3;
private double paddleWidth = 50;
private int dx = 2;
private int dy = 2;
public void init() {
setSize(700, 600);
paddle = new GRect(0, getHeight() - 30, paddleWidth, PADDLE_HEIGHT);
paddle.setFilled(true);
add(paddle);
addBricks();
ball = new GOval(getWidth() / 2, 175, 5, 5);
ball.setFilled(true);
add(ball);
}
public void run() {
animateBall();
// TODO animate paddle
}
public void addBricks() {
double gap = 20;
double brickWidth = getWidth() / COLUMNS_BRICKS;
for (int r = 0; r < ROWS_BRICKS; r++) {
for (int b = 0; b < COLUMNS_BRICKS; b++) {
brick = new GRect(b * brickWidth, gap * r + TOP_GAP,
brickWidth, 10);
brick.setFilled(true);
add(brick);
}
}
}
public void endGame() {
// TODO write end game method
}
public void animateBall() {
while (numTurns > 0) {
ball.move(dx, dy);
pause(15);
/* Look for Object Collision */
GObject topRightObject = getElementAt(ball.getX() + 5, ball.getY());
GObject topLeftObject = getElementAt(ball.getX(), ball.getY());
GObject botRightObject = getElementAt(ball.getX() + 5,
ball.getY() + 5);
GObject botLeftObject = getElementAt(ball.getX(), ball.getY() + 5);
/* Bounce off walls */
if ((ball.getX() >= getWidth() - 5) || ball.getX() <= 0) {
dx = -dx;
}
if (ball.getY() <= 0) {
dy = -dy;
}
if ((ball.getY() >= getHeight() - 5)) {
dy = -dy;
// numTurns--;
// if (numTurns == 0) {
// endGame();
// } else {
// run();
// }
}
/* Bounce off objects, remove bricks */
if (topRightObject != null) {
dy = -dy;
hasCollided(topRightObject);
}
if (topLeftObject != null) {
dy = -dy;
hasCollided(topLeftObject);
}
if (botRightObject != null) {
dy = -dy;
hasCollided(botRightObject);
}
if (botLeftObject != null) {
dy = -dy;
hasCollided(botLeftObject);
}
}
}
private void hasCollided(GObject obj) {
if (obj.equals(paddle)) {
System.out.println("detecting paddle");
} else {
System.out.println("detecting brick");
remove(obj);
}
}
}
Add an if(dy<0) around the part that reverses direction of the ball when it hits the paddle (assuming a negative dy means the ball is heading towards the paddle). This removes the possibility that your direction is being changed, but more than once per collision
private void addBricks(){
for (int i = 0; i < NBRICK_ROWS; i++){
for (int j = 0; j < NBRICKS_PER_ROW; j++){
int y = BRICK_Y_OFFSET + (i * (BRICK_HEIGHT + BRICK_SEP));
int x = (BRICK_X_OFFSET) + (j * (BRICK_WIDTH + BRICK_SEP));
brick = new GRect (x, y, BRICK_WIDTH, BRICK_HEIGHT );
add (brick);
}
}
}
I am trying to make a breakout game here and this is a snippet of code.
I have added a set of rectangles to my canvas. Later in my program I would like to remove some of them when the ball hits them. The problem is that I do not know how to refer to them specifically. That is to say that I do not know what parameters to input in remove() since all of them were created as brick
Thanks!
Whole program below
import acm.graphics.*;
import acm.program.*;
import acm.util.*;
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
public class Breakout extends GraphicsProgram {
/** Width and height of application window in pixels */
public static final int APPLICATION_WIDTH = 440;
public static final int APPLICATION_HEIGHT = 660;
/** Dimensions of game board (usually the same) */
private static final int WIDTH = 400;
private static final int HEIGHT = 600;
/** Dimensions of the paddle */
private static final int PADDLE_WIDTH = 60;
private static final int PADDLE_HEIGHT = 10;
/** Offset of the paddle up from the bottom */
private static final int PADDLE_Y_OFFSET = 30;
/** 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 a brick */
private static final int BRICK_WIDTH =
(WIDTH - (NBRICKS_PER_ROW - 1) * BRICK_SEP) / NBRICKS_PER_ROW;
/** Height of a brick */
private static final int BRICK_HEIGHT = 8;
/** Radius of the ball in pixels */
private static final int BALL_RADIUS = 10;
/** Offset of the top brick row from the top */
private static final int BRICK_Y_OFFSET = 70;
/** Offset of the side bricks from the sides of game window so that the whole set of bricks are in the centre */
private static final int BRICK_X_OFFSET = ((WIDTH - NBRICKS_PER_ROW * (BRICK_WIDTH + BRICK_SEP) + BRICK_SEP) / 2);
/** Number of turns */
private static final int NTURNS = 3;
/** Game speed */
private static final int DELAY = 1;
/* Method: run() */
/** Runs the Breakout program. */
public void run() {
addMouseListeners();
addWorld();
runGame();
}
private void addWorld(){
setSize (APPLICATION_WIDTH, APPLICATION_HEIGHT);
addPlayingBox();
addBricks();
addPaddle();
}
/* lives and number of bricks will be check before game runs
* if there are either no lives of bricks left game is over
* ball and ball physics are only added to the screen after there is a mouse click.
*/
private void runGame(){
while (true){
// add a gameover label
waitForClick();
addBall();
addBallMotion();
}
}
//adds the playing area onto screen
private void addPlayingBox(){
topBounds = new GLine (0, 0, WIDTH, 0);
bottomBounds = new GLine (0, HEIGHT, WIDTH, HEIGHT);
leftBounds = new GLine (0, 0, 0, HEIGHT);
rightBounds = new GLine (WIDTH, 0, WIDTH, HEIGHT);
add (topBounds);
add (bottomBounds);
add (leftBounds);
add (rightBounds);
}
/*bricks are added to the top row and left column 1st and consequently to the its right column
* and to the next row when a row is all filled up
*/
private void addBricks(){
for (int i = 0; i < NBRICK_ROWS; i++){
for (int j = 0; j < NBRICKS_PER_ROW; j++){
int y = BRICK_Y_OFFSET + (i * (BRICK_HEIGHT + BRICK_SEP));
int x = (BRICK_X_OFFSET) + (j * (BRICK_WIDTH + BRICK_SEP));
brick = new GRect (x, y, BRICK_WIDTH, BRICK_HEIGHT );
colorBrick(brick, i);
add (brick);
}
}
}
// every consecutive 2 rows are colored the same
private void colorBrick(GRect brick, int rowNumber){
brick.setFilled (true);
switch (rowNumber + 1) {
case 1: case 2: brick.setColor(Color.red);
break;
case 3: case 4: brick.setColor(Color.orange);
break;
case 5: case 6: brick.setColor(Color.yellow);
break;
case 7: case 8: brick.setColor(Color.green);
break;
case 9: case 10:brick.setColor(Color.cyan);
break;
}
}
//adds paddle to screen
private void addPaddle(){
paddle = new GRect (WIDTH / 2 - PADDLE_WIDTH / 2, HEIGHT - PADDLE_Y_OFFSET, PADDLE_WIDTH, PADDLE_HEIGHT);
paddle.setFilled(true);
paddle.setColor (Color.BLACK);
add (paddle);
}
//creates motion for the paddle according to mouse movement
public void mouseMoved(MouseEvent e){
paddle.setLocation ((e.getX() - PADDLE_WIDTH / 2), (double) (HEIGHT - PADDLE_Y_OFFSET));
/* checks if the paddle within the playing area
* if not, the paddles will stay at the extremities*/
if ( paddle.getX() > (WIDTH - PADDLE_WIDTH)){
paddle.setLocation((double) (WIDTH - PADDLE_WIDTH), (double) (HEIGHT - PADDLE_Y_OFFSET));
}
if ( paddle.getX() < 0){
paddle.setLocation((double) 0, (double) (HEIGHT - PADDLE_Y_OFFSET));
}
}
/* creates the ball
*/
private void addBall(){
double ballInitXPosition = WIDTH / 2 - BALL_RADIUS;
double ballInitYPosition = HEIGHT / 2 - BALL_RADIUS;
ball = new GOval (ballInitXPosition, ballInitYPosition,
BALL_RADIUS * 2, BALL_RADIUS * 2);
ball.setFilled(true);
ball.setColor(Color.BLACK);
add (ball);
}
/* kick start the ball motion with predetermined values
*/
private void addBallMotion(){
// y component of starting velocity; pixels per second
vy = 0.3;
/* x component of starting velocity; pixels per second
* which ranges according to the random generator
* can be negative or positive, ball can go left or right with equal chances
* angle must not be 0 or 180 degrees otherwise the ball will not move anywhere else
*/
vx = rgen.nextDouble(0.0, 0.5);
if (rgen.nextBoolean(0.5)){
vx = -vx;
}
while (true){
ball.move(vx, vy);
checkCollision();
pause(DELAY);
}
}
private void checkCollision(){
checkWallCollision();
checkBrickAndPaddleCollision();
}
//checks for wall collision
private void checkWallCollision(){
if ( (getCollidingObject() == leftBounds) || (getCollidingObject() == rightBounds )){
vx = -vx;
}
//checks for floor and ceiling collision collision
if ( (getCollidingObject() == topBounds) ){
vy = -vy;
}
if ( (getCollidingObject() == bottomBounds)){
remove (ball);
runGame();
}
}
/* check if there is any collision with brick or paddle
*/
private void checkBrickAndPaddleCollision(){
GObject collider = getCollidingObject();
/* brick is removed and y direction of ball is reversed
* bricks counter goes down by 1 and score goes up by 1
*/
if (collider != paddle &&
collider != null &&
collider != topBounds &&
collider != rightBounds &&
collider != bottomBounds &&
collider != leftBounds){
remove(collider);
vy = -vy;
}
/* collide with paddle, y direction is reversed
*/
else if (collider == paddle){
vy = -vy;
}
}
//check for collision at the 4 sides of the ball
//starting with the top and going clockwise
//returns the object nearest to the screen that touches the sides of the ball
private GObject getCollidingObject(){
GObject ballTop = getElementAt ( (ball.getX() + BALL_RADIUS), (ball.getY() - .1) );
GObject ballRight = getElementAt ( (ball.getX() + (BALL_RADIUS * 2) + .1), (ball.getY() + BALL_RADIUS) );
GObject ballBottom = getElementAt ( (ball.getX() + BALL_RADIUS), ball.getY() + (BALL_RADIUS * 2) + .1);
GObject ballLeft= getElementAt ( (ball.getX() - .1), (ball.getY() + BALL_RADIUS) );
if (ballTop != null){
return (ballTop);
}
else if (ballRight != null){
return (ballRight);
}
else if (ballBottom != null){
return (ballBottom);
}
else if (ballLeft != null){
return (ballLeft);
}
return (null);
}
private GRect paddle; // creates a paddle that only moves linearly according to mouses' x coordinate
private GRect brick;
private GOval ball;
private double vx, vy; // x and y components of the ball's velocity
private RandomGenerator rgen = RandomGenerator.getInstance();
// creates a bounding box that is the playing area
private GLine topBounds;
private GLine bottomBounds;
private GLine leftBounds;
private GLine rightBounds;
}
You'll have to maintain a separate mapping of which bricks exist. I imagine you'd need something like this to do collision detection as well. I would do something like the following.
public class Game
{
Collection<Brick> bricks;
Ball ball;
public void initLocation()
{
for (int i = 0; i < NBRICK_ROWS; i++)
{
for (int j = 0; j < NBRICKS_PER_ROW; j++)
{
int y = BRICK_Y_OFFSET + (i * (BRICK_HEIGHT + BRICK_SEP));
int x = (BRICK_X_OFFSET) + (j * (BRICK_WIDTH + BRICK_SEP));
bricks.add(new Brick(x, y));
}
}
}
public void drawBricks()
{
for (Brick brick : bricks)
{
brickRect = new GRect(x, y, BRICK_WIDTH, BRICK_HEIGHT);
add(brick);
}
}
}
public class Brick
{
int x;
int y;
public Brick(int x, int y)
{
this.x = x;
this.y = y;
}
}
public class Ball
{
int x;
int y;
}
This code isn't complete but should give you an idea on how to keep a reference to the brick. When you're checking for collision, you can iterate through the bricks, find any the have a collision with the ball and then call remove() on that brick.
So, if you are using add() from an external library (acm.graphics), you'll need to keep your own copies of bricks that you add. Perhaps add a 2D array of boolean values or a structure like #thattolleyguy suggested to your class then a method to add them
private void addBrick(int x, int y)
{
brickArray[x][y] = true; //your own copy of brick locations
int yloc = BRICK_Y_OFFSET + (i * (BRICK_HEIGHT + BRICK_SEP));
int xloc = (BRICK_X_OFFSET) + (j * (BRICK_WIDTH + BRICK_SEP));
brick = new GRect (xloc, yloc, BRICK_WIDTH, BRICK_HEIGHT );
add (brick);
}
Then you can easily remove them from your array (set that location to false) and from your external library (or you may need a redraw) with a removeBrick method.
Also
The object reference brick is only referenced within this function so it only needs to be local
private void addBricks()
{
GRect brick;
...
add(brick);
...
}
If I was you, I would store all GRects in a List<GRect>. This list should be at the center of your operations.
I suppose the drawing are triggered by repaint() method. Possibly in a sperate thread, you need to check the distance between the ball and each GRect, when you find a GRect intersected with the ball, you can pass that GRect to remove().
One simple solution is to keep an isVisible flag in each GRect and modify it in remove(). BTW, Java Objects are passed by reference, your modification will take effects.
I am new to Java and am learning from Stanford lectures from YouTube.
So I was trying out their assignment to make a breakout game and so far so good until now. I have all my bricks, ball and paddle including the mechanics of the game but when i run the game only one brick can be removed when hit by the ball. see this. That brick happens to be the last brick added to the canvas.
The ball just flies past all other bricks with no effect. The relevant code is below.
Am I lacking some important knowledge about getElementAt here? I have a feeling that getCollidingObject is not assigned to collider, which is making the collision detection faulty. I hope someone can enlighten me on this!
private void addBallMotion(){
// y component of starting velocity; pixels per second
vy = 3.0;
/* x component of starting velocity; pixels per second
* which ranges according to the random generator
* can be negative or positive, ball can go left or right with equal chances
*/
vx = rgen.nextDouble(1.0, 3.0);
if (rgen.nextBoolean(0.5)){
vx = -vx;
}
while (true){
ball.move(vx, vy);
checkCollision();
pause(FPS);
}
}
private void checkCollision(){
checkWallCollision();
checkBrickAndPaddleCollision();
}
private void checkWallCollision(){
//checks for left or right collision
if ( (ball.getX() < leftBounds.getX() ) || (ball.getX() + BALL_RADIUS * 2 > rightBounds.getX()) ){
vx = -vx;
}
//checks for top or bottom collision
if ( (ball.getY() < topBounds.getY() ) || (ball.getY() + BALL_RADIUS * 2 > bottomBounds.getY()) ){
vy = -vy;
}
}
private void checkBrickAndPaddleCollision(){
GObject collider = getCollidingObject();
if (collider == brick){
remove(collider);
vy = -vy;
}
if (collider == paddle){
vy = -vy;
}
}
//check for collision at the 4 edges of the ball
//starting with the left and going clockwise
private GObject getCollidingObject(){
GObject ballLeft= getElementAt (ball.getX() - 1, ball.getY() + BALL_RADIUS);
GObject ballRight= getElementAt (ball.getX() + BALL_RADIUS * 2 + 1, ball.getY() + BALL_RADIUS);
GObject ballTop = getElementAt (ball.getX() + BALL_RADIUS * 2, ball.getY() - 1);
GObject ballBottom= getElementAt (ball.getX() + BALL_RADIUS, ball.getY() + BALL_RADIUS * 2 + 1);
if (ballLeft != null){
return (ballLeft);
}
else if (ballTop != null){
return (ballTop);
}
else if (ballRight != null){
return (ballRight);
}
else if (ballBottom != null){
return (ballBottom);
}
return (null);
}
private GRect paddle; // creates a paddle that only moves linearly according to mouses' x coordinate
private GRect brick;
private GOval ball;
private double vx, vy; // x and y components of the ball's velocity
//private GObject collider;
Here's the whole program:
import acm.graphics.*;
import acm.program.*;
import acm.util.*;
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
public class Breakout extends GraphicsProgram {
/** Width and height of application window in pixels */
public static final int APPLICATION_WIDTH = 400;
public static final int APPLICATION_HEIGHT = 600;
/** Dimensions of game board (usually the same) */
private static final int WIDTH = APPLICATION_WIDTH;
private static final int HEIGHT = APPLICATION_HEIGHT;
/** Dimensions of the paddle */
private static final int PADDLE_WIDTH = 60;
private static final int PADDLE_HEIGHT = 10;
/** Offset of the paddle up from the bottom */
private static final int PADDLE_Y_OFFSET = 30;
/** 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 a brick */
private static final int BRICK_WIDTH =
(WIDTH - (NBRICKS_PER_ROW - 1) * BRICK_SEP) / NBRICKS_PER_ROW;
/** Height of a brick */
private static final int BRICK_HEIGHT = 8;
/** Radius of the ball in pixels */
private static final int BALL_RADIUS = 10;
/** Offset of the top brick row from the top */
private static final int BRICK_Y_OFFSET = 70;
/** Offset of the side bricks from the sides of game window */
private static final int BRICK_X_OFFSET = ((WIDTH - NBRICKS_PER_ROW * (BRICK_WIDTH + BRICK_SEP) + BRICK_SEP) / 2);
/** Number of turns */
private static final int NTURNS = 3;
/** Number of frames per second */
private static final int FPS = 1;
/* Method: run() */
/** Runs the Breakout program. */
public void run() {
addMouseListeners();
addWorld();
// runGame();
}
private void addWorld(){
setSize (APPLICATION_WIDTH, APPLICATION_HEIGHT);
addPlayingBox();
addBricks();
addPaddle();
addBall();
// addCounter();
}
//adds the bound area onto screen
private void addPlayingBox(){
topBounds = new GLine (0, 0, WIDTH, 0);
bottomBounds = new GLine (0, HEIGHT, WIDTH, HEIGHT);
leftBounds = new GLine (0, 0, 0, HEIGHT);
rightBounds = new GLine (WIDTH, 0, WIDTH, HEIGHT);
add (topBounds);
add (bottomBounds);
add (leftBounds);
add (rightBounds);
}
private void addBricks(){
for (int i = 0; i < NBRICK_ROWS; i++){
int y = BRICK_Y_OFFSET + (i * (BRICK_HEIGHT + BRICK_SEP));
for (int j = 0; j < NBRICKS_PER_ROW; j++){
int x = (BRICK_X_OFFSET) + (j * (BRICK_WIDTH + BRICK_SEP));
brick = new GRect (x, y, BRICK_WIDTH, BRICK_HEIGHT );
colorBrick(brick, i);
add (brick);
}
}
}
// every consecutive 2 rows are colored the same
private void colorBrick(GRect brick, int rowNumber){
brick.setFilled (true);
switch (rowNumber + 1) {
case 1: case 2: brick.setColor(Color.red);
break;
case 3: case 4: brick.setColor(Color.orange);
break;
case 5: case 6: brick.setColor(Color.yellow);
break;
case 7: case 8: brick.setColor(Color.green);
break;
case 9: case 10:brick.setColor(Color.cyan);
break;
}
}
//adds paddle to screen
private void addPaddle(){
paddle = new GRect (PADDLE_WIDTH, PADDLE_HEIGHT);
paddle.setFilled(true);
paddle.setColor (Color.BLACK);
add (paddle);
}
//creates motion for the paddle according to mouse movement
public void mouseMoved(MouseEvent e){
paddle.setLocation ((e.getX() - PADDLE_WIDTH / 2), (double) (HEIGHT - PADDLE_Y_OFFSET));
/* checks if the paddle within the playing area
* if not the paddles will stay at the extremities*/
if ( paddle.getX() > (WIDTH - PADDLE_WIDTH)){
paddle.setLocation((double) (WIDTH - PADDLE_WIDTH), (double) (HEIGHT - PADDLE_Y_OFFSET));
}
if ( paddle.getX() < 0){
paddle.setLocation((double) 0, (double) (APPLICATION_HEIGHT - PADDLE_Y_OFFSET));
}
}
private void addBall(){
ball = new GOval (((WIDTH - BALL_RADIUS * 2) / 2), ((HEIGHT - BALL_RADIUS * 2) / 2),
BALL_RADIUS * 2, BALL_RADIUS * 2);
ball.setFilled(true);
ball.setColor(Color.BLACK);
add (ball);
addBallMotion();
}
private void addBallMotion(){
// y component of starting velocity; pixels per second
vy = 3.0;
/* x component of starting velocity; pixels per second
* which ranges according to the random generator
* can be negative or positive, ball can go left or right with equal chances
*/
vx = rgen.nextDouble(1.0, 3.0);
if (rgen.nextBoolean(0.5)){
vx = -vx;
}
while (true){
ball.move(vx, vy);
checkCollision();
pause(FPS);
}
}
private void checkCollision(){
checkWallCollision();
checkBrickAndPaddleCollision();
}
private void checkWallCollision(){
//checks for left or right collision
if ( (ball.getX() < leftBounds.getX() ) || (ball.getX() + BALL_RADIUS * 2 > rightBounds.getX()) ){
vx = -vx;
}
//checks for top or bottom collision
if ( (ball.getY() < topBounds.getY() ) || (ball.getY() + BALL_RADIUS * 2 > bottomBounds.getY()) ){
vy = -vy;
}
}
private void checkBrickAndPaddleCollision(){
GObject collider = getCollidingObject();
if (collider == brick){
remove(collider);
vy = -vy;
}
if (collider == paddle){
vy = -vy;
}
}
//check for collision at the 4 edges of the ball
//starting with the left and going clockwise
private GObject getCollidingObject(){
GObject ballLeft= getElementAt (ball.getX() - 1, ball.getY() + BALL_RADIUS);
GObject ballRight= getElementAt (ball.getX() + BALL_RADIUS * 2 + 1, ball.getY() + BALL_RADIUS);
GObject ballTop = getElementAt (ball.getX() + BALL_RADIUS * 2, ball.getY() - 1);
GObject ballBottom= getElementAt (ball.getX() + BALL_RADIUS, ball.getY() + BALL_RADIUS * 2 + 1);
if (ballLeft != null){
return (ballLeft);
}
else if (ballTop != null){
return (ballTop);
}
else if (ballRight != null){
return (ballRight);
}
else if (ballBottom != null){
return (ballBottom);
}
return (null);
}
private GRect paddle; // creates a paddle that only moves linearly according to mouses' x coordinate
private GRect brick;
private GOval ball;
private double vx, vy; // x and y components of the ball's velocity
private RandomGenerator rgen = RandomGenerator.getInstance();
//private GObject collider;
private GLine topBounds; // creates a bounding box that is the playing area
private GLine bottomBounds;
private GLine leftBounds;
private GLine rightBounds;
}
Exactly as I thought.
Look - You have a field in your class called brick. It's of GRect type. At the beginning you're calling addWorld() method, which calls addBricks(). Now check what you wrote:
private void addBricks(){
for (int i = 0; i < NBRICK_ROWS; i++){
int y = BRICK_Y_OFFSET + (i * (BRICK_HEIGHT + BRICK_SEP));
for (int j = 0; j < NBRICKS_PER_ROW; j++){
int x = (BRICK_X_OFFSET) + (j * (BRICK_WIDTH + BRICK_SEP));
brick = new GRect (x, y, BRICK_WIDTH, BRICK_HEIGHT );
colorBrick(brick, i);
add (brick);
}
}
}
What happens in there? You're having a loop in which brick is overriden NBRICK_ROWS * NBRICKS_PER_ROW times, which causes brick field to be the last created brick on your screen.
Basically, you're doing something similar to this:
int x;
x = 5;
x = 6;
x = 8;
// x is 8 now
And in checkBrickAndPaddleCollision() you're checking only if collider is brick. Which in other words means, you're checking if it's the last brick - if it is, then you remove it.
First of all you should create an array of bricks, not just one field.
ArrayList<GRect> bricks;
instead of:
GRect brick;
And then in addBricks() method, you should have:
bricks.add(new GRect (x, y, BRICK_WIDTH, BRICK_HEIGHT));
instead of:
brick = new GRect (x, y, BRICK_WIDTH, BRICK_HEIGHT );
After this, in checkBrickAndPaddleCollision(), you should not check:
if (collider == brick) {
remove(collider);
vy = -vy;
}
but rather all bricks:
for(GRect brick : bricks) {
if (collider.equals(brick)) { // Note that you should rather use .equals, instead of == as Aurand stated in his comment
remove(collider);
vy = -vy;
}
}
please help. I am new to android game development and java. I want my deer to loop or start from 0,0 again when it touches the border of the screen but i have no idea how to code it.
package com.cmanres.bunnyjourney;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Rect;
public class Spriteleft {
private static final int BMP_COLUMNS = 3;
private static final int BMP_ROWS = 2;
private int x = 0;
private int y=0;
private int xSpeed = 3;
private Levelunogame gameView;
private Bitmap deer1;
private int width;
private int height;
private int currentFrame=0;
public Spriteleft(Levelunogame gameView, Bitmap deer1) {
this.gameView=gameView;
this.deer1=deer1;
this.width = deer1.getWidth() / BMP_COLUMNS;
this.height = deer1.getHeight() / BMP_ROWS;
}
private void update() {
if (x > gameView.getWidth() - width - xSpeed) {
xSpeed = -3;
}
if (x + xSpeed< 0) {
xSpeed = 3;
}
x = x + xSpeed;
currentFrame = ++currentFrame % BMP_COLUMNS;
}
public void onDraw(Canvas canvas) {
update();
int srcX = currentFrame * width;
int srcY = 1 * height;
Rect src = new Rect(srcX, srcY, srcX + width, srcY + height);
Rect dst = new Rect(x, y, x + width, y + height);
canvas.drawBitmap(deer1, src , dst, null);
}
}
that is my code that i followed on a android mobile game tutorial. can anyone show me how to do it? or give any links for a tutorial? I will appreciate it very much.
Assuming your sprite is positioned at x, y with sprite_width, sprite_height
// Check if your sprite position is outside the screen bounds
if( x < 0 || x > gameView.getWidth() - sprite_width
|| y < 0 || y > gameView.getHeight() - sprite_height ) {
// Set x, y to 0,0
x = 0;
y = 0;
}