Jump to content
  • Advertisement
Sign in to follow this  
fdauria

Tenis2D 2Players Basic

This topic is 1682 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

Hello, i am new, i started to program with java, i saw more tutorials or projects in game 2d made in java. My english is not very well haha. 
 
Well. This is my code -  Tenis2D
I would like to receive suggestions to progress with this.
 
 
Stage.java
package juego;

import java.awt.image.ImageObserver;

public interface Stage extends ImageObserver{
	public static final int WIDTH	= 800;
	public static final int HEIGHT	= 480;
	public static final int PLAY_HEIGHT	= HEIGHT;
	public static final int SPEED	= 100;
	public SpriteCache getSpriteCache();
	public SoundCache getSoundCache();
	public void gameOver();
}

Tenis.java (Main)

package juego;

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.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;

@SuppressWarnings("serial")
public class Tenis extends Canvas implements Stage, KeyListener{
	
	private BufferStrategy strategy;
	private SpriteCache spriteCache;
	private SoundCache soundCache;
	
	private ArrayList jugadores;
	private Bola bola;
	private long usedTime; // Fps
	
	private boolean gameEnded = false;
	
	public Tenis(){
		spriteCache = new SpriteCache();
		soundCache = new SoundCache();
		
		JFrame ventana = new JFrame("Tenis");
		JPanel panel = (JPanel) ventana.getContentPane();
		setBounds(0, 0, Stage.WIDTH, Stage.HEIGHT);
		panel.setPreferredSize(new Dimension(Stage.WIDTH, Stage.HEIGHT));
		panel.setBackground(Color.black);
		panel.setLayout(null);
		panel.add(this);

		ventana.setBounds(0, 0, Stage.WIDTH, Stage.HEIGHT);
		ventana.setVisible(true);
		
		//Para que termine el programa y la ejecucion al cerrar la ventana
		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 static void main(String[] args){
		Tenis tenis = new Tenis();
		tenis.game();
	}

	public void game() {
		usedTime = 1000;
		initWorld();
		while(isVisible() && !gameEnded){
			long startTime = System.currentTimeMillis();
			
			updateWorld();
			bola.checkScore();
			checkCollisions();
			paintWorld();
			usedTime = System.currentTimeMillis() - startTime;
			do{
				Thread.yield();
			}while(System.currentTimeMillis() - startTime < 17);	
		}
		paintGameOver();
	}
	
	public void initWorld() {		
		jugadores = new ArrayList();
		for(int i = 1; i <= 2; i++){
			Jugador j = new Jugador(this);
			
			if(i == 1){
				j.setY(Stage.HEIGHT / 2 - j.getHeight() / 2 );
				j.setX(0);
				j.setNumerodejugador(1);
			}
			
			if(i == 2){
				j.setY(Stage.HEIGHT / 2 - j.getHeight() / 2);
				j.setX(Stage.WIDTH - j.getWidth());
				j.setNumerodejugador(2);

			}
			jugadores.add(j);
		}
		
		bola = new Bola(this);
		bola.setX(Stage.WIDTH / 2);
		bola.setY(Stage.HEIGHT / 2);
	}
	
	public void updateWorld(){
		int i = 0;
		while(i < jugadores.size()){
			Jugador j = (Jugador)jugadores.get(i);
			j.act();
			i++;
		}

		bola.act();
	}	

	public void checkCollisions(){
		Rectangle br = bola.getBounds();
		for(int i = 0; i < jugadores.size(); i++){
			Jugador j = (Jugador) jugadores.get(i);
			Rectangle jr = j.getBounds();
			if(jr.intersects(br)){
				bola.setVx(-bola.getVx());
				bola.subirNivel();
			}
		}	
		
	}
	
	public void paintWorld(){
		Graphics2D g = (Graphics2D) strategy.getDrawGraphics();
		g.setColor(Color.black);
		g.fillRect(0, 0, Stage.WIDTH, Stage.HEIGHT);
		
		g.setColor(Color.white);
		g.fillRect(Stage.WIDTH / 2, 0, 5, Stage.HEIGHT);
							
		for(int i = 0; i < jugadores.size(); i++){
			Jugador j = (Jugador) jugadores.get(i);
			j.paint(g);
		}	
		
		bola.paint(g);
		paintStatus(g);
		
		strategy.show();
		
	}	
	
	public void paintStatus(Graphics2D g){
		paintScore(g);
	}
	
	public void paintScore(Graphics2D g){
		g.setFont(new Font("Arial",Font.BOLD,30));
		g.setPaint(Color.white);
		g.drawString(bola.getScore1() + "", Stage.WIDTH / 2 - bola.width * 2 , 30);
		
		g.setFont(new Font("Arial",Font.BOLD,30));
		g.setPaint(Color.white);
		g.drawString(bola.getScore2() + "", Stage.WIDTH / 2 + bola.width * 2 , 30);		
	}
	
	public void keyPressed(KeyEvent e) {	
		for(int i = 0; i < jugadores.size(); i++){
			Jugador j = (Jugador) jugadores.get(i);
			j.keyPressed(e);
		}			
	}

	public void keyReleased(KeyEvent e) {
		for(int i = 0; i < jugadores.size(); i++){
			Jugador j = (Jugador) jugadores.get(i);
			j.keyReleased(e);
		}			
	}

	public void keyTyped(KeyEvent arg0) {}

	public SpriteCache getSpriteCache() {
		return spriteCache;
	}

	public SoundCache getSoundCache() {
		return soundCache;
	}

	public void paintGameOver(){
		Graphics2D g = (Graphics2D) strategy.getDrawGraphics();
		if(bola.getScore1() == bola.getGanador()){
			g.setColor(Color.black);
			g.fillRect(0,0,Stage.WIDTH,Stage.HEIGHT);
			
			g.setFont( new Font("Arial",Font.BOLD,36));
			g.setColor(Color.white);
			g.drawString("Ganador",10 ,Stage.HEIGHT /2);
			
			g.setFont( new Font("Arial",Font.BOLD,36));
			g.setColor(Color.white);
			g.drawString("Perdedor",Stage.WIDTH - 175 ,Stage.HEIGHT /2);			
		}else{
			g.setColor(Color.black);
			g.fillRect(0,0,Stage.WIDTH,Stage.HEIGHT);
			
			g.setFont( new Font("Arial",Font.BOLD,36));
			g.setColor(Color.white);
			g.drawString("Perdedor",10 ,Stage.HEIGHT /2);
			
			g.setFont( new Font("Arial",Font.BOLD,36));
			g.setColor(Color.white);
			g.drawString("Ganador",Stage.WIDTH - 175 ,Stage.HEIGHT /2);
		}
			
		strategy.show();
		soundCache.stopSound("musica.wav");
	}	
	
	public void gameOver() {
		System.out.println("entro");
		gameEnded = true;
	}
}
Actor.java
package juego;

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;
	
