Untitled

mail@pastecode.io avatar
unknown
plain_text
2 years ago
2.4 kB
1
Indexable
Never
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.Timer;

public class SnakeGame extends JPanel implements ActionListener, KeyListener {

    private static final int WIDTH = 500;
    private static final int HEIGHT = 500;

    private Timer timer;
    private int delay = 100;

    private int[] x = new int[100];
    private int[] y = new int[100];
    private int body;
    private int direction = 3; // 1 = left, 2 = right, 3 = up, 4 = down

    public SnakeGame() {
        addKeyListener(this);
        setFocusable(true);
        setFocusTraversalKeysEnabled(false);
        timer = new Timer(delay, this);
        timer.start();
    }

    public void paint(Graphics g) {
        g.setColor(Color.black);
        g.fillRect(0, 0, WIDTH, HEIGHT);
        g.setColor(Color.green);
        for (int i = 0; i < body; i++) {
            g.fillRect(x[i], y[i], 10, 10);
        }
    }

    public void actionPerformed(ActionEvent e) {
        for (int i = body - 1; i > 0; i--) {
            x[i] = x[i - 1];
            y[i] = y[i - 1];
        }
        if (direction == 1) {
            x[0] -= 10;
        }
        if (direction == 2) {
            x[0] += 10;
        }
        if (direction == 3) {
            y[0] -= 10;
        }
        if (direction == 4) {
            y[0] += 10;
        }
        repaint();
    }

    public void keyPressed(KeyEvent e) {
        int code = e.getKeyCode();
        if (code == KeyEvent.VK_LEFT && direction != 2) {
            direction = 1;
        }
        if (code == KeyEvent.VK_RIGHT && direction != 1) {
            direction = 2;
        }
        if (code == KeyEvent.VK_UP && direction != 4) {
            direction = 3;
        }
        if (code == KeyEvent.VK_DOWN && direction != 3) {
            direction = 4;
        }
    }

    public void keyTyped(KeyEvent e) {
    }

    public void keyReleased(KeyEvent e) {
    }

    public static void main(String[] args) {
        JFrame frame = new JFrame();
        SnakeGame game = new SnakeGame();
        frame.add(game);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);