Snake is an older classic video game. It was first created in late 70s. Later it was brought to PCs. In this game the player controls a snake. The objective is to eat as many apples as possible. Each time the snake eats an apple, its body grows. The snake must avoid the walls and its own body. This game is sometimes called Nibbles.
How to Make Snake Game In Swing,Make Snake Game In Swing,Snake Game In Swing,Game In Swing,

Development

The size of each of the joints of a snake is 10px. The snake is controlled with the cursor keys. Initially, the snake has three joints. If the game is finished, the "Game Over" message is displayed in the middle of the board.

Board.java

package com.blogspot.geekonjava;

import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;

import javax.swing.ImageIcon;
import javax.swing.JPanel;
import javax.swing.Timer;

public class Board extends JPanel implements ActionListener {

    private final int B_WIDTH = 300;
    private final int B_HEIGHT = 300;
    private final int DOT_SIZE = 10;
    private final int ALL_DOTS = 900;
    private final int RAND_POS = 29;
    private final int DELAY = 140;

    private final int x[] = new int[ALL_DOTS];
    private final int y[] = new int[ALL_DOTS];

    private int dots;
    private int apple_x;
    private int apple_y;

    private boolean leftDirection = false;
    private boolean rightDirection = true;
    private boolean upDirection = false;
    private boolean downDirection = false;
    private boolean inGame = true;

    private Timer timer;
    private Image ball;
    private Image apple;
    private Image head;

    public Board() {

        addKeyListener(new TAdapter());
        setBackground(Color.black);
        setFocusable(true);

        setPreferredSize(new Dimension(B_WIDTH, B_HEIGHT));
        loadImages();
        initGame();
    }

    private void loadImages() {

        ImageIcon iid = new ImageIcon("dot.png");
        ball = iid.getImage();

        ImageIcon iia = new ImageIcon("apple.png");
        apple = iia.getImage();

        ImageIcon iih = new ImageIcon("head.png");
        head = iih.getImage();
    }

    private void initGame() {

        dots = 3;

        for (int z = 0; z < dots; z++) {
            x[z] = 50 - z * 10;
            y[z] = 50;
        }

        locateApple();

        timer = new Timer(DELAY, this);
        timer.start();
    }

    @Override
    public void paintComponent(Graphics g) {
        super.paintComponent(g);

        doDrawing(g);
    }
    
    private void doDrawing(Graphics g) {
        
        if (inGame) {

            g.drawImage(apple, apple_x, apple_y, this);

            for (int z = 0; z < dots; z++) {
                if (z == 0) {
                    g.drawImage(head, x[z], y[z], this);
                } else {
                    g.drawImage(ball, x[z], y[z], this);
                }
            }

            Toolkit.getDefaultToolkit().sync();

        } else {

            gameOver(g);
        }        
    }

    private void gameOver(Graphics g) {
        
        String msg = "Game Over";
        Font small = new Font("Helvetica", Font.BOLD, 14);
        FontMetrics metr = getFontMetrics(small);

        g.setColor(Color.white);
        g.setFont(small);
        g.drawString(msg, (B_WIDTH - metr.stringWidth(msg)) / 2, B_HEIGHT / 2);
    }

    private void checkApple() {

        if ((x[0] == apple_x) && (y[0] == apple_y)) {

            dots++;
            locateApple();
        }
    }

    private void move() {

        for (int z = dots; z > 0; z--) {
            x[z] = x[(z - 1)];
            y[z] = y[(z - 1)];
        }

        if (leftDirection) {
            x[0] -= DOT_SIZE;
        }

        if (rightDirection) {
            x[0] += DOT_SIZE;
        }

        if (upDirection) {
            y[0] -= DOT_SIZE;
        }

        if (downDirection) {
            y[0] += DOT_SIZE;
        }
    }

