Java snake game 🐍

preview_player
Показать описание
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.
Рекомендации по теме
Комментарии
Автор

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.setResizable(false);
this.pack();
this.setVisible(true);


}
}

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 =
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.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 {
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) {

y[i], UNIT_SIZE, UNIT_SIZE);
}
else {
Color(45, 180, 0));
Color(random.nextInt(255), random.nextInt(255), random.nextInt(255)));
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 =
appleY =
}
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') {
= 'L';
}
break;
case KeyEvent.VK_RIGHT:
if(direction != 'L') {
= 'R';
}
break;
case KeyEvent.VK_UP:
if(direction != 'D') {
= 'U';
}
break;
case KeyEvent.VK_DOWN:
if(direction != 'U') {
= 'D';
}
break;
}
}
}
}

BroCodez
Автор

A fun channel with good English? Am I dead? Is this heaven?

areggrigorian
Автор

Great video! I am working my way through my CS degree and am writing programs that I have to think about for 10x longer than it takes me to code them. Videos like yours remind me that programming is FUN!. It also helps me to understand how the concepts we are learning are used in everyday applications. Subscribed my man! Thanks again!

maxxpellowski
Автор

straight-forward, short, easy to understand;
I came across your channel through this video and I am happy to watch the whole Java playlist and I´m glad that you still making videos.

Well done sir!

janmail
Автор

This may be one of the most underrated coding tutorial/learning youtube channels with out a doubt

colekrause
Автор

such an underrated channel. We need more people like you <3

lorenzangeles
Автор

Your code is great, but i have a suggestion. At 9:12 You define and initialize the GAME_UNIT final constans, which later creates a huge and unnecessary X[] and y[] coordinate arrays. I would rather write this: _static final int GAME_UNITS = (SCREEN_WIDTH * SCREEN_HEIGHT) / _*_*(UNIT_SIZE*UNIT_SIZE); // 576_** In this case the x[] and y[] arrays will be at size 576 which equals 24x24, and in this case this is the exact size of the the game field. After that I would initialize the arrays like this: final int x[] = new int[GAME_UNITS / (SCREEN_WIDTH / UNIT_SIZE)]; which will give you an array with 24 elements. *This way You will save some memory.*

belalehner
Автор

This is the highest quality coding channel I have ever stumbled upon. I will be making full use of the content he is providing. Hopefully he has some more advanced content too.

TechSupportDave
Автор

3 years ago and still helping !! Thank you for giving up your time to help others learn for free!!

americaneagle
Автор

Awesome video! It's short, sweet, to the point; and best of all, it's fairly simple and straight forward. Thank you for sharing the knowledge!

mechasmoke
Автор

Great tutorial, I just started learning Java and had no idea it was so powerful. I did some C++ and it seemed I needed a 3rd party framework for everything, but Java has native libraries for just about everything it seems. All the different classes/interfaces and functions/methods are difficult to keep up with but this video is helping a beginner like me become more familiar.

kHzBANKkHZ
Автор

explanation 100, very easy to understand, code neatness 100. thank you

allamtajusarof
Автор

I'm preparing for uni mate, so these "learn through projects" videos are helping a lot. Keep it up and thank you!

alexandrulolea
Автор

Underated is the only word that describes you bro. Thanks

thezouchcoop
Автор

Thank you 🙏 Bro code. My instructor cited your video sometimes and I learned a lot from your video. It’s cool. Appreciate your work.❤

premkarki
Автор

Bro, I'm sure all the people who watch your videos are enjoying your style of teaching and also like your tips. I really enjoy watching all of your tutorials, you make things look fine and easy. Keep it up, Bro!

saleharja
Автор

Hey fantastic tutorial, thank you! One thing I noticed that is off a bit, the checkCollisions() is off by one UNIT_SIZE on the right and bottom, so you can actually go slightly off the screen on those sides. I just subtracted UNIT_SIZE to fix this.

if(x[0] > SCREEN_WIDTH-UNIT_SIZE) {
running = false;
}

&

if(y[0] > SCREEN_HEIGHT-UNIT_SIZE) {
running = false;
}

Can't wait to dig into more of your videos, thanks again!

keanjaycox
Автор

bro, your channel is truly underrated. u deserve more than at least 10, 000, 000 subs

MananGandhi
Автор

I have completed this project. It was amazing. Give us more project like this.

foysalkhan
Автор

You cannot imagine how you helped me, Bro. I liked this code so much I'm improving it to present it as a simple project for my school :)
My plans are:
Restart button
Pause menu
Top score

diegoaristizabalElDiego