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

November 16th, 2021

Easy Steps to Add 301 Redirects to WordPress » Tell Me How - A Place for Technology Geekier: Before we try to learn how to add 301 redirects to WordPress, we need to understand what they really are. If you run your own website, it is a must to understand the ‘when’ and ‘how’ of using these.

Is Purefit Keto Beneficial For Weight Loss? » Tell Me How - A Place for Technology Geekier: The ketogenic diet is probably something that everyone interested in physical fitness might have heard about. In this diet plan, you eat lots of fat so that your body to burn even more fat.

The Best SEO Practices for Blogging » Tell Me How - A Place for Technology Geekier: How can SEO help your blog and vice versa? Today, we will give you some information about the best SEO Practices for Blogging.

json2view : Some important properties and types » Tell Me How - A Place for Technology Geekier: Here we see some important properties and types of json2view library which you can use in your applications. Just dive and enjoy the tutorials and code.

Yes You Can! How Millennials Can Actually Afford a House » Tell Me How - A Place for Technology Geekier: The consensus across the world is that Millennials can’t afford to buy houses. Sadly, this means that a lot of them have stopped trying.

However, along with this news, how are JDK builds available? Will they be free or paid? Before answering this, it's important to understand what a "valid" JDK for distribution actually means. In practical terms, there is only one set of source code for the JDK. 

The source code is hosted here.

Animated Recycler View is a library that allows you to animate a recycler view in your project like Google does it in its Google Play Store. Only the first visible items are animated there and you will see no animation when the recycler view scrolls up.

There are so many ways to make mobile apps ranging from direct platform specific development (using Java and Kotlin for Android, and ObjC and Swift for iOS), there’s React Native from Facebook, Electrode Native from Walmart, the Ionic framework, Unity for certain types of apps, and the flutter.io fr

This article looks at many categories of Java defects that Kotlin prevents in addition to null safety. Kotlin showed a surprising impact on productivity.

This article looks at many categories of Java defects that Kotlin prevents in addition to null safety.

Now you’re ready to multiply any number with 9 in 3 sec.

28 X 9 = ?

From Step 2, we’ve to subtract 28 with 3 :

28 – 3 = 25(this is your first part of your answer)

Now from Step 1, we’ve to multiply the unit place of 28 by 9 i.e. 8 X 9.

8 X 9 = 72 and we’ll take only unit place of answer i.e.

Today we’re going to learn CRUD example using Spring boot, Kotlin and AngularJS with WebJar. For this tutorial, nothing is assumed except some basic Java experience.

Today, the MVC pattern is used by well-known frameworks such as Ruby on Rails, Apple iOS Development, ASP.NET MVC, etc. While MVP is mostly used for ASP.NET Web Forms applications and MVVM is used by WPF, Caliburn, Silverlight, nRoute, and more.

Android Popup menu is really a good way to make your Android application more elegant and create a great UI.

There are several popular ORM database libraries out there (SQLDelight, GreenDAO, SugarORM) but we’re going to see top 10 Android database library and nearly every one uses reflection for critical database interactions. Back-end developers get things done, plain and simple.

What is BlockChain Advantage and Disadvantage?

Blockchain is a public record of transactions.

Top 3 Mobile Technology Trends in 2018

Here is my Top three technology trends you all should look out for in your endeavors in this new year 2018, which as always, will offer you loads of new opportunities to rock this world.

Top 5 Android Wear Library In 2018

Welcome to 2018. Happy New Year To All Of You.

If you’re planning to make your own Wear app then i can give you list of some great Android Wear library which you can use in 2018.

Android TextView is capable of showing text in your Android app and previously we discuss how to add rotating animation with TextView. This tutorial explains how to use MultiColor TextView in Android application.

This is a simple library to display text with multicolor.

A colleague approached me a while ago and asked me a question about Kotlin. What was this “Nothing type”, and what was it used for? I did not really have a good answer for him at the time.

Since then, I’ve found my answer.

Advanced Kotlin Tips on writing good Kotlin code and using what the language has to offer. There are many benefits of using Kotlin; it is concise, safe and most importantly it is 100% interoperable with Java. It also tries to solve some of the limitations of Java.

You are going to delete lots of lines of code! Yes, it is not a clickbait!

How do you pass your model between activities?

Serializable? EventBus / Otto ? Parcelable? Serializable = Reflection! Run Forest Run!!! It is terrible for Android performance.

Food Tracking Android Timeline View Example

Android Timeline View Library (Using RecyclerView) is simple implementation used to display view like Tracking of shipment/order, steppers etc.

Kotlin, my favourite programming language, has seen a fast adoption on platforms like Android or Server where the code is compiled to Java bytecode. However, as Kotlin also supports compilation to Javascript, the language is starting to receive attention in the Web ecosystem as well.

Justice League

Today i am going to share Review and Rating of recent release movie Justice League.  It’s better than Batman v Superman. But it’s more successful as a trailer for Aquaman or TheFlash than as a movie of its own.

Google Pixel 2 XL vs iPhone X: Find out Best phone

Google is challenging Apple with its second generation of smartphones, the Pixel 2.

You can easily get access to your system even when you do not remember the password. All you need to do in this situation is use the appropriate password recovery software and unlock your computer.

This post is a summary of first impressions of a few android related frameworks that we (Tell Me How Blog) tried out during a competences session recently.

Dagger

“Dagger constructs instances of your application classes and satisfies their dependencies.

The user interface often contains a lot of cluttered code primarily because of the complicated logic it needs to handle.

Thanks to the increasing number of security holes and increased number of cyber attacks, protecting your phone is more important than ever before.

Google knows this so they’ve begun rolling out Google Play Protect which was originally announced at I/O 2017.

Kotlin is all the rage lately. And while I do agree that the language is well thought out, it does have — as with everything else — its flaws.

These are my 10 favorite new Android animation libraries that have come out since October 2017. Some of them aren’t production ready yet, but you may have lots of fun using them. I hope you enjoy these.

Here they are in no particular order:

1.

Vega Scroll Layout is a lightweight animation flowlayout which fade and shrink the head itemView when scrolling.

Animation in Android is a best way to give a valuable UI in any application. So today i am going to how to implement Android rich path animator which can draw as you want animate much as you can.

What is Android Rich Path Animator?

This library define in simple three line:

Rich Android Path.

Contributors
Contributors
Popular Posts
Popular Posts
Archive
Labels
Labels
Loading
Dynamic Views theme. Powered by Blogger. Report Abuse.