Develop Snake Game in Java | Swing & AWT - playproduction.de

Develop Snake Game in Java | Swing & AWT

Code for Interview
Views: 21945
Like: 544
Snake is a classic video game in which a player controls a Snake that must eat apples and avoid walls. Each time, you eat an apple, the Snake grows. The Snakeโ€™s goal is to eat the maximum of apples. Snake is also an ideal game to create when you want to learn to create 2D games in Java.

In this tutorial, weโ€™re going to learn how to create a Snake in Java 2D with Java Swing. You can follow this video to create the Snap Game step by step.

Language Used – Java Core
Concept Used – Swing, AWT & Basic Java Concepts

———————————————————————————-
Clone the source code of the project from the GitHub repository, link below

Google Drive link for all the icons

———————————————————————————-

How to Clone a Github Repository –

Have suggestions, have Errors, Exceptions or anything. Please Comment

JavaScript Projects Playlist –
Java Projects Playlist –
React Projects Playlist –
MERN Stack Projects –
Java Interview Questions –

Notepad in Java –
Travel and Toursim Management System –
Electricity Billing System –
Employyee Management System –
Payroll System –
University Management System –
Airline Management System –
Hotel Management System –

LIKE, SHARE and SUBSCRIBE

Follow us:
Instagram (codeforinterview) –
Telegram (Code for Interview) –
Email – [email protected]

0:00 Welcome to this video
0:30 Introduction of the Video
2:01 Creating a new project
2:35 Creating two classes
2:59 Adding images in the project
3:47 Started Creating the Frame
15:53 Adding images to the Frame
20:08 Placing the images behind each other
29:57 Follow us on Instagram & Telegram
30:36 Location the Apples on the Frame
42:17 Implementing ActionListener Interface
45:24 Implementing Keyboard Events
56:10 Handling collision of Snake with Apple
1:02:27 Handling collision of Snake with self of with Walls
1:11:17 Moving the snake on the frame
1:18:38 Repaint the frame to discover the changes
1:20:12 Adding images and snake on the frame
1:24:00 Handling gameover functionality
1:29:05 Running the project
1:31:18 END!!

