Error solution and help improving enemie spawn methode - java

I tried myself on a little "project" . It is basically a survival game. You move by using W,A,S,D and you shoot in different directions by using the arrow keys. You basically have to survive for as long as possible. The enemies follow you and they freeze on hit and start moving again after about 3 seconds.
The code is the following (execute the "window" class)
Window-class
package TestGame;
import java.awt.Graphics;
public class Window extends GameIntern{
public void init(){
setSize(windowX,windowY);
Thread th = new Thread(this);
th.start();
offscreen = createImage(windowX,windowY);
d = offscreen.getGraphics();
addKeyListener(this);
}
public void paint(Graphics g){
d.clearRect(0,0,windowX,windowY);//clear window
d.drawString(numberEnemies.toString(), 10, 10);//"Score" number of enemies displayed
d.drawRect(x, y, playerWidth, playerHeight);//draw player
for(Enemy e : enemies){//draw all enemies
d.drawRect(e.getx(), e.gety(), playerWidth, playerHeight);
}
for(Bullet b : bullets){//draw all bullets
d.drawOval(b.getx(), b.gety(), bulletSize, bulletSize);
}
g.drawImage(offscreen,0,0,this);
}
public void update(Graphics g){
paint(g);
}
}
GameIntern-class
package TestGame;
import java.applet.Applet;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.util.ArrayList;
import java.util.Random;
public class GameIntern extends Applet implements Runnable , KeyListener {
public int windowX = 854;//size of the window in x direction
public int windowY = 460;//size of the window in y direction
public static int x;//x-coordinate of player
public static int y;//y-coordinate of player
public int playerpositionX = x;
public int playerpositionY = y;
public int playerHeight = 20;//player height
public int playerWidth = 20;//player width
public int playerSpeed = 3;//pixel per frame
public int bulletSize = 5;//diameter of bullets
public int spawnTime = 4;//time for new enemies to spawn in seconds
public int enemySleepTime = 180;//Time an enemy does nothing in Frames per second (180 in 60fps = 3sec)
public boolean alive = true;
public Image offscreen;
public Graphics d;
public boolean up,down,left,right;
private int delay;
private Random random= new Random();
public Integer numberEnemies = new Integer(enemies.size());
protected static ArrayList<Enemy> enemies = new ArrayList<Enemy>(); //List of all enemies
protected static ArrayList<Bullet> bullets = new ArrayList<Bullet>();//List of all bullets
protected static ArrayList<PowerUps> pUps = new ArrayList<PowerUps>();//List of all powerUps
public void run() {
this.x = 400;//startingposition x
this.y = 240;//startingposition y
double ns = 1000000000.0 / 60.0; //60 "frames"
double delta = 0;
long lastTime = System.nanoTime();
while (alive) {
long now = System.nanoTime();
delta += (now - lastTime) / ns;
lastTime = now;
while (delta >= 1) {
repaint();
tick();
collisionEnemy();
// collisionPowerUp();
delta--;
}
}
}
/**
* Method to calculate all objects and their positions per frame
*/
private void tick() {
if(left == true){
if(x>=0 + playerSpeed){
x-=playerSpeed;
}else{ x=0;}//Farthest left x-coordinate
repaint();
}
if(right == true){
if(x<=windowX - playerWidth - playerSpeed){
x+=playerSpeed;
}else{ x=windowX - playerWidth;}//Farthest right x-coordinate
repaint();
}
if(up == true){
if(y>=0 + playerSpeed){
y-=playerSpeed;
}else{ y=0;}//Highest y-coordinate
repaint();
}
if(down == true){
if(y<=windowY - playerHeight - playerSpeed){
y+=playerSpeed;
}else{y=windowY - playerHeight;}//Lowest y-coordinate
repaint();
}
for (Enemy e : enemies) { //Tick every enemy
e.tick();
}
for (Bullet b : bullets){ //Tick every bullet
b.tick();
}
if(delay % (60 * spawnTime) == 0){ //Spawn enemy
enemies.add(new Enemy(random.nextInt(windowX), random.nextInt(windowY)));
numberEnemies++;
}
delay++;
for(Enemy e : enemies){ //collision : enemy & bullet
for(Bullet b : bullets){
if(b.getx()+bulletSize >= e.getx() && b.getx() <= e.getx()+20){
if(b.gety()+bulletSize >= e.gety() && b.gety() <= e.gety()+20){
e.setHit();
b.setRemove();
}
}
}
}
for(int i = 0; i< bullets.size(); i++){ //Remove bullets from ArrayList
if(bullets.get(i).remove){
bullets.remove(i);
}
}
}
public void keyPressed(KeyEvent e) {
if(e.getKeyCode() == 65){//W
left=true;
}
if(e.getKeyCode() == 87){//A
up=true;
}
if(e.getKeyCode() == 68){//S
right=true;
}
if(e.getKeyCode() == 83){//D
down=true;
}
}
public void keyReleased(KeyEvent e) {
if(e.getKeyCode() == 65){//Arrowkey left
left=false;
}
if(e.getKeyCode() == 87){//Arrowkey up
up=false;
}
if(e.getKeyCode() == 68){//Arrowkey right
right=false;
}
if(e.getKeyCode() == 83){//Arrowkey dowm
down=false;
}
if(e.getKeyCode() == 37){//Arrowkey left
bullets.add(new Bullet(x,y,false,false,true,false)); //Direction the bullet has to go
}
if(e.getKeyCode() == 38){//Arrowkey up
bullets.add(new Bullet(x,y,true,false,false,false));//Direction the bullet has to go
}
if(e.getKeyCode() == 39){//Arrowkey right
bullets.add(new Bullet(x,y,false,false,false,true));//Direction the bullet has to go
}
if(e.getKeyCode() == 40){//Arrowkey down
bullets.add(new Bullet(x,y,false,true,false,false));//Direction the bullet has to go
}
}
public void keyTyped(KeyEvent e){}
/**
* Method to see if the player collided with an enemy
*/
public void collisionEnemy(){
for(Enemy e : enemies){
for(int i = 0;i <= playerWidth; i++){
if(GameIntern.x+i >= e.getx() && GameIntern.x+i <= e.getx()+playerWidth){
if(GameIntern.y+i >= e.gety() && GameIntern.y+i <= e.gety()+playerHeight){
alive = false;
}
}
}
}
}
// public void addEnemy(){
// enemies.add(new Enemy(random.nextInt(windowX), random.nextInt(windowY)));
//
// //Spawn enemies inside the filed, not outside the boarder
// if (playerpositionX < playerWidth * 2 || playerpositionX * 2 > windowX - 2*playerWidth || playerpositionY * 2 > windowY - 2*playerHeight || playerpositionY < playerHeight * 2){
// enemies.add(new Enemy(random.nextInt(windowX - 3*playerWidth), random.nextInt(windowY - 3*playerHeight)+3*playerHeight));
// }else {
// int temp1 = random.nextInt(windowX-3*playerWidth);
// if (temp < playerpositionX){
//
// }
// enemies.add(new Enemy(random.nextInt(windowX), random.nextInt(windowY)));
// }
//
// }
}
Bullet-class
package TestGame;
public class Bullet extends GameIntern{
public int x,y;
public boolean up,down,left,right;
public boolean remove;
public Bullet(int x, int y,boolean up,boolean down, boolean left, boolean right){
this.x = x + 8;
this.y = y + 8;
this.up = up;
this.down = down;
this.left = left;
this.right = right;
}
public int getx(){
return this.x;
}
public int gety(){
return this.y;
}
public void setRemove(){
remove=true;
}
public void tick() {
if (up == true) y-=2;
if (down == true) y+=2;
if (left == true) x-=2;
if (right == true) x+=2;
if(x < 0){
remove = true;
}
if(x > 840){
remove = true;
}
if(y < 0){
remove = true;
}
if(y > 470){
remove = true;
}
}
}
Enemy-class
package TestGame;
public class Enemy extends GameIntern {
public int x,y;
public boolean hit = false;
public int counter = 0;
public Enemy(int x, int y) {
this.x = x;
this.y = y;
}
public int getx(){
return this.x;
}
public int gety(){
return this.y;
}
public void setHit(){
hit = true;
counter = enemySleepTime;
}
public void tick() {
if(counter == 0){
if(hit == true){
hit=false;
}
if (x < GameIntern.x) x++;
if (x > GameIntern.x) x--;
if (y < GameIntern.y) y++;
if (y > GameIntern.y) y--;
}else {counter--;}
}
}
After playing for a while i get a
java.util.ConcurrentModificationException
What does that mean?
Also, I struggle to improve the enemy spawn prcess. Right now it sometimes happens, that enemies spawn inside the player. I want to have an imaginary box around the player where enemies dont spawn inside and enemies should always spawn inside the window.
If you have any questions, please feeld free to ask :)
sincerely
Viktor

