Breakout game java - java

I am creating the breakout game and its isn't running just showing the bricks and the paddle and ball. I think its in my for statements in the breakin class.I added in the paddles.getW, paddles. get Y +paddles.getH and for the next for statement I added the balls.getD.
import java.awt.*;
import java.applet.*;
public class Breakin extends Applet implements Runnable
{
/**
*
*/
private static final long serialVersionUID = 1L;
Thread k;
int rows=7;
int columns=8;
Paddle paddles=new Paddle(50,200,10,40);
Ball balls=new Ball (40,150,10);
Brick [] [] bricks =new Brick [rows][columns];
Graphics dbg;
Image dbImage;
Boolean win=false;
public void init(){
int xin=0;
int yin=-15;
for(int r=0; r<rows; r++){
yin +=15;
xin=0;
for(int c=0; c<columns; c++){
int game=(int)(Math.random()*4)+1;
switch(game){
case 1:bricks[r][c]=new Brick(xin,yin,(Color.yellow),20,10);break;
case 2:bricks[r][c]=new Brick(xin,yin,(Color.green),20,10);break;
case 3:bricks[r][c]=new Brick(xin,yin,(Color.orange),20,10);break;
case 4:bricks[r][c]=new Brick(xin,yin,(Color.red),20,10);break;
}
xin+=25;
}
}
balls.setVelocity(2, 2);
}
public void start(){
k=new Thread(this);
if(k!=null){
k.start();
}
}
public void run1 ()
{
while (true)
{
balls.updateVelocity();
paddles.updateXVelo();
if (balls.intersects(paddles.getX(),paddles.getY(),paddles.getX() + paddles.getW(),paddles.getY()+ paddles.getH()));
balls.flipX();
if(balls.getX()<0 || balls.getX()>(200-balls.getD()))
balls.flipX();
for(int r=0; r<rows; r++){
for(int c=0; c<columns; c++){
if(bricks[r][c]!=null){
if(bricks[r][c].intersects(balls.getX(),balls.getY(),balls.getX()+balls.getD(),balls.getY()+ balls.getD())){
bricks[r][c]=null;
balls.flipY();}
}
}
}
repaint();
try{
Thread.sleep(20);
}
catch(InterruptedException ex)
{
}
}
}
public void destory ()
{
k.stop();
}
public void update(Graphics g)
{
if(dbImage==null)
{
dbImage=createImage(this.getSize().width, this.getSize().height);
dbg=dbImage.getGraphics();
}
dbg.setColor(getBackground());
dbg.fillRect(0, 0, this.getSize().width, this.getSize().height);
dbg.setColor(getForeground());
paint(dbg);
g.drawImage(dbImage,0,0,this);
}
public boolean keyDown(Event e, int key)
{
if(key==Event.LEFT)
{
paddles.setVelocity(0);
if (paddles.getX()>0)
paddles.setVelocity(-3);
}
if (key==Event.RIGHT)
{
paddles.setVelocity(0);
if (paddles.getX()<200-paddles.getW())//check this out
paddles.setVelocity(3);
}
return true;
}
public boolean keyUp(Event e, int Key)
{
paddles.setVelocity(0);
return true; //check
}
public void paint(Graphics g){
for(int r=0; r<rows; r++){
for(int c=0; c<columns; c++){
if(bricks[r][c]!=null){
bricks[r][c].drawBrick(g);
}
}
}
balls.pinT(g);
paddles.showT(g);
}
#Override
public void run() {
// TODO Auto-generated method stub
}
}
Paddle.java:
import java.awt.*;
public class Paddle
{
private int x;
private int y;
private int h;
private int w;
private int xVelocity;
public Paddle (int x, int y, int h, int w){
this.x=x;
this.y=y;
this.w=w;
this.h=h;
}
public void begin(int d, int a){
if(d==1){
x+=a;
}
if (d<1){
x-=a;
}
}
public void updateXVelo(){
x+=xVelocity;
}
public void showT(Graphics g)
{
g.setColor(Color.red);
g.fillRect(x, y, w, h);
g.setColor(Color.black);
g.drawRect(x,y,w,h);
}
public int getH(){
return h;
}
public int getW(){
return w;
}
public int getX(){
return x;
}
public int getY(){
return y;
}
public void setVelocity(int x){
xVelocity=x;
}
}
Ball.java:
import java.awt.*;
public class Ball{
public int x;
public int y;
public int d;
public int yvelocity;
public int xvelocity;
public Ball (int x, int y, int d)
{
this.x=x;
this.y=y;
this.d=d;
}
public void pinT(Graphics g)
{
g.setColor(Color.green);
g.fillOval(x,y,d,d);
g.setColor(Color.black);
}
public void flipX(){
xvelocity=-xvelocity;
}
public void flipY(){
yvelocity=-yvelocity;
}
public void setX(int x){
this.x=x;
}
public void setY(int y){
this.y=y;
}
public int getX(){
return x;
}
public int getD(){
return d;
}
public int getY(){
return y;
}
public void setVelocity(int x, int y){
xvelocity=x;
yvelocity=y;
}
public void updateVelocity(){
y+=yvelocity;
x+=xvelocity;
}
public boolean intersects(int x1,int y1,int x2,int y2)
{
return(x2>=x)&&(x+d>=x1)&&(y2>=y)&&(y+d>=y1);
}
}
Brick.java:
import java.awt.*;
public class Brick {
private int x;
private int y;
private Color color=(Color.red);
int w;
int h;
public Brick(int x, int y, Color color, int w, int h){
this.x=x;
this.y=y;
this.color=color;
this.h=h;
this.w=w;
}
public boolean intersects(int x1, int y1, int x2, int y2)
{
return( x2>=x)&&(x+w>=x1)&&(y2>=y)&&(y+h>y1);
}
public void setX(int x){
this.x=x;
}
public void setY(int y){
this.y=y;
}
public void setColor (Color color){
this.color=color;//the :
}
public void drawBrick(Graphics g){
g.setColor(color);
g.fillRect(x, y, w, h);
g.setColor(Color.black);
g.drawRect(x,y,w,h);
}
}

