Skocz do zawartości

Zarchiwizowany

Ten temat jest archiwizowany i nie można dodawać nowych odpowiedzi.

Pietreck

[Java, Eclipse] Wyświetlanie animacji, tutorial "Invaders"

Polecane posty

Witajcie! :happy:

Ostatnio przerabiam sobie tutorial "Invaders, Wojna Światów", w której autor przedstawia krok po kroku jak zrobić grę. Utknąłem w pewnym momencie tutka, gdy przyszło do wyświetlenia animacji. Robię wszystko jak jest podane w tutorialu jednak Eclipse (w nim tworzę) wyrzuca mi błąd:

Przy otwieraniu img/null jako null

Wystapil blad : java.lang.IllegalArgumentExceptioninput == null!

Oto kody poszczególnych klas programu:

WojnaSwiatow.java

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

public class WojnaSwiatow extends Canvas implements Stage {
    
    public long usedTime;
    public BufferStrategy strategia;
    private SpriteCache spriteCache;
    private ArrayList actors;
    
    public WojnaSwiatow() {
        spriteCache = new SpriteCache();
        JFrame okno = new JFrame (".: Wojna Swiatow :.");
        JPanel panel = (JPanel)okno.getContentPane();
        setBounds(0,0,Stage.SZEROKOSC,Stage.WYSOKOSC);
        panel.setPreferredSize(new Dimension(Stage.SZEROKOSC,Stage.WYSOKOSC));
        panel.setLayout(null);
        panel.add(this);
        okno.setBounds(0,0,Stage.SZEROKOSC,Stage.WYSOKOSC);
        okno.setVisible(true);
        okno.addWindowListener( new WindowAdapter(){
            public void windowClosing(WindowEvent e) {
                System.exit(0);
            }
        });
        okno.setResizable(false);
        createBufferStrategy(2);
        strategia = getBufferStrategy();
        requestFocus();
    }
    
    public void initWorld() {
        actors = new ArrayList();
        for (int i = 0; i < 10; i++){
            Monster m = new Monster(this);
            m.setX( (int)(Math.random()*Stage.SZEROKOSC) );
            m.setY( i*20 );
            m.setVx( (int)(Math.random()*3)+1 );
            actors.add(m);
        }
    }
    
    public void paintWorld() {
        Graphics2D g = (Graphics2D)strategia.getDrawGraphics();
        g.setColor(Color.black);
        g.fillRect(0,0,getWidth(), getHeight());
        for(int i = 0; i < actors.size(); i++){
            Actor m = (Actor)actors.get(i);
            m.paint(g);
        }
        g.setColor(Color.white);
        if(usedTime > 0)
            g.drawString(String.valueOf(1000/usedTime)+" fps",0,Stage.WYSOKOSC-50);
        else
            g.drawString("--- fps",0,Stage.WYSOKOSC-50);
        strategia.show();
    }

    public void updateWorld() {
        for(int i = 0; i < actors.size(); i++) {
            Actor m = (Actor)actors.get(i);
            m.act();
        }
    }
    
    public SpriteCache getSpriteCache() {
        return spriteCache;
    }
    
    public void game() {
        usedTime=1000;
        initWorld();
        while (isVisible()) {
            long startTime = System.currentTimeMillis();
            updateWorld();
            paintWorld();
            usedTime = System.currentTimeMillis()-startTime;
            try {
                Thread.sleep(Stage.SZYBKOSC);
            }catch (InterruptedException e) {}
        }
    }

    public static void main(String[] args) {
        WojnaSwiatow inv = new WojnaSwiatow();
        inv.game();
    }
}

Stage.java

import java.awt.image.ImageObserver;

public interface Stage extends ImageObserver {
    public static final int SZEROKOSC = 800;
    public static final int WYSOKOSC = 600;
    public static final int SZYBKOSC = 10;
    public SpriteCache getSpriteCache();
}

SpriteCache.java

import java.awt.image.BufferedImage;
import java.net.URL;
import java.util.HashMap;
import javax.imageio.ImageIO;

public class SpriteCache {
    public HashMap sprites;
    
    public SpriteCache() {
        sprites = new HashMap();
    }
    
    private BufferedImage loadImage(String sciezka) {
        URL url=null;
        try {
            url = getClass().getClassLoader().getResource(sciezka);
            return ImageIO.read(url);
        } catch (Exception e) {
            System.out.println("Przy otwieraniu " + sciezka + " jako " + url);
            System.out.println("Wystapil blad: "+e.getClass().getName()+""+e.getMessage());
            System.exit(0);
            return null;
        }
    }
    
