Category Archives: Juegos

En vacaciones, hacer un pequeño juego

Parabollic2Este, creo, es el primer artículo, de este blog, en el que no voy a hablar de Alfresco. Resulta que estas vacaciones no sabía que hacer y he decidido rememorar los tiempos en los que me hacía mis juegos con el MSX, si, un poco de programación rápida, sin planear nada de ante mano y en unas 5 tardes. De hecho, comencé por mirar los gráficos AWT de Java ya que no tenía grandes pretensiones y casi en el momento empecé a escribir un programa que, en principio, iba a ser un algoritmo de parábola para una bolita, pero luego encontré por Internet un par de gráficos de navecitas así que, finalmente, he hecho un juego de naves.

El juego es muy sencillo, derecha, izquierda, disparo y listo, los enemigos pueden usar 3 tipos de estrategia, una que sigue a la nave amiga, otro que de desplaza a la derecha y otra a la izquierda.

Solo he usado estos tres gráficos que pongo a continuación, que podéis descargar para usarlos:

laser32.png
laser32

nave_azul32.png
nave_azul32

nave_verde32.png
nave_verde32

 

Sobre los sonidos, he usado los siguientes, igualmente podéis usarlos:

explosion2.wav


game_over.wav

 

laser_shot2.wav

 

ready_go.wav

 

Y nada más, a continuación os pongo el código fuente de cada fichero. No esperéis nada especial ni un código modelo dentro de la programación orientada a objetos, lo he ido escribiendo sobre la marcha para hacerlo en eso, cinco tardes de verano.

Fichero: Enemy.java

package com.fegor.games.parabolic;

import java.awt.Graphics;
import java.util.ArrayList;

/**
 * @author 	fegor
 * 
 */
public class Enemy implements Trace {
  private final int STRATEGY_RIGHT = 0;
  private final int STRATEGY_LEFT = 1;
  private final int STRATEGY_PERSECUTION = 2;

  private final int MAX_ENEMY = 7;

  private Graphics gr = null;

  private int enemies;
  private ArrayList<Sprite> enemy;
  private ArrayList<Sprite> laserEnemy;
  private ArrayList<Boolean> shootLaser;
  private ArrayList<Sound> soundLaser;
  private ArrayList<Sound> soundExplotion;
  private ArrayList<Integer> strategy;
  private ArrayList<Boolean> isAlive;

  private int screen_width = 480;
  private int screen_height = 640;

  /**
   * 
   */
  public Enemy() {
    enemy = new ArrayList<Sprite>();
    laserEnemy = new ArrayList<Sprite>();
    shootLaser = new ArrayList<Boolean>();
    soundLaser = new ArrayList<Sound>();
    soundExplotion = new ArrayList<Sound>();
    strategy = new ArrayList<Integer>();
    isAlive = new ArrayList<Boolean>();

    initEnemies();
  }

  /**
   * 
   */
  public void draw() {
    for (int i = 0; i < MAX_ENEMY; i++) {
      if (isAlive.get(i)) {
        enemy.get(i).setGr(gr);
        enemy.get(i).draw();
      }

      if (shootLaser.get(i)) {
        laserEnemy.get(i).setGr(gr);
        laserEnemy.get(i).draw();
      }
    }
  }

  /**
   * @param targetX
   * @param targetDistance
   */
  public void refreshPosition(int targetX, int targetDistance) {
    for (int i = 0; i < MAX_ENEMY; i++) {

      // move from strategy
      if (isAlive.get(i) && strategy.get(i) == STRATEGY_RIGHT) {
        if (enemy.get(i).getX() > screen_width)
          enemy.get(i).setX(0);

        enemy.get(i).moveRight();
      }

      else if (isAlive.get(i) && strategy.get(i) == STRATEGY_LEFT) {
        if (enemy.get(i).getX() == 0)
          enemy.get(i).setX(screen_width);

        enemy.get(i).moveLeft();
      }

      else if (isAlive.get(i) && strategy.get(i) >= STRATEGY_PERSECUTION) {
        if (enemy.get(i).getX() < (targetX - targetDistance))
          enemy.get(i).moveRight();

        else if (enemy.get(i).getX() > (targetX + targetDistance))
          enemy.get(i).moveLeft();
      }

      // down
      if (isAlive.get(i) && enemy.get(i).getY() > screen_height - (enemy.get(i).getHeight() * 2)) {
        enemyDestroy(i);
      }

      else if (isAlive.get(i))
        if ((i == 0) || ((i > 0 && (enemy.get(i - 1).getY() > (32 * 2)))) || (!isAlive.get(i - 1))) {
          enemy.get(i).moveDown();
        }
    }

    // all enemies dead?
    if (enemies <= 0)
      enemiesReset();
  }