Related

JPanel graphics flickering when is used the method getGraphics()

I try to create a class that was similar to the famous Processing, but soon I found a problem, since in Processing there are the setup () and draw () functions, in to which it is possible to perform certain functions, such as square (10,10,50), I tried to imitate it by creating a class, in which there is a Graphics object called "gfx" to which the various figures are added. If you read this papyrus ... thank you and I put below the PFrame class (that is the one that imitates Processing) and the BohClass class which will be the test class.
package PFrame.com;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class PFrame {
private JFrame frame = new JFrame();
private DPane pane = new DPane(); //DPane is a class that extends JPanel
private Graphics2D gfx;
private Color selColor = new Color(255,255,255); //selected color
private boolean fill = true; //the shapes are filled?
public int width = 200, height = 200; //starting frame dimensins
public PFrame() {
//SKY
pane.setPreferredSize(new Dimension(width,height));
//HEAD
title(); //this functions give to the frame the name of the class (in this case "BohClass")
frame.setResizable(false);
//BODY
frame.add(pane);
pane.addComponentListener(new ResizeListener());
//TAIL
size(width,height); //function that setting size
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
gfx = (Graphics2D) pane.getGraphics();
pane.paint(); //DPane function
}
//--|METHODS|--//
//FRAME CONFIG
public final void size(int x, int y) {
width = x;
height = y;
pane.setPreferredSize(new Dimension(width,height));
frame.pack();
frame.setLocationRelativeTo(null);
gfx = (Graphics2D) pane.getGraphics();
}
public final void exit() {
System.exit(0);
}
public final void hide() {
frame.setVisible(false);
}
public final void show() {
frame.setVisible(true);
}
public final void location(int XY) {
frame.setLocation(XY,XY);
}
public final void location(int X, int Y) {
frame.setLocation(X,Y);
}
public final void title() {
frame.setTitle((getClass() + "").split(" ")[1]);
}
public final void title(Object title) {
frame.setTitle(title.toString());
}
public final void resizable() {
frame.setResizable(!frame.isResizable());
}
public final void resizable(boolean resizable) {
frame.setResizable(resizable);
}
//2D CONFIG
public final void fill(boolean fill) {
this.fill = fill;
}
public final void color(int RGB) {
selColor = new Color(RGB,RGB,RGB);
}
public final void color(int R, int G, int B) {
selColor = new Color(R,G,B);
}
//2D
public final void square(int X, int Y, int L) {
rect(X,Y,L,L);
}
public final void square(int X, int Y, int L, int A) {
rect(X,Y,L,L,A);
}
public final void square(int X, int Y, int L, int Ax, int Ay) {
rect(X,Y,L,L,Ax,Ay);
}
public final void rect(int X, int Y, int W, int H) {
gfx.setColor(selColor);
if(fill) gfx.fillRect(X, Y, W, H);
else gfx.drawRect(X, Y, W, H);
}
public final void rect(int X, int Y, int W, int H,int A) {
gfx.setColor(selColor);
if(fill) gfx.fillRoundRect(X, Y, W, H, A, A);
else gfx.drawRoundRect(X, Y, W, H, A, A);
}
public final void rect(int X, int Y, int W, int H,int Ax, int Ay) {
gfx.setColor(selColor);
if(fill) gfx.fillRoundRect(X, Y, W, H, Ax, Ay);
else gfx.drawRoundRect(X, Y, W, H, Ax, Ay);
}
public final void circle(int X, int Y, int d) {
ellipse(X,Y,d,d);
}
public final void ellipse(int X, int Y, int W, int H) {
gfx.setColor(selColor);
if(fill) gfx.fillOval(X, Y, W, H);
else gfx.drawOval(X, Y, W, H);
}
public final void triangle(int Ax, int Ay, int Bx, int By, int Cx, int Cy) {
gfx.setColor(selColor);
if(fill) gfx.fillPolygon(new Polygon(new int[] {Ax,Bx,Cx}, new int[] {Ay,By,Cy}, 3));
else gfx.drawPolygon(new Polygon(new int[] {Ax,Bx,Cx}, new int[] {Ay,By,Cy}, 3));
}
//PANEL CONFIG
public final void background(int RGB) {
pane.setBackground(new Color(RGB,RGB,RGB));
}
public final void background(int R, int G, int B) {
pane.setBackground(new Color(R,G,B));
}
public final void clear() {
gfx.clearRect(0, 0, width, height);
}
//PUBLIC METHODS
public void setup() {}
public void loop() {}
//PRIVATE CLASS PANEL
private class DPane extends JPanel {
private static final long serialVersionUID = 57423L;
public void paint() {
setup();
while(true) {
loop();
}
}
}
//LISTENERS
class ResizeListener implements ComponentListener {
public void componentResized(ComponentEvent e) {
width = pane.getWidth();
height = pane.getHeight();
}
public void componentMoved(ComponentEvent e) {}
public void componentShown(ComponentEvent e) {}
public void componentHidden(ComponentEvent e) {}
}
}
and...
import PFrame.com.*;
public class BohClass extends PFrame {
public void setup() {
size(800,600);
background(100);
}
public void loop() {
color(72,28,47);
triangle(60,10,10,60,110,60);
color(255);
square(12,12,123);
}
public static void main(String[] args) {
new BohClass();
}
}
Like others have said, you should not have a while(true) loop inside your painting function.
Shameless self-promotion: here is a tutorial on custom painting in Swing, coming from a Processing background. Basically you need to create a Timer that triggers a repaint.

