/
rod-pis
/
Snake-for-Java
Обзор
Документация
Войти
/
rod-pis
/
Snake-for-Java
Код
Запросы
0
Задачи
Вики
Пакеты
0
Релизы
0
CI/CD
Аналитика
Безопасность
master
SnakeGame.java
129 строк
4 KB
rod-pis
upload files
15 дек 2025, 18:34
15 дек 2025, 18:34
ed3af57
Код
Авторство
О чём код?
import javax.swing.*; import java.awt.*; import java.awt.event.*; import java.util.Random; public class SnakeGame extends JPanel implements ActionListener { private final int TILE_SIZE = 25; private final int WIDTH = 20; private final int HEIGHT = 20; private final int DELAY = 150; private final int[] x = new int[WIDTH * HEIGHT]; private final int[] y = new int[WIDTH * HEIGHT]; private int snakeLength = 3; private int foodX; private int foodY; private char direction = 'R'; private boolean running = true; private Timer timer; private Random random; public SnakeGame() { setPreferredSize(new Dimension(WIDTH * TILE_SIZE, HEIGHT * TILE_SIZE)); setBackground(Color.BLACK); setFocusable(true); addKeyListener(new KeyAdapter() { @Override public void keyPressed(KeyEvent e) { switch (e.getKeyCode()) { case KeyEvent.VK_LEFT: if (direction != 'R') direction = 'L'; break; case KeyEvent.VK_RIGHT: if (direction != 'L') direction = 'R'; break; case KeyEvent.VK_UP: if (direction != 'D') direction = 'U'; break; case KeyEvent.VK_DOWN: if (direction != 'U') direction = 'D'; break; } } }); random = new Random(); spawnFood(); timer = new Timer(DELAY, this); timer.start(); } private void spawnFood() { foodX = random.nextInt(WIDTH); foodY = random.nextInt(HEIGHT); } @Override protected void paintComponent(Graphics g) { super.paintComponent(g); if (running) { g.setColor(Color.RED); g.fillRect(foodX * TILE_SIZE, foodY * TILE_SIZE, TILE_SIZE, TILE_SIZE); for (int i = 0; i < snakeLength; i++) { if (i == 0) g.setColor(Color.GREEN); else g.setColor(Color.YELLOW); g.fillRect(x[i] * TILE_SIZE, y[i] * TILE_SIZE, TILE_SIZE, TILE_SIZE); } } else { g.setColor(Color.WHITE); g.setFont(new Font("Arial", Font.BOLD, 40)); g.drawString("Game Over", 50, HEIGHT * TILE_SIZE / 2); } } private void move() { for (int i = snakeLength; i > 0; i--) { x[i] = x[i - 1]; y[i] = y[i - 1]; } switch (direction) { case 'U' -> y[0]--; case 'D' -> y[0]++; case 'L' -> x[0]--; case 'R' -> x[0]++; } } private void checkFood() { if (x[0] == foodX && y[0] == foodY) { snakeLength++; spawnFood(); } } private void checkCollisions() { for (int i = snakeLength; i > 0; i--) { if (x[0] == x[i] && y[0] == y[i]) running = false; } if (x[0] < 0 || x[0] >= WIDTH || y[0] < 0 || y[0] >= HEIGHT) running = false; if (!running) timer.stop(); } @Override public void actionPerformed(ActionEvent e) { if (running) { move(); checkFood(); checkCollisions(); } repaint(); } public static void main(String[] args) { JFrame frame = new JFrame("Snake Game"); SnakeGame gamePanel = new SnakeGame(); frame.add(gamePanel); frame.pack(); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setLocationRelativeTo(null); frame.setVisible(true); } }