Ir para o conteúdo
  • Revista PROGRAMAR: Já está disponível a edição #60 da revista programar. Faz já o download aqui!

AJBM

Teclas nem Sempre Funcionam

Mensagens Recomendadas

AJBM

Boas!

Eu estou a fazer um jogo e estou com alguns problemas um deles é, eu adicionei um menu ao jogo, quando eu clico em play mudo de JPanel e vou para o do jogo, o problema é que o jogo não funciona, isto é aparece o jogo mas não consigo mexer a nave. Depois acabo por morrer no jogo e passado um bocado as teclas voltam a funcionar.

Mas se eu não usar o menu, o jogo funciona direitinho.

JFrame

public class SpaceBattle extends JFrame {
public static Cards cards;
public SpaceBattle() {
	cards = new Cards();
	//this.add(new Board()); // com isto nao tenho problemas
	 this.add(cards);// com isto tenho problemas



	this.setVisible(true);
	this.setSize(900, 700);
	this.setResizable(false);
	this.setDefaultCloseOperation(EXIT_ON_CLOSE);

}
public static void main(String[] args) {
	new SpaceBattle();
}
}

CardLayout

public class Cards extends JPanel {
private Menu menu;
private Board board;
public Cards() {
	this.setLayout(new CardLayout());
	this.setSize(900, 700);
	menu = new Menu();
	board = new Board();
	this.add(menu, "Menu");
	this.add(board, "Game");
}
public Menu getMenu() {
	return menu;
}
public Board getBoard() {
	return board;
}
}

Jogo

public class Board extends JPanel implements ActionListener {
private Timer timer;
private Craft craft;
private List<Alien> aliens;
private final byte sleepTime = 5;
private boolean ingame;
private int B_WIDTH;
private int B_HEIGHT;
private int[][] pos = {
	{1380, 29}, {900, 125}, {800, 50},
	{987, 269}, {1000, 250}, {750, 500},
	{500, 100}, {2000, 500}, {800, 500}
};
public Board() {
	this.ingame = false;
	this.setFocusable(true);
	this.setBackground(Color.BLACK);
	this.setDoubleBuffered(true);
	try {
		this.craft = new Craft();
	} catch (MalformedURLException ex) {
		Logger.getLogger(Board.class.getName()).log(Level.SEVERE, null, ex);
	}
	initAliens();
	this.timer = new Timer(this.sleepTime, this);//vai executar actionPerformed a cada sleep time
	this.timer.start();
	System.out.println("contrutor");
	addKeyListener(new TAdapter());
}
@Override
public void addNotify() {
	super.addNotify();
	B_WIDTH = getWidth();
	B_HEIGHT = getHeight();
}
public final void initAliens() {
	aliens = new ArrayList<Alien>();
	for (int i = 0; i < pos.length; i++) {
		aliens.add(new Alien(pos[i][0], pos[i][1]));
	}
}

@Override
public void paint(Graphics g) {
	super.paint(g);
	Graphics2D g2d = (Graphics2D) g;
	if (ingame) {
		g2d.drawImage(craft.getImage(), craft.getX(), craft.getY(), null);
		List<Missile> missiles = craft.getMissiles();
		Iterator<Missile> iter = missiles.listIterator();
		while (iter.hasNext()) {
			Missile mi = iter.next();
			g2d.drawImage(mi.getImage(), mi.getX(), mi.getY(), null);
		}
		Iterator<Alien> iterAliens = aliens.listIterator();
		while (iterAliens.hasNext()) {
			Alien a = iterAliens.next();
			if (a.isVisible()) {
				g2d.drawImage(a.getImage(), a.getX(), a.getY(), null);
			}
		}
		g2d.setColor(Color.WHITE);
		g2d.drawString("Aliens left: " + aliens.size(), 5, 15);
	} else {
		g2d.setColor(Color.WHITE);
		g2d.drawString("Game over", 50, 50);
	}
	Toolkit.getDefaultToolkit().sync();
	g2d.dispose();
}

@Override
public void actionPerformed(ActionEvent e) {
	if (ingame) {
		if (!aliens.isEmpty()) {
			List<Missile> ms = craft.getMissiles();
			Iterator<Missile> iterMissile = ms.listIterator();
			while (iterMissile.hasNext()) {
				Missile m = iterMissile.next();
				if (m.isVisible()) {
					m.move();
				} else {
					iterMissile.remove();
				}
			}
			Iterator<Alien> iterAliens = aliens.listIterator();
			while (iterAliens.hasNext()) {
				Alien a = iterAliens.next();
				if (a.isVisible()) {
					a.move();
				} else {
					iterAliens.remove();
				}
			}
			craft.move();
			checkCollisions();
			repaint();
		} else {
			ingame = false;
			repaint();
		}
	}
}
public void checkCollisions() {
	Rectangle craftBounds = craft.getBounds();
	Iterator<Alien> iter = aliens.listIterator();
	while (iter.hasNext()) {
		Alien alien = iter.next();
		Rectangle alienBounds = alien.getBounds();
		if (craftBounds.intersects(alienBounds)) {
			ingame = false;
			craft.setVisible(false);
			alien.setVisible(false);
			craft.getCraftSound().play();
		}
	}
	List<Missile> ms = craft.getMissiles();
	Iterator<Missile> iterMissiles = ms.listIterator();
	while (iterMissiles.hasNext()) {
		Missile m = iterMissiles.next();
		Rectangle r1 = m.getBounds();
		iter = aliens.listIterator();
		while (iter.hasNext()) {
			Alien a = iter.next();
			Rectangle r2 = a.getBounds();
			if (r1.intersects(r2)) {
				a.getAlienDies().play();
				m.setVisible(false);
				a.setVisible(false);
			}
		}
	}
}
private class TAdapter extends KeyAdapter {
	@Override
	public void keyReleased(KeyEvent e) {
		craft.keyReleased(e);
	}
	@Override
	public void keyPressed(KeyEvent e) {
		if (e.getKeyCode() == KeyEvent.VK_ENTER) {
			ingame = true;
			try {
				craft = new Craft();
			} catch (MalformedURLException ex) {
				JOptionPane.showMessageDialog(null, ex.getMessage());
			}
			initAliens();
			timer.start();
		}
		System.out.println("executado cena das teclas");
		craft.keyPressed(e);
	}
}
public boolean isIngame() {
	return ingame;
}
public void setIngame(boolean ingame) {
	this.ingame = ingame;
}
}