Game collision detection with rectangles

I have started with my first game but cannot figure out how the collision detection should work. The goal is that the player should not be able to go into the wall.
I have following classes Player(), Wall(), Levels() and Game()
Player class is loading the player and handling movement and collisions for the player.
Wall is creating walls, I have one Arraylist in this class which is creating an rectangle for each wall that is created.
Levels class is loading creating and loading all the levels.
Game class is handling the whole game loop and more.
I have tried to compare x and y positions with player and wall, right now I am trying to use the .intersect class which has not been succesfull yet.
Part of Player Class:
public void collision() {
Rectangle r3 = getOffsetBounds();
for (int i = 0; i < Wall.wallList.size(); i++) {
Rectangle w1 = Wall.wallList.get(i);
if (r3.intersects(w1)) {
}}}
public int moveUp(int velY) {
collision();
y -= velY;
return y;
}
public int moveDown(int velY) {
collision();
y += velY;
return y;
}
public int moveLeft(int velX) {
collision();
x -= velX;
return x;
}
public int moveRight(int velX) {
collision();
x += velX;
return x;
}
public Rectangle getOffsetBounds() {
return new Rectangle(x + velX, y + velY, width, height);
}
public int getX() {
return x;
}
public void setX(int x) {
this.x = x;
}
public int getY() {
return y;
}
public void setY(int y) {
this.y = y;
}
public int getVelX() {
return velX;
}
public void setVelX(int velX) {
this.velX = velX;
}
public int getVelY() {
return velY;
}
public void setVelY(int velY) {
this.velY = velY;
}}
Part of Wall Class:
static ArrayList<Rectangle> wallList = new ArrayList<Rectangle>();
public int getX() {
return x;
}
public void setX(int x) {
this.x = x;
}
public int getY() {
return y;
}
public void setY(int y) {
this.y = y;
}
public void setVisisble(Boolean visible) {
this.visible = visible;
}
public Rectangle getBounds() {
return new Rectangle(x,y,width,height);
}
public Rectangle setBounds(int x,int y,int width,int height) {
this.x = x;
this.y = y;
this.width = width;
this.height = height;
return new Rectangle(x,y,width,height);
}}
Part of Levels class where the wall list is setting
if(level1[i][j]==1) {
w = new Wall(j*25, i*25, width, height);
w.paint(g);
Wall.wallList.add(w.setBounds(j*25+10, i*25+10, width, height));
}
Part of Game class where keybindings are
public void KeyBindings() {
keyManager.addKeyBinding(lvl, KeyEvent.VK_UP, "moveUp", (evt) -> {
lvl.player.moveUp(5);
});
keyManager.addKeyBinding(lvl, KeyEvent.VK_DOWN, "moveDown", (evt) -> {
lvl.player.moveDown(5);
});
keyManager.addKeyBinding(lvl, KeyEvent.VK_LEFT, "moveLeft", (evt) -> {
lvl.player.moveLeft(5);
});
keyManager.addKeyBinding(lvl, KeyEvent.VK_RIGHT, "moveRight", (evt) -> {
lvl.player.moveRight(5);
});
}
This is how I always handle any collisions
if (((x1<x2 && x1+w1>x2) || (x2<x1 && x2+w2>x1)) &&
((y1<y2 && y1+h1>y2) || (y2<y1 && y2+h2>y1)))

