Snake od zera.

Kody źródłowe z gry snake

package pl.am.projects.snake;

import java.awt.*;
import java.util.Random;

public class Apple extends Point {
    private static Random random = new Random();

    public Apple() {
        super(random.nextInt(Board.FIELD_X), random.nextInt(Board.FIELD_Y));
    }

    public void draw(Graphics g) {
        g.setColor(Color.RED);
        g.fillOval(x*Board.SIZE, y* Board.SIZE, Board.SIZE, Board.SIZE);
    }
}
package pl.am.projects.snake;

import java.awt.*;

public class Board {
    public static final int FIELD_X = 35;
    public static final int FIELD_Y = 30;
    public static final int SIZE = 25;
    public static final int MAX_X = FIELD_X*SIZE;
    public static final int MAX_Y = FIELD_Y*SIZE;

    public static void draw(Graphics g) {
        g.setColor(Color.darkGray);
        g.fillRect(0,0, MAX_X, MAX_Y);
    }
}
package pl.am.projects.snake;

public enum Direction {
    R, L, U, D
}
package pl.am.projects.snake;

import java.awt.*;

public class Game {
    public static void main(String[] args) {
        EventQueue.invokeLater(() -> {
            MainFrame mainFrame = new MainFrame();
            mainFrame.setVisible(true);
        });
    }
}
package pl.am.projects.snake;

import javax.swing.*;
import java.awt.*;

public class MainFrame extends JFrame {

    public static JLabel score;

    public MainFrame() throws HeadlessException {
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        setTitle("Snake");

        score = new JLabel("Score: ", SwingConstants.CENTER);
        score.setFont(new Font(score.getFont().getName(), Font.BOLD, 30));

        add(new MainPanel());
        add(score, BorderLayout.NORTH);
        pack();
        setLocationRelativeTo(null);
        setResizable(false);
    }
}
package pl.am.projects.snake;

import javax.swing.*;
import java.awt.*;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;

public class MainPanel extends JPanel {

    private Snake snake = new Snake();
    private Apple apple = new Apple();
    private boolean gameOver = false;

    public MainPanel() {
        setPreferredSize(new Dimension(Board.MAX_X, Board.MAX_Y));
        MainTimer timer = new MainTimer();
        timer.start();

        MainFrame.score.setText("Score: " + snake.getSize());

        setFocusable(true);
        addKeyListener(new MyKeyAdapter());
    }

    @Override
    protected void paintComponent(Graphics g) {
        Board.draw(g);
        snake.draw(g);
        apple.draw(g);
    }

    private class MainTimer extends Timer {
        public static final int DELAY = 100;

        public MainTimer() {
            super(DELAY, e -> {
                if (!gameOver) {
                    snake.move();

                    if (snake.eatApple(apple)) {
                        apple = new Apple();
                    }

                    if (snake.isCollision()) {
                        gameOver = true;
                        MainFrame.score.setText("Game Over - Score: " + snake.getSize());
                    }
                    repaint();
                }
            });
        }
    }

    private class MyKeyAdapter extends KeyAdapter {
        @Override
        public void keyPressed(KeyEvent e) {
            switch (e.getKeyCode()) {
                case KeyEvent.VK_LEFT:
                case KeyEvent.VK_A:
                    if (snake.getDirection() != Direction.R) {
                        snake.setDirection(Direction.L);
                    }
                    break;
                case KeyEvent.VK_RIGHT:
                case KeyEvent.VK_D:
                    if (snake.getDirection() != Direction.L) {
                        snake.setDirection(Direction.R);
                    }
                    break;
                case KeyEvent.VK_DOWN:
                case KeyEvent.VK_S:
                    if (snake.getDirection() != Direction.U) {
                        snake.setDirection(Direction.D);
                    }
                    break;
                case KeyEvent.VK_UP:
                case KeyEvent.VK_W:
                    if (snake.getDirection() != Direction.D) {
                        snake.setDirection(Direction.U);
                    }
                    break;
            }
        }
    }
}
package pl.am.projects.snake;

import java.awt.*;
import java.util.ArrayList;
import java.util.List;

public class Snake {

    private List<Point> body;
    private Direction direction;
    private Point ending;

    public Snake() {
        ending = new Point();
        direction = Direction.D;
        body = new ArrayList<>();

        body.add(new Point(2,5));
        body.add(new Point(2,4));
        body.add(new Point(2,3));
    }

    public void draw(Graphics g) {
        g.setColor(Color.BLUE);
        for (Point point : getTail()) {
            g.fillRect(point.x*Board.SIZE, point.y* Board.SIZE, Board.SIZE, Board.SIZE);
        }

        g.setColor(new Color(55, 63, 227));
        g.fillOval(getHead().x*Board.SIZE, getHead().y* Board.SIZE, Board.SIZE, Board.SIZE);
    }

    private Point getHead() {
        return body.get(0);
    }

    private List<Point> getTail() {
        return body.subList(1, body.size());
    }

    public void move() {
        ending.setLocation(body.get(body.size()-1));
        for (int i = body.size()-1; i>0; i--) {
            body.get(i).setLocation(body.get(i-1));
        }

        switch (direction) {
            case D -> getHead().y++;
            case U -> getHead().y--;
            case R -> getHead().x++;
            case L -> getHead().x--;
        }
    }

    public Direction getDirection() {
        return direction;
    }

    public void setDirection(Direction direction) {
        this.direction = direction;
    }

    public boolean isCollision() {
        Point head = getHead();

        for (Point point : getTail()) {
            if (head.equals(point)) {
                return true;
            }
        }

        return head.x < 0 || head.x >= Board.FIELD_X
                || head.y < 0 || head.y >= Board.FIELD_Y;
    }

    public int getSize() {
        return body.size();
    }

    public boolean eatApple(Apple apple) {

        if (getHead().equals(apple)) {
            body.add(new Point(ending));
            MainFrame.score.setText("Score: " + body.size());
            return true;
        }

        return false;
    }
}

Dodaj komentarz

Twój adres e-mail nie zostanie opublikowany. Wymagane pola są oznaczone *