From the JavaDocs:
The iterators returned by this class's iterator and listIterator methods are fail-fast: if the list is structurally modified at any time after the iterator is created, in any way except through the iterator's own remove or add methods, the iterator will throw a ConcurrentModificationException.
The problem is likely caused because you're removing bullets from the ArrayList while trying to paint them in a separate thread. The issue is that the two threads are iterating over the bullets list simultaneously.
//The following for loop is likely the cause
for(int i = 0; i< bullets.size(); i++){
if(bullets.get(i).remove){
bullets.remove(i); // <-- this is the problem
}
}
Instead, try using a thread-safe implementation, e.g.
protected static List<Enemy> enemies =
Collections.synchronizedList(new ArrayList<Enemy>()); //List of all enemies
protected static List<Bullet> bullets =
Collections.synchronizedList(new ArrayList<Bullet>());//List of all bullets
Furthermore, you should change the remove code to avoid an IndexOutOfBoundsException:
LinkedList<Bullet> bulletsToRemove = new LinkedList<>();
for(Enemy e : enemies){ //collision : enemy & bullet
for(Bullet b : bullets){
if(b.getx()+bulletSize >= e.getx() && b.getx() <= e.getx()+20){
if(b.gety()+bulletSize >= e.gety() && b.gety() <= e.gety()+20){
e.setHit();
bulletsToRemove.add(b);
}
}
}
}
for(Bullet b : bulletsToRemove){ //Remove bullets from ArrayList
bullets.remove(b);
}
Regarding the spawning process, a simplistic approach is to just define a minimum distance from the player, call it minDist. Now just pick a random location anywhere on the screen, call it p1. If p1 is less than minDist away from the player, pick a new random location. As long as the player and enemy sprites are relatively small compared to the screen area, this approach should work well.

Related

How do I make my game slower (slower FPS)?

