3

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();

    }
}
mKorbel
  • 109,525
  • 20
  • 134
  • 319
Plaix
  • 831
  • 3
  • 11
  • 20
  • 1
    If you are creating a game use [Slick2D](http://www.slick2d.org/) brilliant library which has most if the stuff you'll need for games like straight out of the box like game loops, opengl, music and animation classes etc. Unless of course you are teaching yourself the workings of painting in Swing than carry on soldier :) – David Kroukamp Jan 27 '13 at 14:53

3 Answers3

11

Several recommendations:

  • Don't draw directly in a JFrame. Check out the drawing tutorials and you'll see to draw in a JPanel or other JComponent's paintComponent(...) method override.
  • The first line of your paintComponent(...) is usually a call to the super's method: super.paintComponent(g)
  • Don't call repaint() inside of paint(...) or paintComponent(...). This is a bad way to try to do uncontrolled animation.
  • Use a Swing Timer instead.
  • Don't name a class the same as a core class, in particular don't name it ActionListener as this will make it nearly impossible for you to use an actual ActionListener when needed.
  • KeyListeners only work if the component listened to is focusable and has the focus.
  • Avoid using KeyListeners with Swing apps but instead use Key Bindings. Please search this site as this has been discussed many times with many examples, some mine.

Please look at the Key Bindings Tutorial and then have a look at my example code for using Key Bindings here and here.

Community
  • 1
  • 1
Hovercraft Full Of Eels
  • 283,665
  • 25
  • 256
  • 373
5

The problems I see, in addition to the ones seen by Hovercraft are:

  • you're not overriding any KeyListener (or KeyAdapter) method. Your method is named KeyPressed, and methods always start with a lower-case letter in Java. The method is named keyPressed(). Always use the @Override annotation when your intention is to override a method. That way, when you don't because you have a typo in the method name, you'll get a compiler error:

     @Override
     public void keyPressed(KeyEvent event) {
         ...
     }
    
  • you're not calling repaint() when a key is pressed, so there's no reason Swing repaints your frame.

JB Nizet
  • 678,734
  • 91
  • 1,224
  • 1,255
4

Games are a different stuff (although some use swing to show a frame). These are the problems in your game.

  • You are calling repaint() inside paint(). 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 your keyPressed() 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 loops

  • Many games use multiple threads. A logic thread which is separate from the EDT so 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 .NET naming convention in java (Starting method names with capitals)

Sri Harsha Chilakapati
  • 11,744
  • 6
  • 50
  • 91