Shooting not working with ArrayList Java 2D Platformer - java

I have never tried to implement shooting in any kind of game before and when I try to remove and element of the ArrayList I'm using it throws and index out of bounds exception. I want to be able to press the enter key, store the current direction that the player is facing and then shoot a projectile in that current direction. Then, once a projectile has reached its destination to remove itself from the ArrayList and not be rendered anymore. However, when it reaches the end of the map (x == Map.mapSizeX), the bullet freezes and that's when the exception is thrown. (Exception in thread "AWT-EventQueue-0" java.lang.IndexOutOfBoundsException: Index: 1, Size: 1).
Code for the shooting class (Projectile.java)
package Engine;
import java.awt.Color;
import java.awt.Graphics2D;
import java.util.ArrayList;
import java.util.Random;
public class Projectile {
public static ArrayList<Integer> bullets = new ArrayList<Integer>(3);
private static DirectionalVector dir = new DirectionalVector();
private static int index = 0;
private static int x,y;
public Projectile(int direction, int x, int y){
dir.applyDirection(direction);
bullets.add(index);
index += 1;
this.x = x;
this.y = y;
}
public void updatePos(){
if (dir.right){
x += 1;
dir.left = false;
dir.down = false;
}
if (dir.left){
x -= 1;
dir.right = false;
dir.down = false;
}
if (dir.down){
y += 1;
dir.left = false;
dir.right = false;
}
if (dir.down){
System.out.println("DOWN");
}
if (dir.right){
System.out.println("RIGHT");
}
if (dir.left){
System.out.println("LEFT");
}
if (x > Map.mapSizeX){
bullets.remove(index);
}
if (x < 0){
bullets.remove(index);
}
if (y > Map.mapSizeY){
bullets.remove(index);
}
if (y < 0){
bullets.remove(index);
}
}
public static void render(Graphics2D g2){
int r = new Random().nextInt(256);
int g = new Random().nextInt(256);
int b = new Random().nextInt(256);
if (r < 50){
r = new Random().nextInt(256);
}
if (g < 50){
g = new Random().nextInt(256);
}
if (b < 50){
b = new Random().nextInt(256);
}
g2.setColor(new Color(r,g,b));
g2.fillRect(x * Map.tileSize, y * Map.tileSize, Map.tileSize, Map.tileSize);
}
Code for the DirectionalVector class
package Engine;
public class DirectionalVector {
public boolean left = false, right = true, down = false;
public DirectionalVector(){
}
public void applyDirection(int id){
if (id == 0){
right = true;
}
if (id == 1){
left = true;
}
if (id == 2){
down = true;
}
}
}
Code for the Player class
package Engine;
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
public class Player implements KeyListener, Runnable{
public static int x = 0,y = 0;
private static boolean right = false, left = false, falling = false, jumping = false;
private Thread thread = new Thread(this, "GAME LOOP");
private static int lastDirectionPressed = 0;
public static Projectile bullet;
public Player(){
thread.start();
}
public void renderPlayer(boolean value, Graphics2D g2){
if (value){
g2.setColor(Color.blue);
g2.fillRect(x * Map.tileSize, y * Map.tileSize, Map.tileSize, Map.tileSize);
}
}
#Override
public void keyPressed(KeyEvent e) {
int c = e.getKeyCode();
if (c == KeyEvent.VK_RIGHT && right){
x += 1;
lastDirectionPressed = 0;
}
if (c == KeyEvent.VK_LEFT && left){
x -= 1;
lastDirectionPressed = 1;
}
if (c == KeyEvent.VK_SPACE && jumping){
y -= 1;
}
if (c == KeyEvent.VK_ENTER){
bullet = new Projectile(lastDirectionPressed, x, y);
}
}
public void update(){
if (x != Map.mapSizeX){
right = Map.getTile(x + 1, y) == 0;
}
if (x > 0){
left = Map.getTile(x - 1, y) == 0;
}
if (x == 0){
left = false;
}
if (x == Map.mapSizeX){
right = false;
}
if (y != Map.mapSizeY){
falling = Map.getTile(x, y + 1) == 0;
}
if (y == Map.mapSizeY){
falling = false;
}
if (falling){
y += 1;
}
}
#Override
public void keyReleased(KeyEvent e) {
}
#Override
public void keyTyped(KeyEvent e) {
}
#Override
public void run(){
while (true){
try{
Thread.sleep(100);
update();
}catch (InterruptedException e){
e.printStackTrace();
}
}
}
}
Code for the ContentPane class (Where all the rendering occurs)
package Engine;
import java.awt.Graphics;
import java.awt.Graphics2D;
import javax.swing.JPanel;
#SuppressWarnings({"serial", "static-access"})
public class ContentPane extends JPanel{
private Map map = new Map();
public Player player = new Player();
public ContentPane(){
}
public void paintComponent(Graphics g){
Graphics2D g2 = (Graphics2D) g;
super.paintComponent(g2);
map.renderMap(true, g2);
player.renderPlayer(true, g2);
if (player.bullet.bullets.size() > 0){
player.bullet.updatePos();
}
for (int i = 0; i < player.bullet.bullets.size(); i++){
player.bullet.render(g2);
}
System.out.println(player.bullet.bullets.size());
repaint();
}
}

Related

Java Tetris Key Listener Not Working (No Errors On Console)

I'm working on a project for my AP computer science class and can't seem to figure out how to get my key listeners to work I've tried using if statements and switch cases but neither of these make the key listeners work. The code consists of three classes Tetris Runner, Canvas, PeiceMaker everything functions fine with exception of the key listeners The key listeners are located at the bottom of the canvas class any help would be appreciated thanks.
Canvas Class
package Tetris;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.Timer;
import Tetris.PieceMaker.Tetronimos;
#SuppressWarnings("serial")
public class Canvas extends JPanel implements ActionListener
{
public static final int CANVASWIDTH = 10;
public static final int CANVASHEIGHT = 22;
private Color[] colors =
{
new Color(0, 0, 0),
new Color(204, 102, 102),
new Color(102, 204, 102),
new Color(102, 102, 204),
new Color(204, 204, 102),
new Color(204, 102, 204),
new Color(102, 204, 204),
new Color(218, 170, 0)
};
private boolean blockSet = false;
private boolean startGame = false;
private boolean pauseGame = false;
private int linesErased = 0;
private int currentX = 0;
private int currentY = 0;
private JLabel scoreLabel;
private Timer time;
private PieceMaker currentShape;
private Tetronimos[] canvas;
public Canvas(TetrisRunner run)
{
setFocusable(true);
currentShape = new PieceMaker();
time = new Timer(500, this);
scoreLabel = run.getScoreLabel();
canvas = new Tetronimos[CANVASWIDTH * CANVASHEIGHT];
clearCanvas();
addKeyListener(new TetrisAdap());
}
public int blockWidth()
{
return (int)getSize().getWidth()/CANVASWIDTH;
}
public int blockHeight()
{
return (int)getSize().getHeight()/CANVASHEIGHT;
}
public Tetronimos shapeLocation(int x, int y)
{
return canvas[y * CANVASWIDTH + x];
}
public void clearCanvas()
{
for(int i = 0; i < CANVASHEIGHT * CANVASWIDTH; i++)
{
canvas[i] = Tetronimos.noShape;
}
}
public void droppedPiece()
{
for(int i = 0; i < 4; i++)
{
int newX = currentX + currentShape.getXPosition(i);
int newY = currentY - currentShape.getYPosition(i);
canvas[newY * CANVASWIDTH + newX] = currentShape.getShape();
}
clearRow();
if(!blockSet)
{
makeNewPiece();
}
}
public void makeNewPiece()
{
currentShape.chooseRandomShape();
currentX = CANVASWIDTH / 2 + 1;
currentY = CANVASHEIGHT - 1 + currentShape.minY();
if(!movePiece(currentShape, currentX, currentY - 1))
{
currentShape.setShape(Tetronimos.noShape);
time.stop();
startGame = false;
scoreLabel.setText("GAME OVER");
}
}
public void moveDownLine()
{
if(!movePiece(currentShape, currentX, currentY - 1))
{
droppedPiece();
}
}
public void actionPerformed(ActionEvent e)
{
if(blockSet)
{
blockSet = false;
makeNewPiece();
} else {
moveDownLine();
}
}
public void drawShape(int x, int y, Tetronimos shape, Graphics g)
{
Color color = colors[shape.ordinal()];
g.setColor(color);
g.fillRect(x + 1, y + 1, blockWidth() - 2, blockHeight() - 2);
g.setColor(color.brighter());
g.drawLine(x, y + blockHeight() - 1, x, y);
g.drawLine(x, y, x + blockWidth() - 1, y);
g.setColor(color.darker());
g.drawLine(x + 1, y + blockHeight() - 1, x + blockWidth() - 1, y + blockHeight() - 1);
g.drawLine(x + blockWidth() - 1, y + blockHeight() - 1, x + blockWidth() - 1, y + 1);
}
public void paint(Graphics g)
{
super.paint(g);
Dimension size = getSize();
int topOfCanvas = (int)size.getHeight() - CANVASHEIGHT * blockHeight();
for(int i = 0; i < CANVASHEIGHT; i++)
{
for(int p = 0; p < CANVASWIDTH; p++)
{
Tetronimos shape = shapeLocation(p, CANVASHEIGHT - i - 1);
if(shape != Tetronimos.noShape)
{
drawShape(p * blockWidth(), topOfCanvas + i * blockHeight(), shape, g);
}
}
}
if(currentShape.getShape() != Tetronimos.noShape)
{
for(int i = 0; i < 4; i++)
{
int x = currentX + currentShape.getXPosition(i);
int y = currentY - currentShape.getYPosition(i);
drawShape(x * blockWidth(), topOfCanvas + (CANVASHEIGHT - y - 1) * blockHeight(), currentShape.getShape(), g);
}
}
}
public void start()
{
if(pauseGame)
{
return;
}
startGame = true;
blockSet = false;
linesErased = 0;
clearCanvas();
makeNewPiece();
time.start();
}
public void pause()
{
if(!startGame)
{
return;
}
pauseGame = !pauseGame;
if(pauseGame)
{
time.stop();
scoreLabel.setText("PAUSED");
} else {
time.start();
scoreLabel.setText(String.valueOf(linesErased));
}
repaint();
}
public boolean movePiece(PieceMaker newPiece, int xVel, int yVel)
{
for(int i = 0; i < 4; i++)
{
int x = xVel + newPiece.getXPosition(i);
int y = yVel - newPiece.getYPosition(i);
if(x < 0 || x >= CANVASWIDTH || y < 0 || y >= CANVASHEIGHT)
{
return false;
}
if(shapeLocation(x, y) != Tetronimos.noShape)
{
return false;
}
}
currentShape = newPiece;
currentX = xVel;
currentY = yVel;
repaint();
return true;
}
public void clearRow()
{
int fullRows = 0;
for(int i = CANVASHEIGHT - 1; i >= 0; i--)
{
boolean rowIsFull = true;
for(int p = 0; p < CANVASWIDTH; p++)
{
if(shapeLocation(p, i) == Tetronimos.noShape)
{
rowIsFull = false;
break;
}
}
if(rowIsFull)
{
fullRows++;
for(int j = i; j < CANVASHEIGHT - 1; j++)
{
for(int k = 0; k < CANVASWIDTH; k++)
{
canvas[j * CANVASWIDTH + k] = shapeLocation(j, k + 1);
}
}
}
if(fullRows > 0)
{
linesErased += fullRows;
scoreLabel.setText(String.valueOf(linesErased));
blockSet = true;
currentShape.setShape(Tetronimos.noShape);
repaint();
}
}
}
public void dropRows()
{
int nextY = currentY;
while(nextY > 0)
{
if(!movePiece(currentShape, currentX, nextY - 1))
{
break;
}
nextY--;
}
droppedPiece();
}
//Tetris Adapter
public class TetrisAdap extends KeyAdapter {
public void KeyPressed(KeyEvent ke)
{
if(!startGame || currentShape.getShape() == Tetronimos.noShape)
{
System.out.println("Here");
return;
}
int keyCode = ke.getKeyCode();
if(keyCode == 'p' || keyCode == 'P')
pause();
if(pauseGame)
return;
if(keyCode == KeyEvent.VK_LEFT)
{
System.out.println("left");
movePiece(currentShape, currentX - 1, currentY);
}
if(keyCode == KeyEvent.VK_RIGHT)
{
System.out.println("right");
movePiece(currentShape, currentX + 1, currentY);
}
if(keyCode == KeyEvent.VK_DOWN)
{
System.out.println("down");
movePiece(currentShape.rotateRight(), currentX, currentY);
}
if(keyCode == KeyEvent.VK_UP)
{
System.out.println("up");
movePiece(currentShape.rotateLeft(), currentX, currentY);
}
if(keyCode == KeyEvent.VK_SPACE)
{
dropRows();
}
if(keyCode == 'd')
moveDownLine();
if(keyCode == 'D')
moveDownLine();
/*
* switch(keyCode)
{
case KeyEvent.VK_LEFT:
System.out.println("left");
movePiece(currentShape, currentX - 1, currentY);
break;
case KeyEvent.VK_RIGHT:
System.out.println("right");
movePiece(currentShape, currentX + 1, currentY);
break;
case KeyEvent.VK_DOWN:
System.out.println("down");
movePiece(currentShape.rotateRight(), currentX, currentY);
break;
case KeyEvent.VK_UP:
System.out.println("up");
movePiece(currentShape.rotateLeft(), currentX, currentY);
break;
case KeyEvent.VK_SPACE:
dropRows();
break;
case 'd' :
moveDownLine();
break;
case 'D' :
moveDownLine();
}
*
*/
}
}
}
Tetris Runner
package Tetris;
import java.awt.BorderLayout;
import javax.swing.JFrame;
import javax.swing.JLabel;
#SuppressWarnings("serial")
public class TetrisRunner extends JFrame
{
private JLabel scoreLabel;
public TetrisRunner()
{
scoreLabel = new JLabel("0");
add(scoreLabel, BorderLayout.SOUTH);
Canvas canvas = new Canvas(this);
add(canvas);
canvas.makeNewPiece();
canvas.start();
setSize(400, 800);
setTitle("Tetris");
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
public static void main(String[] args)
{
TetrisRunner runner = new TetrisRunner();
runner.setLocationRelativeTo(null);
runner.setVisible(true);
}
public JLabel getScoreLabel()
{
return scoreLabel;
}
}
Peice Maker
package Tetris;
import java.util.Random;
public class PieceMaker
{
private Tetronimos shapeChoice;
private int[][] coordinates;
public PieceMaker()
{
coordinates = new int[4][2];
setShape(Tetronimos.noShape);
}
enum Tetronimos
{
noShape(new int[][] { {0,0}, {0,0}, {0,0}, {0,0} }),
lineShape(new int[][] { {0,-1}, {0,0}, {0,1}, {0,2} }),
sShape(new int[][] { {0,-1}, {0,0}, {1,0}, {1,1} }),
zShape(new int[][] { {0,-1}, {0,0}, {-1,0}, {-1,1} }),
tShape(new int[][] { {-1,0}, {0,0}, {1,0}, {0,1} }),
lShape(new int[][] { {-1,-1}, {0,-1}, {0,0}, {0,1} }),
jShape(new int[][] { {-1,-1}, {0,-1}, {0,0}, {0,1} }),
blockShape(new int[][] { {0,0}, {1,0}, {0,1}, {1,1} });
public int[][] shapeCoordinates;
private Tetronimos(int[][] coordinates)
{
this.shapeCoordinates = coordinates;
}
}
public void chooseRandomShape()
{
Random rand = new Random();
int randChoice = Math.abs(rand.nextInt() % 7 + 1);
Tetronimos[] choice = Tetronimos.values();
setShape(choice[randChoice]);
}
public void setShape(Tetronimos shape)
{
for(int i = 0; i < 4; i++)
{
for(int p = 0; p < 2; p++)
{
coordinates[i][p] = shape.shapeCoordinates[i][p];
}
}
shapeChoice = shape;
}
public void setXPosition(int oldX, int newX)
{
coordinates[oldX][0] = newX;
}
public void setYPosition(int oldY, int newY)
{
coordinates[oldY][1] = newY;
}
public int getXPosition(int newX)
{
return coordinates[newX][0];
}
public int getYPosition(int newY)
{
return coordinates[newY][1];
}
public Tetronimos getShape()
{
return shapeChoice;
}
public int minX()
{
int minX = coordinates[0][0];
for(int i = 0; i < 4; i++)
{
minX = Math.min(minX, coordinates[i][0]);
}
return minX;
}
public int minY()
{
int minY = coordinates[0][1];
for(int i = 0; i < 4; i++)
{
minY = Math.min(minY, coordinates[i][1]);
}
return minY;
}
//Rotate piece Left
public PieceMaker rotateLeft()
{
System.out.println("left");
if(shapeChoice == Tetronimos.blockShape)
{
return this;
}
PieceMaker res = new PieceMaker();
res.shapeChoice = shapeChoice;
for(int i = 0; i < 4; i++)
{
res.setXPosition(i, getYPosition(i));
res.setYPosition(i, -getXPosition(i));
}
return res;
}
//Rotate piece right
public PieceMaker rotateRight()
{
System.out.println("right");
if(shapeChoice == Tetronimos.blockShape)
{
return this;
}
PieceMaker res = new PieceMaker();
res.shapeChoice = shapeChoice;
for(int i = 0; i < 4; i++)
{
res.setXPosition(i, -getYPosition(i));
res.setYPosition(i, getXPosition(i));
}
return res;
}
}
You misspelled your keyPressed()-Method. Use
public class TetrisAdap extends KeyAdapter {
public void keyPressed(KeyEvent ke) { ...
instead of
public class TetrisAdap extends KeyAdapter {
public void KeyPressed(KeyEvent ke)
{

How would I test collision for 2 images in Java.

I am currently making a Space Shooter in Java. I am able to make bullets shoot and enemies come from the top, but I am not sure how to check if they intersect. I understand that the Rectangle class has a intersects method, but I am not sure how I would place the rectangles around the bullets and the enemies, since I don't know beforehand how many may be on the screen. How can I do this? Here is my code:
Game.java
package main;
import java.awt.Canvas;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.image.BufferStrategy;
import java.awt.image.BufferedImage;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.JFrame;
public class Game extends Canvas implements Runnable, KeyListener {
//declare values
private static final long serialVersionUID = 1L;
public static final int WIDTH = 800;
public static final int HEIGHT = 600;
public static final String TITLE = "Space Shooter";
private boolean running = false;
private Thread thread;
private Player player;
private BufferedImage playerImage;
private BufferedImage bulletImage;
private BufferedImage enemyImage;
int playerx;
int playery;
int round = 1;
public Game() {
//
player = new Player((WIDTH/2)-32, HEIGHT-200);
//allocates all file resources
try {
playerImage = ImageIO.read(this.getClass().getResourceAsStream("/resources/player.png"));
bulletImage = ImageIO.read(this.getClass().getResourceAsStream("/resources/bullet.png"));
enemyImage = ImageIO.read(this.getClass().getResourceAsStream("/resources/enemy.png"));
} catch (IOException e) {
e.printStackTrace();
}
addKeyListener(this);
setFocusable(true);
requestFocusInWindow();
}
//starts thread
private synchronized void start() {
if (running)
return;
running = true;
thread = new Thread(this);
thread.start();
}
//stops thread
private synchronized void stop() {
if (!running)
return;
running = false;
try {
thread.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.exit(1);
}
#Override
//game loop
public void run() {
long lastTime = System.nanoTime();
final double amountOfTicks = 60.0;
double ns = 1000000000 / amountOfTicks;
double delta = 0;
int updates = 0;
int frames = 0;
long timer = System.currentTimeMillis();
while (running) {
long now = System.nanoTime();
delta += (now - lastTime) / ns;
lastTime = now;
if (delta > 1) {
tick();
updates++;
delta--;
}
Shoot.updateBullets();
Enemy.updateEnemies();
render();
frames++;
if (System.currentTimeMillis() - timer > 1000) {
timer += 1000;
System.out.println(updates + " TICKS, " + frames + " FPS");
updates = 0;
frames = 0;
}
}
stop();
}
//updates sprite locations
public void tick() {
playerx = player.getX();
playery = player.getY();
}
//renders sprites
public void render() {
//setting up triple-buffering
BufferStrategy bs = this.getBufferStrategy();
if (bs == null) {
createBufferStrategy(3);
return;
}
Graphics g = bs.getDrawGraphics();
//////////////////////////////////
g.setColor(Color.BLACK); g.fillRect(0,0,getWidth(), getHeight());
g.drawImage(playerImage, playerx, playery, this);
if (Shoot.allBullets.size() != 0) {
for (int i = 0; i < Shoot.allBullets.size(); i++) {
int bulletx = (int) Shoot.allBullets.get(i).x;
int bullety = (int) Shoot.allBullets.get(i).y;
g.drawImage(bulletImage, bulletx + 21, bullety, this);
}
}
if (Enemy.allEnemies.size() != 0) {
for (int i = 0; i < Enemy.allEnemies.size(); i++) {
int enemyx = (int) Enemy.allEnemies.get(i).x;
int enemyy = (int) Enemy.allEnemies.get(i).y;
g.drawImage(enemyImage, enemyx, enemyy, this);
}
} else {
Enemy.createEnemies(round);
round++;
}
//////////////////////////////////
g.dispose();
bs.show();
}
#Override
public void keyReleased(KeyEvent e) {
int key = e.getKeyCode();
if (key == KeyEvent.VK_SPACE) {
Shoot.addBullet(player.getX(), player.getY());
}
}
public void keyPressed(KeyEvent e) {
int key = e.getKeyCode();
if (key == KeyEvent.VK_UP) {
player.setY(playery -= 20);
} else if (key == KeyEvent.VK_DOWN) {
player.setY(playery += 20);
} else if (key == KeyEvent.VK_RIGHT) {
player.setX(playerx += 40);
} else if (key == KeyEvent.VK_LEFT) {
player.setX(playerx -= 40);
}
}
public void keyTyped(KeyEvent e) {}
public static void main(String[] args) {
Game game = new Game();
JFrame frame = new JFrame(TITLE);
frame.setSize(WIDTH, HEIGHT);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setResizable(false);
frame.add(game);
frame.getContentPane().setBackground(Color.BLACK);
frame.setVisible(true);
game.start();
}
}
Shoot.java
package main;
import java.util.ArrayList;
public class Shoot {
static ArrayList<Point> allBullets = new ArrayList<Point>();
public static void addBullet(int x, int y) {
allBullets.add(new Point(x, y));
}
public static ArrayList<Point> getAllBulletPosistions() {
return allBullets;
}
public static void updateBullets() {
if (allBullets.size() != 0) {
for (int i = 0; i < allBullets.size(); i++) {
allBullets.get(i).y -= 1;
}
}
}
}
Enemy.java
package main;
import java.util.ArrayList;
public class Enemy {
static ArrayList<Point> allEnemies = new ArrayList<Point>();
public static ArrayList<Point> createEnemies(int round) {
for (int i = 0; i < round; i++) {
Point newEnemyLocation = new Point((int) (Math.random()*Game.WIDTH - 64), 0);
if (newEnemyLocation.x < 64) {
newEnemyLocation.x += 70;
}
allEnemies.add(newEnemyLocation);
}
return allEnemies;
}
int validate(int xpos) {
if (xpos > Game.WIDTH - 64) {
xpos -= 64;
}
if (xpos < 64) {
xpos += 64;
}
return xpos;
}
public static ArrayList<Point> updateEnemies() {
if (allEnemies.size() != 0) {
for (int i = 0; i < allEnemies.size(); i++) {
Point enemyLocation = allEnemies.get(i);
if (enemyLocation.y <= Game.HEIGHT) {
allEnemies.get(i).y += 0.1;
} else {
allEnemies.remove(i);
}
}
}
return allEnemies;
}
}
for(int i = 0; i < Shoot.allBullets.size(); i++){
for(int j = 0; j < Enemy.allEnemys.size(); j++){
if(new Rectangle(Shoot.allBullets.get(i).x,Shoot.allBullets.get(i).y, width, height).intersects(new Rectangle(Enemy.allEnemys.get(j).x, Enemy.allEnemys.get(j).y, width, height)){
//on intersect
}
}
}
This would work but you shouldn't create new rectangles like this instead you should create a bullet class and a Enemy class that both contains the position and Rectangle anyways good luck!

Dr Java- Static Error: This class does not have a static void main method accepting String[]

I try running this program and I get a static void error. I am new to this and I have no idea how to fix this problem so any input would be helpful, thank you!
package johnbarthelmes.Java;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import javax.swing.ImageIcon;
import javax.swing.JPanel;
import javax.swing.Timer;
public class Board extends JPanel implements ActionListener {
private final int B_WIDTH = 300;
private final int B_HEIGHT = 300;
private final int DOT_SIZE = 10;
private final int ALL_DOTS = 900;
private final int RAND_POS = 29;
private final int DELAY = 140;
private final int x[] = new int[ALL_DOTS];
private final int y[] = new int[ALL_DOTS];
private int dots;
private int apple_x;
private int apple_y;
private boolean leftDirection = false;
private boolean rightDirection = true;
private boolean upDirection = false;
private boolean downDirection = false;
private boolean inGame = true;
private Timer timer;
private Image ball;
private Image apple;
private Image head;
public Board() {
addKeyListener(new TAdapter());
setBackground(Color.black);
setFocusable(true);
setPreferredSize(new Dimension(B_WIDTH, B_HEIGHT));
loadImages();
initGame();
}
private void loadImages() {
ImageIcon iid = new ImageIcon("dot.png");
ball = iid.getImage();
ImageIcon iia = new ImageIcon("apple.png");
apple = iia.getImage();
ImageIcon iih = new ImageIcon("head.png");
head = iih.getImage();
}
private void initGame() {
dots = 3;
for (int z = 0; z < dots; z++) {
x[z] = 50 - z * 10;
y[z] = 50;
}
locateApple();
timer = new Timer(DELAY, this);
timer.start();
}
#Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
doDrawing(g);
}
private void doDrawing(Graphics g) {
if (inGame) {
g.drawImage(apple, apple_x, apple_y, this);
for (int z = 0; z < dots; z++) {
if (z == 0) {
g.drawImage(head, x[z], y[z], this);
} else {
g.drawImage(ball, x[z], y[z], this);
}
}
Toolkit.getDefaultToolkit().sync();
} else {
gameOver(g);
}
}
private void gameOver(Graphics g) {
String msg = "Game Over";
Font small = new Font("Helvetica", Font.BOLD, 14);
FontMetrics metr = getFontMetrics(small);
g.setColor(Color.white);
g.setFont(small);
g.drawString(msg, (B_WIDTH - metr.stringWidth(msg)) / 2, B_HEIGHT / 2);
}
private void checkApple() {
if ((x[0] == apple_x) && (y[0] == apple_y)) {
dots++;
locateApple();
}
}
private void move() {
for (int z = dots; z > 0; z--) {
x[z] = x[(z - 1)];
y[z] = y[(z - 1)];
}
if (leftDirection) {
x[0] -= DOT_SIZE;
}
if (rightDirection) {
x[0] += DOT_SIZE;
}
if (upDirection) {
y[0] -= DOT_SIZE;
}
if (downDirection) {
y[0] += DOT_SIZE;
}
}
private void checkCollision() {
for (int z = dots; z > 0; z--) {
if ((z > 4) && (x[0] == x[z]) && (y[0] == y[z])) {
inGame = false;
}
}
if (y[0] >= B_HEIGHT) {
inGame = false;
}
if (y[0] < 0) {
inGame = false;
}
if (x[0] >= B_WIDTH) {
inGame = false;
}
if (x[0] < 0) {
inGame = false;
}
if(!inGame) {
timer.stop();
}
}
private void locateApple() {
int r = (int) (Math.random() * RAND_POS);
apple_x = ((r * DOT_SIZE));
r = (int) (Math.random() * RAND_POS);
apple_y = ((r * DOT_SIZE));
}
#Override
public void actionPerformed(ActionEvent e) {
if (inGame) {
checkApple();
checkCollision();
move();
}
repaint();
}
private class TAdapter extends KeyAdapter {
#Override
public void keyPressed(KeyEvent e) {
int key = e.getKeyCode();
if ((key == KeyEvent.VK_LEFT) && (!rightDirection)) {
leftDirection = true;
upDirection = false;
downDirection = false;
}
if ((key == KeyEvent.VK_RIGHT) && (!leftDirection)) {
rightDirection = true;
upDirection = false;
downDirection = false;
}
if ((key == KeyEvent.VK_UP) && (!downDirection)) {
upDirection = true;
rightDirection = false;
leftDirection = false;
}
if ((key == KeyEvent.VK_DOWN) && (!upDirection)) {
downDirection = true;
rightDirection = false;
leftDirection = false;
}
}
}
}
If it helps at all this is the code for the snake game that I got from a Dr Java tutorial in which I followed all the steps correctly as far as I know. There was no errors compiling but when I ran the program I got that error message.
In order to run an application, your class needs a main method with a certain signature, so Java knows what to do. Probably you want to start up the program by showing your JFrame:
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
Board b = new Board();
b.setVisible(true);
}
});
}
You need to add a main method. It's the entry point to every Java application. It looks like it should have this implementation, based on your code sample.
public static void main(String[] args) {
Board board = new Board();
// need to do something else with board here maybe?
}

How do I make an infinite tiled map? (java)

I'm making a tiled map and I came across this problem:
When i'm moving my character it's going off the map and then falls (due to gravity)
How do I make this map infinite?
And also, how do I store which blocks are destroyed and which not? So that i can repaint the screen with the same map and when you walk back to the starting point the brocken blocks are still there.
Just Tell me if I need to provide Code.
I'll give you my world.java
package game.test.src;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.Rectangle;
import javax.swing.ImageIcon;
public class World {
public Rectangle[] blocks;
public boolean[] isSolid;
public Image[] blockImg;
public final int arrayNum = 500;
//Block Images
public Image BLOCK_GRASS, BLOCK_DIRT, BLOCK_STONE, BLOCK_SKY;
private int x, y, xDirection, yDirection;;
//map navigation
static final int PAN_UP = 0, PAN_DOWN = 1, PAN_LEFT= 2, PAN_RIGHT = 3;
public World(){
BLOCK_GRASS = new ImageIcon("H:/2D game test/Game test 2/src/game/test/src/images/tile_grass.png").getImage();
BLOCK_DIRT = new ImageIcon("H:/2D game test/Game test 2/src/game/test/src/images/tile_dirt.png").getImage();
BLOCK_STONE = new ImageIcon("H:/2D game test/Game test 2/src/game/test/src/images/tile_stone.png").getImage();
BLOCK_SKY = new ImageIcon("H:/2D game test/Game test 2/src/game/test/src/images/tile_sky.png").getImage();
blocks = new Rectangle[500];
blockImg = new Image[500];
isSolid = new boolean[arrayNum];
loadArrays();
}
private void loadArrays(){
for(int i = 0; i < arrayNum; i++){
if(x >= 500){
x = 0;
y += 20;
}
if(i >= 0 && i < 100){
blockImg[i] = BLOCK_SKY;
isSolid[i] = false;
blocks[i] = new Rectangle(x, y, 20, 20);
}
if(i >= 100 && i < 125){
blockImg[i] = BLOCK_GRASS;
isSolid[i] = true;
blocks[i] = new Rectangle(x, y, 20, 20);
}
if(i >= 125 && i < 225){
blockImg[i] = BLOCK_DIRT;
isSolid[i] = true;
blocks[i] = new Rectangle(x, y, 20, 20);
}
if(i >= 225 && i < 500){
blockImg[i] = BLOCK_STONE;
isSolid[i] = true;
blocks[i] = new Rectangle(x, y, 20, 20);
}
x += 20;
}
}
public void draw(Graphics g){
for(int i = 0; i < arrayNum; i++){
g.drawImage(blockImg[i], blocks[i].x, blocks[i].y, null);
}
}
public void moveMap(){
for(Rectangle r : blocks){
r.x += xDirection;
r.y += yDirection;
}
}
public void stopMoveMap(){
setXDirection(0);
setYDirection(0);
}
private void setXDirection(int dir){
xDirection = dir;
}
private void setYDirection(int dir){
yDirection = dir;
}
public void navigateMap(int nav){
switch(nav){
default:
System.out.println("default case entered... Doing nothing.");
break;
case PAN_UP:
setYDirection(-1);
break;
case PAN_DOWN:
setYDirection(1);
break;
case PAN_LEFT:
setXDirection(-1);
break;
case PAN_RIGHT:
setXDirection(1);
break;
}
}
}
here is my Player.java
package game.test.src;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.Rectangle;
import java.awt.event.MouseEvent;
import javax.swing.ImageIcon;
public class Player {
static final int MOVE_UP = 0, MOVE_DOWN = 1, MOVE_LEFT= 2, MOVE_RIGHT = 3;
private World world;
private Rectangle playerRect;
private Image playerImg;
//Block Variables
private int hoverX, hoverY;
private boolean hovering = false;
protected static int xDirection;
protected static int yDirection;
private Weapon weapon;
public Player(World world){
this.world = world;
playerImg = new ImageIcon("H:/2D game test/Game test 2/src/game/test/src/images/Character.png").getImage();
playerRect = new Rectangle(50, 0, 10, 36);
weapon = new Weapon(weapon.PICKAXE);
}
private static void setXDirection(int d){
xDirection = d;
}
private static void setYDirection(int d){
yDirection = d;
}
public void update()
{
move();
checkForCollision();
}
private void checkForCollision() {
}
private void move()
{
playerRect.x += xDirection;
playerRect.y += yDirection;
gravity();
}
private void gravity()
{
for(int i=0;i<world.arrayNum; i++)
{
if(!world.isSolid[i])
{
setYDirection(1);
}
else if(world.isSolid[i] && playerRect.intersects(world.blocks[i]))
{
setYDirection(0);
}
}
}
//MotionEvents
public void mousePressed(MouseEvent e)
{
}
public void mouseReleased(MouseEvent e)
{
}
public void mouseClicked(MouseEvent e)
{
}
public void mouseMoved(MouseEvent e)
{
int x = e.getX();
int y = e.getY();
int px = playerRect.x;
int py = playerRect.y;
for(int i = 0; i < world.arrayNum; i++)
{
if(weapon.isEquipped(Weapon.PICKAXE) &&
x > world.blocks[i].x && x < world.blocks[i].x + world.blocks[i].width &&
y > world.blocks[i].x && y < world.blocks[i].y + world.blocks[i].height && world.isSolid[i] &&
(world.blocks[i].x + (world.blocks[i].width / 2) ) <= (px + playerRect.width/2) + weapon.WEAPON_RADIUS &&
(world.blocks[i].x + (world.blocks[i].width / 2) ) >= (px + playerRect.width/2) - weapon.WEAPON_RADIUS &&
(world.blocks[i].y + (world.blocks[i].height / 2) ) <= (py + playerRect.height/2) + weapon.WEAPON_RADIUS &&
(world.blocks[i].y + (world.blocks[i].height / 2) ) >= (py + playerRect.height/2) - weapon.WEAPON_RADIUS)
{
hovering = true;
hoverX = world.blocks[i].x;
hoverY = world.blocks[i].y;
break;
}
else
hovering = false;
}
}
public void mouseDragged(MouseEvent e)
{
}
public void mouseEntered(MouseEvent e)
{
}
public void mouseExited(MouseEvent e)
{
}
//Drawing Methods
public void draw(Graphics g)
{
g.drawImage(playerImg, playerRect.x, playerRect.y, null);
if(hovering)
drawBlockOutline(g);
}
private void drawBlockOutline(Graphics g)
{
g.setColor(Color.black);
g.drawRect(hoverX, hoverY, world.blocks[0].width,world.blocks[0].height);
}
private class Weapon
{
public static final int UNARMED = 0;
public static final int PICKAXE = 1;
public static final int GUN = 2;
public int CURRENT_WEAPON;
public int WEAPON_RADIUS;
public Weapon(int w)
{
switch(w)
{
default:
System.out.println("No weapon selected");
break;
case UNARMED:
CURRENT_WEAPON = UNARMED;
WEAPON_RADIUS = 100;
break;
case PICKAXE:
CURRENT_WEAPON = PICKAXE;
WEAPON_RADIUS = 100;
break;
case GUN:
CURRENT_WEAPON = GUN;
WEAPON_RADIUS = 100;
break;
}
}
public void selectWeapon(int w)
{
switch(w)
{
default:
System.out.println("No weapon selected");
break;
case UNARMED:
CURRENT_WEAPON = UNARMED;
WEAPON_RADIUS = 100;
break;
case PICKAXE:
CURRENT_WEAPON = PICKAXE;
WEAPON_RADIUS = 100;
break;
case GUN:
CURRENT_WEAPON = GUN;
WEAPON_RADIUS = 100;
break;
}
}
public boolean isEquipped(int w)
{
if(w == CURRENT_WEAPON)
{
return true;
}
else
return false;
}
}
public void moveMap(){
for(Rectangle r : world.blocks){
r.x += xDirection;
r.y += yDirection;
}
}
public static void stopMoveMap(){
setXDirection(0);
setYDirection(0);
}
private static void setXDirection1(int dir){
xDirection = dir;
}
private static void setYDirection1(int dir){
yDirection = dir;
}
public static void navigatePlayer(int nav){
switch(nav){
default:
System.out.println("default case entered... Doing nothing.");
break;
case MOVE_UP:
setYDirection1(-1);
break;
case MOVE_DOWN:
setYDirection1(1);
break;
case MOVE_LEFT:
setXDirection1(-1);
break;
case MOVE_RIGHT:
setXDirection1(1);
break;
}
}
}
Thanks for the help!
At a basic level you need a 3 dimensional array to store every single block. The problem is, that won't get you an "Infinite" world, it will get you one limited to memory.
Notch solved it by using "Chunks"--which are 3D arrays of a fixed size that can be swapped to disk when necessary.
You should also learn about how bits can be used to pack storage, for anything large you will need it--For your example, each block can be held in 3 bits, 2 for the blocks and one more for "broken". If you used this instead of a byte array you would use less than 1/2 the storage, which means you could maybe go twice as far in your world before needing to read another chunk from disk.
If you want an easier introduction to writing this kind of app, look into writing a minecraft mod using Bukkit--much of the detail work is handled for you and you can actually pick up a lot of knowledge about how stuff is done before trying to write a Minecraft clone from scratch.
So what you need is essentially a two-dimensional data structure which can be extended indefinitely (or until memory runs out) into both dimensions.
There are myriads of ways to solve this problem.
One way would be a two dimensional double-linked list (double-linked net?) where each map tile has a reference to the four adjacent tiles. That means you keep track of the tile in the center of the viewport and render the scene by iterating into all four directions until you leave the screen. When you hit an un-initialized tile, it's time to generate it.

Collision detection using plain arrays and rectangles--java

I am almost done with my first little java game for my final project. It is a sidescroller where you have to shoot/avoid asteroids. My last problem is figuring out how to make my array of asteroids collide with the player's lasers. Here's what I have so far, there's an "AWT-EventQueue-0" java.lang.NullPointerException" on line 137, that I can't deal with. Any help is appreciated.
Edit: I added in my other classes, I realize it would be hard to judge the functionality of my code if I didn't show you where it came from.
package ShooterGame;
import java.applet.Applet;
import java.applet.AudioClip;
import java.awt.*;
import java.awt.event.*;
import java.util.ArrayList;
import java.util.Random;
import javax.swing.*;
public class Board extends JPanel implements ActionListener
{
Enemy[] baddies = new Enemy[10000];
Player p;
Image img;
int y;
Timer time;
boolean lost = false;
static Font font = new Font("SanSerif", Font.BOLD, 24);
public AudioClip theme, bang, laser;
static ArrayList<Enemy> enemies;
public static int score = 0;
public static int lives = 5;
public Board()
{
p = new Player();
addKeyListener(new ActionListener());
setFocusable(true);
ImageIcon i = new ImageIcon("images/background.png");
img = i.getImage();
time = new Timer(5, this);
time.start();
for(int j = 0; j < baddies.length; j++)
{
Random ran = new Random();
y = ran.nextInt(365)+1;
baddies[j]= new Enemy((100*j + 700), y, "images/asteroid.gif");
}
theme = Applet.newAudioClip(getClass().getResource("theme.mid"));
theme.play();
bang = Applet.newAudioClip(getClass().getResource("bang.wav"));
}
public void actionPerformed(ActionEvent e)
{
checkCollisions();
ArrayList<?> bullets = Player.getBullets();
for(int i = 0; i < bullets.size(); i++)
{
Bullet b = (Bullet)bullets.get(i);
if(b.isVisible() == true)
{
b.move();
}
else
{
bullets.remove(i);
}
}
p.move();
for(int i = 0; i < baddies.length; i++)
{
if(p.x > 400)
{
baddies[i].move(p.getdx());
}
}
repaint();
}
public void paint(Graphics g)
{
super.paint(g);
Graphics2D g2d = (Graphics2D) g;
if(lost)
{
g2d.drawString("You Lose!", 300, 300);
}
if((p.getX() - 590) % 2400 == 0 || (p.getX() - 590) % 2400 == 1)
{
p.nx = 0;
}
if((p.getX() - 1790) % 2400 == 0 ||(p.getX() - 1790) % 2400 == 1)
{
p.nx2 = 0;
}
g2d.drawImage(img, 685-p.nx2, 0, null);
if(p.getX() >= 590)
{
g2d.drawImage(img, 685-p.nx, 0, null);
}
g2d.drawImage(p.getImage(), p.edge, p.getY(), null);
ArrayList<?> bullets = Player.getBullets();
for(int i = 0; i < bullets.size(); i++)
{
Bullet b = (Bullet)bullets.get(i);
g2d.drawImage(b.getImg(), b.getX(), b.getY(), null);
}
for(int i = 0; i < baddies.length; i++)
{
if(baddies[i].isAlive == true)
{
g2d.drawImage(baddies[i].getImg(), baddies[i].getX(), baddies[i].getY(), null);
}
}
g2d.setColor(Color.white);
g2d.drawString("Score: " + score, 0, 320);
g2d.drawString("Lives: " + lives, 80, 320);
}
public void checkCollisions()
{
Rectangle[] rect = new Rectangle[baddies.length];
for(int i = 0; i < baddies.length; i++)
{
Enemy e = (Enemy)baddies[i];
rect[i] = e.getBounds();
}
ArrayList<?> bullets = Player.getBullets();
for (int i = 0; i < bullets.size(); i++)
{
Bullet b = (Bullet) bullets.get(i);
Rectangle b1 = b.getBounds();
if (rect[i].intersects(b1) && baddies[i].isAlive())
{
score++;
baddies[i].isAlive = false;
baddies[i].isVisible = false;
bang.play();
}
Rectangle h = p.getBounds();
if (h.intersects(rect[i]))
{
if(baddies[i].isAlive() == true)
{
lives--;
if(lives < 0)
{
lost = true;
theme.stop();
System.exit(1);
}
}
}
}
}
private class ActionListener extends KeyAdapter
{
public void keyReleased(KeyEvent e)
{
p.keyReleased(e);
}
public void keyPressed(KeyEvent e)
{
p.keyPressed(e);
}
}
}
Enemy
package ShooterGame;
import java.awt.*;
import javax.swing.ImageIcon;
public class Enemy
{
int x, y;
Image img;
boolean isAlive = true;
boolean isVisible = true;
public Enemy(int startX, int startY, String location)
{
x = startX;
y = startY;
ImageIcon l = new ImageIcon(location);
img = l.getImage();
}
public Rectangle getBounds()
{
return new Rectangle(x, y, 60, 60);
}
public int getX()
{
return x;
}
public int getY()
{
return y;
}
public boolean isAlive()
{
return isAlive;
}
public boolean isVisible()
{
return isVisible;
}
public Image getImg()
{
return img;
}
public void move(int dx)
{
x = x - dx;
}
}
Bullet
package ShooterGame;
import java.applet.Applet;
import java.awt.*;
import javax.swing.ImageIcon;
import java.applet.AudioClip;
public class Bullet
{
int x, y;
Image img;
boolean visible;
public Bullet(int startX, int startY)
{
x = startX;
y = startY;
ImageIcon newBullet = new ImageIcon("images/bullet.gif");
img = newBullet.getImage();
visible = true;
}
public Rectangle getBounds()
{
return new Rectangle(x, y, 9, 5);
}
public int getX()
{
return x;
}
public int getY()
{
return y;
}
public Image getImg()
{
return img;
}
public boolean isVisible()
{
return visible;
}
public void move()
{
x = x + 2;
if(x > 700)
{
visible = false;
}
}
public void setVisible(boolean isVisible)
{
visible = isVisible;
}
}
Player
package ShooterGame;
import java.applet.Applet;
import java.applet.AudioClip;
import java.awt.*;
import java.awt.event.KeyEvent;
import java.util.ArrayList;
import javax.swing.ImageIcon;
public class Player
{
int x, dx, y, dy, nx2, nx, edge, ceiling;
Image player;
ImageIcon ib = new ImageIcon("images/player1back.gif");
ImageIcon i = new ImageIcon("images/playerstill.gif");
ImageIcon f = new ImageIcon("images/playerforward.gif");
ImageIcon up = new ImageIcon("images/playerup.gif");
ImageIcon down = new ImageIcon("images/playerdown.gif");
public AudioClip laser;
static ArrayList<Bullet> bullets;
public Player()
{laser = Applet.newAudioClip(getClass().getResource("laser.wav"));
player = ib.getImage();
x = 75;
nx = 0;
nx2 = 685;
y = 172;
edge = 150;
ceiling = 0;
bullets = new ArrayList<Bullet>();
}
public static ArrayList<Bullet> getBullets()
{
return bullets;
}
public void fire()
{
Bullet z = new Bullet((edge + 60), (y+17));
bullets.add(z);
}
public Rectangle getBounds()
{
return new Rectangle(edge, y, 43, 39);
}
public void move()
{
y = y + dy;
if(y < ceiling)
{
y = ceiling;
}
if(y > 290)
{
y = 290;
}
if(dx != -1)
{
if(edge + dx <= 151)
{
edge = edge + dx;
}
else
{
x = x + dx;
nx2 = nx2 + dx;
nx = nx + dx;
}
}
else
{
if(edge + dx > 0)
{
edge = edge + dx;
}
}
}
public int getX()
{
return x;
}
public int getdx()
{
return dx;
}
public int getY()
{
return y;
}
public Image getImage()
{
return player;
}
public void keyPressed(KeyEvent e)
{
int key = e.getKeyCode();
if(key == KeyEvent.VK_RIGHT)
{
dx = 2;
player = f.getImage();
}
if(key == KeyEvent.VK_UP)
{
dy = -1;
player = up.getImage();
}
if(key == KeyEvent.VK_DOWN)
{
dy = 1;
player = down.getImage();
}
if(key == KeyEvent.VK_SPACE)
{
fire();
laser.play();
}
}
public void keyReleased(KeyEvent e)
{
int key = e.getKeyCode();
if(key == KeyEvent.VK_RIGHT)
{
dx = 1;
player = ib.getImage();
}
if(key == KeyEvent.VK_UP)
{
dy = 0;
player = ib.getImage();
}
if(key == KeyEvent.VK_DOWN)
{
dy = 0;
player = ib.getImage();
}
}
}
Frame
package ShooterGame;
import javax.swing.*;
public class Frame
{
public AudioClip theme;
public Frame()
{
JFrame frame = new JFrame();
frame.add(new Board());
frame.setTitle("SideShooter");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(700,365);
frame.setVisible(true);
frame.setLocationRelativeTo(null);
}
public static void main(String[] args)
{
new Frame();
}
}
Ok, so the problem is the line mentioned in the other answer, but I believe it is that all the enemies may not be initialised before it checks collisions. Because you are making 10000 of them to start with, I think your action performed method may be checking collisions before they have all be created.
One thing to try could be to bring down the amount of enemies you have and see if it still keeps happening, try 100 or 1000, but this still won't fix the issue.
You really want to be change your game to run in it's own loop though, at the moment you are only checking collisions when the player performs an action. so if the player stops moving, no collision detection...
I would suggest that you find a book called 'Killer Game Programming in Java', there are free ebook version, and just read the first 2 chapters about making a game loop. The book is a bit old, but the basics of the loop are very good.
This question here also contains a very simple loop, and some suggestions in the comments about how to make it better.
The error is on the line
rect[i] = e.getBounds();
Are you not initializing the bounds of your Enemy class correctly? Alternatively, the Enemy you pulled out of the array could be null.

Categories