So I wrote this code for a game and now that game is very speeded up. I want to lower the FPS so that the game slows down a bit.
I thought the only way out for me is to make a timer. But I'm finding it difficult to locate where to place the timer? Can anyone help me with this?
So I wrote this code for a game and now that game is very speeded up. I want to lower the FPS so that the game slows down a bit.
I thought the only way out for me is to make a timer. But I'm finding it difficult to locate where to place the timer? Can anyone help me with this?
public class Gamepanel extends JPanel implements Runnable, KeyListener {
private static final long serialVersionUID = 1L;
public static final int WIDTH = 500, HEIGHT = 500;
private Thread thread;
private boolean running;
private boolean right = false, left = false, up = false, down= false;
private BodyPart b;
private ArrayList<BodyPart> snake;
private Apple apple;
private ArrayList<Apple> apples;
private Random r;
private int xCoor = 10, yCoor = 10, size = 1;
private int ticks = 0;
public Gamepanel(){
setFocusable(true);
setPreferredSize(new Dimension(WIDTH, HEIGHT));
addKeyListener(this);
snake = new ArrayList<BodyPart>();
apples = new ArrayList<Apple>();
r = new Random();
start();
}
public void start () {
running = true;
thread = new Thread(this);
thread.start();
}
public void stop() {
running = false;
try {
thread.join();
} catch(InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void tick() {
if(snake.size()==0) {
b= new BodyPart(xCoor, yCoor, 10);
snake.add(b);
}
ticks++;
if(ticks > 250000) {
if(right) xCoor++;
if(left) xCoor--;
if(up) yCoor--;
if(down) yCoor++;
ticks = 0;
b = new BodyPart(xCoor, yCoor, 10);
snake.add(b);
if(snake.size() > size) {
snake.remove(0);
}
}
if(apples.size()==0) {
int xCoor = r.nextInt(49);
int yCoor = r.nextInt(49);
apple = new Apple(xCoor,yCoor,10);
apples.add(apple);
}
for(int i = 0; i < apples.size(); i++) {
if(xCoor == apples.get(i).getxCoor() && yCoor == apples.get(i).getyCoor()) {
size++;
apples.remove(i);
i++;
}
}
//COLLISION ON SNAKE BODY
for (int i = 0; i < snake.size(); i++) {
if(xCoor == snake.get(i).getxCoor() && yCoor == snake.get(i).getyCoor()) {
if(i != snake.size() - 1) {
System.out.print("Game Over");
stop();
}
}
//COLLISION ON BORDER
if(xCoor < 0 || xCoor > 49 || yCoor < 0 || yCoor > 49) {
System.out.print("Game Over" + '\n');
System.out.println("Your Score is: " + snake.size());
stop();
}
}
}
public void paint(Graphics g) {
g.clearRect(0, 0, WIDTH, HEIGHT);
g.setColor(Color.BLACK);
g.fillRect(0, 0, WIDTH, HEIGHT);
for (int i=0; i< WIDTH/10; i++) {
g.drawLine(i * 10, 0, i * 10, HEIGHT);
}
for (int i=0; i< HEIGHT/10; i++) {
g.drawLine(0, i * 10, HEIGHT, i * 10);
}
for (int i = 0; i< snake.size(); i++) {
snake.get(i).draw(g);
}
for (int i = 0; i< apples.size(); i++) {
apples.get(i).draw(g);
}
}
#Override
public void run() {
while(running) {
tick();
repaint();
}
}
#Override
public void keyTyped(KeyEvent e) {
// TODO Auto-generated method stub
}
#Override
public void keyPressed(KeyEvent e) {
int key = e.getKeyCode();
if(key == KeyEvent.VK_D && !left) {
right = true;
up = false;
down=false;
}
if(key == KeyEvent.VK_A && !right) {
left = true;
up = false;
down = false;
}
if(key == KeyEvent.VK_W && !down) {
up=true;
left=false;
right=false;
}
if(key == KeyEvent.VK_S && !up) {
down=true;
left=false;
right=false;
}
}
#Override
public void keyReleased(KeyEvent e) {
}
}
The problem with your code is that now, game speed won't be the same on different machines, as some computers may execute your code faster and some may execute slower.
If you want your game to execute on every computer with the same speed you need define some kind of speed for your snake (unit per second) and then in game loop update your snake position based on how much time elapsed from last frame (last call of tick method)
// snake speed
double speed = 1.0; // units per second
// in game loop (your tick method)
position = speed * deltaTime;
now your position is not anymore depended on game framerate. On faster devices game will update snake position more often but deltaTime will be smaller as well as changes of position, on the other hand on slower devices tick method will be called less frequent but deltaTime will be higher

Brick Collision Java [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
I have been working on a Breakout game and have just about everything done except for the brick collision. The ball bounces of the wall and paddle fine, but when it comes to the brick it goes straight through them. I'm pretty sure the problem is in the checkBrick() part of the main class, but have no idea what to do about it.
Main Class:
import java.awt.*;
import java.awt.event.KeyEvent;
import java.applet.*;
import java.util.Random;
import javax.swing.JOptionPane;
public class Breakout extends Applet implements Runnable {
Ball ball = new Ball();
Paddle paddle = new Paddle(135, 375);
Brick[] brick = new Brick[50];
private int bX[] = new int[50];
private int bY[] = new int[50];
private int bW[] = new int[50];
private int bH[] = new int[50];
Thread t;
Random trajectory = new Random();
boolean lose;
Image buffer = null;
// The life cycle of the Applet
// Sets up window
public void init() {
setSize(377, 500);
buffer = createImage(377, 500);
// setBackground(Color.black);
System.out.println("init()");
}
public void start() {
if (t == null) {
t = new Thread(this);
t.start();
}
System.out.println("start()");
}
public void run() {
System.out.println("run()");
Thread.currentThread().setPriority(Thread.MIN_PRIORITY);
while (!lose) {
ball.move();
paddle.move();
checkWall();
checkPaddle();
checkBrick();
ball.move();
repaint();
try {
Thread.sleep(30);
} catch (InterruptedException ex) {
}
Thread.currentThread().setPriority(Thread.MAX_PRIORITY);
}
JOptionPane.showMessageDialog(null, "Game Over");
System.out.println("Termintated");
System.exit(0);
}
public void stop() {
System.out.println("stop()");
}
public void destroy() {
System.out.println("destroy()");
}
public void paint(Graphics g) {
Graphics screen = null;
screen = g;
g = buffer.getGraphics();
g.setColor(Color.black);
g.fillRect(0, 0, 377, 500);
createBricks(g);
createPaddle(g);
createBall(g);
screen.drawImage(buffer, 0, 0, this);
}
public void update(Graphics g) {
paint(g);
}
private void createBricks(Graphics g) {
int brickIndex = 0;
int brickX = 15, brickY = 160;
int brickW = 30, brickH = 10;
for (int i = 0; i <= 4; i++) {
brickX = 15;
brickY -= 20;
for (int n = 0; n < 10; n++) {
brick[brickIndex] = new Brick();
brick[brickIndex].setBounds(brickX, brickY, brickW, brickH);
bX[brickIndex] = brick[brickIndex].x();
bY[brickIndex] = brick[brickIndex].y();
bW[brickIndex] = brick[brickIndex].w();
bH[brickIndex] = brick[brickIndex].h();
brick[brickIndex].setColor(i);
brick[brickIndex].paint(g);
brickIndex++;
brickX += 35;
}
}
}
private void createPaddle(Graphics g) {
paddle.paint(g);
}
private void createBall(Graphics g) {
ball.paint(g);
}
private void checkWall() {
// If ball hits right wall it will bounce
if ((ball.getX() + ball.getR()) >= 380) {
ball.setVX(trajectory.nextInt(2) + -3);
}
// If ball hits left wall it will bounce
if ((ball.getX() - ball.getR()) < -10) {
ball.setVX(trajectory.nextInt(4) + 1);
}
// If ball hits ceiling it will bounce
if ((ball.getY() + ball.getR()) < 12)
ball.setVY(trajectory.nextInt(5) + 1);
// If ball goes through floor it will subtract a life
if ((ball.getY() + ball.getR()) > 515)
lose = true;
}
private void checkBrick() {
for (int i = 0; i < 50; i++) {
int tempX, tempY, tempW, tempH;
tempX = bX[i];
tempY = bY[i];
tempW = bW[i];
tempH = bH[i];
if ((ball.getX() + ball.getR()) < (tempX + tempW)
&& (ball.getX() + ball.getR()) >= tempX) {
if ((ball.getY() + ball.getR()) > (tempY + tempH)
&& (ball.getY() + ball.getR()) <= tempY) {
System.out.println("Brick " + i + " has been hit.");
}
}
}
}
private void checkPaddle() {
// Check for paddle
if ((ball.getX() + ball.getR()) < (paddle.getX() + 100)
&& (ball.getX() + ball.getR()) >= paddle.getX() + 5) {
if ((ball.getY() + ball.getR()) > (paddle.getY() - 5)
&& (ball.getY() + ball.getR()) <= (paddle.getY() + 5)) {
ball.setVX((trajectory.nextInt(7) + -2) + 1);
ball.setVY(trajectory.nextInt(1) + -3);
}
}
}
// Key Detectors
public boolean keyDown(Event e, int key) {
if (key == Event.RIGHT) {
paddle.setVX(0);
if ((paddle.getX() + 100) < 377)
paddle.setVX(10);
}
if (key == Event.LEFT) {
paddle.setVX(0);
if (paddle.getX() > 0)
paddle.setVX(-10);
}
return true;
}
// To make sure it doesn't just keep moving one way
public boolean keyUp(Event e, int key) {
paddle.setVX(0);
return true;
}
}
Ball Class:
import java.awt.Color;
import java.awt.Graphics;
import java.util.Random;
public class Ball
{
private int x, y; //Position
private int vx, vy; //Velocity
private int r; //radius
//constructor
public Ball()
{
x = 177;
y = 315;
vx = 0;
vy = 5;
r = 15;
}
public void paint(Graphics g)
{
g.setColor(Color.white);
g.fillOval(x, y, r, r);
}
//returns the x of origin
public int getX()
{
return x;
}
//returns the y of origin
public int getY()
{
return y;
}
public int getVX()
{
return vx;
}
//returns the y of origin
public int getVY()
{
return vy;
}
//returns the radius r of the ball
public int getR()
{
return r;
}
//sets the velocity of x to a different value
public void setVX(int vx)
{
this.vx = vx;
}
//sets the velocity of y to a different value
public void setVY(int vy)
{
this.vy = vy;
}
//sets the x value
public void setX(int x)
{
this.x = x;
}
//sets the y value
public void setY(int y)
{
this.y = y;
}
//starts making the ball move by changing its coords
public void move()
{
x+= vx;
y+= vy;
}
}
Paddle Class:
import java.awt.Color;
import java.awt.Graphics;
public class Paddle {
// declares variables for x and y coordinates
int x, y;
//The velocity of to move paddle
int vx;
// constructor that takes in x and y coordinates for paddle
public Paddle(int x, int y)
{
this.x = x;
this.y = y;
}
public void paint(Graphics g)
{
// paints paddle
g.setColor(Color.WHITE);
g.fillRect(x, y, 100, 15);
g.setColor(Color.GREEN);
g.drawRect(x, y, 100, 15);
}
// gets x coordinate of paddle
public int getX() {
return x;
}
// sets x coordinate of paddle
public void setX(int x) {
this.x = x;
}
// gets y coordinate of paddle
public int getY() {
return y;
}
// sets y coordinate of paddle
public void setY(int y) {
this.y = y;
}
public void setVX(int vx)
{
this.vx = vx;
}
//Moves the paddle
public void move()
{
x+=vx;
}
}
Brick Class:
import java.awt.Color;
import java.awt.Graphics;
public class Brick
{
private Color color =(Color.cyan);
private int x, y, w, h;
public Brick()
{
//Garbage values that are there just for declaration
x = 0;
y = 0;
w = 10;
h = 10;
}
//Sets color for the brick
public void setColor(int paintC)
{
switch(paintC)
{
case 0:
color = (Color.magenta);
break;
case 1:
color = (Color.blue);
break;
case 2:
color = (Color.yellow);
break;
case 3:
color = (Color.orange);
break;
default:
color = (Color.red);
break;
}
}
//Sets the location then size of the brick
public void setBounds(int x, int y, int w, int h)
{
this.x = x;
this.y = y;
this.w = w;
this.h = h;
}
//returns x value
public int x()
{
return this.x;
}
//returns y value
public int y()
{
return this.y;
}
//returns width value
public int w()
{
return this.w;
}
//returns height value
public int h()
{
return this.h;
}
//Sets x for the brick
public void setX(int x)
{
this.x = x;
}
//Sets y for the brick
public void setY(int y)
{
this.y = y;
}
public void setW(int w)
{
this.w = w;
}
public void setH(int h)
{
this.h = h;
}
public void paint(Graphics g)
{
g.setColor(color);
g.fillRect(x, y, w, h);
g.setColor(Color.green);
g.drawRect(x, y, w, h);
}
}
I've begin running over your code, quite frankly can't be bothered trying to figure out your logic, but what I believe you're trying to deduce is if the brick "contains" the ball, rather then if the ball intersects with the brick.
You don't care how much of the ball or brick are intersecting, only if the they do...for example...
private void checkBrick() {
int tx = ball.getX();
int ty = ball.getY();
int tw = ball.getR();
int th = ball.getR();
tw += tx;
th += ty;
for (int i = 0; i < 50; i++) {
int tempX, tempY, tempW, tempH;
tempX = bX[i];
tempY = bY[i];
tempW = bW[i];
tempH = bH[i];
int rw = tempW + tempX;
int rh = tempH + tempY;
// overflow || intersect
if ((rw < tempX || rw > tx) &&
(rh < tempY || rh > ty) &&
(tw < tx || tw > tempX) &&
(th < ty || th > tempY)) {
System.out.println("Hit");
}
}
}
Now, I stole this from Rectangle#intersects
Basically, if you used the geometry class from the 2D Graphics API, you could reduce this down to...
private void checkBrick() {
Rectangle b = new Rectangle(ball.getX(), ball.getY(), ball.getR(), ball.getR());
for (int i = 0; i < 50; i++) {
int tempX, tempY, tempW, tempH;
tempX = bX[i];
tempY = bY[i];
tempW = bW[i];
tempH = bH[i];
Rectangle brick = new Rectangle(tempX, tempY, tempW, tempH);
System.out.println("brick = " + brick);
if (b.intersects(brick)) {
System.out.println("Break");
}
}
}
And, yes, I did actually run your code
The problem is that the method checkBrick() is not changing anything, it is just printing if the ball has a collision with the brick.
You may want to change the Ball velocity, as you did within checkWall() and checkPaddle().
private void checkBrick() {
for (int i = 0; i < 50; i++) {
...
if (...) {
ball.setVX(...); // Add these lines setting the correct values
ball.setVY(...);
}
}
}
You may also want to check if your if-conditions are correct, and do what you expected.
Assuming tempH is positive,
((ball.getY() + ball.getR()) > (tempY + tempH)
&& (ball.getY() + ball.getR()) <= tempY)
can't ever be true. The > needs to be < and the <= needs to be >=.
Additionally, you'll need to take some kind of action if the brick is hit, rather than just printing out the fact. Sorry, I'm not sure what's supposed to happen - does the brick disappear? Or the ball bounce? Or both?
Second answer (in addition to other answer which I believe is ALSO a problem), your logic is asking if the ball is contained within a brick, but when you create the ball its radius is greater than the height of a brick, so even correcting that logic won't fix the problem.
You should refactor your code to make it read out like natural language, this would help a lot with debugging (or writing less bugs in the first place!) i.e.
in brick class:
public int bottom()
{
return y;
}
public int top()
{
return y + h;
}
in ball class:
public int bottom()
{
return y - r;
}
public int top() {
return y + r;
}
then in main class:
private boolean withinY(brick) {
return (ball.bottom => brick.bottom() && ball.top =< brick.top());
}
then the logic reads nicer (psuedo):
foreach brick in wall {
if (ball.withinY(brick) and ball.withinX(brick))
BAM!!
}
You're checking if the ball is between the left and right side of the brick, but then checking if the ball is both above AND below the brick, because you've got your greater than and less than's mixed up. Also the center of the ball needs to be subtracted from it's Y position.
if ((ball.getY() + ball.getR()) **>** (tempY + tempH) &&
(ball.getY() **+** ball.getR()) **<=** tempY)
could be
if ((ball.getY() + ball.getR()) < (tempY + tempH) &&
(ball.getY() - ball.getR()) >= tempY)
but I'd suggest finding if the top of the ball is between the top and bottom of the brick, OR if the bottom of the ball is between the top and bottom of the brick:
if (((ball.getY() + ball.getR()) < (tempY + tempH) && (ball.getY() - ball.getR()) >= tempY)) ||
((ball.getY() - ball.getR()) < (tempY + tempH) && (ball.getY() - ball.getR()) >= tempY))) {
CODE
}
And use similar logic for finding between left and right sides of the brick

Asteroid game NullPointerException error

I am having some serious problems with my Asteroid game. I'm trying to call my Game.java run() method in my main method in Asteroid.java but I keep getting the same error:
Exception in thread "main" java.lang.NullPointerException
at asteroids.Asteroids.main(Asteroids.java:15)
Java Result: 1
Can someone help me figure out why this is happening?
here is my code:
Asteroids.java
package asteroids;
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
import java.awt.geom.Point2D;
import java.util.ArrayList;
import java.io.IOException;
#SuppressWarnings("serial")
public class Asteroids {
Game game = null;
public static void main(String[] args){
new Asteroids ().game.run ();
}
}
//NEW Game.java//
package asteroids;
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
import java.awt.geom.Point2D;
import java.util.ArrayList;
//#SuppressWarnings("serial")
public class Game extends Applet implements Runnable, KeyListener {
//timing variables
Thread thread;
long startTime, endTime, framePeriod;
//graphics variables
Image img;
Dimension dim;
int width, height;
Graphics g;
//text items
int level, lives, score;
SpaceShip ship;
boolean shipCollision, shipExplode;
//ArrayList to hold asteroids
ArrayList<Asteroid> asteroids = new ArrayList<>();
int numOfAsteroids = 1;
//ArrayList to hold the lasers
ArrayList<Laser> lasers = new ArrayList<>();
final double rateOfFire = 10; //limits rate of fire
double rateOfFireRemaining; //decrements rate of fire
//ArrayList to hold explosion particles
ArrayList<AsteroidExplosion> explodingLines = new ArrayList<>();
//ArrayList to hold ship explosions
ArrayList<ShipExplosion> shipExplosion = new ArrayList<>();
public void Game ()
{
init();
}
public void init() {
resize(900,700); //set size of the applet
dim = getSize(); //get dimension of the applet
width = dim.width;
height = dim.height;
framePeriod = 25; //set refresh rate
addKeyListener(this); //to get commands from keyboard
setFocusable(true);
ship = new SpaceShip(width/2, height/2, 0, .15, .5, .15, .98); //add ship to game
shipCollision = false;
shipExplode = false;
level = numOfAsteroids;
lives = 3;
addAsteroids();
img = createImage(width, height); //create an off-screen image for double-buffering
g = img.getGraphics(); //assign the off-screen image
thread = new Thread(this);
thread.start();
}
#Override
public void paint(Graphics gfx) {
Graphics2D g2d = (Graphics2D) g;
//give the graphics smooth edges
RenderingHints rh = new RenderingHints(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
rh.put(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
g2d.setRenderingHints(rh);
g2d.setColor(Color.BLACK);
g2d.fillRect(0, 0, width, height); //add a black background
//add text for lives, score, and level
g2d.setColor(Color.WHITE);
g2d.drawString("Level : " + level, 10, 690);
g2d.drawString("Lives : " + lives, 110, 690);
g2d.drawString("Score : " + score, 210, 690);
for(Asteroid a: asteroids) { //draw asteroids
a.draw(g2d);
}
for(Laser l : lasers) { //draw lasers
l.draw(g2d);
}
for(AsteroidExplosion e : explodingLines) {
e.draw(g2d);
}
for(ShipExplosion ex : shipExplosion)
ex.draw(g2d);
ship.draw(g2d); //draw ship
if(shipCollision) {
shipExplosion.add(new ShipExplosion(ship.getX(), ship.getY(), 10, 10));
ship.setX(width/2);
ship.setY(height/2);
shipCollision = false;
lives--;
}
gfx.drawImage(img, 0, 0, this); //draw the off-screen image (double-buffering) onto the applet
}
#Override
public void update(Graphics gfx) {
paint(gfx); //gets rid of white flickering
}
#Override
public void run(){
for( ; ; ) {
startTime = System.currentTimeMillis(); //timestamp
ship.move(width, height); //ship movement
for(Asteroid a : asteroids) { //asteroid movement
a.move(width, height);
}
for(Laser l : lasers) { //laser movement
l.move(width, height);
}
for(int i = 0 ; i<lasers.size() ; i++) { //laser removal
if(!lasers.get(i).getActive())
lasers.remove(i);
}
for(AsteroidExplosion e : explodingLines) { //asteroid explosion floating lines movement
e.move();
}
for(int i = 0 ; i<explodingLines.size(); i++) { //asteroid explosion floating lines removal
if(explodingLines.get(i).getLifeLeft() <= 0)
explodingLines.remove(i);
}
for(ShipExplosion ex : shipExplosion){ //ship explosion expansion
ex.expand();
}
for(int i = 0 ; i<shipExplosion.size() ; i++) {
if(shipExplosion.get(i).getLifeLeft() <= 0)
shipExplosion.remove(i);
}
rateOfFireRemaining--;
collisionCheck();
if(asteroids.isEmpty()) {
numOfAsteroids++;
addAsteroids();
level = numOfAsteroids;
}
repaint();
try {
endTime = System.currentTimeMillis(); //new timestamp
if(framePeriod - (endTime-startTime) > 0) //if there is time left over after repaint, then sleep
Thread.sleep(framePeriod - (endTime - startTime)); //for whatever is remaining in framePeriod
} catch(InterruptedException e) {}
}
}
#Override
public void keyPressed(KeyEvent e) {
int key = e.getKeyCode();
//fires laser
if(key == KeyEvent.VK_SPACE) {
if(rateOfFireRemaining <= 0 ) {
lasers.add(ship.fire());
rateOfFireRemaining = rateOfFire;
}
}
if(key == KeyEvent.VK_UP)
ship.setAccelerating(true);
if(key == KeyEvent.VK_RIGHT)
ship.setTurningRight(true);
if(key == KeyEvent.VK_LEFT)
ship.setTurningLeft(true);
if(key == KeyEvent.VK_DOWN)
ship.setDecelerating(true);
}
#Override
public void keyReleased(KeyEvent e) {
int key = e.getKeyCode();
if(key == KeyEvent.VK_UP)
ship.setAccelerating(false);
if(key == KeyEvent.VK_RIGHT)
ship.setTurningRight(false);
if(key == KeyEvent.VK_LEFT)
ship.setTurningLeft(false);
if(key == KeyEvent.VK_DOWN)
ship.setDecelerating(false);
}
#Override
public void keyTyped(KeyEvent e) {
}
public void addAsteroids() {
int numAsteroidsLeft = numOfAsteroids;
int size;
for(int i=0 ; i<numOfAsteroids ; i++) { //add asteroids to game
//randomize starting position
int asteroidX = (int)(Math.random() * width) + 1;
int asteroidY = (int)(Math.random() * height) + 1;
//randomize speed and direction
double xVelocity = Math.random() + 1; //horizontal velocity
double yVelocity = Math.random() + 1; //vertical velocity
//used starting direction
int xDirection = (int)(Math.random() * 2);
int yDirection = (int)(Math.random() * 2);
//randomize horizontal direction
if (xDirection == 1)
xVelocity *= (-1);
//randomize vertical direction
if (yDirection == 1)
yVelocity *= (-1);
//if there are more then four asteroids, any new ones are MEGA asteroids
if(numAsteroidsLeft > 4) {
size = 2;
} else { size = 1;
}
asteroids.add(new Asteroid(size, asteroidX, asteroidY, 0, .1, xVelocity, yVelocity));
numAsteroidsLeft--;
//Make sure that no asteroids can appear right on top of the ship
//get center of recently created asteroid and ship and check the distance between them
Point2D asteroidCenter = asteroids.get(i).getCenter();
Point2D shipCenter = ship.getCenter();
double distanceBetween = asteroidCenter.distance(shipCenter);
//if asteroid center is within 80 pixels of ship's center, remove it from the ArrayList and rebuild it
if(distanceBetween <= 80) {
asteroids.remove(i);
i--;
numAsteroidsLeft++;
}
}
}
public void collisionCheck() {
//cycle through active asteroids checking for collisions
for(int i = 0 ; i < asteroids.size() ; i++) {
Asteroid a = asteroids.get(i);
Point2D aCenter = a.getCenter();
//check for collisions between lasers and asteroids
for(int j = 0 ; j < lasers.size() ; j++) {
Laser l = lasers.get(j);
Point2D lCenter = l.getCenter();
double distanceBetween = aCenter.distance(lCenter);
if(distanceBetween <= (a.getRadius() + l.getRadius())) {
//split larger asteroids into smaller ones, remove smaller asteroids from screen
if(a.getRadius() >= 60) {
for(int k = 0 ; k < 3 ; k++)
explodingLines.add(a.explode());
split(i);
score += 200;
} else if(a.getRadius() >= 30){
for(int k = 0 ; k < 3 ; k++)
explodingLines.add(a.explode());
split(i);
score += 100;
} else {
for(int k = 0 ; k < 3 ; k++)
explodingLines.add(a.explode());
asteroids.remove(i);
score += 50;
}
lasers.remove(j); //remove laser from screen
}
}
//check for collisions between ship and asteroid
Point2D sCenter = ship.getCenter();
double distanceBetween = aCenter.distance(sCenter);
if(distanceBetween <= (a.getRadius() + ship.getRadius())) {
shipCollision = true;
shipExplode = true;
}
}
}
public void split(int i) {
Asteroid a = asteroids.get(i);
double bigAsteroidX = a.getX();
double bigAsteroidY = a.getY();
int size = (a.getSize() / 2);
asteroids.remove(i);
for(int j = 0 ; j<2 ; j++) {
//randomize speed and direction
double xVelocity = Math.random() + 1; //horizontal velocity
double yVelocity = Math.random() + 1; //vertical velocity
//used randomize starting direction
int xDirection = (int)(Math.random() * 2);
int yDirection = (int)(Math.random() * 2);
//randomize horizontal direction
if (xDirection == 1)
xVelocity *= (-1);
//randomize vertical direction
if (yDirection == 1)
yVelocity *= (-1);
asteroids.add(new Asteroid(size, bigAsteroidX, bigAsteroidY, 0, .1, xVelocity, yVelocity));
}
}
}
//Edit Update//
Okay I tried a lot of stuff and discovered that even though the game works when I debug Game.java and it doesn't work when I run it through Asteroids.java. I found that img = createIimg = createImage(width, height); and g = img.getGraphics(); are returning null and that GraphicsEnvironment.isHeadless() is returning true. How should I change my to fix this issue?
Error
Exception in thread "main" java.lang.NullPointerException
at asteroids.Game.init(Game.java:67)
at asteroids.Game.Game(Game.java:45)
at asteroids.Asteroids.main(Asteroids.java:15)
Java Result: 1
You have the var "game" null, and you tried to call the method "run" on this var (game.run); obviously if "game" is null, you can't get the method, and throws nullpointer exception.
Game game=new Game();
that's all you need. Your final code is:
Game game = new Game();//<----- here is the change
public static void main(String[] args){
new Asteroids ().game.run ();
}
This thing is null.
new Asteroids ().game
That's why you get this NullPointerException when you call run on it.
Game game = null;
public static void main(String[] args){
new Asteroids ().game.run ();
}
The prgram is running from the main method. game is null.
Maybe you should have
Game game = new Game(); // instead of null
Try it may be help
Game game = null;
public static void main(String[] args){
If( Asteroids ().game != null ){
new Asteroids ().game.run ();
}
}

Player not moving in 2D Game

I can not seem to get my player to move when certain keys are pressed. I did some debugging and placed a System.out.print("Pressed); in the if statements that check if a key is pressed and it prints out the message every time I press the key, they player just is not moving. Can someone help!
here is the InputHandler class
public class InputHandler implements KeyListener {
public InputHandler(Game game) {
game.addKeyListener(this);
}
public class Key {
private boolean pressed = false;
public void toggle(boolean isPressed) {
pressed = isPressed;
}
public boolean isPressed() {
return pressed;
}
}
// public List<Key> keys = new ArrayList<Key>();
public Key up = new Key();
public Key down = new Key();
public Key left = new Key();
public Key right = new Key();
public void keyPressed(KeyEvent e) {
toggleKey(e.getKeyCode(), true);
}
public void keyReleased(KeyEvent e) {
toggleKey(e.getKeyCode(), false);
}
public void keyTyped(KeyEvent e) {
}
public void toggleKey(int keyCode, boolean isPressed) {
if (keyCode == KeyEvent.VK_W) {
up.toggle(isPressed);
} else if (keyCode == KeyEvent.VK_S) {
down.toggle(isPressed);
} else if (keyCode == KeyEvent.VK_A) {
left.toggle(isPressed);
} else if (keyCode == KeyEvent.VK_D) {
right.toggle(isPressed);
}
}
}
and here is the Player class
public class Player extends Mob {
private InputHandler input;
private int r = 10;
public Player(int x, int y, int speed, InputHandler input) {
super("Player", x, y, 1);
this.input = input;
this.x = x;
this.y = y;
}
public boolean hasCollided(int dx, int dy) {
return false;
}
public void update() {
int dx = 0;
int dy = 0;
if (input.up.isPressed()) {
dy--;
} else if (input.down.isPressed()) {
dy++;
} else if (input.left.isPressed()) {
dx--;
} else if (input.right.isPressed()) {
dx++;
}
if (dx != 0 || dy != 0) {
move(dx, dy);
isMoving = true;
} else {
isMoving = false;
}
if (x < r)
x = r;
if (y < r)
y = r;
if (x > Game.WIDTH - r)
x = Game.WIDTH - r;
if (y > Game.HEIGHT - r)
y = Game.HEIGHT - r;
}
public void render(Graphics2D g) {
g.setColor(Color.BLACK);
g.fillOval(x - r, y - r, 2 * r, 2 * r);
g.setStroke(new BasicStroke(3));
g.setColor(Color.GRAY);
g.drawOval(x - r, y - r, 2 * r, 2 * r);
g.setStroke(new BasicStroke(1));
}
}
and here is the Mob class that has the move() method in it
public Mob(String name, int x, int y, int speed) {
this.name = name;
this.speed = speed;
}
public void move(int dx, int dy) {
if (dx != 0 && dy != 0) {
move(dx, 0);
move(dy, 0);
numSteps--;
return;
}
numSteps++;
if (!hasCollided(dx, dy)) {
if (dy < 0)
movingDir = 0;
if (dy > 0)
movingDir = 1;
if (dx < 0)
movingDir = 2;
if (dx > 0)
movingDir = 3;
x += dx * speed;
y += dy * speed;
}
}
public abstract boolean hasCollided(int dx, int dy);
public String getName() {
return _name;
}
}
From where is the render method inside the Player class called? Have you overridded paint(Graphics) or paintComponent(Graphics) somewhere?
Turns out the JFrame didn't have focus. Once it was in focus the code worked beautifully.
This code has all sorts of problems, but the most pressing seems to be that there is refrences to both _x and x. Choose one and make all the methods use that one. This may help, but honestly it is hard to tell exactly what to fix, maybe start with something simpler?
I found one error with your code for move. You call move(dx, 0) and move(dy, 0) inside an if statement, if both of them are not 0. In the ensuing recursion, they are both 0 and nothing is done. Instead, change the && to a ||
public void move(int dx, int dy) {
if (dx != 0 || dy != 0) {
move(dx, 0);
move(dy, 0);
numSteps--;
return;
}
...
}
There's so much code here that it's really too much for a single question.
A better approach would be to go ahead and make each class smaller. Specifically, don't error check for walls. Just move the mob/whatever around. If there's a problem, then the game(?) will throw an error...
In general, I would say that this approach is overly concerned with "what if?" problems rather than the basics of maneuverings a 2d dungeon with x,y coordinate system.
(Just to confuse matters, what if it was in polar coordinates!? Anyhow...)
After getting your code to run, I went ahead and put it on github for you:
https://github.com/THUFIR/Game2D/tree/master/src/genericGame
Feel free to fork it, please do. Git, or any version control, can really help out when your code was working, but something broke...
Here's the output, very simple:
thufir#dur:~/NetBeansProjects/Game2D$
thufir#dur:~/NetBeansProjects/Game2D$ java -jar dist/Game2D.jar
x 1 y 1
x 4 y 6
thufir#dur:~/NetBeansProjects/Game2D$
driver:
package genericGame;
import static java.lang.System.out;
public class Driver {
public static void main(String[] args) {
Player player = new Player(0, 0, 0);
player.move(1, 1);
out.println(player);
player.move(3, 5);
out.println(player);
}
}
and player:
package genericGame;
import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Graphics2D;
public class Player extends Mob {
private int r = 10;
public Player(int x, int y, int speed) {
super("Player", x, y);
this.x = x;
this.y = y;
}
public boolean hasCollided(int dx, int dy) {
return false;
}
public void update() {
int dx = 0;
int dy = 0;
if (input.up.isPressed()) {
dy--;
} else if (input.down.isPressed()) {
dy++;
} else if (input.left.isPressed()) {
dx--;
} else if (input.right.isPressed()) {
dx++;
}
if (dx != 0 || dy != 0) {
move(dx, dy);
isMoving = true;
} else {
isMoving = false;
}
if (x < r) {
x = r;
}
if (y < r) {
y = r;
}
if (x > Game.WIDTH - r) {
x = Game.WIDTH - r;
}
if (y > Game.HEIGHT - r) {
y = Game.HEIGHT - r;
}
}
public void render(Graphics2D g) {
g.setColor(Color.BLACK);
g.fillOval(x - r, y - r, 2 * r, 2 * r);
g.setStroke(new BasicStroke(3));
g.setColor(Color.GRAY);
g.drawOval(x - r, y - r, 2 * r, 2 * r);
g.setStroke(new BasicStroke(1));
}
}
Hope that helps. Please learn git.
I'll read the other answers to see better solutions, I just hit it with a hammer until it compiled. The naming conventions, organization, and access levels to methods, classes and fields are all, well, let's say, opportunities for improvement.

Java Game freezes at fighting

i'm just programming a java game and what i want to do is that when i press space, the character goes into fight mode for 5 sec and then release it. i already have done, that i press one time, fight mode gets enabled and when i press another time, its getting released but when i try it like this (code at bottom) the game just freezes for 5 sec but nothing happens and i don't even get a error code.
import java.awt.Graphics;
import java.awt.Image;
import java.awt.Toolkit;
import javax.swing.JPanel;
public class Zeichnen extends JPanel {
int x = 10;
int y = 335;
int width = 100;
int height = 106;
int speed = 10;
boolean left = false;
boolean fight = false;
String file = "res/character.png";
Image character;
public void paint(Graphics g) {
super.paintComponent(g);
character = Toolkit.getDefaultToolkit().getImage(file);
g.drawImage(character, x, y, width, height, this);
}
public void moveLeft() {
if (left == false) {
left = true;
if (fight == true) {
x = x + 129;
width = -129;
} else if (fight == false) {
x = x + 100;
width = -100;
}
}
x = x - speed;
rand();
repaint();
}
public void moveRight() {
if (left == true) {
left = false;
if (fight == true) {
x = x - 129;
width = 129;
} else if (fight == false) {
x = x - 100;
width = 100;
}
}
x = x + speed;
rand();
repaint();
}
public void moveUp() {
y = y - speed;
repaint();
}
public void moveDown() {
y = y + speed;
repaint();
}
public void fight() {
long curTime = System.currentTimeMillis();
fight = true;
file = "res/character_fight.png";
if (left == true) {
width = -129;
} else if (left == false) {
width = 129;
}
repaint();
if (System.currentTimeMillis() > curTime + 5000) {
fight = false;
file = "res/character.png";
if (left == true) {
width = -100;
} else if (left == false) {
width = 100;
}
repaint();
}
}
public void rand() {
if (x <= -130) {
x = 770;
} else if (x >= 770) {
x = -130;
}
}
}
The paint chain mechanism should be observed, you should override paintComponent rather than paint. Also don't load images when painting, load them when the JPanel is being initialised.
I do not understand your problem, you want that at the pression of a key, the image of your character changes for 5 seconds? in this case you should implement a listener and then open a timer to schedule a timer task
TimerTask task = new TimerTask() {
#Override
public void run() {
//reset your character to normal state
}
}
};
new Timer().schedule(task, 5000);

Categories