Trabalho de P2 - Java

Jotahaka

Power Member
Boas pessoal, preciso de uma pequena ajuda.
Em programação 2, estamos a fazer um pequeno jogo do género de space invaders, e estou com um problemazinho. Não consigo premir duas teclas ao mesmo tempo.
Se fosse possivel gostava que me ajudassem ;)
O código é este:
Código:
package gui;


import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import jogobaloes.Balão;


import jogobaloes.Jogo;


/**
 *
 * @author João Silva/João Santos
 */
public class JogoFormulário {


    private long jogoIniciado = 0;
    JFrame frame = new JFrame();
    JPanel painelBaloes = new JPanel();
    JPanel painelBotoes = new JPanel();
    JTextField jTextFieldQuantidade;
    JTextField jTextFieldSegundos;
    JButton jButtonIniciar;
    JButton jButtonTerminar;
    private Simulacao simulacao;
    boolean isStopped = true;
    Jogo jogo;
    String nomeJogador;


    public JogoFormulário() {
        nomeJogador = JOptionPane.showInputDialog(null, "Nome do Jogador", "Sem Nome");
        frame.setTitle("Jogo dos baloes");
        frame.setLayout(null);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(640, 480);
        frame.setResizable(false);


        Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();
        frame.setLocation((dim.width - 640) / 2, (dim.height - 480) / 2);


        frame.setVisible(true);


        jButtonIniciar = new JButton("Iniciar Jogo");
        jButtonIniciar.setSize(jButtonIniciar.getPreferredSize());
        jButtonIniciar.setLocation(275, 25);
        jButtonTerminar = new JButton("Terminar Jogo");
        jButtonTerminar.setSize(jButtonTerminar.getPreferredSize());
        jButtonTerminar.setLocation(400, 25);
        jButtonTerminar.setEnabled(false);


        jTextFieldQuantidade = new JTextField("60", 3);
        jTextFieldQuantidade.setSize(jTextFieldQuantidade.getPreferredSize());
        JLabel labelQuantidade = new JLabel("Quantidade Balões: ");
        labelQuantidade.setSize(labelQuantidade.getPreferredSize());
        labelQuantidade.setLocation(5, 10);
        jTextFieldQuantidade.setLocation(125, 10);


        jTextFieldSegundos = new JTextField("60", 3);
        jTextFieldSegundos.setSize(jTextFieldSegundos.getPreferredSize());
        JLabel labelSegundos = new JLabel("Segundos: ");
        labelSegundos.setSize(labelSegundos.getPreferredSize());
        labelSegundos.setLocation(5, 35);
        jTextFieldSegundos.setLocation(125, 35);


        painelBotoes.setLayout(null);
        painelBotoes.setBackground(Color.LIGHT_GRAY);
        painelBotoes.setBounds(2, 350, 630, 96);
        painelBotoes.add(jButtonIniciar);
        painelBotoes.add(jButtonTerminar);
        painelBotoes.add(labelQuantidade);
        painelBotoes.add(jTextFieldQuantidade);
        painelBotoes.add(labelSegundos);
        painelBotoes.add(jTextFieldSegundos);


        painelBaloes.setBackground(Color.WHITE);
        painelBaloes.setBounds(2, 2, 630, 346);


        frame.add(painelBotoes);
        frame.add(painelBaloes);
        frame.repaint();


        jButtonIniciar.addActionListener(new ActionListener() {


            public void actionPerformed(ActionEvent e) {
                iniciarJogo();
            }
        });


        jButtonTerminar.addActionListener(new ActionListener() {


            public void actionPerformed(ActionEvent e) {
                terminarJogo();
            }
        });


        painelBaloes.addKeyListener(new KeyInputHandler());


    }


    public void terminarJogo() {
        isStopped = true;
        jButtonIniciar.setEnabled(true);
        jButtonTerminar.setEnabled(false);
        jTextFieldQuantidade.setEnabled(true);
        jTextFieldSegundos.setEnabled(true);
        Graphics g = painelBaloes.getGraphics();
        g.setColor(Color.WHITE);
        g.fillRect(2, 2, 630, 350);
        g.setColor(Color.RED);
        g.drawString("Jogo Terminado", 280, 180);
    }


    public void desenhar() {
        if (!isStopped) {
            Graphics g = painelBaloes.getGraphics();
            g.setColor(Color.WHITE);
            g.fillRect(0, 0, 640, 355);
            jogo.desenhar(g);
            jTextFieldSegundos.setText(Integer.toString((int) ((System.currentTimeMillis() - jogoIniciado) / 1000)));
        }
    }


    public static void main(String[] args) throws Exception {
        new JogoFormulário();
    }


