Single Tech Games

juego en java 2D – 10mo dia y Código Fuente

invaders.java

import java.awt.Canvas;
import java.awt.Color;
import java.awt.Cursor;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.Rectangle;
import java.awt.TexturePaint;
import java.awt.Toolkit;
import java.awt.Transparency;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.image.BufferStrategy;
import java.awt.image.BufferedImage;
import java.util.ArrayList;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class Invaders extends Canvas implements Stage, KeyListener {
	private BufferStrategy strategy;
	private long usedTime;
	private SpriteCache spriteCache;
	private SoundCache soundCache;
	private ArrayList actors;
	private Player player;
	private BufferedImage background, backgroundTile;
	private int backgroundY;
	private boolean gameEnded=false;
	public Invaders() {
		spriteCache = new SpriteCache();
		soundCache = new SoundCache();
		JFrame ventana = new JFrame("Invaders");
		JPanel panel = (JPanel)ventana.getContentPane();
		setBounds(0,0,Stage.WIDTH,Stage.HEIGHT);
		panel.setPreferredSize(new Dimension(Stage.WIDTH,Stage.HEIGHT));
		panel.setLayout(null);
		panel.add(this);
		ventana.setBounds(0,0,Stage.WIDTH,Stage.HEIGHT);
		ventana.setVisible(true);
		ventana.addWindowListener( new WindowAdapter() {
			public void windowClosing(WindowEvent e) {
				System.exit(0);
			}
		});
		ventana.setResizable(false);
		createBufferStrategy(2);
		strategy = getBufferStrategy();
		requestFocus();
		addKeyListener(this);
    setIgnoreRepaint(true);
		BufferedImage cursor = spriteCache.createCompatible(10,10,Transparency.BITMASK);
		Toolkit t = Toolkit.getDefaultToolkit();
		Cursor c = t.createCustomCursor(cursor,new Point(5,5),"null");
		setCursor(c);
	}
	public void gameOver() {
		gameEnded = true;
	}
	public void initWorld() {
    actors = new ArrayList();
    for (int i = 0; i < 10; i++){
      Monster m = new Monster(this);
      m.setX( (int)(Math.random()*Stage.WIDTH) );
	    m.setY( i*20 );
	    m.setVx( (int)(Math.random()*20-10) );
      actors.add(m);
    }
    player = new Player(this);
    player.setX(Stage.WIDTH/2);
    player.setY(Stage.PLAY_HEIGHT - 2*player.getHeight());
    soundCache.loopSound("musica.wav");
  	backgroundTile = spriteCache.getSprite("oceano.gif");
	  background = spriteCache.createCompatible(
	               Stage.WIDTH,
	     					 Stage.HEIGHT+backgroundTile.getHeight(),
	               Transparency.OPAQUE);
	  Graphics2D g = (Graphics2D)background.getGraphics();
	  g.setPaint( new TexturePaint( backgroundTile,
	                                new Rectangle(0,0,backgroundTile.getWidth(),backgroundTile.getHeight())));
	  g.fillRect(0,0,background.getWidth(),background.getHeight());
	  backgroundY = backgroundTile.getHeight();
	}
	public void addActor(Actor a) {
		actors.add(a);
	}
	public Player getPlayer() {
		return player;
	}
	public void updateWorld() {
		int i = 0;
		while (i < actors.size()) {
			Actor m = (Actor)actors.get(i);
			if (m.isMarkedForRemoval()) {
				actors.remove(i);
			} else {
				m.act();
				i++;
			}
		}
		player.act();
	}
	public void checkCollisions() {
		Rectangle playerBounds = player.getBounds();
		for (int i = 0; i < actors.size(); i++) {
			Actor a1 = (Actor)actors.get(i);
			Rectangle r1 = a1.getBounds();
			if (r1.intersects(playerBounds)) {
				player.collision(a1);
				a1.collision(player);
			}
		  for (int j = i+1; j < actors.size(); j++) {
		  	Actor a2 = (Actor)actors.get(j);
		  	Rectangle r2 = a2.getBounds();
		  	if (r1.intersects(r2)) {
		  		a1.collision(a2);
		  		a2.collision(a1);
		  	}
		  }
		}
	}
	public void paintShields(Graphics2D g) {
		g.setPaint(Color.red);
		g.fillRect(280,Stage.PLAY_HEIGHT,Player.MAX_SHIELDS,30);
		g.setPaint(Color.blue);
		g.fillRect(280+Player.MAX_SHIELDS-player.getShields(),Stage.PLAY_HEIGHT,player.getShields(),30);
		g.setFont(new Font("Arial",Font.BOLD,20));
		g.setPaint(Color.green);
		g.drawString("Shields",170,Stage.PLAY_HEIGHT+20);
	}
	public void paintScore(Graphics2D g) {
		g.setFont(new Font("Arial",Font.BOLD,20));
		g.setPaint(Color.green);
		g.drawString("Score:",20,Stage.PLAY_HEIGHT + 20);
		g.setPaint(Color.red);
		g.drawString(player.getScore()+"",100,Stage.PLAY_HEIGHT  + 20);
	}
	public void paintAmmo(Graphics2D g) {
		int xBase = 280+Player.MAX_SHIELDS+10;
		for (int i = 0; i < player.getClusterBombs();i++) { 			BufferedImage bomb = spriteCache.getSprite("bombUL.gif"); 			g.drawImage( bomb ,xBase+i*bomb.getWidth(),Stage.PLAY_HEIGHT,this); 		} 	} 	 	public void paintfps(Graphics2D g) { 		g.setFont( new Font("Arial",Font.BOLD,12)); 		g.setColor(Color.white); 		if (usedTime > 0)
		  g.drawString(String.valueOf(1000/usedTime)+" fps",Stage.WIDTH-50,Stage.PLAY_HEIGHT);
  	else
	  	g.drawString("--- fps",Stage.WIDTH-50,Stage.PLAY_HEIGHT);
	}
	public void paintStatus(Graphics2D g) {
	  paintScore(g);
	  paintShields(g);
	  paintAmmo(g);
	  paintfps(g);
	}
	public void paintWorld() {
		Graphics2D g = (Graphics2D)strategy.getDrawGraphics();
		g.drawImage( background,
		             0,0,Stage.WIDTH,Stage.HEIGHT,
		             0,backgroundY,Stage.WIDTH,backgroundY+Stage.HEIGHT,this);
		for (int i = 0; i < actors.size(); i++) {
			Actor m = (Actor)actors.get(i);
			m.paint(g);
		}
		player.paint(g);
	  paintStatus(g);
		strategy.show();
	}
	public void paintGameOver() {
		Graphics2D g = (Graphics2D)strategy.getDrawGraphics();
		g.setColor(Color.white);
		g.setFont(new Font("Arial",Font.BOLD,20));
		g.drawString("GAME OVER",Stage.WIDTH/2-50,Stage.HEIGHT/2);
		strategy.show();
	}
	public SpriteCache getSpriteCache() {
		return spriteCache;
	}
	public SoundCache getSoundCache() {
		return soundCache;
	}
	public void keyPressed(KeyEvent e) {
		player.keyPressed(e);
	}
	public void keyReleased(KeyEvent e) {
		player.keyReleased(e);
	}
	public void keyTyped(KeyEvent e) {}
	public void game() {
		usedTime=1000;
		initWorld();
		while (isVisible() && !gameEnded) {
			long startTime = System.currentTimeMillis();
			backgroundY--;
			if (backgroundY < 0)
			  backgroundY = backgroundTile.getHeight();
			updateWorld();
			checkCollisions();
			paintWorld();
			usedTime = System.currentTimeMillis()-startTime;
			do {
  			Thread.yield();
			} while (System.currentTimeMillis()-startTime< 17);
		}
		paintGameOver();
	}
	public static void main(String[] args) {
		Invaders inv = new Invaders();
		inv.game();
	}
}

