Juego de la Serpiente Java (Beta)

Hace tiempo desarrollé parte del (el típico de los móviles ) en Java, aunque no está acabado del todo y quedan muchos detalles por pulir el programa tiene las funciones del juego, si lo queréis desarrollar o lo queréis reusar para cualquier cosa os dejo por aquí el código.

Captura1 Juego de la Serpiente Java (Beta)

Os dejo el código por si lo quereis reutilizar.

 
package serpent;
 
import java.awt.*;
import java.awt.event.*;
 
public class Ventana extends Frame implements WindowListener{
 
   public Ventana(){
      super(".-G A M E   O V E R-."); 
      this.setSize(300, 100); 
      this.init();
      addWindowListener(this);      
   }   
   public void init() {
	     Label etiq1 = new Label( "You loses" );
	     Label etiq2 = new Label( "..." );
	     setLayout( new FlowLayout( FlowLayout.CENTER,20,20) );
	     add( etiq1 );
	     add( etiq2 );
	     }
public void windowActivated(WindowEvent arg0) {   // --- Me obliga al implementar.
	}
public void windowClosed(WindowEvent arg0) {
		System.exit(0);
}
public void windowClosing(WindowEvent arg0) {
		dispose();
}
public void windowDeactivated(WindowEvent arg0) {		
}
public void windowDeiconified(WindowEvent arg0) {
	}
public void windowIconified(WindowEvent arg0) {
	}
public void windowOpened(WindowEvent arg0) {
	}
}
// -------------------
package serpent;
 
import javax.swing.JButton;
import java.awt.FlowLayout;
import java.awt.event.MouseEvent;
 
public class Main extends javax.swing.JFrame {   
	public JButton jButton1= new JButton("Button");
    public Main() {   
        initComponents(); 
    }      
    private void initComponents() {      	       	    
    	    jButton1.addMouseListener(new java.awt.event.MouseAdapter()
    	      {
    	        public void mouseClicked(MouseEvent e){
    	          jButton1_mouseClicked(e);
    	        }
    	      });    	
    	tableroGUI1 = new TableroGUI(12,true);  //*************** Depende que se vean o no de la dimension del tablero 
 
    	setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);   
        javax.swing.GroupLayout tableroGUI1Layout = new javax.swing.GroupLayout(tableroGUI1);   
        tableroGUI1.setLayout(tableroGUI1Layout);   
        tableroGUI1Layout.setHorizontalGroup(   
            tableroGUI1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)   
            .addGap(0, 349, Short.MAX_VALUE)   
        );   
        tableroGUI1Layout.setVerticalGroup(   
            tableroGUI1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)   
            .addGap(0, 349, Short.MAX_VALUE)   
 
        );   
        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());   
        getContentPane().setLayout(layout);   
        layout.setHorizontalGroup(   
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)   
            .addGroup(layout.createSequentialGroup()   
                .addContainerGap()   
                .addComponent(tableroGUI1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)   
                .addContainerGap(10, Short.MAX_VALUE))   //anchura despues del tablero
        );   
        layout.setVerticalGroup(   
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)   
            .addGroup(layout.createSequentialGroup() 
            	.addComponent(tableroGUI1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)   
                .addContainerGap(100, Short.MAX_VALUE)) //altura  despues del tablero  
        );
        pack(); 
        getContentPane().setLayout(new FlowLayout());        
    }   
    public static void main(String args[]) {   
        java.awt.EventQueue.invokeLater(new Runnable() {   
             public void run() {   
             new Main().setVisible(true);          
            }   
        });   
    }     
    public static TableroGUI tableroGUI1;
 
	private void jButton1_mouseClicked(MouseEvent e){
	//*****when clicked
		 java.awt.EventQueue.invokeLater(new Runnable() {   
	          public void run() {   
	             new Main().setVisible(true);    
	            }   
	        });  		
	}
	public TableroGUI getTableroGUI1() {
		return tableroGUI1;
	}
	public void setTableroGUI1(TableroGUI tableroGUI1) {
		this.tableroGUI1 = tableroGUI1;
	} 
}
//-----------------------
package serpent;
 
import javax.swing.*;  
 
public class TableroGUI extends javax.swing.JPanel {   
 