76 Comments

  1. Hello sir,
    I have a query that should i use my own code or i use gui to make java project ? because with gui i can make project faster you know buttons and labels etc they are already made and i just want place them in frame so this is my query give me suggestion about this
    Thank u for take my comment.

  2. bro u are awesome please bring more java games tutorials and projects

  3. woah woah woah that was quite different from usual projects , and a bit tough too.

  4. Kele wla OP๐Ÿ˜‚๐Ÿ˜‚
    By the way loved your whole video…you have explained everything with so much detail and you've got a new subscriber โœŒ๏ธ

  5. ek baar dot and box game with 4 compititors bana do na plz

  6. Hi. Cn you tell me that in nested for loops, why do we need to initialize a variable in the outer loop which we need in the inner loop.
    for example— Find all the 2 digit prime numbers using nested for loops.
    Scanner input= new Scanner(System.in);
    int count;
    for (int i =10;i<=99;i++) {
    int num = input.nextInt();
    count = 0; //Can you tell me that why do we need to initialize the count variable here?. Whenever I am initializing outside the outer loop it is not giving me the correct answer.

    for (int j = 1;j<=num;j++) {
    if (i%j == 0) {
    count++;
    }
    }
    if (count == 2) {
    System.out.println(i);
    }
    }

  7. ๐Ÿ˜Š๐Ÿ˜Š๐Ÿ˜Š๐Ÿ˜Šthnk uu so much for this vodeo!!! its really helped me a lot!!! n besides all that….. that smile while u written a function name wrong by mistake… that was very cute ๐Ÿ˜Š๐Ÿ˜Š๐Ÿ˜Š๐Ÿ˜Š

  8. Have you made use of linked list by any chance?

  9. Bro trust me I really enjoyed watching the video.. I really like the way you explained the project โคโค and the way you smile ๐Ÿ’œ๐Ÿ’œ

  10. Bro how do we add sound effects while snake eats apple and the sound of game over?

  11. Bilkul perfection hai, theek hai ? , and that laugh is more soothing than tony kakkar's song ๐Ÿ˜‚๐Ÿ˜‚

  12. Code run karne ke baad Game Over aa raha hae. Game khel nehi pa raha hu. Kiya karu?

  13. Hi Bro, I saw this video. I need your help. Actually main ye project bana raha hu. To jab images yani 3 dot images ko call kar raha hu to wo render nhi ho rahi h. Maine apko Instagram par bhi message kiya h bro. Agar aap free ho to main mere system ka access apko de dunga SKYPE par ya kisi par bhi to main screen share kr lunga apke sath to aap check kr lijiyega ke error kaha h. I know aap busy honge. But jaise hi aap free ho mera ye images wala bug aap check kr lijiyega. Maine theek waise hi code mention kiya h jaisa aapne btaya h video me. Phir bhi NetBeans error through kr rha h.

  14. MY program is not Running
    No EROR created

  15. sir board ()
    {
    SetPreferredsize(new Dimension());
    }

  16. Sir buttons(Key) is not working… kindly help

  17. BRO IF WE CAN HEAR U FOR 1HR.30MINS. THEN WE CAN HEAR U FOR MORE 30 MINS, SO NEED TO RUSH AT THE END. JST PROPERLY EXPLAIN ALL THE METHODS AND VARIABLES USED THOROUGHLY(WHY AND HOW) BY U AT THE END. BEFORE RUSHING INTO COMPLETE THE VIDEO ANYHOW, U WERE GREAT IN EXPLAINING THINGS BUT THEN WE LOST U. DO KEEP THIS IN MIND. OTHERWISE, U WERE GREAT. GOD BLESS YOU.

  18. kudos to this person who explained each and every line

  19. Hey too good, Works perfectly fine and main i can understand each and every logic. Thanks buddy.

    You got a new Subscriber ๐Ÿ™‚ ๐Ÿ™‚

  20. After watching this video till 8 mins quickly I subscribed the channel…. very easily explained… thanks ๐Ÿ‘

  21. Hey pls tell ki ye code sublime me chl jayega kya or agr nhi to kya changes krne honge???? Plsss pls bta dena๐Ÿฅบ

  22. Thankyou so much for this video,,i tried this and it came out perfect ,,nice teaching and I enjoyed learning alott

  23. I HAVE AN ERROR THAT "Board is not abstract and does not override abstract method actionperformed" HELP PLZ!!!!!!!!

    package snake;

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

    public class Board extends JPanel implements ActionListener {
    private Image apple;
    private Image dot;
    private Image head;
    private final int DOT_SIZE = 10;
    private final int RANDOM_POSITION = 29;
    private int apple_x;
    private int apple_y;
    private final int ALL_DOTS = 900;
    private final int x[] = new int[ALL_DOTS];
    private final int y[] = new int[ALL_DOTS];
    private boolean leftDirection = false;
    private boolean rightDirection = true;
    private boolean uptDirection = false;
    private boolean downDirection = false;
    private boolean inGame = true;
    private int dots;
    private Timer timer;

    Board(){
    addKeyListener(new TAdapter());
    setBackground(Color.BLACK);
    setPreferredSize(new Dimension(300,300));
    setFocusable(true);
    loadImages();
    initGame();

    }
    public void loadImages (){
    ImageIcon i1 = new ImageIcon(ClassLoader.getSystemResource("D:\Javaprojeleri\Snake\src\snake\apple.png"));
    apple = i1.getImage();
    ImageIcon i2 = new ImageIcon(ClassLoader.getSystemResource("D:\Javaprojeleri\Snake\src\snake\dot.png"));
    dot = i2.getImage();
    ImageIcon i3 = new ImageIcon(ClassLoader.getSystemResource("D:\Javaprojeleri\Snake\src\snake\head.png"));
    head = i3.getImage();

    }
    public void initGame(){
    dots = 3;
    for(int z=0 ;z<dots;z++){
    x[z]= 50 – z * DOT_SIZE;
    y[z] = 50;
    }
    locateApple();
    timer = new Timer(140,this);
    timer.start();
    }
    public void locateApple(){
    int r = (int) (Math.random() * RANDOM_POSITION);
    apple_x = (r * DOT_SIZE);
    r = (int) (Math.random() * RANDOM_POSITION);
    apple_y = (r * DOT_SIZE);
    }
    public void checkApple(){
    if((x[0] == apple_x) && (y[0] == apple_y)){
    dots++;
    locateApple();
    }

    }
    public void paintcomponent(Graphics g){
    super.paintComponent(g);

    draw(g);

    }
    public void draw (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(dot, x[z],y[z], this);
    }

    }
    Toolkit.getDefaultToolkit().sync();

    }else{
    gameOver(g);
    }

    }

    public void gameOver(Graphics g){
    String msg = "Game Over";
    Font font = new Font("SAN_SERIF",Font.BOLD, 14);
    FontMetrics metrices = getFontMetrics(font);
    g.setColor(Color.WHITE);
    g.setFont(font);
    g.drawString(msg, (300 – metrices.stringWidth(msg))/2, 300/2);
    }

    public 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] >= 300 ){
    inGame = false;
    }

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

    }

    public 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 (uptDirection) {
    y[0] -= DOT_SIZE;
    }
    if (downDirection) {
    y[0] += DOT_SIZE;
    }
    }
    public void actionperformed(ActionEvent ae){
    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;
    uptDirection = false;
    downDirection=false;
    }
    if(key == KeyEvent.VK_RIGHT && (!leftDirection)){
    rightDirection = true;
    uptDirection = false;
    downDirection=false;
    }
    if(key == KeyEvent.VK_UP && (!downDirection)){
    uptDirection = true;
    leftDirection = false;
    rightDirection=false;
    }
    if(key == KeyEvent.VK_DOWN && (!uptDirection)){
    downDirection = true;
    leftDirection = false;
    rightDirection=false;
    }
    }
    }
    }

  24. Very Amazing… Project bna ke mazaa aya
    Aur Games banao bhai๐Ÿ’ฏ๐Ÿ‘

  25. how do i make a restart button for this???? please tell me

  26. Sir multi snake add karke batao sir please

  27. do u know why i clean and build this proyect and when double click the .jar file of the proyect nothing happens?

  28. bro ye channel pahle mil gya hota aaj me job hold kr pata

  29. Sir muze he aapka project karna hai but mere netbeans me new project creat karte time kuch option aa rahe hai
    1) java with Maven
    2) java with gradle
    3) java with ant

    Is mese kya choose karu sir please reply sir please ๐Ÿ™๐Ÿ™๐Ÿ™๐Ÿ™๐Ÿ™๐Ÿ™๐Ÿ™๐Ÿ™๐Ÿ™๐Ÿ™๐Ÿ™๐Ÿ™๐Ÿ™๐Ÿ™๐Ÿ™๐Ÿ™๐Ÿ™๐Ÿ™๐Ÿ™๐Ÿ™๐Ÿ™๐Ÿ™๐Ÿ™๐Ÿ™๐Ÿ™๐Ÿ™๐Ÿ™๐Ÿ™๐Ÿ™๐Ÿ™๐Ÿ™๐Ÿ™๐Ÿ™๐Ÿ™๐Ÿ™๐Ÿ™๐Ÿ™๐Ÿ™๐Ÿ™๐Ÿ™๐Ÿ™๐Ÿ™๐Ÿ™๐Ÿ™๐Ÿ™๐Ÿ™๐Ÿ™

  30. Bhai aap regular kam kro ye sach me bhot acha smjha rhe ho aap

  31. I'm getting this error
    Failed to execute goal org.codehaus.mojo:exec-maven-plugin:1.5.0:exec (default-cli) on project SnakeGame: Command execution failed.: Process exited with an error: 1 (Exit value: 1) -> [Help 1]
    Can somebody help me out here?

  32. Can I mention this game in project section in my resume?

  33. bhaiii helpppp!!!!!!!!
    cannot resolve mwthod setprefrredSize in board
    wt to do noww

  34. can you please make a Tic Tac toe AI with Minimax Algo

  35. Please show scores and highest score in game.

  36. bhai beech beech me hassi gajab hi hai yrr teri .

Leave a Reply

Your email address will not be published.