Develop Snake Game in Java | Swing & AWT
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!!
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.
Citizen Card System using java
bro u are awesome please bring more java games tutorials and projects
woah woah woah that was quite different from usual projects , and a bit tough too.
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 βοΈ
ye har cheez k baad hasna zruri hai kya?
ek baar dot and box game with 4 compititors bana do na plz
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);
}
}
ππππ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 ππππ
Have you made use of linked list by any chance?
Bro trust me I really enjoyed watching the video.. I really like the way you explained the project β€β€ and the way you smile ππ
Bro how do we add sound effects while snake eats apple and the sound of game over?
Bilkul perfection hai, theek hai ? , and that laugh is more soothing than tony kakkar's song ππ
where is the timer ..?
Code run karne ke baad Game Over aa raha hae. Game khel nehi pa raha hu. Kiya karu?
Restart ka option Bhi hona chahiye?
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.
MY program is not Running
No EROR created
sir board ()
{
SetPreferredsize(new Dimension());
}
Sir buttons(Key) is not working… kindly help
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.
Thanku so much
kudos to this person who explained each and every line
Bhaya.. Aur new new game banao please
Hey too good, Works perfectly fine and main i can understand each and every logic. Thanks buddy.
You got a new Subscriber π π
thanks buddy !!! keep going !!
After watching this video till 8 mins quickly I subscribed the channel…. very easily explained… thanks π
Hey pls tell ki ye code sublime me chl jayega kya or agr nhi to kya changes krne honge???? Plsss pls bta denaπ₯Ί
Thankyou so much for this video,,i tried this and it came out perfect ,,nice teaching and I enjoyed learning alott
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;
}
}
}
}
Very Amazing… Project bna ke mazaa aya
Aur Games banao bhaiπ―π
how do i make a restart button for this???? please tell me
There is No English translation huh?
Sir multi snake add karke batao sir please
do u know why i clean and build this proyect and when double click the .jar file of the proyect nothing happens?
bro ye channel pahle mil gya hota aaj me job hold kr pata
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 πππππππππππππππππππππππππππππππππππππππππππππππ
Bhai aap regular kam kro ye sach me bhot acha smjha rhe ho aap
Intellij idea m krna h yee
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?
Can I mention this game in project section in my resume?
bhaiii helpppp!!!!!!!!
cannot resolve mwthod setprefrredSize in board
wt to do noww
can you please make a Tic Tac toe AI with Minimax Algo
bhai aap haste bhut sahi ho
Op channel
You are doing great job.love you
Please show scores and highest score in game.
bhai beech beech me hassi gajab hi hai yrr teri .
Can I get the source code please
Think h sir