Craft

public class Craft {
private final String craft = "craft.jpg";
private int dx, dy, x, y, width, height;
private Image image;
private boolean visible;
private List<Missile> missiles;
private final int CRAFT_SIZE = 40;
private final String AUDIOPATH = "src/Sounds/Explosao.wav";
private Sound craftSound;
public Craft() throws MalformedURLException {
	ImageIcon icon = new ImageIcon(this.getClass().getResource(this.getCraft()));
	this.image = icon.getImage();
	this.x = 40;
	this.y = 60;
	visible = true;
	width = image.getWidth(null);
	height = image.getHeight(null);
	missiles = new ArrayList<Missile>();
	craftSound = new Sound(AUDIOPATH);
}
public Sound getCraftSound() {
	return craftSound;
}
public void setVisible(boolean visible) {
	this.visible = visible;
}
public Rectangle getBounds() {
	return new Rectangle(x, y, width, height);
}
/**
 * @return the craft
 */
public String getCraft() {
	return craft;
}
/**
 * @return the dx
 */
public int getDx() {
	return dx;
}
/**
 * @param dx the dx to set
 */
public void setDx(int dx) {
	this.dx = dx;
}
public List getMissiles() {
	return missiles;
}
/**
 * @return the dy
 */
public int getDy() {
	return dy;
}
/**
 * @param dy the dy to set
 */
public void setDy(int dy) {
	this.dy = dy;
}
/**
 * @return the x
 */
public int getX() {
	return x;
}
/**
 * @param x the x to set
 */
public void setX(int x) {
	this.x = x;
}
/**
 * @return the y
 */
public int getY() {
	return y;
}
/**
 * @param y the y to set
 */
public void setY(int y) {
	this.y = y;
}
/**
 * @return the image
 */
public Image getImage() {
	return image;
}
/**
 * @param image the image to set
 */
public void setImage(Image image) {
	this.image = image;
}
public void move() {
	if (this.x > 900) {
		this.x = 20;
	}
	if (this.y > 690) {
		this.y = 20;
	}
	if (this.x < 10) {
		this.x = 850;
	}
	if (this.y < 10) {
		this.y = 650;
	} else {
		this.x += this.dx;
		this.y += this.dy;
	}

}
public void fire() {

	missiles.add(new Missile(x + CRAFT_SIZE, y + CRAFT_SIZE / 2));
	missiles.add(new Missile(x + CRAFT_SIZE, y + CRAFT_SIZE / 2 + 40));
}
public void keyPressed(KeyEvent e) {
	int key = e.getKeyCode();
	if (key == KeyEvent.VK_SPACE) {
		fire();
	}
	if (key == KeyEvent.VK_LEFT) {
		this.dx = -1;
	}
	if (key == KeyEvent.VK_RIGHT) {
		this.dx = 1;
	}
	if (key == KeyEvent.VK_UP) {
		this.dy = -1;
	}
	if (key == KeyEvent.VK_DOWN) {
		this.dy = 1;
	}
}
public void keyReleased(KeyEvent e) {
	int key = e.getKeyCode();
	if (key == KeyEvent.VK_LEFT) {
		this.dx = 0;
	}
	if (key == KeyEvent.VK_RIGHT) {
		this.dx = 0;
	}
	if (key == KeyEvent.VK_UP) {
		this.dy = 0;
	}
	if (key == KeyEvent.VK_DOWN) {
		this.dy = 0;
	}
}
}

