Erro Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 400 out of bounds for length 400

estou aprendendo a criar jogos, sou muito novo nisso, eu tento dar play mas fica aparecendo esse erro

Exception in thread “main” java.lang.ArrayIndexOutOfBoundsException: Index 400 out of bounds for length 400
at com.Cauã.World.World.(World.java:18)
at com.Cauã.main.Game.(Game.java:47)
at com.Cauã.main.Game.main(Game.java:77)

<package com.Cauã.main;

import java.awt.Canvas;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.image.BufferStrategy;
import java.awt.image.BufferedImage;
import java.util.ArrayList;
import java.util.List;

import javax.swing.JFrame;

import com.Cauã.Entity.Entity;
import com.Cauã.Entity.Player;
import com.Cauã.World.World;
import com.Cauã.graficos.Spritesheet;

public class Game extends Canvas implements Runnable,KeyListener{
private static final long serialVersionUID = 1L;
public static JFrame frame;
private Thread thread;
private boolean isRunning = true;
private final int WIDTH = 240;
private final int HEIGHT = 160;
private final int SCALE = 3;

    private BufferedImage image;
    
    public List<Entity> entities;
    public static Spritesheet spritesheet;
    
    public static World world;
    
    public static Player player;
    
	public Game() {
		addKeyListener(this);
	    setPreferredSize(new Dimension(WIDTH*SCALE,HEIGHT*SCALE));
		initFlame();
		world = new World ("/mapa.png");
		image = new BufferedImage(WIDTH,HEIGHT,BufferedImage.TYPE_INT_ARGB);
	    entities = new ArrayList<Entity>();
	    spritesheet = new Spritesheet("/spritesheet.png");
	    
	    player = new Player(0,0,19,21,spritesheet.getSprite(39, 0, 19, 21));
	    entities.add(player);
	    

	}
	public void initFlame() {
		frame = new JFrame();
		frame.add(this);
		frame.setResizable(false);
		frame.pack();
		frame.setLocationRelativeTo(null);
		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		frame.setVisible(true);}
	
	public synchronized void start() {
		thread = new Thread (this);
		isRunning = true;
		thread.start();
	}
	
	public synchronized void stop () {
		
	}
	public static void main(String[] args) {
	
		Game game = new Game();
	    game.start();
	}
	    
	public void tick() {
		for(int i = 0; i < entities.size(); i++) {
			Entity e = entities.get(i);
			e.tick();
		}
	}
	
	public void render() {
		BufferStrategy bs = this.getBufferStrategy();
		if(bs == null) {
			this.createBufferStrategy(3);
			return;
		}
		Graphics g = image.getGraphics();
		g.setColor(new Color(0,0,0));
		g.fillRect(0, 0, WIDTH, HEIGHT);
		world.render(g);
		for(int i = 0; i < entities.size(); i++) {
			Entity e = entities.get(i);
			e.render(g);
			}
		g.dispose();
		g = bs.getDrawGraphics();
		g.drawImage(image, 0, 0,WIDTH*SCALE,HEIGHT*SCALE,null );
		bs.show();
		
	}
	
	public void run() {
		long lastTime = System.nanoTime();
		double amontOfTicks = 60.0;
		double ns = 1000000000 / amontOfTicks;
		double delta = 0;
		int frames = 0;
		double timer = System.currentTimeMillis();
		while(isRunning) {
			long now = System.nanoTime();
			delta+= (now - lastTime) / ns;
			lastTime = now;
			if(delta >= 1) {
				tick();
				render();
				frames++;
				delta--;
			}
			if(System.currentTimeMillis() - timer >= 1000) { 
				System.out.println("FPS: " + frames );
				frames = 0;
				timer+=1000;
			}
		}

}

