import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.util.ArrayList;
public class Main extends JFrame implements ActionListener {
private ArrayList<Point> snakePoints;
public static void main(String[] args) {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
snakePoints = new ArrayList<>();
direction = KeyEvent.VK_RIGHT;
addKeyListener(new KeyAdapter() {
public void keyPressed(KeyEvent e) {
int key = e.getKeyCode();
if ((key == KeyEvent.VK_LEFT) && direction != KeyEvent.VK_RIGHT) {
direction = KeyEvent.VK_LEFT;
if ((key == KeyEvent.VK_RIGHT) && direction != KeyEvent.VK_LEFT) {
direction = KeyEvent.VK_RIGHT;
if ((key == KeyEvent.VK_UP) && direction != KeyEvent.VK_DOWN) {
direction = KeyEvent.VK_UP;
if ((key == KeyEvent.VK_DOWN) && direction != KeyEvent.VK_UP) {
direction = KeyEvent.VK_DOWN;
snakePoints.add(new Point(100, 100));
snakePoints.add(new Point(90, 100));
snakePoints.add(new Point(80, 100));
food = new Point(200, 200);
timer = new Timer(100, this);
public void paint(Graphics g) {
for (Point point : snakePoints) {
g.fillRect(point.x, point.y, 10, 10);
g.fillRect(food.x, food.y, 10, 10);
public void actionPerformed(ActionEvent e) {
private void checkFood() {
if (snakePoints.get(0).equals(food)) {
int x = (int) (Math.random() * 79) * 10;
int y = (int) (Math.random() * 59) * 10;
private void checkCollision() {
for (int i = 1; i < snakePoints.size(); i++) {
if (snakePoints.get(0).equals(snakePoints.get(i))) {
if (snakePoints.get(0).x < 0 || snakePoints.get(0).x > 790 ||
snakePoints.get(0).y < 0 || snakePoints.get(0).y > 590) {
Point head = snakePoints.get(0);
Point newHead = head.getLocation();
snakePoints.add(0, newHead);
snakePoints.remove(snakePoints.size() - 1);
private void gameOver(Graphics g) {
String message = "Проигрыш";
Font font = new Font("Победа", Font.BOLD, 30);
FontMetrics metrics = getFontMetrics(font);
g.drawString(message, (800 - metrics.stringWidth(message)) / 2, 300);