    private void checkCollision() {

        for (int z = dots; z > 0; z--) {

            if ((z > 4) && (x[0] == x[z]) && (y[0] == y[z])) {
                inGame = false;
            }
        }

        if (y[0] >= B_HEIGHT) {
            inGame = false;
        }

        if (y[0] < 0) {
            inGame = false;
        }

        if (x[0] >= B_WIDTH) {
            inGame = false;
        }

        if (x[0] < 0) {
            inGame = false;
        }
        
        if(!inGame) {
            timer.stop();
        }
    }

    private void locateApple() {

        int r = (int) (Math.random() * RAND_POS);
        apple_x = ((r * DOT_SIZE));

        r = (int) (Math.random() * RAND_POS);
        apple_y = ((r * DOT_SIZE));
    }

    @Override
    public void actionPerformed(ActionEvent e) {

        if (inGame) {

            checkApple();
            checkCollision();
            move();
        }

        repaint();
    }

    private class TAdapter extends KeyAdapter {

        @Override
        public void keyPressed(KeyEvent e) {

            int key = e.getKeyCode();

            if ((key == KeyEvent.VK_LEFT) && (!rightDirection)) {
                leftDirection = true;
                upDirection = false;
                downDirection = false;
            }

            if ((key == KeyEvent.VK_RIGHT) && (!leftDirection)) {
                rightDirection = true;
                upDirection = false;
                downDirection = false;
            }

            if ((key == KeyEvent.VK_UP) && (!downDirection)) {
                upDirection = true;
                rightDirection = false;
                leftDirection = false;
            }

            if ((key == KeyEvent.VK_DOWN) && (!upDirection)) {
                downDirection = true;
                rightDirection = false;
                leftDirection = false;
            }
        }
    }
}
First we will define the constants used in our game.
private final int B_WIDTH = 300;
private final int B_HEIGHT = 300;
private final int DOT_SIZE = 10;
private final int ALL_DOTS = 900;
private final int RAND_POS = 29;
private final int DELAY = 140;
The B_WIDTH and B_HEIGHT constants determine the size of the board. The DOT_SIZE is the size of the apple and the dot of the snake. The ALL_DOTS constant defines the maximum number of possible dots on the board (900 = (300*300)/(10*10)). The RAND_POS constant is used to calculate a random position for an apple. The DELAY constant determines the speed of the game.
private final int x[] = new int[ALL_DOTS];
private final int y[] = new int[ALL_DOTS];
These two arrays store the x and y coordinates of all joints of a snake.
private void loadImages() {

    ImageIcon iid = new ImageIcon("dot.png");
    ball = iid.getImage();

    ImageIcon iia = new ImageIcon("apple.png");
    apple = iia.getImage();

    ImageIcon iih = new ImageIcon("head.png");
    head = iih.getImage();
}
In the loadImages() method we get the images for the game. The ImageIcon class is used for displaying PNG images.
private void initGame() {

    dots = 3;

    for (int z = 0; z < dots; z++) {
        x[z] = 50 - z * 10;
        y[z] = 50;
    }

    locateApple();

    timer = new Timer(DELAY, this);
    timer.start();
}
In the initGame() method we create the snake, randomly locate an apple on the board, and start the timer.
private void checkApple() {

    if ((x[0] == apple_x) && (y[0] == apple_y)) {

        dots++;
        locateApple();
    }
}
If the apple collides with the head, we increase the number of joints of the snake. We call the locateApple() method which randomly positions a new apple object.

In the move() method we have the key algorithm of the game. To understand it, look at how the snake is moving. We control the head of the snake. We can change its direction with the cursor keys. The rest of the joints move one position up the chain. The second joint moves where the first was, the third joint where the second was etc.
for (int z = dots; z > 0; z--) {
    x[z] = x[(z - 1)];
    y[z] = y[(z - 1)];
}
This code moves the joints up the chain.
if (leftDirection) {
    x[0] -= DOT_SIZE;
}
This line moves the head to the left.
In the checkCollision() method, we determine if the snake has hit itself or one of the walls.
for (int z = dots; z > 0; z--) {

    if ((z > 4) && (x[0] == x[z]) && (y[0] == y[z])) {
        inGame = false;
    }
}
If the snake hits one of its joints with its head the game is over.
if (y[0] >= B_HEIGHT) {
    inGame = false;
}
The game is finished if the snake hits the bottom of the board.