	public void keyTyped(KeyEvent e) {
		
	}
		
	
	public void keyPressed(KeyEvent e) {
		if(e.getKeyCode() == KeyEvent.VK_RIGHT ||
				e.getKeyCode() == KeyEvent.VK_D) {
			System.out.println(player);
			player.right = true;
		}
		else if(e.getKeyCode() == KeyEvent.VK_LEFT ||
				e.getKeyCode() == KeyEvent.VK_A) {
			player.left = true;
		}
		if(e.getKeyCode() == KeyEvent.VK_UP ||
				e.getKeyCode() == KeyEvent.VK_W) {
			player.up = true;
		}
		else if(e.getKeyCode() == KeyEvent.VK_DOWN ||
				e.getKeyCode() == KeyEvent.VK_S) {
			player.down = true;
		}
	}

package com.Cauã.World;

import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.IOException;

import javax.imageio.ImageIO;

public class World {

public World(String path) {
	try {
		BufferedImage mapa = ImageIO.read(getClass().getResource(path));
	int[] pixels = new int[mapa.getWidth() * mapa.getHeight()];
	mapa.getRGB(0, 0, mapa.getWidth(), mapa.getHeight(), pixels, 0, mapa.getWidth());
	for( int xx = 0; xx < mapa.getWidth();xx++) {
		for(int yy = 0; xx < mapa.getHeight();yy++) {
			int pixelAtual = pixels[xx + (yy*mapa.getWidth())];
			if (pixelAtual == 0xFF000000) {
				//chão
			}else if(pixelAtual == 0xFFFFFFFF) {
				//parede
			}
		}
		}
	
	} catch (IOException e) {
		e.printStackTrace();
	}
}
public void render(Graphics g) {
	
}

}

package com.Cauã.graficos;

import java.awt.image.BufferedImage;
import java.io.IOException;

import javax.imageio.ImageIO;

public class Spritesheet {

private BufferedImage spritesheet;

public Spritesheet(String path) {
	try {
		spritesheet = ImageIO.read(getClass().getResource(path));
	} catch (IOException e) {
		e.printStackTrace();
	}
}

public BufferedImage getSprite(int x,int y,int width,int height) {
	return spritesheet.getSubimage(x, y, width, height);
}

}
package com.Cauã.Entity;

import java.awt.Graphics;
import java.awt.image.BufferedImage;

public class Entity {

protected double x;
protected double y;
protected int width;
protected int height;

private BufferedImage sprite;

public Entity(int x, int y, int width, int height,BufferedImage sprite) {
	this.x = x;
	this.y = y;
	this.width = width;
	this.height = height;
	this.sprite = sprite;
}

public int getX() {
	return (int)this.x;
}
public int getY() {
	return (int)this.y;
}
public double getWidth() {
	return this.width;
}
public double getHeight() {
	return this.height;
}

public void tick() {
	
}public void render(Graphics g) {
	g.drawImage(sprite, this.getX(), this.getY(), null);
}

}
package com.Cauã.Entity;

import java.awt.Graphics;
import java.awt.image.BufferedImage;

import com.Cauã.main.Game;

public class Player extends Entity{

public boolean right,up,left,down;
public int right_dir = 0, left_dir = 1;
public int dir = right_dir;
public double speed = 1.4;

private int frames = 0,maxFlames = 5,index = 0, maxIndex = 3;
private boolean moved = false;
private BufferedImage[] rightPlayer;
private BufferedImage[] leftPlayer;

public Player(int x, int y, int width, int height, BufferedImage sprite) {
	super(x, y, width, height, sprite);
	
	rightPlayer = new BufferedImage[4];
	leftPlayer = new BufferedImage[4];

	for(int i = 0;i < 4;i++) {
		rightPlayer[i] = Game.spritesheet.getSprite(40 + (i*20), 0, 20, 20);
		}
	for(int i = 0;i < 4;i++) {
		leftPlayer[i] = Game.spritesheet.getSprite(40 + (i*20), 20, 20, 20);
		}

}


public void tick() {
	moved = false;
	if(right) { 
		moved = true;
		dir = right_dir;
		x+=speed;
		}
	else if(left) {
		moved = true;
		dir = left_dir;
		x-=speed;
		}
	if(up) {
		moved = true;
		y-=speed;
		}
	else if(down) {
		moved = true;
		y+=speed;
		}
	if(moved) {
		frames++;    
		if(frames == maxFlames) {
			frames = 0;
			index++;
			if(index > maxIndex) {
				index = 0;
			}
		}
	}
	}
public void render(Graphics g) {
	if(dir == right_dir) {
	g.drawImage(rightPlayer[index],this.getX(),this.getY(),null);
	}
	else if(dir == left_dir) {
		g.drawImage(leftPlayer[index], this.getX(),this.getY(),null);
	}
	
		
	
	}
}

agradeço desde já :0

O for mais interno está errado, você deveria comparar se yy < mapa.getHeight(), mas está comparando se xx < mapa.getHeight().

Pergunta:
Porque as variáveis se chamam xx e yy?
Não seria mais legível ser x e y, que é justamente o que elas representam?

1 curtida

continua dando o mesmo erro e o bagulho do x e y e só por custume

Por que vc está multiplicando yy pela largura? isso vai certamente estourar seu array.
Suponha:
Largura: 10
Altura 15

Seu array 10 x 15 será de 150 posições.

No primeiro ciclo do seu loop, quando xx for 0 e yy for 15, você está tentando buscar o índice “0 + (15 * 10)” que é 150. Mas a posição máxima no seu array é 149 (pois começa em 0). E conforme seu xx vai aumentando, isso só piora.

resolvido!!!
na linha 17 da Class World eu estava botando
for(int yy = 0;xx < mapa.getHeight();yy++)
ao invés de
for(int yy = 0;yy < mapa.getHeight();yy++)

Sim, essa foi a resposta do @staroski. Marca a dele como solução.

1 curtida