Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 21 of 21

Thread: Help with Snake Game Java Code: It's Impossible to Lose the Game

  1. #1
    Junior Member
    Join Date
    Oct 2012
    Posts
    7
    Thanks
    1
    Thanked 0 Times in 0 Posts

    Default Help with Snake Game Java Code: It's Impossible to Lose the Game

    So the code I have I didn't make, but I want to mess around with it and make it better. I'm a beginner and just want to explore the language on my own, but I don't have any idea how to fix it. The game doesn't end when it hits the boundaries -- it keeps going on like a PacMan game. It also doesn't end when it collides with another section of itself. Can anyone tell me how to make this code work properly?

    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import java.util.*;
     
    class Snake extends JFrame implements KeyListener, Runnable {
     
        JPanel p1, p2;
        JButton[] lb = new JButton[200];
        JButton bonusfood;
        JTextArea t;
        int x = 500, y = 250, gu = 2, directionx = 1, directiony = 0, speed = 50, difference = 0, oldx, oldy, score = 0;
        int[] lbx = new int[300];
        int[] lby = new int[300];
        Point[] lbp = new Point[300];
        Point bfp = new Point();
        Thread myt;
        boolean food = false, runl = false, runr = true, runu = true, rund = true, bonusflag = true;
        Random r = new Random();
        JMenuBar mymbar;
        JMenu game, help, level;
     
        public void initializeValues() {
            gu = 3;
            lbx[0] = 100;
            lby[0] = 150;
            directionx = 10;
            directiony = 0;
            difference = 0;
            score = 0;
            food = false;
            runl = false;
            runr = true;
            runu = true;
            rund = true;
            bonusflag = true;
        }
     
        Snake() {
            super("Snake");
            setSize(500, 330);
            //Create Menue bar with functions
            creatbar();
            //initialize all variables
            initializeValues();
            // Start of UI design
            p1 = new JPanel();
            p2 = new JPanel();
            // t will view the score
            t = new JTextArea("Score ==>" + score);
            t.setEnabled(false);
            t.setBackground(Color.BLACK);
            // snake have to eat bonousfood to growup
            bonusfood = new JButton();
            bonusfood.setEnabled(false);
            // will make first snake
            createFirstSnake();
     
            p1.setLayout(null);
            p2.setLayout(new GridLayout(0, 1));
            p1.setBounds(0, 0, x, y);
            p1.setBackground(Color.blue);
            p2.setBounds(0, y, x, 30);
            p2.setBackground(Color.RED);
     
            p2.add(t); // will contain score board
            // end of UI design
            getContentPane().setLayout(null);
            getContentPane().add(p1);
            getContentPane().add(p2);
     
            show();
            setDefaultCloseOperation(EXIT_ON_CLOSE);
     
            addKeyListener(this);
            // start thread
            myt = new Thread(this);
            myt.start(); // go to run() method
        }
     
        public void createFirstSnake() {
            // Initially the snake has small length 3
            for (int i = 0; i < 3; i++) {
                lb[i] = new JButton("lb" + i);
                lb[i].setEnabled(false);
                p1.add(lb[i]);
                lb[i].setBounds(lbx[i], lby[i], 10, 10);
                lbx[i + 1] = lbx[i] - 10;
                lby[i + 1] = lby[i];
            }
        }
     
        public void creatbar() {
            mymbar = new JMenuBar();
     
            game = new JMenu("Game");
     
            JMenuItem newgame = new JMenuItem("New Game");
            JMenuItem exit = new JMenuItem("Exit");
     
            newgame.addActionListener(
                    new ActionListener() {
     
                        public void actionPerformed(ActionEvent e) {
                            reset();
                        }
                    });
     
            exit.addActionListener(new ActionListener() {
     
                public void actionPerformed(ActionEvent e) {
                    System.exit(0);
                }
            });
     
            game.add(newgame);
            game.addSeparator();
            game.add(exit);
     
            mymbar.add(game);
     
            level = new JMenu("Level");
     
            mymbar.add(level);
     
            help = new JMenu("Help");
     
            JMenuItem creator = new JMenuItem("Creator");
            JMenuItem instruction = new JMenuItem("Instraction");
     
            creator.addActionListener(new ActionListener() {
     
                public void actionPerformed(ActionEvent e) {
                    JOptionPane.showMessageDialog(p2, "Name :Abdullah al hasb\nRollno :2006331093\nSub :cse\ninstitute :sust");
                }
            });
     
            help.add(creator);
            help.add(instruction);
            mymbar.add(help);
     
            setJMenuBar(mymbar);
        }
     
        void reset() {
            initializeValues();
            p1.removeAll();
     
            myt.stop();
     
            createFirstSnake();
            t.setText("Score==>" + score);
     
            myt = new Thread(this);
            myt.start();
        }
     
        void growup() {
            lb[gu] = new JButton();
            lb[gu].setEnabled(false);
            p1.add(lb[gu]);
     
            int a = 10 + (10 * r.nextInt(48));
            int b = 10 + (10 * r.nextInt(23));
     
            lbx[gu] = a;
            lby[gu] = b;
            lb[gu].setBounds(a, b, 10, 10);
     
            gu++;
        }
        // this method contains the logic to move the snake. player will define the derection
        // this method just forward the snake to the right derection which deriction is pressed
        // by the player.
        void moveForward() {
            for (int i = 0; i < gu; i++) {
                lbp[i] = lb[i].getLocation();
            }
     
            lbx[0] += directionx;
            lby[0] += directiony;
            lb[0].setBounds(lbx[0], lby[0], 10, 10);
     
            for (int i = 1; i < gu; i++) {
                lb[i].setLocation(lbp[i - 1]);
            }
     
            if (lbx[0] == x) {
                lbx[0] = 10;
            } else if (lbx[0] == 0) {
                lbx[0] = x - 10;
            } else if (lby[0] == y) {
                lby[0] = 10;
            } else if (lby[0] == 0) {
                lby[0] = y - 10;
            }
     
            if (lbx[0] == lbx[gu - 1] && lby[0] == lby[gu - 1]) {
                food = false;
                score += 5;
                t.setText("Score==>" + score);
                if (score % 50 == 0 && bonusflag == true) {
                    p1.add(bonusfood);
                    bonusfood.setBounds((10 * r.nextInt(50)), (10 * r.nextInt(25)), 15, 15);
                    bfp = bonusfood.getLocation();
                    bonusflag = false;
                }
            }
     
            if (bonusflag == false) {
                if (bfp.x <= lbx[0] && bfp.y <= lby[0] && bfp.x + 10 >= lbx[0] && bfp.y + 10 >= lby[0]) {
                    p1.remove(bonusfood);
                    score += 100;
                    t.setText("Score ==>" + score);
                    bonusflag = true;
                }
            }
     
            if (food == false) {
                growup();
                food = true;
            } else {
                lb[gu - 1].setBounds(lbx[gu - 1], lby[gu - 1], 10, 10);
            }
     
            for (int i = 1; i < gu; i++) {
                if (lbp[0] == lbp[i]) {
                    t.setText("GAME OVER " + score);
                    try {
                        myt.join();
                    } catch (InterruptedException ie) {
                    }
                    break;
                }
            }
     
            p1.repaint();
            show();
        }
     
        public void keyPressed(KeyEvent e) {
            // snake move to left when player pressed left arrow
            if (runl == true && e.getKeyCode() == 37) {
                directionx = -10; // means snake move right to left by 10pixels
                directiony = 0;
                runr = false;     // run right(runr) means snake cant move from left to right
                runu = true;      // run up   (runu) means snake can move from down to up
                rund = true;      // run down (run down) means snake can move from up to down
            }
            // snake move to up when player pressed up arrow
            if (runu == true && e.getKeyCode() == 38) {
                directionx = 0;
                directiony = -10; // means snake move from down to up by 10 pixel
                rund = false;     // run down (run down) means snake can move from up to down
                runr = true;      // run right(runr) means snake can move from left to right
                runl = true;      // run left (runl) means snake can move from right to left
            }
            // snake move to right when player pressed right arrow
            if (runr == true && e.getKeyCode() == 39) {
                directionx = +10; // means snake move from left to right by 10 pixel
                directiony = 0;
                runl = false;
                runu = true;
                rund = true;
            }
            // snake move to down when player pressed down arrow
            if (rund == true && e.getKeyCode() == 40) {
                directionx = 0;
                directiony = +10; // means snake move from left to right by 10 pixel
                runu = false;
                runr = true;
                runl = true;
            }
        }
     
        public void keyReleased(KeyEvent e) {
        }
     
        public void keyTyped(KeyEvent e) {
        }
     
        public void run() {
            for (;;) {
                // Move the snake move forword. In the start of the game snake move left to right,
                // if player press up, down, right or left arrow snake change its direction according to
                // pressed arrow
                moveForward();
                try {
                    Thread.sleep(speed);
                } catch (InterruptedException ie) {
                }
            }
        }
    }

    Driver:
    public class SnakeDriver {
     
     
        public static void main(String[] args) {
     
            new Snake();
        }
     
    }


  2. #2
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,140
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: Help with Snake Game Java Code: It's Impossible to Lose the Game

    Try debugging your code by adding println() statements to show execution progress and how variable values are changing. For example:
    Add a: System.out.println("var=" + var);
    after every line where a variable is changed by an assignment statement or read into.

    The print out will show you what the computer sees when it executes the code and should help you fix it.
    If you don't understand my answer, don't ignore it, ask a question.

  3. The Following User Says Thank You to Norm For This Useful Post:

    haruspex_icis (December 13th, 2012)

  4. #3
    Junior Member
    Join Date
    Oct 2012
    Posts
    7
    Thanks
    1
    Thanked 0 Times in 0 Posts

    Default Re: Help with Snake Game Java Code: It's Impossible to Lose the Game

    Could you give an example of where that might be useful? Also, I don't know if the code for the terminations boundaries has been written.

  5. #4
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,140
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: Help with Snake Game Java Code: It's Impossible to Lose the Game

    where that might be useful
    This would be one place to print out the variables:
    The game doesn't end when it hits the boundaries
    What variables are hitting the boundaries? Where and how should the boundary be detected?
    If you don't understand my answer, don't ignore it, ask a question.

  6. #5
    Junior Member
    Join Date
    Oct 2012
    Posts
    7
    Thanks
    1
    Thanked 0 Times in 0 Posts

    Default Re: Help with Snake Game Java Code: It's Impossible to Lose the Game

    should I implement something like ActionListener and make a rectangle around the game board to be hit?

  7. #6
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,140
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: Help with Snake Game Java Code: It's Impossible to Lose the Game

    What problems are you trying to solve with the action listener
    and with the rectangle?
    If you don't understand my answer, don't ignore it, ask a question.

  8. #7
    Junior Member
    Join Date
    Oct 2012
    Posts
    7
    Thanks
    1
    Thanked 0 Times in 0 Posts

    Default Re: Help with Snake Game Java Code: It's Impossible to Lose the Game

    well what I was thinking was maybe set a rectangle with boundaries that, when hit, call the Action Listener to stop the game.

  9. #8
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,140
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: Help with Snake Game Java Code: It's Impossible to Lose the Game

    That's not now actionlisteners work. They are for handling user actions like when a button is pressed.
    If you don't understand my answer, don't ignore it, ask a question.

  10. #9
    Junior Member
    Join Date
    Oct 2012
    Posts
    7
    Thanks
    1
    Thanked 0 Times in 0 Posts

    Default Re: Help with Snake Game Java Code: It's Impossible to Lose the Game

    so how what would I use in that case?

  11. #10
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,140
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: Help with Snake Game Java Code: It's Impossible to Lose the Game

    how what would I use in that case?
    Please explain.
    If you don't understand my answer, don't ignore it, ask a question.

  12. #11
    Junior Member
    Join Date
    Oct 2012
    Posts
    7
    Thanks
    1
    Thanked 0 Times in 0 Posts

    Default Re: Help with Snake Game Java Code: It's Impossible to Lose the Game

    sorry, exclude that "how"

  13. #12
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,140
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: Help with Snake Game Java Code: It's Impossible to Lose the Game

    Same response. Please explain what you are trying to do.
    If you don't understand my answer, don't ignore it, ask a question.

  14. #13
    Junior Member
    Join Date
    Oct 2012
    Posts
    7
    Thanks
    1
    Thanked 0 Times in 0 Posts

    Default Re: Help with Snake Game Java Code: It's Impossible to Lose the Game

    what I want to do is create a boundary the size of the display window that when hit, ends the current game. I also need to find a way to the game to terminate when the snake body comes into contact with itself.

  15. #14
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,140
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: Help with Snake Game Java Code: It's Impossible to Lose the Game

    Can you use the boundary of the window where the snake is moving? For example locations 0 and width or height?
    If you don't understand my answer, don't ignore it, ask a question.

  16. #15
    Member
    Join Date
    Jul 2012
    Posts
    71
    Thanks
    1
    Thanked 7 Times in 7 Posts

    Default Re: Help with Snake Game Java Code: It's Impossible to Lose the Game

    first i would recommend adding the method setResizable() right after the setSize() method in the constructor and make its parameter false so the user cant maximize the window becuase you've defined an explicit size for the game environment anyway... for your problem however u should make another method called endSnake() or some appropriate name that handles the case whenever the starting point of the snake touches a space that itself is already occupying and terminate because right now ur code just lets the snake overlap itself and continue playing

  17. #16
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,140
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: Help with Snake Game Java Code: It's Impossible to Lose the Game

    The game could adjust it self to the size of the window. It shouldn't have hardcoded values for the location of the boundaries.
    If you don't understand my answer, don't ignore it, ask a question.

  18. #17
    Member
    Join Date
    Jul 2012
    Posts
    71
    Thanks
    1
    Thanked 7 Times in 7 Posts

    Default Re: Help with Snake Game Java Code: It's Impossible to Lose the Game

    how would the game do that? he has hardcoded values i'm guessing because i ran the program and the game size didn't maximize with the window

  19. #18
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,140
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: Help with Snake Game Java Code: It's Impossible to Lose the Game

    Change the values of x and y as the window is resized,
    If you don't understand my answer, don't ignore it, ask a question.

  20. #19
    Member
    Join Date
    Jul 2012
    Posts
    71
    Thanks
    1
    Thanked 7 Times in 7 Posts

    Default Re: Help with Snake Game Java Code: It's Impossible to Lose the Game

    so instead of hardcoding the x and y just declare them and pass them as the parameters for setBounds()? how will they know to resize with the window?

  21. #20
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,140
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: Help with Snake Game Java Code: It's Impossible to Lose the Game

    how will they know to resize with the window?
    Use a listener.
    If you don't understand my answer, don't ignore it, ask a question.

  22. #21
    Member
    Join Date
    Jul 2012
    Posts
    71
    Thanks
    1
    Thanked 7 Times in 7 Posts

    Default Re: Help with Snake Game Java Code: It's Impossible to Lose the Game

    Hey I gotta solution if u needed it. Go to your moveForward() method and look at the for loop where "GAME OVER" is located... Change the lbp[0] == lbp[i] to lpb[0].equals(lbp[i]) and your game should work because lbp refers to objects and when comparing objects you should use the equals() method and only use == when comparing primitive data types like short, int & double... Hope it works!!!

Similar Threads

  1. [SOLVED] more help with snake game
    By godlynom in forum What's Wrong With My Code?
    Replies: 21
    Last Post: October 4th, 2012, 03:32 PM
  2. [SOLVED] Help with the Snake in a Snake Game
    By godlynom in forum What's Wrong With My Code?
    Replies: 20
    Last Post: September 27th, 2012, 06:41 PM
  3. Snake Game
    By Cuju in forum What's Wrong With My Code?
    Replies: 6
    Last Post: February 19th, 2011, 08:31 PM
  4. Snake Game In Java
    By Shyamz1 in forum What's Wrong With My Code?
    Replies: 2
    Last Post: February 10th, 2011, 10:00 AM
  5. Snake game in java
    By freaky in forum Object Oriented Programming
    Replies: 0
    Last Post: April 19th, 2010, 11:04 AM

Tags for this Thread