Estava programando um jogo bem simples. Que está incluso na aula do curso da "Danki code ". O jogo pong. Só para teste. Coloquei o comando das teclas. Funciona assim: Se eu apertar a tecla “e” o personagem se move. Mas o problema é que não funciona. Eu pesquisei em outros tópicos, discussões mas, não consegui resolver o problema quem conseguir me ajudar eu agradeço. O código está abaixo:
Classe Game:
package pong;
import java.awt.Canvas;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.image.BufferStrategy;
import java.awt.image.BufferedImage;
import javax.swing.JFrame;
public class Game extends Canvas implements Runnable,KeyListener{
public static int WIDTH = 240;
public static int HEIGHT = 140;
public static int SCALE = 4;
public Player player;
public BufferedImage layer = new BufferedImage(WIDTH,HEIGHT,BufferedImage.TYPE_INT_RGB);
public Game() {
this.setPreferredSize(new Dimension(WIDTH*SCALE, HEIGHT*SCALE));
this.addKeyListener(this);
player = new Player(100,HEIGHT-10);
}
public void tick() {
player.tick();
}
public void render() {
BufferStrategy bs = this.getBufferStrategy();
if(bs == null) {
this.createBufferStrategy(3);
return;
}
Graphics g = layer.getGraphics();
player.render(g);
g = bs.getDrawGraphics();
g.drawImage(layer, 0,0, WIDTH*SCALE,HEIGHT*SCALE,null);
bs.show();
}
public static void main(String[] args) {
Game game = new Game();
JFrame frame = new JFrame("Pong do manel");
frame.setResizable(false);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(game);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
new Thread(game).start();
}
@Override
public void run() {
requestFocus();
while(true) {
tick();
render();
try {
Thread.sleep(1000/60);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
@Override
public void keyPressed(KeyEvent e) {
if(e.getKeyCode() == e.VK_RIGHT) {
System.out.println("Pressed RIGHT");
player.right = true;
}
else if(e.getKeyCode() == e.VK_LEFT) {
System.out.println("Pressed LEFT");
player.left = true;
}
}
@Override
public void keyReleased(KeyEvent e) {
// TODO Auto-generated method stub
}
@Override
public void keyTyped(KeyEvent e) {
// TODO Auto-generated method stub
}
}
Classe Player :
import java.awt.Color;
import java.awt.Graphics;
public class Player {
public boolean right,left;
public int x,y;
public Player(int x,int y) {
this.x = x;
this.y = y;
}
public void tick() {
if(right)
{
x++;
}
else if(left)
{
x--;
}
}
public void render(Graphics g) {
g.setColor(Color.BLUE);
g.fillRect(x,y, 40, 10);
}
}