Images not working with repaint() in Java Game

I am trying to get images to display in my game. The background of my game works, but I am unable to get my playerIcon, bulletIcon and heartIcon images working.
My imageLoader class: (Working correctly)
package BullHellSpel;
import java.awt.image.BufferedImage;
import java.io.IOException;
import javax.imageio.ImageIO;
public class ImageLoader {
public static BufferedImage loadImage(String path){
try {
return ImageIO.read(ImageLoader.class.getResource(path));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
System.exit(1);
}
return null;
}
}
The important parts of my Game Class: (Which correctly loads my bg.png image)
public void run()
{
init();
}
private void init(){
bg = ImageLoader.loadImage("/bg.png");
}
private void render(){
BufferStrategy bs = this.getBufferStrategy();
if(bs == null){
this.createBufferStrategy(3);
return;
}
Graphics g = bs.getDrawGraphics();
//You can draw here
g.drawImage(bg, 0, 0, null);
handler.render(g);
g.dispose();
bs.show();
}
My Bullet Class: (Not working correctly)
package BullHellSpel;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Rectangle;
import java.awt.image.BufferedImage;
import java.util.Random;
public class Bullet extends GameObject {
private BufferedImage bulletIcon;
private Handler handler;
public Bullet(int x, int y, ID id, Handler handler) {
super(x, y, id);
this.handler = handler;
Random rand = new Random();
velX = rand.nextInt(5) + 3;
velY = rand.nextInt(3) + 2;
}
public Rectangle getBounds(){
return new Rectangle(x, y, 10, 10);
}
public void run()
{
init();
}
private void init(){
bulletIcon = ImageLoader.loadImage("/bullet.png");
}
public void tick() {
x += velX;
y += velY;
if(x <= 0 || x >= Game.WIDTH - 16) velX *= -1;
}
public void repaint() {
Graphics g = null;
g.drawImage(bulletIcon, x, y, null);
//g.setColor(Color.yellow);
//g.fillRect(x, y, 10, 10);
}
public void repaint(Graphics g) {
g.drawImage(bulletIcon, x, y, null);
//g.setColor(Color.yellow);
//g.fillRect(x, y, 10, 10);
}
}
My GameObject Class:
package BullHellSpel;
import java.awt.Graphics;
import java.awt.Rectangle;
public abstract class GameObject {
protected int x, y;
protected ID id;
protected int velX, velY;
public GameObject(int x, int y, ID id){
this.x = x;
this.y = y;
this.id = id;
}
public abstract void tick();
public abstract void repaint(Graphics g);
public abstract Rectangle getBounds();
public void setX(int x){
this.x = x;
}
public void setY(int y){
this.y = y;
}
public void getY(int y){
this.y = y;
}
public void getX(int x){
this.x = x;
}
public void setId(ID id){
this.id = id;
}
public ID getId(){
return id;
}
public void setVelX(int velX){
this.velX = velX;
}
public void setVelY(int velY){
this.velY = velY;
}
public int getVelX(int velX){
return velX;
}
public int getVelY(int velY){
return velY;
}
}
My Handler class:
package BullHellSpel;
import java.awt.Graphics;
import java.util.LinkedList;
public class Handler {
LinkedList<GameObject> object = new LinkedList<GameObject>();
public void tick(){
for(int i = 0; i < object.size(); i++){
GameObject tempObject = object.get(i);
tempObject.tick();
}
}
public void render(Graphics g){
for(int i = 0; i < object.size(); i++){
GameObject tempObject = object.get(i);
tempObject.repaint(g);
}
}
public void addObject(GameObject object){
this.object.add(object);
}
public void removeObject(GameObject object){
this.object.remove(object);
}
}
I have tried drawing with render(), render(Graphics g), repaint() and repaint(Graphics g), but nothing seems to work. I'm 99% sure that the path of my image is correct and the placeholder squares I used before I had my images work fine with both the render(Graphics g) and the repaint(Graphics g). When I launch the game I don't get any errors. Why is my image not being displayed?

