Question

I'm new to Java and I'm trying to make a simple snake game, but the paint method only gets called once and never again, even though the thread keeps running. I tried another fix on this site that used another class, but that did not work.

public class Snake extends JPanel implements Runnable {

 boolean gamerunning = true;
    int snake_x = 50, snake_y = 50, snake_dir = 2;  //for snake_dir 1=up 2=right 3=down 4=left
    int[] snake_xt, snake_yt;

    public static void main(String args[]) {

        JFrame frame = new JFrame();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(600,600);
        frame.setVisible(true);
        frame.add(new Snake());

        (new Thread(new Snake())).start();
        System.out.println("Running");
    }

    @Override
    public void run() {
        try {
            while (gamerunning) {
                Thread.sleep(500);
                System.out.println(snake_x);
                tick();
                repaint();
            }
        } catch (InterruptedException e) {}
    }

    @Override
    public void paintComponent(Graphics g) {
        super.paintComponent(g);
        System.out.println("painting");
        g.setColor(Color.black);
        g.fillRect(snake_x, snake_y, 10,10);
    }

    public void tick() { 
        System.out.println("tick");
        switch(snake_dir) {
            case 1:
                snake_y -= 10;
                break;
            case 2:
                snake_x += 10;
                break;
            case 3:
                snake_y += 10;
                break;
            case 4:
                snake_x -= 10;
                break;
        }
    }
}
Was it helpful?

Solution

Your problem is: You are not adding the same snake you are drawing!

frame.add(new Snake());

(new Thread(new Snake())).start();

Each of this lines creates a new Snake, the fist one gets drawn, the second one gets moved.

Try

Snake s = new Snake();
frame.add(s);

(new Thread(s)).start();

instead.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top