  /**
   * 
   */
  public void shoot() {
    for (int i = 0; i < MAX_ENEMY; i++) {
      if ((!shootLaser.get(i)) && isAlive.get(i))
        if (((int) (Math.random() * 99)) == 0) {
          shootLaser.set(i, true);
          soundLaser.get(i).play();
        }

      if (shootLaser.get(i)) {
        if (laserEnemy.get(i).getX() == 0) {
          laserEnemy.get(i).setX(enemy.get(i).getX() + (enemy.get(i).getWidth() / 2));
          laserEnemy.get(i).setY(enemy.get(i).getY() + (enemy.get(i).getHeight()));
        }

        if (shootLaser.get(i) && (laserEnemy.get(i).getY() < screen_height - laserEnemy.get(i).getHeight()))
          laserEnemy.get(i).moveDown();

        else {
          laserEnemy.get(i).setX(0);
          shootLaser.set(i, false);
        }
      }
    }
  }

  /**
   * @param s
   * @return
   */
  public boolean collition(Sprite s) {
    boolean res = false;
    for (int i = 0; i < MAX_ENEMY; i++) {
      if (isAlive.get(i) && enemy.get(i).hasCollition(s)) {
        soundExplotion.get(i).play();
        res = true;
        enemyDestroy(i);
        if (isTrace) 
          System.out.println("Collition enemy " + i + " to " + s.getName());
      }
    }

    return res;
  }

  /**
   * @param s
   * @return
   */
  public boolean laserCollition(Sprite s) {
    boolean res = false;
    for (int i = 0; i < MAX_ENEMY; i++) {
      if (shootLaser.get(i) && laserEnemy.get(i).hasCollition(s)) {
        res = true;
        laserDestroy(i);
        if (isTrace)
          System.out.println("Collition laser " + i + " to " + s.getName());
      }
    }

    return res;
  }

  /**
   * 
   */
  private void initEnemies() {

    // Create enemies, laser and soundss
    for (int i = 0; i < MAX_ENEMY; i++) {
      enemy.add(new Sprite());
      isAlive.add(true);
      laserEnemy.add(new Sprite());
      laserEnemy.get(i).setMoveStepY(10);
      shootLaser.add(false);
      soundLaser.add(new Sound("laser_shot2.wav"));
      soundExplotion.add(new Sound("explosion2.wav"));
      strategy.add(null);

      enemy.get(i).addImage("nave_verde32.png");
      laserEnemy.get(i).addImage("laser32.png");
    }

    enemiesReset();
  }

  /**
   * @param e
   * @param i
   */
  private void reset(Sprite e, int i) {
    e.setX((screen_width / MAX_ENEMY) * i);
    e.setY(32);
    e.setMoveStepX(1);
  }

  /**
   * 
   */
  private void enemiesReset() {
    if (isTrace)
      System.out.println("Enemies reset");
    
    for (int i = 0; i < MAX_ENEMY; i++) {
      reset(enemy.get(i), i);
      strategy.set(i, (int) (Math.random() * 3));
      isAlive.set(i, true);
    }

    enemies = MAX_ENEMY;
  }

  /**
   * @param i
   */
  private void enemyDestroy(int i) {
    isAlive.set(i, false);
    enemies--;
  }

  /**
   * @param i
   */
  private void laserDestroy(int i) {
    shootLaser.set(i, false);
  }

  /**
   * @param gr
   */
  public void setGr(Graphics gr) {
    this.gr = gr;
  }

  /**
   * @param screen_width
   */
  public void setScreen_width(int screen_width) {
    this.screen_width = screen_width;
  }