Menu

public class Menu extends javax.swing.JPanel {

/**
 * Creates new form Menu
 */
public Menu() {
	initComponents();
}

public JButton getCredits() {
	return Credits;
}

public JButton getExit() {
	return Exit;
}

public JButton getPlay() {
	return play;
}

/**
 * This method is called from within the constructor to initialize the form.
 * WARNING: Do NOT modify this code. The content of this method is always
 * regenerated by the Form Editor.
 */
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">						  
private void initComponents() {

	play = new javax.swing.JButton();
	Credits = new javax.swing.JButton();
	Exit = new javax.swing.JButton();
	jLabel1 = new javax.swing.JLabel();

	setFocusable(false);
	setMaximumSize(new java.awt.Dimension(900, 700));
	setMinimumSize(new java.awt.Dimension(900, 700));
	setOpaque(false);
	setPreferredSize(new java.awt.Dimension(900, 700));
	setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());

	play.setText("Play");
	play.addActionListener(new java.awt.event.ActionListener() {
		public void actionPerformed(java.awt.event.ActionEvent evt) {
			playActionPerformed(evt);
		}
	});
	add(play, new org.netbeans.lib.awtextra.AbsoluteConstraints(410, 400, 67, 40));

	Credits.setText("Credits");
	Credits.addActionListener(new java.awt.event.ActionListener() {
		public void actionPerformed(java.awt.event.ActionEvent evt) {
			CreditsActionPerformed(evt);
		}
	});
	add(Credits, new org.netbeans.lib.awtextra.AbsoluteConstraints(410, 460, -1, 40));

	Exit.setText("Exit");
	Exit.addActionListener(new java.awt.event.ActionListener() {
		public void actionPerformed(java.awt.event.ActionEvent evt) {
			ExitActionPerformed(evt);
		}
	});
	add(Exit, new org.netbeans.lib.awtextra.AbsoluteConstraints(410, 520, 67, 40));

	jLabel1.setFont(new java.awt.Font("Old English Text MT", 0, 48)); // NOI18N
	jLabel1.setText("Space Battle");
	add(jLabel1, new org.netbeans.lib.awtextra.AbsoluteConstraints(330, 130, 311, 98));
}// </editor-fold>						

private void playActionPerformed(java.awt.event.ActionEvent evt) {									
	CardLayout card = (CardLayout) SpaceBattle.cards.getLayout();
	card.show(SpaceBattle.cards, "Game");
	SpaceBattle.cards.getBoard().setIngame(true);

}									

private void ExitActionPerformed(java.awt.event.ActionEvent evt) {									
	System.exit(0);
}									



// Variables declaration - do not modify					
private javax.swing.JButton Credits;
private javax.swing.JButton Exit;
private javax.swing.JLabel jLabel1;
private javax.swing.JButton play;
// End of variables declaration				  
}

Partilhar esta mensagem


Ligação para a mensagem
Partilhar noutros sites

Crie uma conta ou ligue-se para comentar

Só membros podem comentar

Criar nova conta

Registe para ter uma conta na nossa comunidade. É fácil!

Registar nova conta

Entra

Já tem conta? Inicie sessão aqui.

Entrar Agora

×

Aviso Sobre Cookies

Ao usar este site você aceita os nossos Termos de Uso e Política de Privacidade. Este site usa cookies para disponibilizar funcionalidades personalizadas. Para mais informações visite esta página.