Snake.java

package com.blogspot.geekonjava;

import java.awt.EventQueue;
import javax.swing.JFrame;


public class Snake extends JFrame {

    public Snake() {

        add(new Board());
        
        setResizable(false);
        pack();
        
        setTitle("Snake");
        setLocationRelativeTo(null);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }
    

    public static void main(String[] args) {
        
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {                
                JFrame ex = new Snake();
                ex.setVisible(true);                
            }
        });
    }
}
This is the main class.
setResizable(false);
pack();
The setResizable() method affects the insets of the JFrame container on some platforms. Therefore, it is important to call it before the pack() method. Otherwise, the collision of the snake's head with the right and bottom borders might not work correctly.
2

View comments

  1. Hi I'm having trouble loading the images it seems like it can't detect the images T^T Help I have already copied the .png images in the class package but it doesn't work

    ReplyDelete
    Replies
    1. Are you put that images in any folder or in root folder ?

      Delete
Easy Steps to Add 301 Redirects to WordPress
Easy Steps to Add 301 Redirects to WordPress
Is Purefit Keto Beneficial For Weight Loss?
Is Purefit Keto Beneficial For Weight Loss?
The Best SEO Practices for Blogging » Tell Me How - A Place for Technology Geekier
The Best SEO Practices for Blogging » Tell Me How - A Place for Technology Geekier
json2view : Some important properties and types » Tell Me How - A Place for Technology Geekier
json2view : Some important properties and types » Tell Me How - A Place for Technology Geekier
Yes You Can! How Millennials Can Actually Afford a House » Tell Me How - A Place for Technology Geekier
Yes You Can! How Millennials Can Actually Afford a House » Tell Me How - A Place for Technology Geekier
THE BEST GADGETS FOR STUDYING OF 2020 &raquo; Tell Me How - A Place for Technology Geekier
THE BEST GADGETS FOR STUDYING OF 2020 &raquo; Tell Me How - A Place for Technology Geekier
JDK Alternatives for Production
Transition Page Recycler using Animated Recycler View
Transition Page Recycler using Animated Recycler View
Best programming for Android after analyse APK
Best programming for Android after analyse APK
Top 6 Java Defects can resolve by Kotlin
Top 6 Java Defects can resolve by Kotlin
Magic Multiply by 9 Trick without Pen and Paper
Magic Multiply by 9 Trick without Pen and Paper
[CRUD Example] : Spring Boot with Kotlin and AngularJS
[CRUD Example] : Spring Boot with Kotlin and AngularJS
What is MVC, MVP and MVVM in details?
What is MVC, MVP and MVVM in details?
How to Add Popup Menu in Android?
How to Add Popup Menu in Android?
Top 5 Android and Kotlin Database Libraries
Top 5 Android and Kotlin Database Libraries
BlockChain Technology - Advantage and Disadvantage
BlockChain Technology - Advantage and Disadvantage
Android Technology Trends in 2018
Android Technology Trends in 2018
Comparison between all Android Wear Library
Comparison between all Android Wear Library
Multicolor TextView for Android
Multicolor TextView for Android
Nothing Type in Kotlin
Nothing Type in Kotlin
Advanced Kotlin Tips
Advanced Kotlin Tips
Awesome Kotlin Parcelize Feature - Need to Know
Awesome Kotlin Parcelize Feature - Need to Know
Create Food Order Tracking app using Android Timeline View Library
Create Food Order Tracking app using Android Timeline View Library
Let's build a Firefox extension with Kotlin
Justice League Reviews Round-up
Justice League Reviews Round-up
Google Pixel 2 XL vs iPhone X: Find out Best phone
Google Pixel 2 XL vs iPhone X: Find out Best phone
Password Recovery Reviews
Password Recovery Reviews
Which Android Dependency Injection is best?
Which Android Dependency Injection is best?
What is MVC, MVP and MVVM in details
What is MVC, MVP and MVVM in details
Google Play Protect – A New Way To Protect Your Phone
Google Play Protect – A New Way To Protect Your Phone
Some Kotlin Problem with solutions Every developer need to know
Some Kotlin Problem with solutions Every developer need to know
Best Android Animation Library in 2017
How to Implement Vega Scroll Layout Android Slider?
How to Implement Vega Scroll Layout Android Slider?
How to Add Android Rich Path Animator?
How to Add Android Rich Path Animator?
Topbar Menu with Guillotine Android animation
Topbar Menu with Guillotine Android animation
Implement Android Prevent Screen Off library?
Implement Android Prevent Screen Off library?
Android P support Java 9 with Kotlin updates?
Android P support Java 9 with Kotlin updates?
Tutorial : Create Augmented Reality in Kotlin
Anyone to Create Custom Ransomware Virus
Anyone to Create Custom Ransomware Virus
Android Oreo vs. iOS 11: The Next-Gen OS Battle
Android Oreo vs. iOS 11: The Next-Gen OS Battle
Android 7 Vs Android 8
Android 7 Vs Android 8
Google launched Android Oreo See the features
Google launched Android Oreo See the features
How to Android Image Compression Using ImageZipper Library?
How to Android Image Compression Using ImageZipper Library?
How to use FileStack File Picker for Cloud in Android
How to use FileStack File Picker for Cloud in Android
Create UberCar Animation with Android Library
Create UberCar Animation with Android Library
How to Add FloatingView Animation in Android?
How to Add FloatingView Animation in Android?
Add Material Shadow in Android
Add Material Shadow in Android
Daily used Kotlin Code Snippet
Daily used Kotlin Code Snippet
Kotlin without JVM Using Kotlin Native
Kotlin without JVM Using Kotlin Native
How to add GraphView in Android using Graph Library?
How to add GraphView in Android using Graph Library?
ConstraintLayout in Android
ConstraintLayout in Android
How to implement GIFView in Android
How to implement GIFView in Android
Android Instant Run - How it works?
Android Instant Run - How it works?
Use Springy Facebook Rebound?
Use Springy Facebook Rebound?
Add Pull To Make Soup animation in Android
Add Pull To Make Soup animation in Android
Use PreviewSeekBar for Android Video App
Use PreviewSeekBar for Android Video App
KOIN – Functional Kotlin dependency injection framework
KOIN – Functional Kotlin dependency injection framework
Lottie - How to Convert Adobe After Effects to Kotlin
Lottie - How to Convert Adobe After Effects to Kotlin
Boost Android Development using Top 30 Android Tools
Boost Android Development using Top 30 Android Tools
Add Android Increment ProductView in your project?
Add Android Increment ProductView in your project?
Latest features in Android Studio 3.0 Canary 6
Latest features in Android Studio 3.0 Canary 6
How to use Android Audio Widget Overlay View
How to use Android Audio Widget Overlay View
Crumbling Image SlideView in Android
Crumbling Image SlideView in Android
Tinder like SwipeView in Android
Tinder like SwipeView in Android
Android Test with Kotlin
Android Test with Kotlin
How to use Android FabulousFilter with Floating Action Button
How to use Android FabulousFilter with Floating Action Button
How LastAdapter can remove RecyclerView and ViewHolder?
How LastAdapter can remove RecyclerView and ViewHolder?
Kotlin's 5 best things you probably don’t know
Kotlin's 5 best things you probably don’t know
Google Play like UI with RecyclerView Snapping Example
Google Play like UI with RecyclerView Snapping Example
Kotlin 1.1.2 version launched with 15 features
Kotlin 1.1.2 version launched with 15 features
Kotlin disadvantage - 7 reason why i don't like it
Kotlin disadvantage - 7 reason why i don't like it
Facebook New Stories button for Android using PopupBubble Library
Facebook New Stories button for Android using PopupBubble Library
How to add Infinite Cycle ViewPager in Android Application
How to add Infinite Cycle ViewPager in Android Application
Android Side Menu Animation Library
Android Side Menu Animation Library
Fan Layout Manager Android Animation Library
Fan Layout Manager Android Animation Library
ExpectAnim Android Kotlin Animation Library
ExpectAnim Android Kotlin Animation Library
What is Kotlin Anko? How it make development easier with Kotlin?
What is Kotlin Anko? How it make development easier with Kotlin?
Android SpaceTabLayout Animation Tutorial
Android SpaceTabLayout Animation Tutorial
Deca core Features of mPhone 8 Specification
Deca core Features of mPhone 8 Specification
Android Studio Shortcut key
Android Studio Shortcut key
iPhone 8 would have oLED like display
iPhone 8 would have oLED like display
Make Reddit Like Android App Using Kotlin
Make Reddit Like Android App Using Kotlin
Grand Theft Auto V bonuses and discount for limited time
Grand Theft Auto V bonuses and discount for limited time
Android Vertical Stepper Form Library » Tell Me How - A Place for Technology Geekier
Android Vertical Stepper Form Library » Tell Me How - A Place for Technology Geekier
How to implement and customize android search dialog?
How to implement and customize android search dialog?
Dual Core V/S Quad Core : Which is best?
Dual Core V/S Quad Core : Which is best?
Add multiple Adapter - MultiViewAdapter Android Library » Tell Me How - A Place for Technology Geekier
Add multiple Adapter - MultiViewAdapter Android Library » Tell Me How - A Place for Technology Geekier
Android AdaptiveTableLayout CSV Library » Tell Me How - A Place for Technology Geekier
Android AdaptiveTableLayout CSV Library » Tell Me How - A Place for Technology Geekier
How to Prevent and Remove Ransomware virus
How to Prevent and Remove Ransomware virus
How to deal with Android Cards?
How to deal with Android Cards?
Add Android Swipe to delete using Swiperoo Adapter » Tell Me How - A Place for Technology Geekier
Add Android Swipe to delete using Swiperoo Adapter » Tell Me How - A Place for Technology Geekier
Bubble picker Android Library » Tell Me How - A Place for Technology Geekier
Bubble picker Android Library » Tell Me How - A Place for Technology Geekier
How to Add Wave Sidebar Animation Android » Tell Me How - A Place for Technology Geekier
How to Add Wave Sidebar Animation Android » Tell Me How - A Place for Technology Geekier
Android Spruce Animation Library » Tell Me How - A Place for Technology Geekier
Android Spruce Animation Library » Tell Me How - A Place for Technology Geekier
How to Add Progress Button Android Library
How to Add Progress Button Android Library
How to add Android Photofilter Library : Easy way to editing image » Tell Me How
How to add Android Photofilter Library : Easy way to editing image » Tell Me How
[Comparison]: Apple Siri v/s Google Assistant v/s Microsoft Cortona v/s Amazon Alexa
[Comparison]: Apple Siri v/s Google Assistant v/s Microsoft Cortona v/s Amazon Alexa
Android DebugKit : Easy way to debug Android Apps » Tell Me How - A Place for Technology Geekier
Android DebugKit : Easy way to debug Android Apps » Tell Me How - A Place for Technology Geekier
Add Android FAB option menu with Gooey Effect » Tell Me How - A Place for Technology Geekier
Add Android FAB option menu with Gooey Effect » Tell Me How - A Place for Technology Geekier
Contributors
Contributors
Popular Posts
Popular Posts
Archive
Labels
Labels
Loading
Dynamic Views theme. Powered by Blogger. Report Abuse.