i was writing a little snake like game and i was implementing the key event listener, so it listens when the arrow keys are pressed it increment or decrement the position of the oval in the frame. Below is my code, what do you think is happening? i tried googling for possible solution, but i turned out empty.
package snakegame;
import java.awt.Graphics;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import javax.swing.JFrame;
/**
*
* @author PlaixHax0r
*/
public class SnakeGame extends JFrame{
int x, y;
public class ActionListener extends KeyAdapter{
public void KeyPressed(KeyEvent a){
int KeyCode = a.getKeyCode();
if(KeyCode == KeyEvent.VK_RIGHT){
x++;
}
if(KeyCode == KeyEvent.VK_LEFT){
x--;
}
if(KeyCode == KeyEvent.VK_DOWN){
y++;
}
if(KeyCode == KeyEvent.VK_UP){
y--;
}
}
public void KeyReleased(KeyEvent a){
}
}
public SnakeGame(){
addKeyListener(new ActionListener());
setTitle("Snake 1.0");
setVisible(true);
setSize(500, 500);
setResizable(false);
setDefaultCloseOperation(EXIT_ON_CLOSE);
x=150;
y=150;
}
public void paint(Graphics g){
g.drawString("Welcome to Snake Empire", 180, 50);
g.fillOval(x, y, 15, 15);
repaint();
}
public static void main(String[] args) {
new SnakeGame();
}
}
Games are a different stuff (although some use swing to show a frame). These are the problems in your game.
You are calling
repaint()insidepaint(). It schedules another paint event before one actually completes. Calling it so many times would burst of your cpu. If you just need to move the oval, just call the repaint at the end of yourkeyPressed()method.You had no control on timing. This leads to a condition where your game runs fast on a fast system and slow on slow system. Try searching for
game loopsMany games use multiple threads. A logic thread which is separate from the
EDTso as to prevent the CPU from hogging and let input be detected at the normal rate.Avoid rendering directly onto a frame. It is recommended only if you want active rendering and create a
BufferStrategy(though you won’t use the paint method).You aren’t using double buffering. It causes the game to flicker.
Never directly change the positions of objects directly in input state. Just change their particular velocities and simple add them to the positions (Also use negative velocities) when updating to ensure that the objects are updated only at regular intervals.
And finally try to search for
java game development tutorials. There’s a simple framework here (tutorial) which gives a good introduction to the subject. (It’s a snake game example).Get rid of the
.NETnaming convention in java (Starting method names with capitals)