Java Game Coding - Basic Snake Game (ECLIPSE) - playproduction.de

Java Game Coding – Basic Snake Game (ECLIPSE)

MobileiGames
Views: 162386
Like: 2081
Thanks pj6444 I learned coding this snake game in Java.
You can check out his channel ► or
Check this code in my pastebin here ►

I did some little modification on his code and tried my best to understand every important details.

I also try my best to code this as quick as possible but this the best I can. Probably after a year I can code it faster.
———————————————————————————————
Please support my personal and DiY Channel Here:
Main channel:

130 Comments

  1. hi hmm my snake moves too fast how can i fix this? i really appreciate your tutorial. :>

  2. //***************************************

    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;

    }

    }

    }

    }

  3. How can I increase and decrease the speed of snake please reply me

  4. I'm new to coding and whenever I put the bracket to end the code if you know what I mean it says there is a problem I don't know what to do.

  5. mentira que tu digitou com o teclado virtual, tu é um mito

  6. instead of public static final int WIDTH = 500, HEIGHT = 500; and setPreferredSize(new Dimension (WIDTH,HEIGHT));

    in the main class you could have just added : frame.setSize(500,500);

  7. Did you use the depth and breadth first search? Because I need some help please

  8. Thank you this is my first java game.

  9. bro I even managed to create the game but I don’t know the buttons that make it go to the red dot, how can you teach me ??

  10. For some reason I get this error: Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException pls help

  11. 25:11 for me this doesn’t work, pls help

    Or what keys I should press

  12. The start of my game development journey

  13. How do you export the program from the workspace to your desktop?

  14. help brr0
    Error: Main method not found in class Main, please define the main method as:

    public static void main(String[] args)

    or a JavaFX application class must extend javafx.application.Application

    I can't run the program

  15. Thank you really helpful because I was switching from python this was a great Kickstarter thanks dude (but could someone please help with my error at 7:46 it says "Unreachable code")

  16. Why my eclips not completing the code automatically..

  17. i have one doubt if i remove the stop function and if the snake touches edges in one side it will
    come from another side like that how to do?

  18. I dont have "Import Graphics (jawa.awt)" at 6:12

    please help me
    😭

  19. I have gotten to the last typed item is "snake.remove(0);" and you have clicked run. the display of the game comes up and the yellow snake moves. but on eclipse on my computer the snake does not show or move on the black screen. The time of the video is approximately 21:22 on the video. Can you direct me to what i have missed or what i need to add to make the snake appear and move? Thank you!

  20. i tried this, but my snake is moving only one direction.

  21. I completed the code, but for some reason the apples don't spawn

  22. It didn't work and I wasted my entire day I think it's because I'm on a Mac a and not a windows

  23. How about scoreboard ang play again?

  24. Can you just write what he writes?

  25. I can't control the snake the key pressed method isn't working can someone help ?

  26. This guy laptop F button 😑 😒 🤣 not working

  27. All is okay but after running my program snake can goes only right direction 😔 can you please help me.

  28. How i control the snake like up, down , left and right

  29. Can do change the red dot into picture?

Leave a Reply

Your email address will not be published.