Duvida (imagem, troca de dados,etc..)

1 resposta
Z

Ola sou novo aqui… tou com uma serie de problemas…
tou tendo que "criar"um jogo em java mas minhas dificuldades são enormes…
Primeiro tou postando as linhas de codigo para vcs terem ideia…
1º-sinto dificuldade de botar uma imagem… como o jogo eh aquele famoso da serpente eu tenho que botar imagem no lugar dos retangulos que estaão nesta primeira classe… alguem pode ajudar?

import java.awt.<em>;

import java.awt.event.</em>;

import javax.swing.*;

public class Segmento {

private Graphics g;

private int x;

private int y;

private int l;

private int h;

private ImageIcon im1,im2,im3;
public void setX(int x){

this.x=x;

}
public void setY(int y){

this.y=y;

}
public int getX (){

return this.x;

}
public int getY (){

return this.y;

}

public Segmento (int a,int b){

setX(a);
setY(b);

im1=new ImageIcon("corpo.jpg");
im2=new ImageIcon("cabeca.jpg");
im3=im1;

l=20;
h=20;

}

public void setI(){

im3=im1;

}
public void setG(Graphics g){

this.g=g;

this.g.setColor(Color.blue);

System.out.println(g.getColor().toString());

}
public void draw(){

setG(g);

im3.paintIcon(this,g,0,0);

g.fillRect(getX(),getY(),l,h);

}

public void move(int x, int y){

System.out.println(entrei nomove);

g.setColor(Color.white);

g.fillRect(getX(),getY(),l,h);

g.drawRect(getX(),getY(),l,h);
setX(x);
  setY(y);
  g.setColor(Color.blue);
  g.fillRect(getX(),getY(),l,h);
  g.drawRect(getX(),getY(),l,h);

}
}

tipo onde tem drawRect eu queria por uma imagem… mas não sei como…

segundo eu tava fazendo estas imagens serem desenhadas em um canvas e este ficar dentro de um frame! So que alguns problemas aconteceram…
primeiro simplesmente não ficou funcional a JMenuBar do frame… segundo o canvas dentro do Frame ficou deslocado… e não no limite da tela…

Percebi tambem que minha orientação a objetos esta pessima ja que tive que fazer dois metodos diferentes para a locomoção da serpente… e mesmo assim da um erro!!!

import javax.swing.<em>;

import java.awt.event.</em>;

import java.awt.<em>;

import java.util.</em>;