What is wrong with my inheritance structure?

I'm trying to make a program that shows inheritance and polymorphism. The program is supposed to show a flag (specifically, the flag of Guinea).
This is the code:
import java.awt.*;
import javax.swing.*;
public class FlagB extends JPanel
{
public void paint (Graphics g)
{
Flag Guinea = new Flag(50,290,560);
Guinea.drawFlag(g);
}
public static void main(String[] args)
{
JFrame frame = new JFrame("Bolivian Flag");
frame.add(new FlagB());
frame.setSize(1000,725);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
class Flag
{
private FlagBase fb;
private FitRect rp; //rp for rectangle parameters
private LeftTriColor lt;
private MiddleTriColor mt;
private RightTriColor rt;
private int x;
private int y;
private int z;
public Flag(int x,int y,int z)
{
this.x = x;
this.y = y;
this.z = z;
fb = new FlagBase();
rp = new FitRect(x,y,z);
lt = new LeftTriColor(x,y,z);
mt = new MiddleTriColor(x,y,z);
rt = new RightTriColor(x,y,z);
}
public void drawFlag(Graphics g)
{
fb.FlagBase(g);
lt.drawRect(g);
mt.drawRect(g);
rt.drawRect(g);
}
}
class FlagBase // The outline of the flag
{
public void FlagBase(Graphics g)
{
g.setColor(Color.BLACK);
g.drawRect(49,49,876,562);
}
}
class FitRect
{
protected int l;
protected int length;
protected int width;
public FitRect(int x,int y,int z)
{
x = l;
y = length;
z = width;
}
}
class LeftTriColor extends FitRect
{
public LeftTriColor(int x,int y,int z)
{
super(x,y,z);
}
public void drawRect(Graphics g)
{
g.setColor(Color.RED);
g.fillRect(l,l,length,width);
}
}
class MiddleTriColor extends FitRect
{
public MiddleTriColor(int x,int y,int z)
{
super(x,y,z);
}
public void drawRect(Graphics g)
{
g.setColor(Color.YELLOW);
g.fillRect(l+length+1,l,length,width);
}
}
class RightTriColor extends FitRect
{
public RightTriColor(int x,int y,int z)
{
super(x,y,z);
}
public void drawRect(Graphics g)
{
g.setColor(Color.GREEN);
g.fillRect(l+2*length+3,l,length+1,width);
}
}
The only thing that shows up in the new window is the flag's outline. I think it has something to do with the argument passing of FitRect. Is that it, or is it something else?
I've been using JCreator.
This should solve it.
class FitRect
{
protected int l;
protected int length;
protected int width;
public FitRect(int x,int y,int z)
{
l = x; //was x = l
length = y; //was y = length
width = z; //was z = width
}
}

Circle collision detection

I have created a program that drawing 2 circle on the screen and using keyboard ASWD and arrow key to move around..here is the code
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
class BallObject {
private int x;
private int y;
private int radius;
BallObject() {
x=0;
y=0;
radius=0;
}
BallObject (int x,int y,int radius) {
this.x=x;
this.y=y;
this.radius=radius;
}
public void setX(int x) {this.x=x;}
public void setY(int y) {this.y=y;}
public void setRadius(int r) {radius=r;}
public int getX() {return x;}
public int getY() {return y;}
public int getRadius() {return radius;}
}
class Ball extends JFrame implements KeyListener {
BallObject ball1;
BallObject ball2;
Ball() {
super("Simple Ball");
setSize(800,600); //set screen resolution
ball1 = new BallObject(getWidth()/2,getHeight()/2,20);
ball2 = new BallObject(40,40,20);
addKeyListener(this);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
}
public void paint(Graphics g) {
Graphics2D g2d = (Graphics2D)g;
g2d.setColor(Color.BLACK);
g2d.fill(new Rectangle(0,0,800,600));
//drawing ball1
g2d.setColor(Color.RED);
g2d.fillOval(ball1.getX(),ball1.getY(),ball1.getRadius()*2,ball1.getRadius()*2);
//drawing ball2
g2d.setColor(Color.GREEN);
g2d.fillOval(ball2.getX(),ball2.getY(),ball2.getRadius()*2,ball2.getRadius()*2);
}
public static void main (String args[]) {
new Ball();
}
public void keyPressed(KeyEvent e) {
if(e.getKeyCode()==KeyEvent.VK_LEFT)
ball1.setX(ball1.getX()-2);
if(e.getKeyCode()==KeyEvent.VK_RIGHT)
ball1.setX(ball1.getX()+2);
if(e.getKeyCode()==KeyEvent.VK_UP)
ball1.setY(ball1.getY()-2);
if(e.getKeyCode()==KeyEvent.VK_DOWN)
ball1.setY(ball1.getY()+2);
if(e.getKeyCode()==KeyEvent.VK_A){
ball2.setX(ball2.getX()-2);
//System.out.println("Hello");
}
if(e.getKeyCode()==KeyEvent.VK_D)
ball2.setX(ball2.getX()+2);
if(e.getKeyCode()==KeyEvent.VK_W)
ball2.setY(ball2.getY()-2);
if(e.getKeyCode()==KeyEvent.VK_S)
ball2.setY(ball2.getY()+2);
repaint();
}
//redraw the screen to show the updated ball location
public void keyTyped(KeyEvent e) {}
public void keyReleased(KeyEvent e) {}
}
Now i need to test the collision..Once two balls are touching each other.it will show a message "COLLISION DETECTED"..pls help...
Isn't it simply: if the distance of both center points is less or equal to the sum of the radiuses, then there is a collision?

Categories