  /**
   * @param screen_height
   */
  public void setScreen_height(int screen_height) {
    this.screen_height = screen_height;
  }

  /**
   * @return
   */
  public ArrayList<Boolean> getIsAlive() {
    return isAlive;
  }

  /**
   * @param isAlive
   */
  public void setIsAlive(ArrayList<Boolean> isAlive) {
    this.isAlive = isAlive;
  }

  /**
   * @return
   */
  public int getEnemies() {
    return enemies;
  }

  /**
   * @param enemies
   */
  public void setEnemies(int enemies) {
    this.enemies = enemies;
  }

  /**
   * @return
   */
  public ArrayList<Boolean> getShootLaser() {
    return shootLaser;
  }

  /**
   * @return
   */
  public ArrayList<Sound> getSoundLaser() {
    return soundLaser;
  }

}

 

Fichero: Game.java

package com.fegor.games.parabolic;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Toolkit;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.util.ArrayList;

import javax.swing.JPanel;

/**
 * @author fegor
 *
 */
public class Game extends JPanel implements Runnable, Trace {

  private static final long serialVersionUID = -3239737141818043435L;
  private static final int STARSHIPS_COLLITION = 1;
  private static final int STARSHIPBLUE_LOSS = 2;
  private static final int STARSHIPGREEN_LOSS = 3;
  private static final int INIT_DELAY = 30;
  private static final int SCREEN_WIDTH = 480;
  private static final int SCREEN_HEIGHT = 640;
  private static final int MAX_STARS = 100;
  private static final int NUM_STARSHIPS = 5;

  private int delay = INIT_DELAY;

  private Color colorTextBlink;
  private int score = 0;
  private int numStarShips = NUM_STARSHIPS;
  private boolean shootStarShipBlue = false;
  private boolean isGameOver = false;
  private boolean isWaitStart = true;
  private int dx;

  private Enemy enemy;
  private Sprite starShipBlue;
  private Sprite laserStarShipBlue;

  private Sound soundLaserBlue;
  private Sound soundExplosionBlue;
  private Sound soundReadyGo;
  private Sound soundGameOver;

  private ArrayList<Star> stars = new ArrayList<Star>();
  private int moveStars = 0;
  private int distance = 10;

  private Thread thread;

  /**
   * 
   */
  public Game() {
    setBackground(Color.BLACK);
    setDoubleBuffered(true);

    enemy = new Enemy();
    enemy.setScreen_width(SCREEN_WIDTH);
    enemy.setScreen_height(SCREEN_HEIGHT);

    starShipBlue = new Sprite();
    starShipBlue.addImage("nave_azul32.png");
    resetStarShipBlue();

    laserStarShipBlue = new Sprite();
    laserStarShipBlue.addImage("laser32.png");
    laserStarShipBlue.setMoveStepY(10);

    soundReadyGo = new Sound("ready_go.wav");
    soundGameOver = new Sound("game_over.wav");
    soundLaserBlue = new Sound("laser_shot2.wav");
    soundExplosionBlue = new Sound("explosion2.wav");

    // Generate stars
    int nColor;
    for (int i = 0; i < MAX_STARS; i++) {
      nColor = (int) (Math.random() * 256 - 1);
      Color color = new Color(nColor, nColor, nColor);
      stars.add(new Star((int) (Math.random() * SCREEN_WIDTH - 1),
          (int) (Math.random() * (SCREEN_HEIGHT - 1 + 32)), color));
    }
  }

  /* (non-Javadoc)
   * @see java.lang.Runnable#run()
   */
  @Override
  public void run() {
    while (true) {
      if (isWaitStart) {
        colorTextBlink = (colorTextBlink == Color.GREEN ? Color.BLACK : Color.GREEN);
        repaint();
        try {
          Thread.sleep(300);
        }

        catch (InterruptedException ie) {
          System.out.println(ie);
        }
      }

      else if (isGameOver) {
        colorTextBlink = (colorTextBlink == Color.GREEN ? Color.BLACK : Color.GREEN);
        repaint();
        try {
          Thread.sleep(300);
        }

        catch (InterruptedException ie) {
          System.out.println(ie);
        }
      }

      else {
        loop();
        repaint();
        try {
          Thread.sleep(delay);
        }

        catch (InterruptedException ie) {
          System.out.println(ie);
        }
      }
    }
  }

