Code Examples - Miknielsen/OOSE2015_MiniProject GitHub Wiki

Examples of key parts of the code

Key elements of the code that allows others modify the game as they wish.

Bricks

In order to create the bricks that the player is going to target a nested for loop will cycle once through each brick and construct a new brick. It is important to notice that this will once run once as running it through each frame would redraw bricks even if they were considered dead.

if(!bricksCreated) {
	for (int i = 0; i<matrixY; i++) {
		for (int j = 0; j < matrixX; j++) {
			brick[i][j] = new Brick(g, 5+(i*65), 10+(j*25));
	        }
	}
	bricksCreated = true;
}

Instead the bricks are redrawn within the brick collision detection nested for loops. When the detection algorithm has run once it will check if the brick is considered dead (i.e. x-coordinate = 655). If it is still considered alive it will redraw the brick that frame.

if(brick[k][j].getXpos() != 655) {
	brick[k][j] = new Brick(g, 5+(k*65), 10+(j*25));
}

Brick Collision Detection

In order to detect whether or not the ball has hit a brick in any given frame the code will run through all of the bricks that are still considered "alive" (i.e. getXpos() does not return 655). The block below shows only the collision detection of the top parts of the detection algorithm, the rest can be found in the render method of SimpleSlickGame.java in the source directory.

for (int k = 0; k<matrixY; k++) {
        for (int j = 0; j < matrixX; j++) {
                if(brick[k][j].getXpos() != 655 &&
                   ball.getYcoord() >= brick[k][j].getYpos() - 3 &&
                   ball.getYcoord() <= brick[k][j].getYpos() + 3 &&
            	   ball.getXcoord() >= brick[k][j].getXpos() - 3 &&
            	   ball.getXcoord() <= brick[k][j].getXpos() + brick[k][j].getLength() +3) { 			
                        ball.changeYdirection();
                        System.out.println("TOP");
                        brick[k][j].setXpos(655);
                        brick[k][j].setYpos(725);
                } else if

                (...)
        }
}

This will cycle through all of the bricks and check if the any coordinate of the ball is equal to a coordinate of any given brick +- 3 pixels. The three pixels margin of error is set in place in case the program skips frames.

Slick2D

Since the movement speed of both the ball and the player is based on pixels moved per frame, it is important to set a target frame rate for the program, so that the speed will be consistent over multiple different systems. A low framerate will mean that any movements within the game will be slowed down.

The limitation of the framerate is performed with the following piece of code. This can be found within the main method of SimpleSlickGame.java in the source directory

appgc.setTargetFrameRate(120);

JavaDoc

JavaDoc files can be found in the /pages/ folder within this repository