Space Invaders




Stage.java


package interfaces;
/**
 *
 * @author dansan
 */
public interface Stage {
    static final int ANCHO = 800;
    static final int ALTO = 600;
    static final int NIVELES = 5;
}

Escenario.java


package spaceinvaders;

import java.awt.Graphics2D;
import java.awt.Image;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.imageio.ImageIO;

/**
 *
 * @author dansan
 */
public class Escenario {

    Image imagen = null;
    Principal spaceInvaders;

    public Escenario(Principal spaceInvaders) {
        this.spaceInvaders = spaceInvaders;
        try {
            this.imagen = ImageIO.read(getClass().getClassLoader().getResource("recursos/oceano.gif"));
        } catch (IOException ex) {
            Logger.getLogger(Player.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    public void paint(Graphics2D g) {
        g.drawImage(imagen, 0, 0, spaceInvaders.getWidth(), spaceInvaders.getHeight(), null);
    }

}

Explosion.java


package spaceinvaders;

import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.imageio.ImageIO;

/**
 *
 * @author dansan
 */
public class Explosion {
    
    int x, y;
    int cuadro = 0;
    Image imagen = null;
    
    public Explosion(int x, int y){
        this.x = x;
        this.y = y;
        this.cuadro = 0;
        try {
            this.imagen = ImageIO.read(getClass().getClassLoader().getResource("recursos/explosion.png"));
        } catch (IOException ex) {
            Logger.getLogger(Monstruo.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    
    public void paint(Graphics g) {
        Graphics2D g2d = (Graphics2D) g;
        while(cuadro<4 data-blogger-escaped-0="" data-blogger-escaped-64="" data-blogger-escaped-catch="" data-blogger-escaped-cuadro="" data-blogger-escaped-evel.severe="" data-blogger-escaped-ex="" data-blogger-escaped-g2d.drawimage="" data-blogger-escaped-imagen="" data-blogger-escaped-log="" data-blogger-escaped-logger.getlogger="" data-blogger-escaped-nterruptedexception="" data-blogger-escaped-null="" data-blogger-escaped-pre="" data-blogger-escaped-thread.sleep="" data-blogger-escaped-try="" data-blogger-escaped-x="" data-blogger-escaped-xplosion.class.getname="" data-blogger-escaped-y="">

Misil.java


package spaceinvaders;

import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.Rectangle;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.imageio.ImageIO;

/**
 *
 * @author dansan
 */
public class Misil {

    int x, y, vy;
    Image imagen = null;
    Rectangle bounds;
    boolean marcadoBorrar;

    public Misil(int x, int y) {
        this.x = x;
        this.y = y;
        vy = -10;
        marcadoBorrar = false;
        try {
            this.imagen = ImageIO.read(getClass().getClassLoader().getResource("recursos/misil.gif"));
        } catch (IOException ex) {
            Logger.getLogger(Monstruo.class.getName()).log(Level.SEVERE, null, ex);
        }
        bounds = new Rectangle(x, y, imagen.getWidth(null), imagen.getHeight(null));
    }

    public void mover(int ancho, int alto) {
        y += vy;
        if (y < 0) {
            marcadoBorrar = true;
        }
        bounds.setLocation(x, y);
    }

    public void paint(Graphics2D g) {
        g.drawImage(imagen, x, y, null);
    }

}

Monstruo.java


package spaceinvaders;

import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.Rectangle;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.imageio.ImageIO;

/**
 *
 * @author dansan
 */
public class Monstruo {

    static final int ANCHO = 32;
    static final int ALTO = 32;
    int x, y, vx, vy;
    int cuadro;
    Image imagen = null;
    Rectangle bounds;
    boolean marcadoBorrar;

    public Monstruo(int x, int y) {
        this.x = x;
        this.y = y;
        marcadoBorrar = false;
        this.cuadro = 0;
        try {
            this.imagen = ImageIO.read(getClass().getClassLoader().getResource("recursos/monstruo.png"));
        } catch (IOException ex) {
            Logger.getLogger(Monstruo.class.getName()).log(Level.SEVERE, null, ex);
        }
        bounds = new Rectangle(x, y, ANCHO, ALTO);
    }
    
    public void setVelocidad(int vx, int vy){        
        if (x < 400)
            this.vx = -vx;
        this.vy = vy;
    }

    public void mover(int ancho, int alto) {
        x += vx;
        y += vy;
        if (x < 0 || x > ancho - bounds.getWidth()) {
            vx = -vx;
        }
        if (y > alto) {
            marcadoBorrar = true;
        }
        bounds.setLocation(x, y);
    }

    public void paint(Graphics2D g) {
        g.drawImage(imagen, x, y, x + 32, y + 32, cuadro * 32, 0, cuadro * 32 + 32, 32, null);
        cuadro++;
        if (cuadro > 2) {
            cuadro = 0;
        }
    }

}

Player.java


package spaceinvaders;

import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.Rectangle;
import java.awt.event.KeyEvent;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.imageio.ImageIO;

/**
 *
 * @author dansan
 */
public class Player {

    int x, y, vx, vy;
    Image imagen = null;
    Rectangle bounds;
    boolean arriba;
    boolean abajo;
    boolean izquierda;
    boolean derecha;

    public Player(int x, int y) {
        this.x = x;
        this.y = y;
        vx = 0;
        vy = 0;
        try {
            this.imagen = ImageIO.read(getClass().getClassLoader().getResource("recursos/nave.gif"));
        } catch (IOException ex) {
            Logger.getLogger(Player.class.getName()).log(Level.SEVERE, null, ex);
        }
        bounds = new Rectangle(x, y, imagen.getWidth(null), imagen.getHeight(null));
    }

    public void mover()
    {
        vy = 0;
        vx = 0;
        
        if(abajo)
            vy = 10;                   
        if(arriba)
            vy = -10;
        if(derecha)
            vx = 10;
        if(izquierda)
            vx = -10;
        
        x = x + vx;
        y = y + vy;
        
        if (x < 0) {
            x = 0;
        }
        if (x > 800 - imagen.getWidth(null)) {
            x = 800 - imagen.getWidth(null);
        }

        if (y < 0) {
            y = 0;
        }
        if (y > 550 - imagen.getHeight(null)) {
            y = 550 - imagen.getHeight(null);
        }
        bounds.setLocation(x, y);
    }
    
    public void keyPressed(KeyEvent e) {
        if (e.getKeyCode() == KeyEvent.VK_UP) {
            arriba = true;
        } else if (e.getKeyCode() == KeyEvent.VK_DOWN) {
            abajo = true;
        } else if (e.getKeyCode() == KeyEvent.VK_RIGHT) {
            derecha = true;
        } else if (e.getKeyCode() == KeyEvent.VK_LEFT) {
            izquierda = true;
        }
    }

    public void keyReleased(KeyEvent e) {
        if (e.getKeyCode() == KeyEvent.VK_UP) {
            arriba = false;
        } else if (e.getKeyCode() == KeyEvent.VK_DOWN) {
            abajo = false;
        } else if (e.getKeyCode() == KeyEvent.VK_RIGHT) {
            derecha = false;
        } else if (e.getKeyCode() == KeyEvent.VK_LEFT) {
            izquierda = false;
        }
    }

    public void paint(Graphics2D g) {
        g.drawImage(imagen, x, y, null);
    }

}

Sound.java


package spaceinvaders;

import java.applet.Applet;
import java.applet.AudioClip;

/**
 *
 * @author dansan
 */
public class Sound {

    private AudioClip EXPLOSION;
    private AudioClip FONDO;

    public AudioClip getEXPLOSION() {
        EXPLOSION = Applet.newAudioClip(getClass().getClassLoader().getResource("recursos/explosion.wav"));
        return EXPLOSION;
    }

    public AudioClip getFONDO() {
        FONDO = Applet.newAudioClip(getClass().getClassLoader().getResource("recursos/musica.wav"));
        return FONDO;
    }

}

Principal.java


package spaceinvaders;

import interfaces.Stage;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JFrame;
import javax.swing.JPanel;

/**
 *
 * @author Programador
 */
public class Principal extends JPanel implements Stage, KeyListener {

    ArrayList monstruos;
    ArrayList misiles;
    ArrayList puntajesTope;
    Player player;
    Escenario escenario;
    Sound sound;
    int vidas = 3, puntos = 0, nivel = 1;
    int mVel = 3;
    boolean seguir = true;

    public Principal() {
        monstruos = new ArrayList<>();
        misiles = new ArrayList<>();
        puntajesTope = new ArrayList<>();
        player = new Player(400, 500);
        escenario = new Escenario(this);
        sound = new Sound();
    }

    public void llenarPuntajesTope() {
        for (int i = 0; i < NIVELES; i++) {
            if (i == 0) {
                puntajesTope.add(100);
            } else {
                puntajesTope.add(puntajesTope.get(i - 1) * 2);
            }
        }
    }

    public boolean cambioNivel() {
        boolean cambio = false;
        if (puntos >= puntajesTope.get(nivel - 1)) {
            cambio = true;
        }
        return cambio;
    }

    public void imprimirGano() {
        seguir = false;
        limpiar();
        Graphics2D g2d = (Graphics2D) getGraphics();
        g2d.setColor(Color.WHITE);
        g2d.setFont(new Font("Arial", Font.BOLD, 20));
        g2d.drawString("GANASTE", 350, 250);
        g2d.drawString("SCORE: " + puntos, 350, 350);
    }

    public void imprimirPerdio() {
        seguir = false;
        limpiar();
        Graphics2D g2d = (Graphics2D) getGraphics();
        g2d.setColor(Color.WHITE);
        g2d.setFont(new Font("Arial", Font.BOLD, 20));
        g2d.drawString("GAME OVER", 350, 250);
        g2d.drawString("SCORE: " + puntos, 350, 350);
    }

    public void crearMonstruos() {
        int x = (int) (Math.random() * ANCHO);
        int y = 0;
        Monstruo m = new Monstruo(x, y);
        m.setVelocidad(mVel, mVel);
        monstruos.add(m);
    }

    public void crearMisil() {
        if (misiles.size() < 10) {//solo se permiten 10 misiles a la vez
            int x = player.x;
            int y = player.y;
            Misil m = new Misil(x, y);
            misiles.add(m);
        }
    }

    public void actualizarMundo() {
        for (int i = 0; i < monstruos.size(); i++) {
            monstruos.get(i).mover(ANCHO, ALTO);
            if (monstruos.get(i).marcadoBorrar) {
                monstruos.remove(i);
            }
        }
        for (int i = 0; i < misiles.size(); i++) {
            misiles.get(i).mover(ANCHO, ALTO);
            if (misiles.get(i).marcadoBorrar) {
                misiles.remove(i);
            }
        }
        player.mover();
    }

    public void paint(Graphics g) {
        super.paint(g);
        Graphics2D g2d = (Graphics2D) g;
        escenario.paint(g2d);
        g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
        g2d.setColor(Color.WHITE);
        g2d.setFont(new Font("Arial", Font.BOLD, 20));
        g2d.drawString("SCORE: " + puntos, 50, 50);
        g2d.drawString("NIVEL: " + nivel, 600, 50);
        for (int i = 0; i < monstruos.size(); i++) {
            monstruos.get(i).paint(g2d);
        }
        for (int i = 0; i < misiles.size(); i++) {
            misiles.get(i).paint(g2d);
        }
        player.paint(g2d);
    }

    public void collisiones() {
        boolean cambio = false;
        for (int i = 0; i < monstruos.size(); i++) {
            for (int j = 0; j < misiles.size(); j++) {
                if (misiles.get(j).bounds.intersects(monstruos.get(i).bounds)) {
                    monstruos.get(i).marcadoBorrar = true;
                    misiles.get(j).marcadoBorrar = true;
                    puntos += 10;
                    cambio = cambioNivel();
                }
            }
        }
        //Veo si monstruos colisionaron nave
        for (int i = 0; i < monstruos.size(); i++) {
            if (monstruos.get(i).bounds.intersects(player.bounds)) {
                sound.getEXPLOSION().play();
                vidas--;
                Explosion explosion = new Explosion(player.x, player.y);
                explosion.paint(getGraphics());
                explosion = null;
                limpiar();
            }
        }
        //cambio el nivel
        if (cambio) {
            mVel += 5;
            nivel++;
            for (int i = 0; i < monstruos.size(); i++) {
                monstruos.get(i).setVelocidad(mVel, mVel);
            }
        }
        //Perdio
        if (vidas == 0) {
            imprimirPerdio();
        }
        //gano
        if (nivel > 5) {
            imprimirGano();
        }
    }

    public void limpiar() {
        player = null;
        player = new Player(400, 500);
        monstruos.clear();
        misiles.clear();
        try {
            Thread.sleep(3000);
        } catch (InterruptedException ex) {
            Logger.getLogger(Principal.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    public static void main(String[] args) throws InterruptedException {
        int velocidad = 100;
        JFrame frame = new JFrame("Space invaders");
        frame.setSize(ANCHO, ALTO);
        frame.setResizable(false);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        Principal spaceInvaders = new Principal();
        spaceInvaders.setPreferredSize(new Dimension(frame.getWidth(), frame.getHeight()));
        spaceInvaders.setLayout(null);
        spaceInvaders.llenarPuntajesTope();
        frame.add(spaceInvaders);
        frame.setVisible(true);
        frame.addKeyListener(spaceInvaders);
        frame.setFocusable(true);
        spaceInvaders.sound.getFONDO().loop();
        int tiempo = 0;
        while (spaceInvaders.seguir) {
            spaceInvaders.actualizarMundo();
            spaceInvaders.repaint();
            spaceInvaders.collisiones();
            Thread.sleep(velocidad);
            tiempo += 100;
            if (tiempo >= 1000) {
                spaceInvaders.crearMonstruos();
                tiempo = 0;
            }
        }
    }

    @Override
    public void keyTyped(KeyEvent e) {
        //player.keyPressed(e);
    }

    @Override
    public void keyPressed(KeyEvent e) {
        if (e.getKeyCode() == KeyEvent.VK_SPACE) {
            crearMisil();
        } else {
            player.keyPressed(e);
        }
    }

    @Override
    public void keyReleased(KeyEvent e) {
        player.keyReleased(e);
    }

}

Proyecto Netbeans

Github

Comentarios