	private ImageIcon agua, tocado;   
	private ImageIcon up,down,left,right;			//------Donde está almacenada la cabeze de la serpiente
    private boolean tipoTablero;   
    private CasillasGUI [][] casillas ;        
    public TableroGUI() {   
        initComponents();   
    }   
    Ventana emergente = new Ventana();
    public TableroGUI(int size, boolean tipo) { 		//---------Crea la estructura del tablero
 
    	initComponents();   
        int x,y;   
        setLayout(new java.awt.GridLayout(size, size));   
        this.tipoTablero = tipo;   
        cargarImagenes();   
        casillas = new CasillasGUI[size][size];   
        for (int i = 0; i < size; i++){   
            for (int j = 0; j < size; j++){   
                casillas[i][j] = new CasillasGUI(this);    
                casillas[i][j].setFondo(agua);   
                x = (i * 35)+1;   
                y = (j * 35)+1;   
                casillas[i][j].setBounds(x, y, 34, 34);	   
                this.add(casillas[i][j]);	  
                            }   
        }   
    }   
    public boolean getTipoTablero(){   
        return this.isTipoTablero();   
    }   
     void pintar(int x, int y){ 				//------ Metodo para pintar.    	
 
     	 this.casillas[x][y].setFondo(tocado);     
         this.repaint();   
        System.out.println(" X= "+x+" Y= "+y);   //---------Traza para saber en que casilla esta .
    }     
 
 
     void pintar(int direccion,int x, int y){ 				//------ Metodo para pintar.         
    	 if (casillas[x][y]==casillas[x][y]) {    		 
    	 }
    	 switch(direccion){ 
			 case 1:
				 if (casillas[x][y].getFondo()==agua){
				 this.casillas[x][y].setFondo(left);     
		         this.repaint();   
				 }
				 else {
 
				   emergente.setVisible(true);				   
				   this.setVisible(false);
 
				 }
		         break;	
			 case 2:
				 if (casillas[x][y].getFondo()==agua){
		    	 this.casillas[x][y].setFondo(right);     
	             this.repaint();   
				 }
	             else {
 
					   emergente.setVisible(true);
					   this.setVisible(false);	   
 
	             }
		         break;	
			 case 3:
				 if (casillas[x][y].getFondo()==agua){
		    	 this.casillas[x][y].setFondo(up);     
		         this.repaint(); 
    	 		}
		         else {
 
					   emergente.setVisible(true);
					   this.setVisible(false);	         }
		         break;	 
			 case 4:
				 if (casillas[x][y].getFondo()==agua){
		    	 this.casillas[x][y].setFondo(down);     
		         this.repaint();
     				}
		         else {
 
			           emergente.setVisible(true);
			           this.setVisible(false);
		         }
		         break;	 
    	 }  
     }     
    void pintarAgua(int x , int y){
    	this.casillas[x][y].setFondo(agua);
    	this.repaint();
    }
    private void cargarImagenes() {   								 //---------Carga las imágenes
        this.agua = this.cargarFondo("agua.gif");   
        this.tocado = this.cargarFondo("tocado.gif");   
        this.up= this.cargarFondo("up.gif");
        this.down= this.cargarFondo("down.gif");
        this.left= this.cargarFondo("left.gif");
        this.right= this.cargarFondo("right.gif");        
 
    }   
    protected static ImageIcon cargarFondo(String ruta) {   		 //----------Contiene donde estan las imágenes
        java.net.URL localizacion = TableroGUI.class.getResource(ruta);   
        if (localizacion != null) {   
            return new ImageIcon(localizacion);   
        } else {   
            System.err.println("No se ha encontrado el archivo: " + ruta);   
            return null;   
        }   
    }   
    public int[] getCoordenadas(CasillasGUI casilla) {   //------Devuelve donde esta el Mouse (when click)
        int [] coordenadas = new int[2];   
        for (int i=0; i < this.casillas.length; i++) {   
            for (int j=0; j < this.casillas.length; j++) {   
                if (this.casillas[i][j] == casilla) {   //--- CORRIGE ESTO SI NO ES ASÍ. 
                										//----Casillas toma el valor que le introducimos por el mouse
                    coordenadas[0] = i;   
                    coordenadas[1] = j;   
                }         }   
        }   
        return coordenadas;   
    }   
 