    public void iniciarJogo() {


        isStopped = false;


        jogo = new Jogo(Integer.parseInt(jTextFieldQuantidade.getText()), Integer.parseInt(jTextFieldSegundos.getText()), nomeJogador);


        simulacao = new Simulacao();


        jButtonIniciar.setEnabled(false);
        jButtonTerminar.setEnabled(true);
        jTextFieldQuantidade.setEnabled(false);
        jTextFieldSegundos.setEnabled(false);


        jogo.iniciar();
        jogoIniciado = System.currentTimeMillis();


        painelBaloes.requestFocus();


        simulacao.start();
    }


    private class Simulacao extends Thread {


        @Override
        public void run() {


            while (!isStopped) {
                if (System.currentTimeMillis() - jogoIniciado >= jogo.getTempoJogo() * 1000) {
                    terminarJogo();
                } else {


                    try {
                        Thread.sleep(100);
                    } catch (Exception ioe) {
                    }


                    jogo.iterar();
                    desenhar();
                }
            }
        }
    }


    private class KeyInputHandler extends KeyAdapter {


        public void keyPressed(KeyEvent e) {


            if (e.getKeyCode() == KeyEvent.VK_LEFT) {
                jogo.moverArma(-20, 0);
            }
            if (e.getKeyCode() == KeyEvent.VK_RIGHT) {
                jogo.moverArma(20, 0);
            }
            if (e.getKeyCode() == KeyEvent.VK_UP) {
                jogo.moverArma(0, -20);
            }
            if (e.getKeyCode() == KeyEvent.VK_DOWN) {
                jogo.moverArma(0, 20);
            }
            if (e.getKeyCode() == KeyEvent.VK_SPACE) {
                jogo.tentaDisparar();
            }
        }
    }
    
}
Cumps
 
Última edição:
Código:
package gui;


import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import jogobaloes.Balão;


import jogobaloes.Jogo;


/**
 * 
 * @author João Silva/João Santos
 */
public class JogoFormulário {


	private long jogoIniciado = 0;
	JFrame frame = new JFrame();
	JPanel painelBaloes = new JPanel();
	JPanel painelBotoes = new JPanel();
	JTextField jTextFieldQuantidade;
	JTextField jTextFieldSegundos;
	JButton jButtonIniciar;
	JButton jButtonTerminar;
	private Simulacao simulacao;
	boolean isStopped = true;
	Jogo jogo;
	String nomeJogador;


	public JogoFormulário() {
nomeJogador = JOptionPane.showInputDialog(null, "Nome do Jogador", "Sem Nome");
frame.setTitle("Jogo dos baloes");
frame.setLayout(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOS E);
frame.setSize(640, 480);
frame.setResizable(false);




Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();
frame.setLocation((dim.width - 640) / 2, (dim.height - 480) / 2);




frame.setVisible(true);




jButtonIniciar = new JButton("Iniciar Jogo");
jButtonIniciar.setSize(jButtonIniciar.getPreferred Size());
jButtonIniciar.setLocation(275, 25);
jButtonTerminar = new JButton("Terminar Jogo");
jButtonTerminar.setSize(jButtonTerminar.getPreferr edSize());
jButtonTerminar.setLocation(400, 25);
jButtonTerminar.setEnabled(false);




jTextFieldQuantidade = new JTextField("60", 3);
jTextFieldQuantidade.setSize(jTextFieldQuantidade. getPreferredSize());
JLabel labelQuantidade = new JLabel("Quantidade Balões: ");
labelQuantidade.setSize(labelQuantidade.getPreferr edSize());
labelQuantidade.setLocation(5, 10);
jTextFieldQuantidade.setLocation(125, 10);




jTextFieldSegundos = new JTextField("60", 3);
jTextFieldSegundos.setSize(jTextFieldSegundos.getP referredSize());
JLabel labelSegundos = new JLabel("Segundos: ");
labelSegundos.setSize(labelSegundos.getPreferredSi ze());
labelSegundos.setLocation(5, 35);
jTextFieldSegundos.setLocation(125, 35);




painelBotoes.setLayout(null);
painelBotoes.setBackground(Color.LIGHT_GRAY);
painelBotoes.setBounds(2, 350, 630, 96);
painelBotoes.add(jButtonIniciar);
painelBotoes.add(jButtonTerminar);
painelBotoes.add(labelQuantidade);
painelBotoes.add(jTextFieldQuantidade);
painelBotoes.add(labelSegundos);
painelBotoes.add(jTextFieldSegundos);




painelBaloes.setBackground(Color.WHITE);
painelBaloes.setBounds(2, 2, 630, 346);




frame.add(painelBotoes);
frame.add(painelBaloes);
frame.repaint();




jButtonIniciar.addActionListener(new ActionListener() {




public void actionPerformed(ActionEvent e) {
iniciarJogo();
}
});




jButtonTerminar.addActionListener(new ActionListener() {




public void actionPerformed(ActionEvent e) {
terminarJogo();
}
});




painelBaloes.addKeyListener(new KeyInputHandler());




}


