Snake Game In Java With Free Source Code

The Snake Game in Java was developed using Java Programming. This game is good for students or beginners who want to learn programming.

A Snake game is an older classic video game. The game was first created in the late 70s. Later, it was brought to PCs.

Snake Game In Java With Source Code
Snake Game In Java With Source Code

In this game, the player controls a snake. The objective of this game is to eat as many mugs of beer as possible. Each time the snake eats an apple, its body grows, and then the head of the snake.

The snake must avoid the walls and its own body.

This Snake Game Java Code also includes a downloadable source code for free. Just find the downloadable button below and click to start downloading.

To start creating a Snake game, make sure that you have NetBeans IDE or any platform Java installed on your computer.

About the Snake Game In Java

Project Name:Snake Game In Java With Source Code
Language/s Used:JAVA
Database:None
Type:Desktop Application
Developer:IT SOURCECODE
Updates:0
Snake Game In Java– Project Information

How To Create Snake Game In Java? A step-by-step Guide with Source Code

Time needed: 5 minutes

These are the steps for making the Snake Game In Java With Source Code.

  • Step 1: Create a project.

    First, open the file and then click “project” to create.
    snake game create project

  • Step 2: Create a project name.

    Second, name your project.
    snake game project name

  • Step 3: Create JFrame.

    Third, create a “JFrame” form.
    snake game create jframe

  • Step 4: Create a JFrame name.

    Fourth, name your JFrame form.
    snake game jframe name

  • Step 5: Project Design.

    Fifth, The actual design of the project.
    snake game output

The Code Given Below Is For The Connection Module

package cls;

import java.sql.Connection;

import java.sql.DriverManager;

import java.sql.SQLException;

import javax.swing.JOptionPane;

/**

 *

 * @author bagong

 */

public class ClassDB {

    // static final int math.random

    private static Connection koneksi;

    //  public static void main string args    

    public static Connection getkoneksi() {

        if (koneksi == null) {

            try {

                String url = new String();

                String user = new String();

                String password = new String();

                url = "jdbc:mysql://localhost:3306/snake";

                user = "root";

                password = "";

                DriverManager.registerDriver(new com.mysql.jdbc.Driver());

                koneksi = DriverManager.getConnection(url, user, password);

                // JOptionPane.showMessageDialog(null,"Koneksi Berhasil");

            } catch (SQLException t) {

                JOptionPane.showMessageDialog(null, "Error membuat koneksi");

            }

        }

        return koneksi;

    }

}

This module serves as a bridge between Java NetBeans and the MySQL database. 

The Code Given Below Is For The Player Name Module

private void nama() {

    // We stored the public class snake in the nama variable    

    Nama = JOptionPane.showInputDialog(this, "Please Input Your Name:");

    if (Nama == null) {

        System.exit(0);

    } else {

        if (Nama.equals("")) {

            JOptionPane.showMessageDialog(this, "Name Already Exist!");

            nama();

        } else {

            try {

                Connection c = ClassDB.getkoneksi();

                Statement st = (Statement) c.createStatement();

                String ceknama = "Select * from score where nama = '" + Nama.toString() + "'";

                ResultSet r = st.executeQuery(ceknama);

                if (r.next()) {

                    return;

                } else {

                    try {

                        st.executeUpdate("Insert into score(nama) values('" + Nama.toString() + "')");

                    } catch (Exception e) {

                        System.out.println(e);

                    }

                }



            } catch (Exception e) {

                System.out.println(e);

            }

        }

    }

}

This module is the module for entering the name of the player to start the game and the positions of the snake.

The Code Given Below Is For Updating the Score Module

private void updatescore() {

    try {

        Connection c = ClassDB.getkoneksi();

        Statement s = (Statement) c.createStatement();

        String cektinggi = "Select * from score where nama = '" + Nama.toString() + "'";

        ResultSet r = s.executeQuery(cektinggi);

        if (r.next()) {

            scoretinggi = Integer.parseInt(r.getString("score"));

            if (scorenya <= scoretinggi) {

                return;

            } else {

                String sqel = "UPDATE score Set score ='" + scorenya + "' where nama = '" + Nama.toString() + "'";

                s.executeUpdate(sqel);

            }


        }

    } catch (Exception e) {

        System.out.println(e);

    }

}

In this module, the score of the game is updated using void keypresses.

The Code Given Below Is For The Game Over Module

private void gameOver(Graphics g) {

    updatescore();

    if (scorenya <= highscore) {

        String msg = "Your Score: = " + scorenya;

        Font small = new Font("Helvetica", Font.BOLD, 14);

        FontMetrics metr = getFontMetrics(small);



        g.setColor(Color.white);

        g.setFont(small);

        g.drawString(msg, (Lebar - metr.stringWidth(msg)) / 2, Tinggi / 2);



    } else {

        String msgg = "Congratulation High Score = " + scorenya;

        Font small = new Font("Helvetica", Font.BOLD, 14);

        FontMetrics metr = getFontMetrics(small);



        g.setColor(Color.blue);

        g.setFont(small);

        g.drawString(msgg, (Lebar - metr.stringWidth(msgg)) / 2, Tinggi / 2);

    }


}

In this module, which is the module for game over function void move.

Screenshots:

In this screenshot, which is the start-game output of the game
This screenshot is the start-game output of the game.

In this screenshot, which is the Enter name text field of the game
This screenshot is the Enter name text field of the game.

In this screenshot, which is the game over output
This screenshot is the game over-output.

Downloadable Source Code Below

Anyway, if you want to level up your programming knowledge, especially Java, try this new article I’ve made for you Best Java Projects With Source Code For Beginners Free Download.

Summary

The Snake Game Java is built fully in Java and MySQL Database. It has a full-featured Graphical User Interface (GUI) with all the functionalities.

This article is a way to enhance and develop our skills and logic ideas, which is important in practicing the Java programming language, which is the most well-known and most usable programming language in many companies.

Inquiries

If you have any questions or suggestions about Snake Game In Java With Source Code, please feel free to leave a comment below.

Leave a Comment