	public Actor(Stage stage){
		this.stage 	 = stage;
		spriteCache  = stage.getSpriteCache();
		currentFrame = 0;
		frameSpeed 	 = 1;
		t = 0;		
	}
	
	public void paint(Graphics2D g){
		g.drawImage(spriteCache.getSprite(spriteNames[currentFrame]),x,y,stage);
	}

	public int getX() {	return x; }
	public void setX(int x) { this.x = x;}
	
	public int getY() {	return y; }
	public void setY(int y) { this.y = y; }
	
	public int getWidth() {	return width; }
	public void setWidth(int width) { this.width = width;}
	
	public int getHeight() { return height; }
	public void setHeight(int height) {	this.height = height; }	
	
    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 Rectangle getBounds(){
		return new Rectangle(x,y,width,height);
	}

	public void collision(Actor a){	}
	
	public void act(){ 
		t++;
		if(t % frameSpeed == 0){
			t = 0;			
			currentFrame = (currentFrame + 1) % spriteNames.length;
		}
	}
}

Bola.java (ball)
package juego;

public class Bola extends Actor{
	protected int vx=4;
	protected int vy=4;
	
	private int ganador = 10;
	private int score1;
	private int score2;
		
	private int proxNivel;
	private int nivel;
	
	public Bola(Stage stage){
		super(stage);
		setSpriteNames( new String[] { "bola.gif" });
		score1 = 0;
		score2 = 0;
		nivel  = 0;
		proxNivel = 2;
	}
	
	public void act(){
		super.act();
		x += vx;
		y += vy;
		
		if(x < 0){
			vx = -vx;
			score2 ++;
		}
		
		if(x > Stage.WIDTH - width){
			vx = -vx;
			score1 ++;
		}		
			
			
		if(y < 0 || y > Stage.HEIGHT - height * 2){
			vy = -vy;
		}
	}
	
	public void checkScore(){
		if(score1 == ganador || score2 == ganador)
			stage.gameOver();
			
	}
	
	public void subirNivel(){
		nivel ++;
		if(nivel == proxNivel){
			subirVelocidad();
			nivel = 0;
		}		
	}
		