  /**
   * 
   */
  private void resetGame() {
    delay = INIT_DELAY;
    score = 0;
    numStarShips = NUM_STARSHIPS;
    resetStarShipBlue();
    enemy = null;
    enemy = new Enemy();
  }

  /**
   * 
   */
  private void resetStarShipBlue() {
    starShipBlue.setX((SCREEN_WIDTH + starShipBlue.getWidth()) / 2);
    starShipBlue.setY(SCREEN_HEIGHT - (starShipBlue.getHeight() * 2));
    starShipBlue.setMoveStepX(5);
  }

  /**
   * 
   */
  private void resetLaserStarShipBlue() {
    laserStarShipBlue.setX(-32);
    laserStarShipBlue.setY(-32);
    shootStarShipBlue = false;
  }

  /* (non-Javadoc)
   * @see javax.swing.JComponent#addNotify()
   */
  @Override
  public void addNotify() {
    super.addNotify();
    thread = new Thread(this);
    thread.start();
  }

  /* (non-Javadoc)
   * @see javax.swing.JComponent#paint(java.awt.Graphics)
   */
  @Override
  public void paint(Graphics g) {
    super.paint(g);
    Graphics2D g2d = (Graphics2D) g;

    if (isGameOver) {
      g.setColor(Color.GREEN);
      g.setFont(new Font("Monospaced", Font.BOLD, 40));
      g.drawString("GAME OVER", (SCREEN_WIDTH / 2) - (3 * 40), SCREEN_HEIGHT / 2);
      g.setFont(new Font("Monospaced", Font.BOLD, 26));
      g.drawString("SCORE: " + score, (SCREEN_WIDTH / 2) - (5 * 26), (SCREEN_HEIGHT / 2) + 120);
      g.setColor(colorTextBlink);
      g.drawString("PRESS S TO BEGIN", (SCREEN_WIDTH / 2) - (5 * 26), (SCREEN_HEIGHT / 2) + 60);
    }

    else if (isWaitStart) {
      g.setColor(Color.GREEN);
      g.setFont(new Font("Monospaced", Font.BOLD, 30));
      g.drawString("PARABOLIC STARSHIPS", (SCREEN_WIDTH / 2) - (6 * 30), (SCREEN_HEIGHT / 2));
      g.setColor(colorTextBlink);
      g.setFont(new Font("Monospaced", Font.BOLD, 20));
      g.drawString("PRESS S TO BEGIN", (SCREEN_WIDTH / 2) - (5 * 20), (SCREEN_HEIGHT / 2) + 60);
    }

    else {
      g.setColor(Color.GREEN);
      g.setFont(new Font("Monospaced", Font.BOLD, 20));
      g.drawString("LIVES: " + numStarShips, 10, 16);
      g.drawString("LEVEL: " + ((INIT_DELAY + 1) - delay), (SCREEN_WIDTH / 2) - (3 * 20), 16);
      g.drawString("SCORE: " + score, SCREEN_WIDTH - (7 * 20), 16);

      for (int i = 0; i < MAX_STARS; i++) {
        g.setColor(stars.get(i).getColor());
        stars.get(i).setGr(g2d);
        stars.get(i).draw();
      }

      if (enemy.getEnemies() == 0 && delay > 5)
        delay--;

      enemy.setGr(g2d);
      enemy.draw();

      starShipBlue.setGr(g2d);
      starShipBlue.draw();

      if (shootStarShipBlue) {
        laserStarShipBlue.setGr(g2d);
        laserStarShipBlue.draw();
      }
    }

    Toolkit.getDefaultToolkit().sync();
    g.dispose();
  }

