
Java snake game 🐍
Bro Code
Views: 1145110
Like: 28995
Java snake game tutorial for beginners
#Java #snake #game
Coding boot camps hate him! See how he can teach you to code with this one simple trick…
Bro Code is the self-proclaimed #1 tutorial series on coding in various programming languages and other how-to videos in the known universe.
16.03.2023
dope thanks
For anyone wondering how to add a restart button, add this to your KeyPressed method:
case KeyEvent.VK_SPACE:
new gameFrame();
break;
Change the key to something else if you’d like
Sit back
Relax
Enjoy 😉
Hell yeah! u are the best
Thank you! You really help me so that I can learn programming. Keep go on like this.
Thanks so much for making this video! I find it so fun to learn Java this way 🙂
will this code run on macos?
I found the best Coding teacher, I'm sure that I will master java soon
Why is the source code shown in description not same as the code in the video?
How to fix this issue"main method not found in class GamePannel"?
Cant execute
Hey Bro Code, I'm having problem on run, When you did your first run 15:17 , when i tried, it just loaded and nothing opened like screen, Please help me
What a great videos, even me who dont know more about java understand what he says and how to using it 🤯
This is what i need
NEED HELP!!
The KeyEvent.VK_RIGHT,LEFT,DOWN,UP
Is not working in my visual studio,it doest not show error but the snake doesn't move when pressed keys…please help
Bro this is awesome! Thank you!
heyyyyyyyyyy, even I'm Brazilian and I don't speak English very well I understanded many things, "você é foda!"
GOOD
Thanks for your tutorials) Nice work!!!
P.S.
static final int GAME_UNITS = (SCREEN_WIDTH/UNIT_SIZE)*(SCREEN_HEIGHT/UNIT_SIZE);
How do I make it so that the new apple never appears on the same spot as one of the body parts of the snake?
idk why when ever I try to draw something like a line or rect it wont show anything
tite
Random
I'm trying to follow along step-by-step, but I got to the fillOval portion (about 20:45), and Eclipse won't recognize it like it does in the video, and when I manually set fillOval, running the program only gives a black window.
What could I be missing?
I am not able to get the Grid and the Apple in my console what could be the reason for it?
gracias bro, me salvaste de un parcial 😀
Why are you so cool
nice
source code bro
I don't really get the x and y arrays. I know bro's saying that when they are both 0 they are the snake's head, but I don't really know how the program calculates it. If I were to code this alone, I wouldn't know why should I divide the area of the screen by the unit_size and how will that give us the coordinates of the snake's head. I get that it's an array that holds the possible coordinates but the idea is fuzzy in my mind. I can't quite grasp it. May anyone help me understand, please?
AND thank you!!!
Great Video, you helped me a lot. But how can i add an Icon for the red ball
Please make spring boot crash course,
Thanks
Bad ass, thanks man. This was helpful and fun to do
>
i saw that apples get generated inside the sanke bodypart how can i remove this?
Good to know java still exists
Really cool!
How to make a project report on this project
i don't use timer in java??
because this's can't add DELAY plsss??
For anyone who wants to pause the game…
boolean paused = false;
if(paused){ //put this in the paint component
timer.stop();
g.setColor(new Color(0, 0, 0, 128));
g.fillRect(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT);
g.setColor(Color.WHITE);
g.setFont(new Font("Ink Free", Font.BOLD, 30));
FontMetrics metrics = getFontMetrics(g.getFont());
g.drawString("Paused", (SCREEN_WIDTH – metrics.stringWidth("Paused"))/2, SCREEN_HEIGHT/2);
} else {
paused = false;
}
case KeyEvent.VK_SPACE -> { //Adds pause button with space bar
if (timer.isRunning()) {
paused = !paused
} else {
timer.start();
}
for anyone having trouble with the Timer not taking parameters check that you imported javax.swing.Timer and not java.util.Timer
How does the game can restart when it shows the gameover screen?
I just tried it calling startGame(); but it didn't work.
can anybody explain how this code works (SCREEN_WIDTH/UNIT_SIZE) * UNIT_SIZE)
Is there something i could be missing, the first time you ran the game I ran it too, kind of am coding and following along with you. Although is there something that I am. missing, that I was supposed to download before hand?
Thank you very much
Bro. i am don't 'R','L','U','D' not working
How many line of codes were used for this?
Digital from digitally sign ☢️ in and get forgotten power of Play blunk swim exposure and face facial belongs frame vitals p mussels waves and maybe physical episode of supernatural fanfiction another world miss potential nose non satisfied moods system dynamics and statistic bug schemo
Something notes something hang past passion style and myth maybe else waves circuit court non satisfied or nonconfedent access to accurate anatomy of brain 🧠 shadow magnetic 🧭 time and forgotten in instructor graphics.verifictry
This the most giga channel on YouTube thanks bro
I didn't really expect this video to blow up. This was meant to be more of a practice project.
I probably would have spent more time optimizing the code if I knew it would get this many views lol
Well what you see is what you get I guess…
//*****************************************
public class SnakeGame {
public static void main(String[] args) {
new GameFrame();
}
}
//*****************************************
import javax.swing.JFrame;
public class GameFrame extends JFrame{
GameFrame(){
this.add(new GamePanel());
this.setTitle("Snake");
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setResizable(false);
this.pack();
this.setVisible(true);
this.setLocationRelativeTo(null);
}
}
//*****************************************
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.Random;
public class GamePanel extends JPanel implements ActionListener{
static final int SCREEN_WIDTH = 1300;
static final int SCREEN_HEIGHT = 750;
static final int UNIT_SIZE = 50;
static final int GAME_UNITS = (SCREEN_WIDTH*SCREEN_HEIGHT)/(UNIT_SIZE*UNIT_SIZE);
static final int DELAY = 175;
final int x[] = new int[GAME_UNITS];
final int y[] = new int[GAME_UNITS];
int bodyParts = 6;
int applesEaten;
int appleX;
int appleY;
char direction = 'R';
boolean running = false;
Timer timer;
Random random;
GamePanel(){
random = new Random();
this.setPreferredSize(new Dimension(SCREEN_WIDTH,SCREEN_HEIGHT));
this.setBackground(Color.black);
this.setFocusable(true);
this.addKeyListener(new MyKeyAdapter());
startGame();
}
public void startGame() {
newApple();
running = true;
timer = new Timer(DELAY,this);
timer.start();
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
draw(g);
}
public void draw(Graphics g) {
if(running) {
/*
for(int i=0;i<SCREEN_HEIGHT/UNIT_SIZE;i++) {
g.drawLine(i*UNIT_SIZE, 0, i*UNIT_SIZE, SCREEN_HEIGHT);
g.drawLine(0, i*UNIT_SIZE, SCREEN_WIDTH, i*UNIT_SIZE);
}
*/
g.setColor(Color.red);
g.fillOval(appleX, appleY, UNIT_SIZE, UNIT_SIZE);
for(int i = 0; i< bodyParts;i++) {
if(i == 0) {
g.setColor(Color.green);
g.fillRect(x[i], y[i], UNIT_SIZE, UNIT_SIZE);
}
else {
g.setColor(new Color(45,180,0));
//g.setColor(new Color(random.nextInt(255),random.nextInt(255),random.nextInt(255)));
g.fillRect(x[i], y[i], UNIT_SIZE, UNIT_SIZE);
}
}
g.setColor(Color.red);
g.setFont( new Font("Ink Free",Font.BOLD, 40));
FontMetrics metrics = getFontMetrics(g.getFont());
g.drawString("Score: "+applesEaten, (SCREEN_WIDTH – metrics.stringWidth("Score: "+applesEaten))/2, g.getFont().getSize());
}
else {
gameOver(g);
}
}
public void newApple(){
appleX = random.nextInt((int)(SCREEN_WIDTH/UNIT_SIZE))*UNIT_SIZE;
appleY = random.nextInt((int)(SCREEN_HEIGHT/UNIT_SIZE))*UNIT_SIZE;
}
public void move(){
for(int i = bodyParts;i>0;i–) {
x[i] = x[i-1];
y[i] = y[i-1];
}
switch(direction) {
case 'U':
y[0] = y[0] – UNIT_SIZE;
break;
case 'D':
y[0] = y[0] + UNIT_SIZE;
break;
case 'L':
x[0] = x[0] – UNIT_SIZE;
break;
case 'R':
x[0] = x[0] + UNIT_SIZE;
break;
}
}
public void checkApple() {
if((x[0] == appleX) && (y[0] == appleY)) {
bodyParts++;
applesEaten++;
newApple();
}
}
public void checkCollisions() {
//checks if head collides with body
for(int i = bodyParts;i>0;i–) {
if((x[0] == x[i])&& (y[0] == y[i])) {
running = false;
}
}
//check if head touches left border
if(x[0] < 0) {
running = false;
}
//check if head touches right border
if(x[0] > SCREEN_WIDTH) {
running = false;
}
//check if head touches top border
if(y[0] < 0) {
running = false;
}
//check if head touches bottom border
if(y[0] > SCREEN_HEIGHT) {
running = false;
}
if(!running) {
timer.stop();
}
}
public void gameOver(Graphics g) {
//Score
g.setColor(Color.red);
g.setFont( new Font("Ink Free",Font.BOLD, 40));
FontMetrics metrics1 = getFontMetrics(g.getFont());
g.drawString("Score: "+applesEaten, (SCREEN_WIDTH – metrics1.stringWidth("Score: "+applesEaten))/2, g.getFont().getSize());
//Game Over text
g.setColor(Color.red);
g.setFont( new Font("Ink Free",Font.BOLD, 75));
FontMetrics metrics2 = getFontMetrics(g.getFont());
g.drawString("Game Over", (SCREEN_WIDTH – metrics2.stringWidth("Game Over"))/2, SCREEN_HEIGHT/2);
}
@Override
public void actionPerformed(ActionEvent e) {
if(running) {
move();
checkApple();
checkCollisions();
}
repaint();
}
public class MyKeyAdapter extends KeyAdapter{
@Override
public void keyPressed(KeyEvent e) {
switch(e.getKeyCode()) {
case KeyEvent.VK_LEFT:
if(direction != 'R') {
direction = 'L';
}
break;
case KeyEvent.VK_RIGHT:
if(direction != 'L') {
direction = 'R';
}
break;
case KeyEvent.VK_UP:
if(direction != 'D') {
direction = 'U';
}
break;
case KeyEvent.VK_DOWN:
if(direction != 'U') {
direction = 'D';
}
break;
}
}
}
}
//*****************************************