	public void subirVelocidad(){
		if(vx < 0)
			vx--;
		if(vx > 0)
			vx++;
		
		if(vy < 0)
			vy--;
		if(vy > 0)
			vy++;		
	}
	
	public int getVx() {
		return vx;
	}

	public void setVx(int vx) {
		this.vx = vx;
	}

	public int getVy() {
		return vy;
	}

	public void setVy(int vy) {
		this.vy = vy;
	}

	public int getScore1() {
		return score1;
	}

	public void setScore1(int score1) {
		this.score1 = score1;
	}

	public int getScore2() {
		return score2;
	}

	public void setScore2(int score2) {
		this.score2 = score2;
	}
	
	public int getGanador(){
		return ganador;
	}
	
}

Jugador.java(Player)

package juego;

import java.awt.event.KeyEvent;

public class Jugador extends Actor{

	protected int vy;
	private boolean up=false,down=false;
	private int speed = 4;
	private int numerodejugador;
	private int score;
	
	public Jugador(Stage stage){
		super(stage);
		setSpriteNames( new String[]{"jugador.gif"});
		score = 0;
	}
	
	//Actualiza en pantalla
	public void act(){
		super.act();
		y += vy;
		
		if(y < 0)
			y = 0;
		if(y > Stage.HEIGHT - (getHeight() + getHeight() / 4 ))
			y = Stage.HEIGHT - (getHeight() + getHeight() / 4 );
	}
	
	protected void updateSpeed(){
		vy = 0;
		if(up) vy = -speed;
		if(down) vy = speed;
	}
	
	public void keyPressed(KeyEvent e){
		if(numerodejugador == 2)
		{
			switch(e.getKeyCode()){
				case KeyEvent.VK_DOWN: 
					down = true;
					break;
				case KeyEvent.VK_UP:
					up = true;
					break;
			}	
			updateSpeed();

		}
		if(numerodejugador == 1)
		{
			switch(e.getKeyCode()){
				case KeyEvent.VK_S: 
					down = true;
					break;
				case KeyEvent.VK_W:
					up = true;
					break;
			}	
			updateSpeed();
		}
	}
	
	public void keyReleased(KeyEvent e){
		if(numerodejugador == 2)
		{
			switch(e.getKeyCode()){
				case KeyEvent.VK_DOWN: 
					down = false;
					break;
				case KeyEvent.VK_UP:
					up = false;
					break;
			}	
			updateSpeed();
		}
		if(numerodejugador == 1)
		{
			switch(e.getKeyCode()){
				case KeyEvent.VK_S: 
					down = false;
					break;
				case KeyEvent.VK_W:
					up = false;
					break;
			}	
			updateSpeed();
		}
	}
	
	public int getScore(){ return score; }
	public void setScore(int i){ score = i; } 
	public void addScore(int i){ score += i; }	

	public int getNumerodejugador() { return numerodejugador; }
	public void setNumerodejugador(int n) {	numerodejugador = n; }

	public int getVy(){ return vy; }
	public void setVy(int i){ this.vy = i; }	
	
	
	
	
}

ResourcesCache.java ( Thanks to a tutorial )

package juego;

import java.net.URL;
import java.util.HashMap;

public abstract class ResourceCache {
	@SuppressWarnings("rawtypes")
	protected HashMap resources;
	
	@SuppressWarnings("rawtypes")
	public ResourceCache(){
		resources = new HashMap();
	}
	
	protected Object loadResource(String name){
		URL url = null;
		url = getClass().getClassLoader().getResource(name);
		return loadResource(url);
	}
	
	@SuppressWarnings("unchecked")
	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 ( Thanks to a tutorial )

package juego;

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();
	}
	
	public void stopSound(final String name){
		getAudioClip(name).stop();
	}

}

SpriteCache.java ( Thanks to a tutorial )

package juego;

import java.awt.GraphicsConfiguration;
import java.awt.GraphicsEnvironment;
import java.awt.Image;
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.out.println(0);
			return null;
		}
	}
	
	public BufferedImage getSprite(String name){
		return (BufferedImage) getResource(name);
	}

	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 boolean imageUpdate(Image img, int infoflags, int x, int y,int width, int height) {
		return (infoflags & (ALLBITS|ABORT)) == 0;
	}	
}

Now i start to program a game 2D with tanks and bullets

 
Thanks
Edited by fdauria

Share this post


Link to post
Share on other sites
Advertisement
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

GameDev.net is your game development community. Create an account for your GameDev Portfolio and participate in the largest developer community in the games industry.

Sign me up!