  /**
   * 
   */
  public void loop() {
    int i;

    moveShipBlue();

    // stars move
    if (moveStars == 5) {
      for (i = 1; i < MAX_STARS; i++) {
        if (stars.get(i).getY() < SCREEN_HEIGHT)
          stars.get(i).setY(stars.get(i).getY() + 1);

        else {
          stars.get(i).setX((int) (Math.random() * (SCREEN_WIDTH - 1)));
          stars.get(i).setY(32);
        }

      }
      moveStars = 0;
    }

    else
      moveStars++;

    // enemy move
    enemy.refreshPosition(starShipBlue.getX(), distance);

    // Laser of starship blue
    if (shootStarShipBlue) {
      if (laserStarShipBlue.getX() == -32) {
        laserStarShipBlue.setX(starShipBlue.getX() + (starShipBlue.getWidth() / 2));
        laserStarShipBlue.setY(starShipBlue.getY() - (starShipBlue.getHeight()));
      }

      if (laserStarShipBlue.getY() > 32)
        laserStarShipBlue.moveUp();

      else
        resetLaserStarShipBlue();
    }

    // Laser of enemies
    enemy.shoot();

    // Collitions
    if (enemy.collition(starShipBlue)) {
      managerCollition(STARSHIPS_COLLITION);
    }

    else if (enemy.collition(laserStarShipBlue)) {
      managerCollition(STARSHIPGREEN_LOSS);
    }

    else if (enemy.laserCollition(starShipBlue)) {
      managerCollition(STARSHIPBLUE_LOSS);
    }
  }

  /**
   * @param status
   */
  private void managerCollition(int status) {
    if (status == STARSHIPS_COLLITION || status == STARSHIPBLUE_LOSS) {
      if (numStarShips > 0) {
        if (status == STARSHIPS_COLLITION) {
          soundExplosionBlue.play();
          resetStarShipBlue();
        }

        else {
          soundExplosionBlue.play();
          resetStarShipBlue();
        }

        numStarShips--;
      }

      else {
        soundGameOver.play();
        isGameOver = true;
        if (isTrace)
          System.out.println("Game Over");
      }
    }

    else if (status == STARSHIPGREEN_LOSS) {
      score++;
      resetLaserStarShipBlue();
    }
  }

  /**
   * @return
   */
  public int getScreenWidth() {
    return SCREEN_WIDTH;
  }

  /**
   * @return
   */
  public int getScreenHeight() {
    return SCREEN_HEIGHT;
  }

  /**
   * 
   */
  private void moveShipBlue() {
    int x = starShipBlue.getX();
    
    if (x > 1 && dx == -1)
      starShipBlue.moveLeft();

    else if (x < (SCREEN_WIDTH - starShipBlue.getWidth()) && dx == 1)
      starShipBlue.moveRight();
  }

  /**
   * @return
   */
  public KeyListener keyboardControl() {
    KeyListener keyListener = new KeyListener() {

      @Override
      public void keyPressed(KeyEvent e) {
        int c = e.getKeyCode();

        switch (c) {
        case KeyEvent.VK_LEFT:
          dx = -1;

          break;

        case KeyEvent.VK_RIGHT:
          dx = 1;
          break;

        case KeyEvent.VK_S:
          if (isWaitStart) {
            soundReadyGo.play();
            isWaitStart = false;
            if (isTrace)
              System.out.println("Start");
          }

          else if (isGameOver) {
            soundReadyGo.play();
            resetGame();
            isGameOver = false;
            if (isTrace)
              System.out.println("Start");
          }
          break;

        case KeyEvent.VK_SPACE:
          if (!shootStarShipBlue) {
            shootStarShipBlue = true;
            soundLaserBlue.play();
          }
          break;

        default:
          break;
        }

        repaint();
      }

      /**
       * @param e
       */
      @Override
      public void keyReleased(KeyEvent e) {
        int c = e.getKeyCode();

        switch (c) {
        case KeyEvent.VK_LEFT:
          dx = 0;
          break;

        case KeyEvent.VK_RIGHT:
          dx = 0;
          break;

        default:
          break;
        }
      }

      /**
       * @param e
       */
      @Override
      public void keyTyped(KeyEvent e) {
        // TODO Auto-generated method stub
      }
    };

    return keyListener;
  }
}

 

Fichero: Main.java

package com.fegor.games.parabolic;

import javax.swing.JFrame;

/**
 * @author fegor
 *
 */
public class Main extends JFrame {

  private static final long serialVersionUID = 1L;

