import javax.swing.*; import java.awt.*; import java.awt.event.*; public class SnakeXenziaSwing extends JPanel implements ActionListener, KeyListener private final int WIDTH = 400, HEIGHT = 400, UNIT_SIZE = 25; private final int GAME_UNITS = (WIDTH * HEIGHT) / (UNIT_SIZE * UNIT_SIZE); private int[] x = new int[GAME_UNITS]; private int[] y = new int[GAME_UNITS]; private int bodyLength = 3; private int foodX, foodY; private char direction = 'R'; private boolean running = false; private Timer timer;
@Override public void paintComponent(Graphics g) super.paintComponent(g); if (running) g.setColor(Color.RED); g.fillOval(foodX, foodY, UNIT_SIZE, UNIT_SIZE); g.setColor(Color.GREEN); for (int i = 0; i < bodyLength; i++) g.fillRect(x[i], y[i], UNIT_SIZE, UNIT_SIZE); else g.setColor(Color.RED); g.drawString("Game Over - Score: " + (bodyLength-3), WIDTH/2-50, HEIGHT/2); Snake Xenzia JAVA GAMES
private void startGame() running = true; // Initialize snake position (middle) for (int i = 0; i < bodyLength; i++) x[i] = WIDTH/2 - i*UNIT_SIZE; y[i] = HEIGHT/2; generateFood(); timer = new Timer(100, this); timer.start(); import javax
private void checkFood() if (x[0] == foodX && y[0] == foodY) bodyLength++; generateFood(); HEIGHT = 400