java 2d game -lagging and collision issue - java

I am designing a simple java 2d game.where an aircraft shoots missiles and they hit alien ships.(pictures are attached for a better understanding).
Now I need to detect when the missile hits the alien ship. So as to count the number of total hits. I used the rectangle1.intersects(rec2)method, but instead of giving me an integer 1 as the answer (after the boolean of course) it gives me some funny answer. I guess like how much the two rectangles intersect...
Also when adding new aliens in an arraylist I use the following: I add new aliens every two seconds, but this slows down the game very much.
So please guide me on these two issues.
There is a game class (contains the main frame), board class (the panel on which I draw) alient, missile and craft class. Below I am giving the the actionPerformed() of the panel class which gets called by a timer every 2ms (the rest of the code is below).
///CODE TO BE FOCUSED ON
import java.awt.*;
import java.awt.event.*;
import java.util.ArrayList;
import javax.swing.*;
public class game extends JFrame {
static long z;
game()
{
add(new board());
setBounds(0, 0, 500, 500);
setVisible(true);
setLayout(null);
setLocationRelativeTo(null);
setTitle("\t\t...................::::~~~~'S GAME~~~~:::::...............");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public static void main(String[] args) {
new game();
z = System.currentTimeMillis();
}
}
class board extends JPanel implements ActionListener
{
Timer t = new Timer(5, this);
public ArrayList alien_list;
craft craft_list = new craft();
Label l = new Label();
int total_hits = 0;
public board() {
setFocusable(true);
setLayout(null);
setDoubleBuffered(true);
setBackground(Color.BLACK);
addKeyListener(craft_list);
l.setBounds(0, 0, 150, 30);
l.setBackground(Color.GREEN);
add(l);
t.start();
alien_list = new ArrayList();
alien_list.add(new alien(0, 100));
alien_list.add(new alien(0, 150));
alien_list.add(new alien(0, 200));
}
public void paint(Graphics g) {
super.paint(g);
Graphics2D g1 = (Graphics2D) g;
long z = (System.currentTimeMillis() - game.z) / 1000;
if (z >= 60)
{
remove(l);
g.setColor(Color.red);
g1.drawString("time up", 100, 100);
} else
{
g1.drawImage(craft_list.getImage(), craft_list.getX(),
craft_list.getY(), null);
ArrayList a = craft_list.getmissile();
for (int i = 0; i < a.size(); i++) {
missile m = (missile) a.get(i);
g1.drawImage(m.getImage(), m.getX(), m.getY(), null);
}
l.setText("time elapsed:" + " " + +z + " " + "hits:" + " "
+ total_hits);
for (int i = 0; i < alien_list.size(); i++) {
alien m = (alien) alien_list.get(i);
g1.drawImage(m.getImage(), m.getX(), m.getY(), null);
}
}
}
public void actionPerformed(ActionEvent e) {
ArrayList a = craft_list.getmissile();
for (int i = 0; i < a.size(); i++) {
missile m = (missile) a.get(i);
if (m.visible == true)
m.move();
else
a.remove(i);
}
long z = (System.currentTimeMillis() - game.z) / 1000;
if (z % 3 == 0)
alien_list.add(new alien(-10, 100));
for (int j = 0; j < alien_list.size(); j++) {
alien m = (alien) alien_list.get(j);
if (m.visible == true)
m.move();
else
alien_list.remove(j);
}
craft_list.move();
collison();
repaint();
}
public void collison() {
ArrayList a = craft_list.getmissile();
for (int i = 0; i < a.size(); i++) {
missile m = (missile) a.get(i);
Rectangle r1 = m.getBounds();
for (int j = 0; j < alien_list.size(); j++) {
alien l = (alien) alien_list.get(j);
Rectangle r2 = l.getBounds();
if (r1.intersects(r2)) {
total_hits++;
m.setVisible(false);
l.setVisible(false);
}
}
}
}
}
class craft extends KeyAdapter
{
int x = 250;
int y = 400;
ArrayList m = new ArrayList();
Image i;
int dx, dy;
craft() {
ImageIcon i1 = new ImageIcon("1a.jpg");
i = i1.getImage();
}
public Image getImage() {
return i;
}
public int getX() {
return x;
}
public int getY() {
return y;
}
public void move() {
x += dx;
y += dy;
if (x < 0)
x = 0;
if (x > 450)
x = 450;
if (y > 420)
y = 420;
if (y < 200)
y = 200;
}
public void keyPressed(KeyEvent k)
{
int key = k.getKeyCode();
if (key == KeyEvent.VK_SPACE) {
fire();
}
if (key == KeyEvent.VK_LEFT) {
dx = -1;
}
if (key == KeyEvent.VK_RIGHT) {
dx = 1;
}
if (key == KeyEvent.VK_UP) {
dy = -1;
}
if (key == KeyEvent.VK_DOWN) {
dy = 1;
}
}
public void keyReleased(KeyEvent e) {
int key = e.getKeyCode();
if (key == KeyEvent.VK_LEFT) {
dx = 0;
}
if (key == KeyEvent.VK_RIGHT) {
dx = 0;
}
if (key == KeyEvent.VK_UP) {
dy = 0;
}
if (key == KeyEvent.VK_DOWN) {
dy = 0;
}
}
public void fire() {
m.add(new missile(getX() + 13, getY() - 6));
}
public ArrayList getmissile() {
return m;
}
public Rectangle getBounds() {
return new Rectangle(x, y, i.getWidth(null), i.getHeight(null));
}
}
class missile {
Image i;
int x, y;
public boolean visible;
missile(int x, int y) {
this.x = x;
this.y = y;
visible = true;
ImageIcon i1 = new ImageIcon("1c.jpg");
i = i1.getImage();
}
public Image getImage() {
return i;
}
public int getX() {
return x;
}
public int getY() {
return y;
}
public void move() {
y--;
if (y < 0)
visible = false;
}
public Rectangle getBounds() {
return new Rectangle(x, y, i.getWidth(null), i.getHeight(null));
}
public void setVisible(boolean t) {
this.visible = t;
}
}
class alien {
Image i;
int x, y;;
public boolean visible;
public alien(int x, int y)
{
this.x = x;
this.y = y;
ImageIcon i1 = new ImageIcon("b.jpg");
i = i1.getImage();
visible = true;
}
public int getX() {
return x;
}
public int getY() {
return y;
}
public Image getImage() {
return i;
}
public void move() {
x++;
if (x > 500)
visible = false;
}
public Rectangle getBounds() {
return new Rectangle(x, y, i.getWidth(null), i.getHeight(null));
}
public void setVisible(boolean t) {
this.visible = t;
}
}

Ok, your code format is kind of unreadable and invites everybody to oversee otherwise obvious bugs. That is what I have seen so far for your performance issue:
getBounds() creates a new Rectangle instance every time it gets called. You should update the bounds rectangle at the last line of your move() and just return the rectangle instance instead of creating a new one.
Reuse Image or ImageIcon objects. There is no need to load the same jpg file over and over again in a constructor. Make it static or use a image cache.
Instead of o++ in fire() you should use o = m.size(). Mainly because you never call o--, you only remove the rocket from the ArrayList.
And at that point everybody loses track of what o and m means. Name your variables better! o should be amountOfRockets and m should be listOfRockets.
When you use Eclipse, press ctrl + shift + f to format the code which I highly recommend. After that go through your code and name the variables correctly. That means you should give them a descriptive name. And finally: let the name of your classes start with an upper case.
Very likely that this will not yet remove all issues but it will at least help us to understand and read your code easier... which might lead us to a solution...
Update:
You still haven't done 1. and 2. I suggested but you did 3.
Here is what 1. should be as a sample for the Alien class:
private Rectangle bounds
//constructor
Alien() {
// your stuff and the bounds:
bounds = new Rectangle(x, y, i.getWidth(null), i.getHeight(null));
}
public void move() {
bounds.x++;
if (bounds.x > 500)
visible = false;
}
public Rectangle getBounds() {
return bounds;
}
You need to implement that for the Rocket class as well.
What I still don't get is where you remove the old Alien objects. Just setting their visibility is not enough. You should remove them from the list of your Alien objects. Otherwise you will loop through objects that are not there anymore.

Related

Using Processing to Create Arcade of Games, after game is chosen. Won't draw, still runs. processing

Hi basically whenever I click p or b to run one of my games they run, but you can't see them as they don't draw over the main menu screen. These games do work if separated.
PImage pongImage, brickImage;
boolean mouseDown = false;
boolean [] keys = new boolean [128];
Ball ball;
Paddleb gamerPaddle;
static ArrayList<Brick> bricks = new ArrayList();
Puck puck;
Paddle one;//left
Paddle two;//right
int oneScore = 0;
int twoScore = 0;
int gameScreen = 0;
void setup() {
fullScreen();
ball = new Ball();//creating objects
gamerPaddle = new Paddleb();
puck = new Puck();//creating objects
one = new Paddle(true);
two = new Paddle(false);
}
void draw() {
menuPress();
if (gameScreen == 0) {
mainMenu();
}
if (gameScreen ==1) {
gamePong();
}
if (gameScreen == 2) {
gameBrick();
}
}
void keyReleased() {
keys[key] = false;
one.move(0);
two.move(0);
gamerPaddle.move(0);
}
void menuPress() {
if (keys['p'] == true) {
gameScreen = 1;
} else if (keys ['b'] == true) {
gameScreen =2;
} else {
gameScreen = 0;
}
}
void moves() {
if (keys['w'] == true) {
one.move(-10);
} else if (keys['s'] == true) {
one.move(10);
}
if (keys['i'] == true) {
two.move(-10);
} else if (keys['k'] == true) {
two.move(10);
}
if (keys['a'] == true) {
gamerPaddle.move(-10);
} else if (keys['d'] == true) {
gamerPaddle.move(10);
}
}
void keyPressed() {
keys[key] = true;
}
void drawBricks() {
for (int i = 0; i <= bricks.size() - 1; i++) {
fill(255);
rectMode(CORNER);
rect(bricks.get(i).x, bricks.get(i).y, bricks.get(i).s, bricks.get(i).s2);
}
}
void bricksSetup() {
rectMode(CORNER);
float s = 80;
float x = width/4;
float y = Brick.space;
while (y < height/2) {
while (x < width - width/4) {
bricks.add(new Brick(x, y, s, s));
x +=90;
}
x = width/4;
y +=90;
}
}
void mainMenu() {
float picsY = height/2;
float brickX = 2 * width/3;
float pongX = width/3 - width/4;
pongImage = loadImage("pong photo.PNG");
brickImage = loadImage("Brick breaker.PNG");
pongImage.resize(width/4, height/4);
brickImage.resize(width/4, height/4);
background(150);
fill(255);
textSize(72);
text("AhMen's Arcade", width/5 + width/7, height/3);
image(pongImage, pongX, picsY);
text("Pong", width/6, 4 * height/5 + height/50);
image(brickImage, brickX, picsY);
text("Brick Breaker", 2 * width/3 + width/100, 4 * height/5 + height/50);
}
void gamePong() {
background(0);
System.out.println("cat");
boolean gameEnding = false;
do {
background(0);
one.screen();//creates paddle
two.screen();
puck.position();
puck.sides();
puck.screen();
moves();
puck.checkHitOne(one);
puck.checkHitTwo(two);
one.refresh();//limits y movement and keeps it moving at speed of 0 to make stops and starts not noticible
two.refresh();
fill(255);
textSize(32);
text(oneScore, 20, 50);
text(twoScore, width-40, 50);
textMode(CENTER);
text("PONG", width/2-55, 50);
} while (gameEnding != true);
exit();
}
void gameBrick() {
System.out.println("ya");
background(0);
bricksSetup();
ball.position();
while (ball.y - ball.r > height || ball.p1Score >= ((bricks.size()-1)*50)) {
System.out.println('l');
background(0);
moves();
drawBricks();
ball.checkHitTwo(gamerPaddle);
ball.checkHitBrick();
gamerPaddle.screen();//creates paddle
gamerPaddle.refresh();//limits y movement and keeps it moving at speed of 0 to make stops and starts not noticible
gamerPaddle.refresh();
ball.position();
ball.sides();
ball.screen();
ball.score();
}
exit();
}
this is just the main method btw, I do have other methods for the objects. I am not sure why this doesn't work, but if someone that has an Idea what the issue may be please lmk.
The processing draw function does not run on a seperate thread. When you have a while loop, which doesn't end, the draw-function never gets executed anymore.
You have to use variables scoped to the processing file and not just a function and then modify those variables inside the functions you currently use as the game-loops.
For example, if you want a program where a ball moves to the right and returns to coordinate 0 after passing it, you would have to structure it like this:
Ball ball = new Ball();
void draw() {
playBallGame();
drawBall();
}
void playBallGame() {
if (ball.x > width) ball.x = 0;
ball.x++;
}
Not like this:
void draw() {
drawBall();
playBallGame();
}
void playBallGame() {
Ball ball = new Ball();
while (true) {
if (ball.x > width) ball.x = 0;
ball.x++;
}
}

Calculating the line thickness when drawing

I can draw lines, but the thickness is constant. I need to change the thickness when I press a button. In this example pressing 'w' will increase the thickness and pressing 'q' will decrease the thickness.
import java.awt.*;
import java.applet.*;
import sun.swing.SwingUtilities2;
public class draw extends Applet {
boolean isBlack = true;
Point startPoint;
Point points[];
int numPoints;
boolean drawing;
int n = 0;
#Override
public void init() {
startPoint = new Point(0, 0);
points = new Point[10000];
drawing = false;
resize(300, 400);
}
#Override
public void paint(Graphics g) {
if (n == 0) {
g.setColor(Color.red);
}
if (n == 1) {
g.setColor(Color.green);
}
if (n == 2) {
g.setColor(Color.blue);
}
if (n == 3) {
g.setColor(Color.black);
}
int oldX = startPoint.x;
int oldY = startPoint.y;
for (int i = 0; i < numPoints; ++i) {
g.drawLine(oldX, oldY, points[i].x, points[i].y);
oldX = points[i].x;
oldY = points[i].y;
}
}
#Override
public boolean keyDown(Event evt, int key) {
char keyChar = (char) key;
if (keyChar == 'w') {
n++;
if (n > 3) {
n = 0;
}
}
if (keyChar == 'q') {
n--;
if (n < 0) {
n = 3;
}
}
return true;
}
#Override
public boolean mouseDown(Event evt, int x, int y) {
if (!drawing) {
startPoint.x = x;
startPoint.y = y;
}
drawing = !drawing;
return true;
}
#Override
public boolean mouseMove(Event evt, int x, int y) {
if ((drawing) && (numPoints < 10000)) {
points[numPoints] = new Point(x, y);
++numPoints;
repaint();
}
return true;
}
}
But I can't calculate the thickness of the line, how would I do that?
You need to use the Graphics2D package:
Graphics2D g2 = SwingUtilities2.getGraphics2D(g);
g2.setStroke(new BasicStroke(n));
g2.drawLine(oldX, oldY, points[i].x, points[i].y);
I think that's is all you need. It's been awhile since I've worked with it.

Why collision algorithm in my applet game does not work properly ?

This is my game project. It's very simple version of "Flappy Bird" and I have some serious problems with how the collisions algorithm works. I wrote 2 separate code fragments for collision, for wall1 and wall2. The problem begins when the ball is trying to go through a hole because somehow the program is detecting a collision with a wall. I'm almost positive that the collision algorithm was written correctly because I have been checking it all day.
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
import java.util.Random;
import java.util.Timer;
import java.util.logging.Level;
import java.util.logging.Logger;
public class Game extends Applet implements KeyListener, Runnable {
Image bground;
Random generator = new Random();
int r1;
int wall1x;
int wall1y;
int wall1long;
int wall2x;
int wall2y;
int wall2long;
Timer timer;
private Image i;
private Graphics doubleG;
int r2;
int blok_x1 = 800;
int blok_y1;
int blok_x = 800;
int blok_y = 0;
int blok_x_v = 2;
int ballX = 20;
int ballY = 20;
int dx = 0;
int dyclimb = 1;
int dyrise = 1;
double gravity = 3;
double jumptime = 0;
int FPS = 100;
public int tab[];
public boolean grounded = true, up = false;
boolean OVER = false;
#Override
public void init() {
bground = getImage(getCodeBase(), "12.png");
this.setSize(600, 400);
tab = new int[100];
for (int t = 0; t < 100; t++) {
tab[t] = generator.nextInt(380) + 1;
}
addKeyListener(this);
}
#Override
public void keyPressed(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_LEFT) {
ballX -= 10;
}
if (e.getKeyCode() == KeyEvent.VK_RIGHT) {
ballX += 10;
}
if (e.getKeyCode() == KeyEvent.VK_UP) {
ballY -= 10;
up = true;
}
if (e.getKeyCode() == KeyEvent.VK_DOWN) {
ballY += 10;
}
}
#Override
public void paint(Graphics g) {
g.drawImage(bground, 0, 0, this);
if (OVER == false) {
for (int i = 0; i < 100; i++) {
g.setColor(Color.green);
wall1x = blok_x + i * 400;
wall1y = blok_y;
wall1long = tab[i];
g.fillRect(wall1x, wall1y, 20, wall1long);
g.setColor(Color.green);
wall2x = blok_x1 + i * 400;
wall2y = tab[i] + 60;
wall2long = 400 - tab[i];
g.fillRect(wall2x, wall2y, 20, wall2long);
g.setColor(Color.green);
}
g.setColor(Color.red);
g.fillOval(ballX, ballY, 20, 20);
} else {
g.drawString("GAME OVER", 300, 300);
}
}
#Override
public void update(Graphics g) {
if (i == null) {
g.setColor(Color.green);
i = createImage(this.getSize().width, this.getSize().height);
doubleG = i.getGraphics();
g.setColor(Color.green);
}
doubleG.setColor(getBackground());
g.setColor(Color.green);
doubleG.fillRect(0, 0, this.getSize().width, this.getSize().height);
doubleG.setColor(getForeground());
g.setColor(Color.green);
paint(doubleG);
g.drawImage(i, 0, 0, this);
}
#Override
public void run() {
int time = 10;
while (true) {
if (up == true) {
ballY -= dyclimb;
time--;
} else {
ballY += dyrise;
}
if (time == 0) {
time = 10;
up = false;
}
blok_x--;
blok_x1--;
if (ballX > 600 || ballX < 0 || ballY > 400 || ballY < 0) {
OVER = true;
}
for (int i = 0; i < 100; i++) { // collision algorithm
wall1x = blok_x + i * 400;
wall1y = blok_y;
wall1long = tab[i];
if (ballX + 20 >= wall1x && ballX <= wall1x + 20 && ballY <= wall1y + wall1long && ballY >= wall1x - 20) { //wall1
OVER = true;
}
}
for (int i = 0; i < 100; i++) {
wall2x = blok_x1 + i * 400;
wall2y = tab[i] + 60;
wall2long = 400 - tab[i];
if (ballX + 20 >= wall2x && ballX <= wall2x + 20 && ballY <= wall2y + wall2long && ballY >= wall2x - 20) { //wall2
OVER = true;
}
}
repaint();
try {
Thread.sleep(17);
} catch (InterruptedException ex) {
Logger.getLogger(NewApplet.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
#Override
public void start() {
Thread thread = new Thread(this);
thread.start();
}
#Override
public void keyTyped(KeyEvent e) {
}
#Override
public void keyReleased(KeyEvent e) {
}
}
Use Rectangle class. There's a method called Intersect or Intersection or something like that.
Say you have one object moving. Make a Rectangle to match the object in position(basically an invisible cover for the object).
Do the same things with another object.
When both are to collide, use the intersection method to check on the collision by using the rectangles.
These might help
http://docs.oracle.com/javase/7/docs/api/java/awt/Rectangle.html
Java method to find the rectangle that is the intersection of two rectangles using only left bottom point, width and height?
java.awt.Rectangle. intersection()

2d array of objects

im really new in Java. I just need to explain how to declare 2D array of objects, i have something like:
package breakout;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.Color;
import java.awt.Font;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JOptionPane;
public class Breakout extends JPanel {
public class Ball {
private
int x = 400;
int y = 300;
int speed = 2;
int dirx = 1;
int diry = -1;
public
void bounce(int px, int py, int lx, int ly) {
if ((x + 10 >= 800 && dirx == 1) || (x <= 0 && dirx == -1))
dirx *= -1;
if (y <= 0 && diry == -1)
diry *= -1;
if (y + 10 >= py && y <= py + ly && diry == 1 && x + 10 >= px && x <= px + lx)
diry *= -1;
}
int getX() {
return x;
}
int getY() {
return y;
}
void setDirx(){
dirx *= -1;
}
void setDiry(){
diry *= -1;
}
void move() {
x += speed*dirx;
y += speed*diry;
}
void paint(Graphics2D g) {
g.fillOval(x,y,10,10);
}
}
public class Paddle {
private
int x = 400;
int y = 520;
int width = 100;
int height = 6;
int speed = 6;
int dirL = 0;
int dirR = 0;
public
void move() {
x -= speed*dirL;
x += speed*dirR;
}
void stop() {
if (x <= 0)
x = 0;
if (x + width >= 800)
x = 800 - width;
}
int getX() {
return x;
}
int getY() {
return y;
}
int getWidth() {
return width;
}
int getHeight() {
return height;
}
void paint(Graphics2D g) {
g.fillRect(x,y,width,height);
}
public void keyReleased(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_LEFT)
dirL = 0;
else if (e.getKeyCode() == KeyEvent.VK_RIGHT)
dirR = 0;
else {
dirL = 0;
dirR = 0;
}
}
public void keyPressed(KeyEvent e) {
switch(e.getKeyCode()) {
case KeyEvent.VK_LEFT:
dirL = 1;
break;
case KeyEvent.VK_RIGHT:
dirR = 1;
break;
}
}
}
public class Brick {
private
int x;
int y;
int width;
int height;
boolean alive;
boolean inX = false,inY = false;
public
void setUpBrick(int px, int py, int w, int h, boolean al) {
x = px;
y = py;
width = w;
height = h;
alive = al;
}
void setAlive(boolean alive) {
this.alive = alive;
}
void paint(Graphics2D g) {
if (alive)
g.fillRect(x,y,width,height);
}
boolean collision(int bx, int by) {
if (alive) {
if (bx + 10 >= x && bx <= x + width && by + 10 >= y && by <= y + height) {
setAlive(false);
return true;
} else return false;
}
else return false;
}
void inAreaX(int bx) {
if (bx + 10 >= x && bx <= x + width) {
System.out.println("inAreaX");
inX = true;
} else {
inX = false;
}
}
void inAreaY(int by) {
if (by + 10 >= y && by <= y + height) {
System.out.println("inAreaY");
inY = true;
} else {
inY = false;
}
}
boolean isInAreaX () {
if (inX)
return true;
else return false;
}
boolean isInAreaY () {
if (inY)
return true;
else return false;
}
}
Ball ball = new Ball();
Paddle paddle = new Paddle();
Brick[][] brick = new Brick[8][4];
for (int i = 0; i < 8; i++) {
for (int j = 0; j < 4; j++) {
brick[i][j].setUpBrick(j * 101, i * 51, 100, 50, true);
}
}
void bounce() {
for (int i = 0; i < 8; i++) {
for (int j = 0; j < 4; j++) {
brick[i][j].inAreaX(ball.getX());
brick[i][j].inAreaY(ball.getY());
if (brick[i][j].collision(ball.getX(), ball.getY())) {
if (brick[i][j].isInAreaX()) {
ball.setDiry();
} else if (brick[i][j].isInAreaY()) {
ball.setDirx();
}
}
}
}
}
void move() {
ball.bounce(paddle.getX(), paddle.getY(), paddle.getWidth(),paddle.getHeight());
ball.move();
paddle.move();
paddle.stop();
bounce();
}
public Breakout() {
addKeyListener(new KeyListener() {
public void keyTyped(KeyEvent e) {
}
public void keyReleased(KeyEvent e) {
paddle.keyReleased(e);
}
public void keyPressed(KeyEvent e) {
paddle.keyPressed(e);
}
});
setFocusable(true);
}
public void paint(Graphics g) {
super.paint(g);
Graphics2D g2d = (Graphics2D) g;
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g2d.setColor(Color.RED);
ball.paint(g2d);
g2d.setColor(Color.BLACK);
paddle.paint(g2d);
g2d.setColor(Color.ORANGE);
for (int i = 0; i < 8; i++)
for (int j = 0; j < 4; j++)
brick[i][j].paint(g2d);
}
public static void main(String[] args) throws InterruptedException {
JFrame window = new JFrame("Tennis");
Breakout game = new Breakout();
window.add(game);
window.setSize(800,600);
window.setVisible(true);
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
while (true) {
game.move();
game.repaint();
Thread.sleep(10);
}
}
i need to inicialize 2d array of brick, but it says that first for is unexpected token. How to write it? Thank you.
Unless if I have miscounted your opening and closing braces, your for loop is not inside any method, it's directly in your class body. That's why you're getting unexpected token. You will probably want to move it into the Breakout constructor.
In order to create a 2D array in Java, you can create such an array like this:
Object testArray = new Object[10][10];
This array is now a 10*10 array with memory allocated for 100 Object references.
You can create pointers two Objects with a double for-loop:
for (int i = 0; i < testArray.length(); i++) {
for (int j = 0; j < testArray.length; j++) {
testArray[i][j] = Object; //here you input the objects that you want to point to
}
}
Move the logic from setUpBrick to a constructor.
public class Brick {
private int x;
private int y;
private int width;
private int height;
private boolean alive;
private boolean inX = false,inY = false;
public Brick(int px, int py, int w, int h, boolean al) {
x = px;
y = py;
width = w;
height = h;
alive = al;
}
...
}
Then change
brick[i][j].setUpBrick(j * 101, i * 51, 100, 50, true);
to
brick[i][j] = new Brick(j*101, i*51, 100, 50, true);
Also note that access modifiers don't apply to a whole section of your class. In your example,
private
int x;
int y;
int width;
int height;
boolean alive;
boolean inX = false,inY = false;
means that only x is going to be private. The rest of the members will get the default access modifier.
One more tip. A couple of your methods can be simplified.
boolean isInAreaY () {
if (inY)
return true;
else return false;
}
can be written as:
boolean isInAreaY() {
return inY;
}

Detect mouseclick on object Slick2d

I've made this code that successfully creates a 16x12 grid by 50x50 squares on a 800x600px board.
As you can see, the player moves to the coordinates of the players mouseclick.
Each square of the grid has an object of Felt (field) on it, which can be laast (locked). If a fields lock attribute is set to 1, the player should not be moved to that position.
How do i detect the field a player tries to move on to achieve this?
public class SimpleGame extends BasicGame{
private Image plane;
private float planeX;
private float planeY;
public SimpleGame()
{
super("SpilTest");
}
#Override
public void init(GameContainer gc) throws SlickException {
plane = new Image("figur.png");
}
#Override
public void update(GameContainer gc, int delta) throws SlickException {
Input input = gc.getInput();
if (input.isMousePressed(input.MOUSE_LEFT_BUTTON)) {
this.planeX = input.getMouseX() - 30;
this.planeY = input.getMouseY() - 50;
}
}
public void render(GameContainer gc, Graphics g) throws SlickException {
Felt board[][] = nytGrid();
int distancex = 0;
int distancey = 0;
int counter = 0;
for (int i=0; i < board.length ; i++) {
for (int j=0; j < board[i].length ; j++) {
if (board[i][j].getLaast() == 1) {
g.setColor(Color.red);
g.fillRect(distancex, distancey, 50, 50);
}
distancex += 50;
counter++;
if (counter == 16) {
distancey += 50;
distancex = 0;
counter = 0;
}
}
}
g.drawImage(plane, planeX, planeY);
}
public static void main(String[] args) throws SlickException {
AppGameContainer app = new AppGameContainer(new SimpleGame());
app.setDisplayMode(800, 600, false);
app.setTargetFrameRate(60);
app.start();
}
public Felt[][] nytGrid() {
Felt [][] board = new Felt[16][12];
for (int i=0; i < board.length ; i++) {
for (int j=0; j < board[i].length ; j++) {
int x = i;
int y = j;
board[i][j] = new Felt(x, y);
if (i == 5 && j == 5) {
board[i][j].setLaast(1);
}
}
}
return board;
}
}
First off, you should probably initialize the board in the init() method instead of render, so it doesn't have to do it every frame, and move the declaration for the grid next to the plane, planeX and planeY declarations in the class.
Now to disable movement into a locked square, first add a method to check if a square at certain coordinates is locked, so something along the lines of:
private boolean isLocked(int x, int y) {
int square = board[x/50][y/50];
if (square == 1) return true;
else return false;
}
Next modify the part of your update() method where you update the plane coordinates, so vaguely something like:
if (input.isMousePressed(input.MOUSE_LEFT_BUTTON)) {
int destX = input.getMouseX() - 30;
int destY = input.getMouseY() - 50;
if (!isLocked(destX, destY)) {
this.planeX = destX;
this.planeY = destY;
}
}
It's easy!
int mx = Mouse.getX();
int my = Mouse.getY();
But, it gives you the world cordinates, and you have to translate it to pixels:
int mx = Mouse.getX();
int my = Mouse.getY() * -1 + (Window.WIDTH / 2) + 71;

Categories

Resources