  /**
   * 
   */
  public Main() {
    Game game = new Game();
    setTitle("Naves");
    setDefaultCloseOperation(EXIT_ON_CLOSE);
    setSize(game.getScreenWidth(), game.getScreenHeight());
    setLocationRelativeTo(null);
    setResizable(false);
    add(game);
    addKeyListener(game.keyboardControl());
    setFocusable(true);
    setVisible(true);
  }
  
  /**
   * @param args
   */
  public static void main(String args[]) {
    new Main();
  }
}

 

Fichero: Sound.java

package com.fegor.games.parabolic;

import java.io.BufferedInputStream;
import java.io.IOException;
import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.Clip;
import javax.sound.sampled.DataLine;
import javax.sound.sampled.LineUnavailableException;
import javax.sound.sampled.SourceDataLine;

/**
 * @author fegor
 *
 */
public class Sound implements Runnable {

  Thread thread;

  String soundFile;
  BufferedInputStream bs;
  AudioInputStream ais;
  Clip clip;

  /**
   * @param soundFile
   */
  public Sound(String soundFile) {
    this.soundFile = soundFile;
  }

  /**
   * 
   */
  public void play() {
    thread = new Thread(this);
    thread.start();
  }

  /* (non-Javadoc)
   * @see java.lang.Runnable#run()
   */
  /* (non-Javadoc)
   * @see java.lang.Runnable#run()
   */
  @Override
  public void run() {
    try {
      if (bs != null) {
        return;
      }
      
      bs = new BufferedInputStream(
          Sound.class.getResourceAsStream("/com/fegor/games/parabolic/resources/" + soundFile));
      ais = AudioSystem.getAudioInputStream(bs);
      
      final int BUFFER_SIZE = 128000;
      SourceDataLine sourceLine = null;

      AudioFormat audioFormat = ais.getFormat();
      DataLine.Info info = new DataLine.Info(SourceDataLine.class, audioFormat);

      sourceLine = (SourceDataLine) AudioSystem.getLine(info);
      sourceLine.open(audioFormat);
      
      sourceLine.start();
      int nBytesRead = 0;
      byte[] abData = new byte[BUFFER_SIZE];
      while (nBytesRead != -1) {
        try {
          nBytesRead = bs.read(abData, 0, abData.length);
        } catch (IOException e) {
          e.printStackTrace();
        }
        if (nBytesRead >= 0) {
          sourceLine.write(abData, 0, nBytesRead);
        }
      }

      sourceLine.drain();
      sourceLine.close();
      bs.close();
      bs.close();
      bs = null;
    } 
    
    catch (IOException e) {
      e.printStackTrace();
    } 
    
    catch (LineUnavailableException e) {
      e.printStackTrace();
    System.exit(1);
    } 
    
    catch (Exception e) {
      e.printStackTrace();
      System.exit(1);
    }
  }
}

 

Fichero: Sprite.java

package com.fegor.games.parabolic;

import java.awt.Graphics;
import java.awt.Image;
import java.awt.Rectangle;
import java.awt.image.BufferedImage;
import java.awt.image.ImageObserver;
import java.net.URL;
import java.util.ArrayList;
import javax.imageio.ImageIO;

/**
 * @author fegor
 *
 */
public class Sprite implements ImageObserver {
  private int x;
  private int y;
  private int width;
  private int height;
  private int nImage;
  private int moveStepX;
  private int moveStepY;
  private String name;
  
  private ArrayList<BufferedImage> alImage = new ArrayList<BufferedImage>();
  private Graphics gr = null;
  
  /**
   * 
   */
  public Sprite() {
    x = 0;
    y = 0;
    width = 16;
    height = 16;
    nImage = 0;
    moveStepX = 1;
    moveStepY = 1;	
    name = null;
  }
  
  /**
   * 
   */
  public void moveRight() {
    x += moveStepX;
  }
  
  /**
   * 
   */
  public void moveLeft() {
    x -= moveStepX;
  }
  
  /**
   * 
   */
  public void moveUp() {
    y -= moveStepY;
  }
  
  /**
   * 
   */
  public void moveDown() {
    y += moveStepY;
  }
  