    public CasillasGUI[][] getCasillas() {   
        return casillas;         
    }   
    public void setCasillas(CasillasGUI[][] casillas) {   
        this.casillas = casillas;   
    }   
    public boolean isTipoTablero() {   
        return tipoTablero;   
    }       
    public void setTipoTablero(boolean tipoTablero) {   
        this.tipoTablero = tipoTablero;   
    }     
    private void initComponents() {   //------------------ Dimension del tablero
        setLayout(null);   
        setBackground(new java.awt.Color(0, 0, 0));   
        setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));   
        setPreferredSize(new java.awt.Dimension(421, 421));   
 
    }
}  
//----------------------------
package serpent;
 
import java.awt.*;   
import java.awt.event.*;   
import javax.swing.*;   
 
public class CasillasGUI extends javax.swing.JPanel implements MouseListener {   
 
	public TableroGUI tablero;   
    private ImageIcon fondo;   
    private static int [] casillaMarcada = new int[2];   
    public boolean oneForTime =true;	
    public static int paraDondeVa;
    public SerPintada recogeSerpen=new SerPintada();
 
    public CasillasGUI(TableroGUI t) {   
        initComponents();          
        this.tablero = t;  
        this.setFocusable(true);     			   // El tablero puede ganar el Foco (for use keyboard)    
        if(this.tablero.getTipoTablero() == true){ // tablero responde a clics?   
            this.addMouseListener(this); 		   // Que pueda recibir eventos del Mouse. clickis            
            this.addKeyListener(new Teclado());    // Despues de que pueda ganar el foco,
        }   									   // que responda a eventos de teclado, classe Teclado.
    }   
    public void setFondo(ImageIcon fondo){   
        this.fondo = fondo;   
    }   
    public ImageIcon getFondo(){           
        return fondo;   
    }   
    private void initComponents() {   
        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);   
        this.setLayout(layout);   
        layout.setHorizontalGroup(   
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)   
            .addGap(0, 161, Short.MAX_VALUE)   
        );   
        layout.setVerticalGroup(   
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)   
            .addGap(0, 193, Short.MAX_VALUE)   
        );   
    }                          
    public void paintComponent(Graphics g){   
        super.paintComponent(g);   
        g.drawImage(fondo.getImage(), 0,0,this.getWidth(),this.getHeight(),this);   
    }   
    public void mouseClicked(MouseEvent e){}   
    public void mouseEntered(MouseEvent e){}   
    public void mouseExited(MouseEvent e){}   
    public void mousePressed(MouseEvent e){   
            this.setCasillaMarcada(tablero.getCoordenadas((CasillasGUI)e.getComponent()));    
            this.tablero.pintar(this.getCasillaMarcada()[0],this.getCasillaMarcada()[1]);  
 
    }   
    public void mouseReleased(MouseEvent e){}   
    public static int[] getCasillaMarcada() {   
        return casillaMarcada;   
    }                          
 
    public static void setCasillaMarcada(int[] aCasillaMarcada) {   
        casillaMarcada = aCasillaMarcada;        
    }    
 public class Teclado implements KeyListener{      
	 	private int x =5, y=5;		 	//--- Posición inicial que toma el Keylistener
	 	private int direccion;
	//-----Los metodos setterX and setterY controlaran que valor puede alcanzar X e Y. 
 
	 	public void setterX(int xx){	
	 		if (x+1==tablero.getX() && xx==+1){	  //-------- Hay que encontrar otro valor que no sea getX,
	 			x=tablero.getX()-2;				  //-------- pues si lo vario de 12 da error. new TableroGUI(12,true);	
	 	}									  //-------- al salirse del tablero.	
	 		if (x==0 && xx==-1 ){
	 			x=0; 	 			
	 		}
	 		else{
	 			x=x+xx;
	 		}			 		
	 	}					 		
		public void setterY(int yy){
			if (y+1==tablero.getX() && yy==+1){	
 			 	y=tablero.getX()-2; 			  			 	
 			}
			if (y==0 && yy==-1){
			 	y=0;
					}
			else{
			 	y=y+yy;
		}			}			 		
	    public Teclado() {           
	        // este constructor no se usará, se deja para poder crear el bean.           
	    }   
	    public Teclado(TableroGUI t) { 	   	    	
	    }
		public void keyPressed(KeyEvent tecla) {					
			tablero.pintar(x, y);		    //----La instancia tablero llama al metodo pintar, y le pasa los argumentos x y
											//----aqui pintaria la posicion actual. Antes de que pinte el keyPressed.
											//----y parecerá que se ha movido.
	    			                    	//----no se porqué me obliga a que sea final el modificaer.
	    									//----Lo queria hacer con un String pero switch solo permite enum o int.
			   switch(tecla.getKeyCode()){ 
				 case KeyEvent.VK_LEFT:				 
					 leftRightUpDown(1);					 
					 break;	
			     case KeyEvent.VK_RIGHT:
			    	 leftRightUpDown(2);	    	 
			    	 break;		
			     case KeyEvent.VK_UP: 			    	 	
			    	 leftRightUpDown(3);					    	 
				     break;		
			     case KeyEvent.VK_DOWN:
			    	 leftRightUpDown(4); 
			    	 break;
			 }					
		}			
		public void keyReleased(KeyEvent arg0) {
		//	System.out.println("pruebaRelease");			//---------Traza
		}
		public void keyTyped(KeyEvent arg0) {
		//	 System.out.println("pruebaTyped");			//---------Traza
		} 
		public void leftRightUpDown(int leftRightUpDown){  //---- Los aparte en un mismo metodo para porderlos
			tablero.pintar(x, y);
			recogeSerpen.insertData(x, y);
			paraDondeVa=leftRightUpDown;									   //---- llamar desde el reloj automatico;
			if (leftRightUpDown==1){
			 setterX(-1);
			 direccion=1;			
	    	 tablero.pintar(direccion,x, y);
			}		
			if (leftRightUpDown==2){
			 setterX(+1);
	    	 direccion=2;
	    	 tablero.pintar(direccion,x, y);
			}
			if (leftRightUpDown==3){
			 setterY(-1);
	    	 direccion=3;
	    	 tablero.pintar(direccion,x, y);	
			}
			if (leftRightUpDown==4){
			 setterY(+1);
	    	 direccion=4;			    	 
	    	 tablero.pintar(direccion,x, y); 
			}
			if (oneForTime==true){
		    this.relojito(paraDondeVa);				//****--- Inicializa , luego se pone 
			recogeSerpen.relojitoRecoge();
			oneForTime=false;
			}	
		}	
		public void relojito(final int leftRightUpDown){
 
	             Timer timer = new Timer (500, new ActionListener (){
	             public void actionPerformed(ActionEvent e){	            	 
	            	 leftRightUpDown(paraDondeVa);	            	             
	            	 System.out.println("funciona");
	            	// tablero.pintar();	            	 
	             }			
	         });
	         timer.start();
		} 	}
 	public class SerPintada {		
		public int pint[][] = new int[200][2];
		public int ejeX=0;
		public int ejeY=0;	
		public int borraEjeX=0;
		public int borraEjeY=0;
			public int uno=0;
			public int dos=0;		
 
	public void insertData (int x, int y) {	///*---- Escribe las posiciones	
												//**---  por las que pasa la serpiente
	    ejeY=0;
		pint[ejeX][ejeY]=x;
		ejeY++;
	    pint[ejeX][ejeY]=y;
		ejeX++;	
	}
	public void borra (){
			dos=0;
			int numero1=0;
			int numero2=0;
			numero1=pint[uno][dos];
			dos++;
			numero2=pint[uno][dos];
			tablero.pintarAgua(numero1, numero2);
			System.out.println("recoge "+numero1+" y "+numero2 );
			uno++;			
		}	
	public void relojitoRecoge(){			 
		  Timer timer2 = new Timer (1500, new ActionListener (){		    	 
		     public void actionPerformed(ActionEvent e){
		    	 borra(); 	     }			
		 });		   
		 timer2.start();
		}		 }
}
//-------------------
package serpent;
 
	public class PopUpLoses extends javax.swing.JDialog {
		public PopUpLoses(){
 
		}
	    /** Creates new form PopupButton */
	    public PopUpLoses(java.awt.Frame parent, boolean modal) {
	        super(parent, modal);
	        initComponents();
 
	}	    
	    private void initComponents() {
	        jPopupMenu1 = new javax.swing.JPopupMenu();
	    }
	    private javax.swing.JPopupMenu jPopupMenu1;
	}
Tags: , , , , ,

Artículos relacionados