    public BufferedImage getSprite(String sciezka) {
        BufferedImage img = (BufferedImage)sprites.get(sciezka);
        if (img == null) {
            img = loadImage(sciezka);
            sprites.put(sciezka, img);
        }
        return img;
    }
}

Monster.java

public class Monster extends Actor{
    protected int vx;
    
    public Monster(Stage stage) {
        super(stage);
        setSpriteNames( new String[] {"minka0.gif","minka1.gif","minka2.gif","minka4.gif","minka5.gif","minka6.gif","minka7.gif","minka8.gif"});
    }
    
    public void act() {
        super.act();
        x+=vx;
        if (x < 0 || x > Stage.SZEROKOSC)
            vx = -vx;
    }
    
    public int getVx() { return vx; }
    public void setVx(int i) {vx = i; }

}

Actor.java

import java.awt.Graphics2D;
import java.awt.image.BufferedImage;

public class Actor {
    protected int x, y;
    protected int width, height;
    protected String spriteName;
    protected Stage stage;
    protected SpriteCache spriteCache;
    //animation
    
    protected int currentFrame;
    protected String[] spriteNames;
    
    /*public Actor(Stage stage) {
        this.stage = stage;
        spriteCache = stage.getSpriteCache();
    }*/
    
    //animation
    
    public Actor (Stage stage) {
        this.stage = stage;
        spriteCache = stage.getSpriteCache();
        currentFrame = 0;
    }

    public void paint(Graphics2D g){
        g.drawImage(spriteCache.getSprite(spriteName), x,y, stage );
    }
    
    public int getX() { return x; }
    public void setX(int i) { x = i; }
    
    public int getY() { return y; }
    public void setY(int i) { y = i; }
    
    public String getSpriteName() { return spriteName; }
    
    /*public void setSpriteName(String string) {
        spriteName = string;
        BufferedImage image = spriteCache.getSprite(spriteName);
        height = image.getHeight();
        width = image.getWidth();
    }*/
    
    public void setSpriteNames(String[] names) {
        spriteNames = names;
        height = 0;
        width = 0;
        for(int i = 0; i < names.length; i++) {
            BufferedImage image = spriteCache.getSprite(spriteNames[i]);
            height = Math.max(height,image.getHeight());
            width = Math.max(width, image.getWidth());
        }
    }
    
    public int getHeight() { return height; }
    public int getWidth() { return width; }
    public void setHeight(int i) { height = i; }
    public void setWidth(int i) { width = i; }
    
    public void act() {
        currentFrame = (currentFrame + 1) % spriteNames.length;
    }
}

Ogólnie w programie chodzi aby wyświetlania była animacja złożona z 8 obrazków. Oczywiście obrazki znajdują się w odpowiednim folderze, a więc to nie jest problemem. Mam wrażenie, że program wczytuje po koleji obrazki od minka0.gif nie do minka8.gif, tylko do...nulla. Tak jakby traktował null jako kolejny plik graficzny do wczytania.

Jeśli ktoś z Was przerabiał już ten tutorial, bądź sprawnie posługuje się Javą i dałby radę wychwycić błąd w programie byłbym bardzo wdzięczny!

Pozdro :wink:

Link do komentarza
Udostępnij na innych stronach

    private BufferedImage loadImage(String sciezka) {
        URL url=null;
        try {
            url = getClass().getClassLoader().getResource(sciezka);
            return ImageIO.read(url);
        } catch (Exception e) {
            System.out.println("Przy otwieraniu " + sciezka + " jako " + url);
            System.out.println("Wystapil blad: "+e.getClass().getName()+""+e.getMessage());
            System.exit(0);
            return null;
        }
    }

getResource

public URL getResource(String name)

Finds the resource with the given name. A resource is some data (images, audio, text, etc) that can be accessed by class code in a way that is independent of the location of the code.

The name of a resource is a '/'-separated path name that identifies the resource.

This method will first search the parent class loader for the resource; if the parent is null the path of the class loader built-in to the virtual machine is searched. That failing, this method will invoke findResource(String) to find the resource.

Parameters:

name - The resource name

Returns:

A URL object for reading the resource, or null if the resource could not be found or the invoker doesn't have adequate privileges to get the resource.

Since:

1.1

Zwróć szczególną uwagę na to co i kiedy zwraca ta metoda.

Link do komentarza
Udostępnij na innych stronach



  • Kto przegląda   0 użytkowników

    • Brak zalogowanych użytkowników przeglądających tę stronę.
×
×
  • Utwórz nowe...