class Serpente {

private Segmento cb;
private int t=0;
private Vector vector;


public Serpente(){
	vector = new Vector();
	cb = new Segmento(200,200);
	vector.add(new Segmento(200,200));
	vector.add(new Segmento(200,200));
	vector.add(new Segmento(200,200));
	vector.add(new Segmento(200,200));
}

public int getX(){
	return cb.getX();
}
public int getY(){
	return cb.getY();
}

public void setT(int t){
	this.t=t;
}

public int getT(){
	return this.t;
}

public void setG(Graphics g){
	Segmento s;
	
	cb.setG(g);
	for (int i=(vector.size()-1);i&gt;=0;i--){
		s=(Segmento) vector.get(i);
		s.setG(g);
	}
}

public void draw(){
	
  for(int i=(vector.size()-1);i&gt;=0;i--){
  	Segmento s ;
  	s=(Segmento) vector.get(i);
  	s.draw();
  }
  cb.draw();
}

public void serpenteAndar(){
	Segmento s,v;
	if(vector.contains(cb)){System.out.println("merda");}
	else{		
		for(int i=(vector.size()-1); i&gt;=1; i--){
			int j=i-1;
				s=(Segmento) vector.get(i);
				v=(Segmento) vector.get(j);
				s.setX(v.getX());
				s.setY(v.getY());
				
														
			
		}
		s=(Segmento) vector.get(0);
		s.setX(cb.getX());
		s.setY(cb.getY());
		
		if (t==1) cb.setX(cb.getX()-20);
		if (t==2) cb.setY(cb.getY()-20);
		if (t==3) cb.setX(cb.getX()+20);
		if (t==4) cb.setY(cb.getY()+20);
		
	}
}	

public void serpenteAndar(int k, int l){
	Segmento s,v;
	if(vector.contains(cb)){System.out.println("merda");}
	else{		
		for(int i=(vector.size()-1); i&gt;=1; i--){
			int j=i-1;
				s=(Segmento) vector.get(i);
				v=(Segmento) vector.get(i-1);
				System.out.println("asss");
				s.move(v.getX(),v.getY());			
				System.out.println("caca");		
		}
		s=(Segmento) vector.get(0);
		System.out.println("miu");
		s.move(cb.getX(), cb.getY());
		cb.move(k,l);
		
	}
}

import java.awt.<em>;

import javax.swing.</em>;

import java.awt.event.*;

public class SerpenteKanvas extends Canvas{
private Serpente serp;

public SerpenteKanvas(){
	setBackground(Color.white);
	serp=new Serpente();
	addKeyListener ( new KeyAdapter() {
		public void keyPressed (KeyEvent e) {
		  			
		  switch ( e.getKeyCode() ){
		   	case 37 : {if(getT()==3){}else{setT(1);} break;}
		  	case 38 : {if(getT()==4){}else{setT(2);} break;}
		  	case 39 : {if(getT()==1){}else{setT(3);} break;}
		  	case 40 : {if(getT()==2){}else{setT(4);} break;}
		  	}		  
		 }
	} );

}
public void setT(int t){
	serp.setT(t);
}

public int getT(){
	return serp.getT();
}

public int getX(){
	return serp.getX();
}
public int getY(){
	return serp.getY();
}

public void paint(Graphics g){
	serp.setG(g);
							
	serp.draw();
	serp.serpenteAndar();
    		
	
}

}


import java.awt.<em>;

import javax.swing.</em>;

import java.awt.event.<em>;

import <a href="http://java.net">java.net</a>.</em>;

import <a href="http://java.io">java.io</a>.*;

class SerpenteFrame extends JFrame {

Container c;
JPanel pnBottom;
SerpenteKanvas canvas;
private int p;
private JRadioButtonMenuItem nivelItem[];
private ButtonGroup nivelGroup;
private String nivel[]={"Nivel 1","Nivel 2","Nivel 3"};


private int delay = 50;
Timer s;
DataOutputStream out;
ServerSocket server;
Socket conexao;	


public void iniConexao(){
	
	try {
	    server = new ServerSocket(10000);
	    conexao = server.accept();
	    System.out.println(" Conexao com "+conexao.getInetAddress().toString());    	    
	    out = new DataOutputStream(conexao.getOutputStream());
	    
	    
	} catch (IOException e) {
	    System.out.println(e.toString());
	
	}    
	
}

public SerpenteFrame(){
	
	iniConexao();    		
	c=getContentPane();
	canvas=new SerpenteKanvas();
	/****************************************** JMenu e componentes */
		JMenu arquivoMenu=new JMenu("Arquivo");
	arquivoMenu.setMnemonic('A');
	
	/********************************************/
	
	JMenuItem novoItem=new JMenuItem("Novo Jogo");
	novoItem.setMnemonic('N');
	
	novoItem.addActionListener(
		new ActionListener(){
			public void actionPerformed(ActionEvent event){
				canvas=new SerpenteKanvas();
				repetirAcao();
				
			}
		}
	);
	arquivoMenu.add(novoItem);
	/********************************************/
	
	JMenuItem pontosItem=new JMenuItem("Pontuação");
	pontosItem.setMnemonic('P');
	
	pontosItem.addActionListener(
		new ActionListener(){
			public void actionPerformed(ActionEvent event){
				JOptionPane.showMessageDialog( null, 
				"Você fez: "+ p+" no ultimo jogo!","Pontuação!!"
				,JOptionPane.PLAIN_MESSAGE);
			}
		}
	);
	arquivoMenu.add(pontosItem);
	/********************************************/
	
	
	
	JMenu nivelMenu=new JMenu("Nivel");
	nivelMenu.setMnemonic('l');
	
	nivelItem =new JRadioButtonMenuItem[nivel.length];
	nivelGroup=new ButtonGroup();
	    	
	for (int count=0;count&lt;nivel.length;count++){
		nivelItem[count]=
			new JRadioButtonMenuItem(nivel[count]);
			nivelMenu.add(nivelItem[count]);
			nivelGroup.add(nivelItem[count]);
			nivelItem[count].addActionListener(
			new ActionListener(){
			public void actionPerformed(ActionEvent event){
				if(event.getSource()==nivel[0]){
					delay=250;
				}
				else if(event.getSource()==nivel[1]){
					delay=180;
				}
				else delay=100;		
			}
		});
	}

	
	
	arquivoMenu.add(nivelMenu);
	arquivoMenu.addSeparator();
	
	
	
	/********************************************/
	JMenuItem sobreItem=new JMenuItem("Sobre...");
	sobreItem.setMnemonic('S');
	
	sobreItem.addActionListener(
		new ActionListener(){
			public void actionPerformed(ActionEvent event){
				JOptionPane.showMessageDialog( null, 
				"Bem vindo ao cobra!"+"\n A sua funcão é comer o maior numero"+
				"\n possivel de ovos... BOA SORTE!!","Sobre...",JOptionPane.PLAIN_MESSAGE);
			}
		}
	);
	arquivoMenu.add(sobreItem);
	
	
	/************************************************/
	   	
	JMenuItem sairItem=new JMenuItem("Sair");
	sairItem.setMnemonic('S'); 	
	
	
	sairItem.addActionListener(
		new ActionListener(){
			public void actionPerformed(ActionEvent event){
				System.exit(0);
			}
		}
	);
	arquivoMenu.add(sairItem);
	/***********************************************/
	
	JMenuBar bar=new JMenuBar();
	setJMenuBar(bar);
	bar.add(arquivoMenu);
	bar.setBorderPainted(true);
	
	/***********************************************/
	
	addWindowListener(new WindowAdapter() {
		public void windowClosing(WindowEvent e) {
			dispose();
			System.exit(0);
		}
	});
	/*********************************************** Fim de JMenu e componentes*/
	
   
	c.add("Center",canvas);
	setSize(500,500);
	setVisible(true);
	setResizable(false);
}


	
public void repetirAcao(){
	
	
	ActionListener taskPerformer = new ActionListener() {
    	public void actionPerformed(ActionEvent e) {
     		if(canvas.getY()==(getHeight()-20)| canvas.getY()==-20 || canvas.getX()==-20){
     			s.stop();
     			JOptionPane.showMessageDialog( null, 
				"Você bateu na parede e morreu!!!"+"\n Mais sorte na próxima vez!"
				,"CRASH!!!",JOptionPane.ERROR_MESSAGE);
     			
     		}         		
     		if(canvas.getX() &gt;= getWidth())  {
     			try {
     				out.writeInt(canvas.getX() - getWidth());
		      		out.writeInt(canvas.getY());
		    	} catch (IOException ex)  {}
			}
			canvas.repaint();
		}
    	
  	};
  	s=new Timer(delay, taskPerformer);
  	s.start(); 	
}



public static void main(String args[]){
	SerpenteFrame mainframe=new SerpenteFrame();		
	mainframe.repetirAcao();
	
}

}


Pra finalizar um erro ocorre na tentaiva de fazer a serpente se locomover pela tela cliente (esta classe que segue)… e percebo que tem algo a ver com o metodo serpenteAndar(int k,intl); pois ela que não consegue mandar para o cliente os segumentos adicionais! So fica indo um dos segmentos… e não a serpente inteira…

import javax.swing.*;

import javax.swing.<em>;

import java.awt.event.</em>;

import java.awt.<em>;

import <a href="http://java.net">java.net</a>.</em>;

import <a href="http://java.io">java.io</a>.*;

class SerpenteCliente extends JFrame {

Serpente s;
int x=0;
int y=0;

DataInputStream in;
Socket conexao;

  

public void iniConexao(){
	
	try {
	    
	    conexao = new Socket ("127.0.0.1",10000);
	    in = new DataInputStream(conexao.getInputStream());
	    
	    
	} catch (IOException e) {
	    System.out.println(e.toString());
	
	}    
	
}



public SerpenteCliente () {
	
	iniConexao();
	s= new Serpente();
	
	
	

    setBackground(Color.white);
	addWindowListener(new WindowAdapter() {
		public void windowClosing(WindowEvent e) {
			dispose();
			System.exit(0);
		}
	});
}

public void recebeDados() {
		while (true) {
			
	   		try {
	   				
	     		x= in.readInt();
	       		y= in.readInt();
	       		
	       		
	      		repaint();
	      		
	      	
	      		
	   		}catch (IOException ex) {System.out.println(ex);}    
	   	
	   	System.out.println(x);
	   	System.out.println(y);
		
	}   
}



public void paint(Graphics g) {
    
    	s.setG(g);	       	
    	s.serpenteAndar(x,y);
 	
} 


public static void main (String args[]) {
   
    System.out.println("Starting Serpente Cliente...");
	SerpenteCliente mainFrame = new SerpenteCliente();
	mainFrame.setSize(500,500);
	mainFrame.setResizable(false);
	mainFrame.setTitle("Serpente Cliente");
	mainFrame.setVisible(true);
	mainFrame.recebeDados();
}

}

Sei que parece muita cosia mas se vocês derem uma boa olhada vão ver que não… Peço muito a ajuda pois é um trabalho de um curso e não tou conseguindo resolver estes problemas…

Caso alguem consiga resolver qualquer um dos problemas manda um e-mail pra mim ok??? [email removido] ou [email removido]

Muito obrigado pela ajuda …

1 Resposta

Z

Tipo… este trabalho é para entregar nest sexta feira…
deem uma olhada ai e me deem o toque ok???
Um abraço…

Criado 22 de janeiro de 2005
Ultima resposta 22 de jan. de 2005
Respostas 1
Participantes 1