Outra duvida com space invaders

Coloquei na sessão java basico e ninguem soube responder… então vou tentar aqui

fiz o space invaders, não da erro algum no netbeans mas não carrega absolutamente nada, fica uma janela preta apenas =P!
(segui o coke and code: http://www.cokeandcode.com/info/tut2d.html)
Game.java


package space;


import java.awt.Canvas;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics2D;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.image.BufferStrategy;
import java.util.ArrayList;
import javax.swing.JFrame;
import javax.swing.JPanel;


public class Game extends Canvas {

private ArrayList removeList = new ArrayList();
private BufferStrategy strategy;
private boolean gameRunning = true;
private ArrayList entities = new ArrayList();
private Entity ship;
private int alienCount;
private boolean waitingForKeyPress = true;
private boolean logicRequiredThisLoop = false;
private String message = "";
private boolean leftPressed = false;
private boolean rightPressed = false;
private boolean firePressed = false;
private double moveSpeed = 300;
private long lastFire = 0;
private long firingInterval = 500;

     public Game(){

        JFrame container = new JFrame("Kinaite");
        JPanel panel = (JPanel) container.getContentPane();

        panel.setPreferredSize(new Dimension(800,600));
	panel.setLayout(null);
        setBounds(0,0,800,600);
        panel.add(this);


        setIgnoreRepaint(true);


        container.pack();
        container.setResizable(false);
        container.setVisible(true);
        
        container.addWindowListener(new WindowAdapter() {
			public void windowClosing(WindowEvent e) {
				System.exit(0);
			}
		});

        addKeyListener(new KeyInputHandler());
        requestFocus();

        createBufferStrategy(2);
        strategy = getBufferStrategy();

    }

     public void updateLogic() {
		logicRequiredThisLoop = true;
	}

public void tryToFire() {
	if (System.currentTimeMillis() - lastFire < firingInterval) {
		return;
	}

	lastFire = System.currentTimeMillis();
	ShotEntity shot = new ShotEntity(this,"sprites/shot.gif",ship.getX()+10,ship.getY()-30);
	entities.add(shot);
}


     public void removeEntity(Entity entity) {
		removeList.add(entity);
	}

     private void startGame() {
		// clear out any existing entities and intialise a new set

		entities.clear();
		initEntities();

		// blank out any keyboard settings we might currently have

		leftPressed = false;
		rightPressed = false;
		firePressed = false;
	}

   private void initEntities() {
   
       ship = new ShipEntity(this,"sprites/ship.gif",370,550);
	entities.add(ship);
       
       alienCount = 0;
	for (int row=0;row<5;row++) {
		for (int x=0;x<12;x++) {
			Entity alien = new AlienEntity(this,"sprites/alien.png",100+(x*50),(50)+row*30);
			entities.add(alien);
			alienCount++;
		}
	}
   }

  public void notifyDeath(){
    message = "Você perdeu =P!";
    waitingForKeyPress = true;
   }

  public void notifyAlienKilled (){
                alienCount--;

		if (alienCount == 0) {
			notifyWin();
		}

                for (int i=0;i<entities.size();i++) {
			Entity entity = (Entity) entities.get(i);

			if (entity instanceof AlienEntity) {
				// speed up by 2%

				entity.setHorizontalMovement(entity.getHorizontalMovement() * 1.02);
			}
		}
  }

  public void notifyWin(){
  message = "Você ganhou";
  waitingForKeyPress = true;
  }

    public void gameloop(){
     long lastLoopTime = System.currentTimeMillis();

        while (gameRunning){
         long delta = System.currentTimeMillis() - lastLoopTime;
	lastLoopTime = System.currentTimeMillis();

        Graphics2D g = (Graphics2D) strategy.getDrawGraphics();
        g.setColor(Color.black);
        g.fillRect(0,0,800,600);
        g.dispose();
        strategy.show();
        try { Thread.sleep(10); } catch (Exception e) {}

        if (!waitingForKeyPress) {
				for (int i=0;i<entities.size();i++) {
					Entity entity = (Entity) entities.get(i);

					entity.move(delta);
				}
			}

        if (logicRequiredThisLoop) {
	for (int i=0;i<entities.size();i++) {
		Entity entity = (Entity) entities.get(i);
		entity.doLogic();
	}

	logicRequiredThisLoop = false;
}

        for (int i=0;i<entities.size();i++) {
				Entity entity = (Entity) entities.get(i);

				entity.draw(g);
			}
                        
        for (int p=0;p<entities.size();p++) {
	for (int s=p+1;s<entities.size();s++) {
		Entity me = (Entity) entities.get(p);
		Entity him = (Entity) entities.get(s);
			
		if (me.collidesWith(him)) {
			me.collidedWith(him);
			him.collidedWith(me);
		}
	}
}
        if (logicRequiredThisLoop) {
				for (int i=0;i<entities.size();i++) {
					Entity entity = (Entity) entities.get(i);
					entity.doLogic();
				}
				
				logicRequiredThisLoop = false;
			}

        if (waitingForKeyPress) {
				g.setColor(Color.white);
				g.drawString(message,(800-g.getFontMetrics().stringWidth(message))/2,250);
				g.drawString("Aperte Qualquer tecla",(800-g.getFontMetrics().stringWidth("Aperte Qualquer tecla"))/2,300);
			}
        
        ship.setHorizontalMovement(0);

			if ((leftPressed) && (!rightPressed)) {
				ship.setHorizontalMovement(-moveSpeed);
			} else if ((rightPressed) && (!leftPressed)) {
				ship.setHorizontalMovement(moveSpeed);
			}

        if (firePressed) {
	tryToFire();
}
try { Thread.sleep(10); } catch (Exception e) {}


        }
    }

    private class KeyInputHandler extends KeyAdapter {
private int pressCount = 1;
	public void keyPressed(KeyEvent e) {
		if (e.getKeyCode() == KeyEvent.VK_LEFT) {
			leftPressed = true;
		}
		if (e.getKeyCode() == KeyEvent.VK_RIGHT) {
			rightPressed = true;
		}
		if (e.getKeyCode() == KeyEvent.VK_SPACE) {
			firePressed = true;
		}
	}

	public void keyReleased(KeyEvent e) {
		if (e.getKeyCode() == KeyEvent.VK_LEFT) {
			leftPressed = false;
		}
		if (e.getKeyCode() == KeyEvent.VK_RIGHT) {
			rightPressed = false;
		}
		if (e.getKeyCode() == KeyEvent.VK_SPACE) {
			firePressed = false;
		}
	}

	public void keyTyped(KeyEvent e) {
		if (e.getKeyChar() == 27) {
			System.exit(0);
		}
	}
}



    public static void main(String[] args) {
       Game g = new Game();
       g.gameloop();



    }
}

Entity.java

package space;

import java.awt.Graphics;
import java.awt.Rectangle;

public abstract class Entity {

    protected double x;
    protected double y;
    protected double dx;
    protected double dy;
    protected String ref;
    private Sprite sprite;
    private Rectangle me;
    private Rectangle him;

    public Entity(String ref,int x,int y) {
		this.sprite = SpriteStore.get().getSprite(ref);
		this.x = x;
		this.y = y;
    }

    public boolean collidesWith(Entity other) {
	me.setBounds((int) x,(int) y,sprite.getWidth(),sprite.getHeight());
	him.setBounds((int) other.x,(int) other.y,other.sprite.getWidth(),other.sprite.getHeight());

	return me.intersects(him);
}

    public void move(long delta) {

		x += (delta * dx) / 1000;
		y += (delta * dy) / 1000;
    }

    public void draw(Graphics g) {
	sprite.draw(g,(int) x,(int) y);
}

    public void setHorizontalMovement(double dx) {
		this.dx = dx;
	}

    public void setVerticalMovement(double dy) {
		this.dy = dy;
	}

    public double getHorizontalMovement() {
		return dx;
	}

    public double getVerticalMovement() {
		return dy;
	}

    public void doLogic() {
	}

    public int getX() {
		return (int) x;
	}

    	public int getY() {
		return (int) y;
	}

    public abstract void collidedWith(Entity other);
}

AlienEntity.java



package space;

public class AlienEntity extends Entity {

    private Game game;
    private double moveSpeed = 75;

   public AlienEntity(Game game,String ref,int x,int y) {

		super(ref,x,y);
		this.game = game;
		dx = -moveSpeed;
	}

   public void doLogic() {

	dx = -dx;
	y += 10;

	if (y > 570) {
		game.notifyDeath();
	}
}

    public void move(long delta) {

        //limite de um lado;
	if ((dx < 0) && (x < 10)) {
		game.updateLogic();
	}


        //chegou ao limite do lado oposto?
	if ((dx > 0) && (x > 750)) {
		game.updateLogic();
	}

	// proceed with normal move
	super.move(delta);
}
public void collidedWith(Entity other) {}
}

ShipEntity.java


package space;


public class ShipEntity extends Entity{

    private Game game;

    public ShipEntity(Game game, String ref,int x,int y) {

                super(ref,x,y);
		this.game = game;
	}
    
    public void move(long delta) {

	if ((dx < 0) && (x < 10)) {
		return;
	}

       // não se move após o limite
	if ((dx > 0) && (x > 750)) {
		return;
	}

	super.move(delta);
}

    public void collidedWith(Entity other) {
	if (other instanceof AlienEntity) {
		game.notifyDeath();
	}
}

}

ShotEntity.java



package space;


public class ShotEntity extends Entity {

    private Game game;
    private double moveSpeed = -300;
    private boolean used = false;


    public ShotEntity (Game game,String sprite, int x, int y){
     super(sprite,x,y);

     this.game = game;
		
    dy = moveSpeed;
    }

    public void move(long delta) {
	super.move(delta);

	if (y < -100) {
		game.removeEntity(this);
	}
}

    public void collidedWith(Entity other) {
	if(used){
            return;
        }

        if (other instanceof AlienEntity) {
		game.removeEntity(this);
		game.removeEntity(other);

		game.notifyAlienKilled();
	}
}
}

Sprite.java



package space;

import java.awt.Graphics;
import java.awt.Image;

public class Sprite {

    private Image image;

    public Sprite(Image image){
           this.image = image;
    }

      public int getWidth() {
	return image.getWidth(null);
	}

  public int getHeight() {
		return image.getHeight(null);
	}

       public void draw(Graphics g,int x,int y) {
		g.drawImage(image,x,y,null);
	}




}

SpriteStore.java




package space;

import java.awt.GraphicsConfiguration;
import java.awt.GraphicsEnvironment;
import java.awt.Image;
import java.awt.Transparency;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.net.URL;
import java.util.HashMap;
import javax.imageio.ImageIO;


public class SpriteStore {


    private static SpriteStore single = new SpriteStore();

    public static SpriteStore get() {
	return single;
}
        private HashMap sprites = new HashMap();


    public Sprite getSprite(String ref){        
     
        if (sprites.get(ref) != null) {
			return (Sprite) sprites.get(ref);
		}
        
        
        BufferedImage sourceImage = null;
        
        
     try {
			URL url = this.getClass().getClassLoader().getResource(ref);
			if (url == null) {
				fail("Can't find ref: "+ref);
			}
			sourceImage = ImageIO.read(url);
		} catch (IOException e) {
			fail("Failed to load: "+ref);
		}
   
     //Carrega a imagem com a VGA ao invez de usar a CPU
     GraphicsConfiguration gc = GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice().getDefaultConfiguration();
		Image image = gc.createCompatibleImage(sourceImage.getWidth(),sourceImage.getHeight(),Transparency.BITMASK);
    //desenhar o sprite
                image.getGraphics().drawImage(sourceImage,0,0,null);
    //Cria e retorna o sprite
                Sprite sprite = new Sprite(image);
		sprites.put(ref,sprite);
		
		return sprite;
                
                
    }
     
                private void fail(String message) {
		System.err.println(message);
		System.exit(0);
	}
                
    }

Sim eu tive um pouco de dificuldade no que esta relacionado aos sprites em si (imagens) não entendi oque ele fez para os spirtes aparecerem na tela, mas como o codigo estava la, eu colei no meu codigo, mas alem disso o resto eu entendi.

Certifique-se que:

  1. Você tem o pacote sprite no seu projeto (note que falei pacote, e não pasta no disco);
  2. As letras maiúsculas e minúsculas dos nomes de pasta e arquivo são idênticos.

Além disso, o código não dá nenhuma exception?

Pacote… nope… irei criar e depois testar (tinha a pasta no disco)

Sobre os exceptions, tem 1, não da erro no net beans, oque é meio estranho, a unica coisa que ele fala que está errado é isso:

[code]
ship.setHorizontalMovement(0);

		if ((leftPressed) && (!rightPressed)) {
			ship.setHorizontalMovement(-moveSpeed);
		} else if ((rightPressed) && (!leftPressed)) {
			ship.setHorizontalMovement(moveSpeed);
		}

    if (firePressed) {
tryToFire();

}
try { Thread.sleep(10); } catch (Exception e) {}[/code]

Qual é o texto da Exception?

try { URL url = this.getClass().getClassLoader().getResource(ref); if (url == null) { fail("Can't find ref: "+ref); } sourceImage = ImageIO.read(url); } catch (IOException e) { fail("Falha ao carregar: "+ref); }

e é erro de execução mesmo. tipo este é meu primeiro programa que eu utilizo sprites, logo eu não sei absolutamente nada de como organizar os sprites no projeto, poderia ser isso certo?
para confirmar onde eu deixo os sprites do projeto?

No seu caso, você deve criar um pacote chamado sprites entre os fontes do seu projeto, e colocar as imagens lá dentro.

ok eu fiz isso, estranhamente ele continua a tela preta, nem a mensagem do inicio aparece…
os keys triggering funcionam (no caso o esc fecha a janela)

Já tentou usar o depurador?

não… na verdade nem sei oque é isto… mas eu acho que o netbeans ja vem com isso não? vou me informar do que é e tentarei.
E sobre o suposto erro de execução que o net beans acusava, eu joguei um try nessa parte : ship.setHorizontalMovement(0); e ele parou de aparecer. mas continua sem ação (tela preta)

deixei ele rodando por uns minutos e deu esses erros:

Exception in thread “main” java.lang.NullPointerException
at space.Game.tryToFire(Game.java:78)
at space.Game.gameLoop(Game.java:213)
at space.Game.main(Game.java:257)

Opa com esse erro o problema já fica mais claro.

Você não está chamando startGame() em lugar nenhum. Com isso, o método initEntities() nunca é chamado e a variável ship continua valendo nulo, o que ocasiona o nullpointerexception na linha 78 do método tryToFire().

Troque seu main para:

Game g = new Game(); g.startGame(); g.gameloop();

Depurador é o que permite que você rode o código Java passo-a-passo no Netbeans. Basta clicar na barra na lateral do código no Netbeans, e vc você verá uma bola vermelha lá. Ao executar, o código parará lá. Aí vc pode usar os comandos na barra de tarefas (há teclas de atalho para eles) para executar seu código linha-a-linha. Você poderá até mesmo verificar valores de variáveis enquanto segue a execução do código.

ah sim mudei meu main… mas o erro mudou agora =P

Exception in thread “main” java.lang.NullPointerException
at space.Entity.collidesWith(Entity.java:25)
at space.Game.gameloop(Game.java:186)
at space.Game.main(Game.java:262)

no coke and code tem o link para os codigos-fonte… eu comparei, parece que eu não esqueci de nada, mas continua os erros.
link: http://www.cokeandcode.com/info/showsrc/showsrc.php?src=../spaceinvaders/org/newdawn/spaceinvaders/Game.java

Ah obrigado pela atenção e por me ajudar, eu acabei por descobrir + ou - oque era, estou corrigindo aos poucos, o meu codigo estava uma bangunça, dai eu estou organizando e ja comecei a ver os resultados.

Desculpe reviver o topico, mas tenho outra duvida, pra mim colocar um background image neste codigo, como eu faria? ja tentei uns 4 tipos diferentes. parece que o destino esta contra mim.

Carregue uma imagem grande.
E desenhe ela por primeiro na cena.

O comando para desenhar a imagem pode substituir esse, da linha 152 da classe game:
g.fillRect(0,0,800,600);

Afinal, uma imagem de fundo do tamanho da tela acaba limpando tudo que está desenhado mesmo, eliminando a necessidade de limpar o fundo.

mas que comando eu usaria?
ja que não posso usar Image por ser abstrata.

Você pode carregar a sua imagem no SpriteStore, como você já está fazendo para a nave e para os inimigos.

E depois é só chamar o draw do Sprite do fundo.

vlw, muito obrigado :)!