  /**
   * 
   */
  public void draw() {
    if (gr == null) 
      System.out.println("Not graphics found for visualize sprite");
    
    else {
      if (nImage < alImage.size()) 
        nImage = 0;
      
      else
        nImage++;
      
      gr.drawImage(alImage.get(nImage), x, y, (ImageObserver) this);
    }
  }
  
  /**
   * @param img
   */
  public void addImage(String img) {
    if (name == null) 
      name = img;
    alImage.add(loadImage(img));
  }
  
  /**
   * @param image
   * @return
   */
  private BufferedImage loadImage(String image) {
    BufferedImage bi = null;
    try {
      URL url = Sprite.class.getResource("/com/fegor/games/parabolic/resources/" + image);
      bi = ImageIO.read(url);
      this.width = bi.getWidth();
      this.height = bi.getHeight();
      return bi;
    }

    catch (Exception e) {
      System.out.println("Image not found");
      return null;
    }
  }

  /**
   * @return
   */
  public int getX() {
    return x;
  }

  /**
   * @param x
   */
  public void setX(int x) {
    this.x = x;
  }

  /**
   * @return
   */
  public int getY() {
    return y;
  }

  /**
   * @param y
   */
  public void setY(int y) {
    this.y = y;
  }

  /**
   * @return
   */
  public int getWidth() {
    return width;
  }

  /**
   * @param width
   */
  public void setWidth(int width) {
    this.width = width;
  }

  /**
   * @return
   */
  public int getHeight() {
    return height;
  }

  /**
   * @param height
   */
  public void setHeight(int height) {
    this.height = height;
  }

  /**
   * @param gr
   */
  public void setGr(Graphics gr) {
    this.gr = gr;
  }

  /**
   * @param moveStepX
   */
  public void setMoveStepX(int moveStepX) {
    this.moveStepX = moveStepX;
  }

  /**
   * @param moveStepY
   */
  public void setMoveStepY(int moveStepY) {
    this.moveStepY = moveStepY;
  }

  /* (non-Javadoc)
   * @see java.awt.image.ImageObserver#imageUpdate(java.awt.Image, int, int, int, int, int)
   */
  @Override
  public boolean imageUpdate(Image img, int infoflags, int x, int y, int width, int height) {
    System.out.println("imageUpdate");
    return false;
  }
  
  /**
   * @return
   */
  public Rectangle getBounds() {
    return new Rectangle(x, y, width, height);
  }
  
  /**
   * @param s
   * @return
   */
  public boolean hasCollition(Sprite s) {
    return s.getBounds().intersects(getBounds());
  }

  /**
   * @return
   */
  public String getName() {
    return name;
  }

  /**
   * @param name
   */
  public void setName(String name) {
    this.name = name;
  }
}

 

Fichero: Star.java

package com.fegor.games.parabolic;

import java.awt.Color;
import java.awt.Graphics;

/**
 * @author fegor
 *
 */
public class Star {
  int x, y;
  Color color;
  private Graphics gr = null;

  /**
   * @param x
   * @param y
   * @param color
   */
  public Star(int x, int y, Color color) {
    this.x = x;
    this.y = y;
    this.color = color;
  }
  
  /**
   * 
   */
  public void draw() {
    if (gr == null) 
      System.out.println("Not graphics found for visualize sprite");
    
    else 
      gr.drawLine(x, y, x, y);
  }
  
  /**
   * @return
   */
  public int getX() {
    return x;
  }

  /**
   * @param x
   */
  public void setX(int x) {
    this.x = x;
  }

  /**
   * @return
   */
  public int getY() {
    return y;
  }

  /**
   * @param y
   */
  public void setY(int y) {
    this.y = y;
  }

  /**
   * @return
   */
  public Color getColor() {
    return color;
  }

  /**
   * @param color
   */
  public void setColor(Color color) {
    this.color = color;
  }
  
  /**
   * @param gr
   */
  public void setGr(Graphics gr) {
    this.gr = gr;
  }
}

 

Fichero: Trace.java

package com.fegor.games.parabolic;

/**
 * @author fegor
 *
 */
public interface Trace {
  public static final Boolean TRON = true;
  public static final Boolean TROFF = false;
  
  public static Boolean isTrace = TRON;
}

 

¡FELIZ VERANO!