Actor.java

import java.awt.Graphics2D;
import java.awt.Rectangle;
import java.awt.image.BufferedImage;
public class Actor {
protected int x,y;
protected int width, height;
protected String[] spriteNames;
protected int currentFrame;
protected int frameSpeed;
protected int t;
protected Stage stage;
protected SpriteCache spriteCache;
protected boolean markedForRemoval;
public Actor(Stage stage) {
this.stage = stage;
spriteCache = stage.getSpriteCache();
currentFrame = 0;
frameSpeed = 1;
t=0;
}
public void remove() {
markedForRemoval = true;
}
public boolean isMarkedForRemoval() {
return markedForRemoval;
}
public void paint(Graphics2D g){
g.drawImage( spriteCache.getSprite(spriteNames[currentFrame]), 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 int getFrameSpeed() {return frameSpeed;    }
public void setFrameSpeed(int i) {frameSpeed = i;    }
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() {
t++;
if (t % frameSpeed == 0){
t=0;
currentFrame = (currentFrame + 1) % spriteNames.length;
}
}
public Rectangle getBounds() {
return new Rectangle(x,y,width,height);
}
public void collision(Actor a){
}
}

Bomb.java

public class Bomb extends Actor {
public static final int UP_LEFT = 0;
public static final int UP = 1;
public static final int UP_RIGHT = 2;
public static final int LEFT = 3;
public static final int RIGHT = 4;
public static final int DOWN_LEFT = 5;
public static final int DOWN = 6;
public static final int DOWN_RIGHT = 7;
protected static final int BOMB_SPEED = 5;
protected int vx;
protected int vy;
public Bomb(Stage stage, int heading, int x, int y) {
super(stage);
this.x = x;
this.y = y;
String sprite ="";
switch (heading) {
case UP_LEFT : vx = -BOMB_SPEED; vy = -BOMB_SPEED; sprite="bombUL.gif";break;
case UP : vx = 0; vy = -BOMB_SPEED; sprite="bombU.gif";break;
case UP_RIGHT: vx = BOMB_SPEED; vy = -BOMB_SPEED; sprite="bombUR.gif";break;
case LEFT : vx = -BOMB_SPEED; vy = 0; sprite = "bombL.gif";break;
case RIGHT : vx = BOMB_SPEED; vy = 0; sprite = "bombR.gif";break;
case DOWN_LEFT : vx = -BOMB_SPEED; vy = BOMB_SPEED; sprite="bombDL.gif";break;
case DOWN : vx = 0; vy = BOMB_SPEED; sprite = "bombD.gif";break;
case DOWN_RIGHT : vx = BOMB_SPEED; vy = BOMB_SPEED; sprite = "bombDR.gif";break;
}
setSpriteNames( new String[] {sprite});
}
public void act() {
super.act();
y+=vy;
x+=vx;
if (y < 0 || y > Stage.HEIGHT || x < 0 || x > Stage.WIDTH)
remove();
}

Bullet.java

public class Bullet extends Actor {
	protected static final int BULLET_SPEED=10;
	public Bullet(Stage stage) {
		super(stage);
		setSpriteNames( new String[] {"misil.gif"});
	}
	public void act() {
		super.act();
		y-=BULLET_SPEED;
		if (y < 0) 		  remove(); 	} }

Laser.java

public class Laser extends Actor {
protected static final int BULLET_SPEED=3;
public Laser(Stage stage) {
super(stage);
setSpriteNames( new String[] {"disparo0.gif","disparo1.gif","disparo2.gif"});
setFrameSpeed(10);
}
public void act() {
super.act();
y+=BULLET_SPEED;
if (y > Stage.PLAY_HEIGHT)
     remove();
	}
}

Monster.java

public class Monster extends Actor {
	protected int vx;
	protected static final double FIRING_FREQUENCY = 0.01;
	public Monster(Stage stage) {
		super(stage);
		setSpriteNames( new String[] {"bicho0.gif","bicho1.gif"});
		setFrameSpeed(35);
	}
	public void act() {
		super.act();
		x+=vx;
		if (x < 0 || x > Stage.WIDTH)
		  vx = -vx;
		if (Math.random()<FIRING_FREQUENCY)
		  fire();
	}
	public int getVx() { return vx; }
	public void setVx(int i) {vx = i;	}
	public void collision(Actor a) {
		if (a instanceof Bullet || a instanceof Bomb) {
		  remove();
		  stage.getSoundCache().playSound("explosion.wav");
		  spawn();
		  stage.getPlayer().addScore(20);
		}
	}
	public void spawn() {
		Monster m = new Monster(stage);
		m.setX( (int)(Math.random()*Stage.WIDTH) );
    m.setY( (int)(Math.random()*Stage.PLAY_HEIGHT/2) );
	  m.setVx( (int)(Math.random()*20-10) );
	  stage.addActor(m);
	}
	public void fire() {
		Laser m = new Laser(stage);
		m.setX(x+getWidth()/2);
		m.setY(y + getHeight());
		stage.addActor(m);
		stage.getSoundCache().playSound("photon.wav");
	}
}

Player.java

import java.awt.event.KeyEvent;
public class Player extends Actor {
	public static final int MAX_SHIELDS = 200;
	public static final int MAX_BOMBS = 5;
	protected static final int PLAYER_SPEED = 4;
	protected int vx;
	protected int vy;
	private boolean up,down,left,right;
	private int clusterBombs;
	private int score;
	private int shields;
	public Player(Stage stage) {
		super(stage);
		setSpriteNames( new String[] {"nave.gif"});
		clusterBombs = MAX_BOMBS;
		shields = MAX_SHIELDS;
		score = 0;
	}
	public void act() {
		super.act();
		x+=vx;
		y+=vy;
		if (x < 0 )
                    x = 0;
                if (x > Stage.WIDTH - getWidth())
		  x = Stage.WIDTH - getWidth();
		if (y < 0 )
                  y = 0;
                if ( y > Stage.PLAY_HEIGHT-getHeight())
		  y = Stage.PLAY_HEIGHT - getHeight();
	}
	public int getVx() { return vx; }
	public void setVx(int i) {vx = i;	}
 	public int getVy() { return vy; }
  public void setVy(int i) {vy = i;	}
  protected void updateSpeed() {
  	vx=0;vy=0;
  	if (down) vy = PLAYER_SPEED;
  	if (up) vy = -PLAYER_SPEED;
  	if (left) vx = -PLAYER_SPEED;
  	if (right) vx = PLAYER_SPEED;
  }
  public void keyReleased(KeyEvent e) {
   	switch (e.getKeyCode()) {
  		case KeyEvent.VK_DOWN : down = false;break;
		  case KeyEvent.VK_UP : up = false; break;
		  case KeyEvent.VK_LEFT : left = false; break;
		  case KeyEvent.VK_RIGHT : right = false;break;
   	}
   	updateSpeed();
  }
  public void keyPressed(KeyEvent e) {
  	switch (e.getKeyCode()) {
		  case KeyEvent.VK_UP : up = true; break;
		  case KeyEvent.VK_LEFT : left = true; break;
		  case KeyEvent.VK_RIGHT : right = true; break;
		  case KeyEvent.VK_DOWN : down = true;break;
		  case KeyEvent.VK_SPACE : fire(); break;
		  case KeyEvent.VK_B : fireCluster(); break;
  	}
  	updateSpeed();
  }
  public void fire() {
   	Bullet b = new Bullet(stage);
   	b.setX(x);
   	b.setY(y - b.getHeight());
   	stage.addActor(b);
   	stage.getSoundCache().playSound("missile.wav");
  }
  public void fireCluster() {
  	if (clusterBombs == 0)
  	  return;
  	clusterBombs--;
  	stage.addActor( new Bomb(stage, Bomb.UP_LEFT, x,y));
	  stage.addActor( new Bomb(stage, Bomb.UP,x,y));
	  stage.addActor( new Bomb(stage, Bomb.UP_RIGHT,x,y));
	  stage.addActor( new Bomb(stage, Bomb.LEFT,x,y));
	  stage.addActor( new Bomb(stage, Bomb.RIGHT,x,y));
  	stage.addActor( new Bomb(stage, Bomb.DOWN_LEFT,x,y));
  	stage.addActor( new Bomb(stage, Bomb.DOWN,x,y));
	  stage.addActor( new Bomb(stage, Bomb.DOWN_RIGHT,x,y));
  }
  public int getScore() {		return score;	}
  public void setScore(int i) {	score = i;	}
  public void addScore(int i) { score += i;  }
	public int getShields() {	return shields;	}
	public void setShields(int i) {	shields = i;	}
	public void addShields(int i) {
		shields += i;
		if (shields > MAX_SHIELDS) shields = MAX_SHIELDS;
	}
	public void collision(Actor a) {
		if (a instanceof Monster ) {
		  a.remove();
		  addScore(40);
		  addShields(-40);
		}
		if (a instanceof Laser ) {
			a.remove();
			addShields(-10);
		}
		if (getShields() < 0)
		  stage.gameOver();
	}
	public int getClusterBombs() {	return clusterBombs;	}
	public void setClusterBombs(int i) {	clusterBombs = i;	}
}

ResourceCache.java

import java.net.URL;
import java.util.HashMap;
public abstract class ResourceCache {
	protected HashMap resources;
	public ResourceCache() {
	  resources = new HashMap();
	}
	protected Object loadResource(String name) {
		URL url=null;
		url = getClass().getClassLoader().getResource(name);
		return loadResource(url);
	}
	protected Object getResource(String name) {
		Object res = resources.get(name);
		if (res == null) {
			res = loadResource("res/"+name);
			resources.put(name,res);
		}
		return res;
	}
	protected abstract Object loadResource(URL url);
}

SoundCache.java

import java.applet.Applet;
import java.applet.AudioClip;
import java.net.URL;
public class SoundCache extends ResourceCache{
	protected Object loadResource(URL url) {
		return Applet.newAudioClip(url);
	}
	public AudioClip getAudioClip(String name) {
	  return (AudioClip)getResource(name);
	}
	public void playSound(final String name) {
		 new Thread(
       new Runnable() {
       	public void run() {
			    getAudioClip(name).play();
       	}
       }
		 ).start();
	}
	public void loopSound(final String name) {
		new Thread(
	  new Runnable() {
	   public void run() {
			   getAudioClip(name).loop();
	   }
	  }
		).start();	}
}

SpriteCache.java

import java.awt.Graphics;
import java.awt.GraphicsConfiguration;
import java.awt.GraphicsEnvironment;
import java.awt.Image;
import java.awt.Transparency;
import java.awt.image.BufferedImage;
import java.awt.image.ImageObserver;
import java.net.URL;
import javax.imageio.ImageIO;
public class SpriteCache extends ResourceCache implements ImageObserver{
	protected Object loadResource(URL url) {
		try {
			return ImageIO.read(url);
		} catch (Exception e) {
			System.out.println("No se pudo cargar la imagen de "+url);
			System.out.println("El error fue : "+e.getClass().getName()+" "+e.getMessage());
			System.exit(0);
			return null;
		}
	}
	public BufferedImage createCompatible(int width, int height, int transparency) {
		GraphicsConfiguration gc =
		  GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice().getDefaultConfiguration();
		BufferedImage compatible = gc.createCompatibleImage(width,height,transparency);
		return compatible;
	}
	public BufferedImage getSprite(String name) {
		BufferedImage loaded = (BufferedImage)getResource(name);
		BufferedImage compatible = createCompatible(loaded.getWidth(),loaded.getHeight(),Transparency.BITMASK);
		Graphics g = compatible.getGraphics();
		g.drawImage(loaded,0,0,this);
		return compatible;
	}
  public boolean imageUpdate(Image img, int infoflags,int x, int y, int w, int h) {
	   return (infoflags & (ALLBITS|ABORT)) == 0;
  }
}

Stage.java

import java.awt.image.ImageObserver;
public interface Stage extends ImageObserver {
	public static final int WIDTH=800;
	public static final int HEIGHT=600;
	public static final int PLAY_HEIGHT = 500;
	public static final int SPEED=10;
	public SpriteCache getSpriteCache();
	public SoundCache getSoundCache();
	public void addActor(Actor a);
	public Player getPlayer();
	public void gameOver();
}

Páginas: 1 2 3

0 0 votes
Article Rating
Subscribe
Notify of
guest
3 Comments
Newest
Oldest Most Voted
Inline Feedbacks
View all comments
lan

amgo no encuentro el codigo!

[…] Actualizo el 03/05/2012… Ufff Cuanto tiempo estuve revisando los links y al parecer planetalia ya no pone el curso así que decidí postear el código fuente, este código no tiene ninguna explicación, solo es el código que encontré entre mis carpetas de muuuuuucho tiempo. Me imagino que ahora hay muchos mejores tutoriales, pero igual lo posteo para cualquier referencia, el código esta acá […]