	public void terminarJogo() {
		isStopped = true;
		jButtonIniciar.setEnabled(true);
		jButtonTerminar.setEnabled(false);
		jTextFieldQuantidade.setEnabled(true);
		jTextFieldSegundos.setEnabled(true);
		Graphics g = painelBaloes.getGraphics();
		g.setColor(Color.WHITE);
		g.fillRect(2, 2, 630, 350);
		g.setColor(Color.RED);
		g.drawString("Jogo Terminado", 280, 180);
	}


	public void desenhar() {
		if (!isStopped) {
			Graphics g = painelBaloes.getGraphics();
			g.setColor(Color.WHITE);
			g.fillRect(0, 0, 640, 355);
			jogo.desenhar(g);
			jTextFieldSegundos.setText(Integer.toString((int) ((System
					.currentTimeMillis() - jogoIniciado) / 1000)));
		}
	}


	public static void main(String[] args) throws Exception {
		new JogoFormulário();
	}


	public void iniciarJogo() {


		isStopped = false;


		jogo = new Jogo(Integer.parseInt(jTextFieldQuantidade.getText()),
				Integer.parseInt(jTextFieldSegundos.getText()), nomeJogador);


		simulacao = new Simulacao();


		jButtonIniciar.setEnabled(false);
		jButtonTerminar.setEnabled(true);
		jTextFieldQuantidade.setEnabled(false);
		jTextFieldSegundos.setEnabled(false);


		jogo.iniciar();
		jogoIniciado = System.currentTimeMillis();


		painelBaloes.requestFocus();


		simulacao.start();
	}


	private class Simulacao extends Thread {


		@Override
		public void run() {


			while (!isStopped) {
				if (System.currentTimeMillis() - jogoIniciado >= jogo
						.getTempoJogo() * 1000) {
					terminarJogo();
				} else {


					try {
						Thread.sleep(100);
					} catch (Exception ioe) {
					}


					jogo.iterar();
					desenhar();
				}
			}
		}
	}


	private class KeyInputHandler extends KeyAdapter {


		public void keyPressed(KeyEvent e) {


			if (e.getKeyCode() == KeyEvent.VK_LEFT) {
				jogo.moverArma(-20, 0);
			}
			if (e.getKeyCode() == KeyEvent.VK_RIGHT) {
				jogo.moverArma(20, 0);
			}
			if (e.getKeyCode() == KeyEvent.VK_UP) {
				jogo.moverArma(0, -20);
			}
			if (e.getKeyCode() == KeyEvent.VK_DOWN) {
				jogo.moverArma(0, 20);
			}
			if (e.getKeyCode() == KeyEvent.VK_SPACE) {
				jogo.tentaDisparar();
			}
		}
	}

Aqui está ele identado... Ao menos faço isso.
 
Podes tentar criar booleanos que representam a acção de movimento ou disparo, já que da forma que tens acho que não verifica os vários inputs ao mesmo tempo e sim um de cada vez.

Código:
[LEFT][COLOR=#EDEDED]                                       


                                            [/COLOR]public void keyPressed(KeyEvent e) {[/LEFT]                                         
                                            if (e.getKeyCode() == KeyEvent.VK_LEFT) {               
                                                         left = true;            
                                            }           
                                           if (e.getKeyCode() == KeyEvent.VK_RIGHT) {               
                                                         right = true;            
                                            }            
                                           if (e.getKeyCode() == KeyEvent.VK_UP) {                
                                                        up = true;           
                                            }           
                                             if (e.getKeyCode() == KeyEvent.VK_DOWN) {              
                                                        down = true;            
                                            }            
                                            if (e.getKeyCode() == KeyEvent.VK_SPACE) {                
                                                        shoot = true;            
                                            }

                                      }

                                           public void keyReleased(KeyEvent e) {

                                            if (e.getKeyCode() == KeyEvent.VK_LEFT) {               
                                                         left = false;            
                                            }           
                                           if (e.getKeyCode() == KeyEvent.VK_RIGHT) {               
                                                         right = false;            
                                            }            
                                           if (e.getKeyCode() == KeyEvent.VK_UP) {                
                                                        up = false;           
                                            }           
                                             if (e.getKeyCode() == KeyEvent.VK_DOWN) {              
                                                        down = false;            
                                            }            
                                            if (e.getKeyCode() == KeyEvent.VK_SPACE) {                
                                                        shoot = false;            
                                            }
                                        }


Depois na thread principal antes de iterar e desenha, fazes um sequencia de if's verificando cada booleano e ai sim fazes as movimentações indicadas ;)


Código:
    int x = 0;
    int y = 0;

    if(up)
      y+=20;
    if(right)
      x+=20;
     (....)


     jogo.moverArma(x,y);
 
Pronto está testado e a funcionar na perfeição!
Muito obrigado pela ajuda, abraço ;)

Obrigado a todos os que tentaram ajudar..
 
Back
Topo