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 16 of 16

Thread: Back again with problems in my Snake Game

  1. #1
    Member
    Join Date
    Sep 2013
    Posts
    36
    Thanks
    13
    Thanked 0 Times in 0 Posts

    Default Back again with problems in my Snake Game

    I'm having trouble getting the program to randomly display the food. Right now I'm just trying to get a rectangle box to randomly display in some x,y coordinates and the program is doing this and switching the coordinates each time but the object(rectangle) isn't appearing on the screen, any suggestions? Thanks again you guys always help out.

    Here is the code there are four parts to it now.

    The frame

    import java.awt.event.*;
    import javax.swing.*;
    import java.awt.*;
     
    public class snakeFrame extends JFrame
    {
       private static final int FRAME_WIDTH = 400;
       private static final int FRAME_HEIGHT = 400;
     
     
       private boolean right = false;
       private boolean left = false;
       private boolean up = false;
       private boolean down = false;
       private boolean wallCollision = true;
       private boolean onBoard = true; 
       private boolean food = true; 
     
       // calls the other classes 
       private snakeBody snake;
       private snakeFood newFood; 
     
       private Timer t; 
     
     
     
     
       class KeyStrokeListener implements KeyListener
       {
     
          public void keyPressed(KeyEvent event) 
          {
             String key = KeyStroke.getKeyStrokeForEvent(event).toString().replace("pressed ", ""); 
             if (key.equals("DOWN"))
             {
                down = true;
                right = false;
                left = false;
                up = false;          
             }
             else if ( key.equals("UP"))
             {
                up = true;
                right = false;
                down = false;
                left = false;          
             }
             else if ( key.equals("LEFT"))
             {
                left = true;
                right = false;
                down = false;
                up = false;
     
             }
             else if (key.equals("RIGHT"))
             {
     
                right = true;
                left = false;
                down = false;
                up = false;          
             }
     
          }
          public void keyTyped(KeyEvent event) {}
          public void keyReleased(KeyEvent event) {
     
          }
     
       }
     
       public snakeFrame()
       {
          snake = new snakeBody();
          newFood = new snakeFood();
          add(newFood); 
          add(snake);
     
     
          snake.addKeyListener(new KeyStrokeListener());
          snake.setFocusable(true);
     
     
     
        class TimerListener implements ActionListener
        {
     
          public void actionPerformed(ActionEvent event)
          {
            if (left == true)
            {
                snake.moveRectangleBy(-5, 0);
                snake.getBox_X();
                snake.getBox_Y();  
                System.out.println(snake.getBox_Y());
                System.out.println(snake.getBox_X());
     
            }
     
            if (right == true)
            {
                snake.moveRectangleBy(5, 0);
                snake.getBox_X(); 
                System.out.println(snake.getBox_X());
                snake.getBox_Y();  
                System.out.println(snake.getBox_Y());
     
            }
            if (up == true)
            {
                snake.moveRectangleBy(0, -5);  
                snake.getBox_Y();   
                System.out.println(snake.getBox_Y()); 
                snake.getBox_X();  
                System.out.println(snake.getBox_X());   
            }
     
            if (down == true)
            {
                snake.moveRectangleBy(0, 5); 
                snake.getBox_Y(); 
                System.out.println(snake.getBox_Y());
                            snake.getBox_X();  
                System.out.println(snake.getBox_X());
            } 
     
     
          // checks collision for snake and frame height
         if( snake.getBox_X()> FRAME_HEIGHT)
             onBoard = false; 
     
          if (snake.getBox_X() < 0)
             onBoard = false; 
     
          if(snake.getBox_Y() > FRAME_WIDTH)
             onBoard = false;
     
          if(snake.getBox_Y() < 0)
             onBoard = false; 
     
          if(onBoard == false)
             System.out.println("Collision"); 
     
          if(onBoard == true)
             System.out.println("On Board"); 
     
     
          /* // checks collision for snake and food
          if( food.getFood_X() == snake.getBox_X())
             food = false; 
     
          if (food.getFood_X() == snake.getBox_X())
             newFood = false; 
     
          if(food.getFood_Y() == snake.getBox_Y())
             newFood = false;
     
          if(food.getFood_Y() == snake.getBox_Y())
             newFood = false; 
     
          if(newFood == false)
             System.out.println("Food in Game"); 
     
          if(onBoard == true)
             System.out.println("Need new Food"); */ 
     
          }
     
       }
     
          TimerListener listener2 = new TimerListener();
     
          final int DELAY = 100; 
          t = new Timer(DELAY, listener2);
          t.start(); 
     
     
          setSize(FRAME_WIDTH, FRAME_HEIGHT);
     
       }
     
     
     
    }

    The Food code for the random food to generate

    import java.awt.event.*;
    import javax.swing.*;
    import java.awt.*;
     
     
    public class snakeFood extends JComponent
    {
       // Food_x and y will be declared in find food
       private int Food_X;
       private int Food_Y;
       // size of the food
       private int food_WIDTH = 10;
       private int food_HEIGHT = 10;
       // used to create a random coordinate for food x and y
       private int xyCoordinate; 
       private final int RandomPosition = 124;
     
       private Graphics g2; 
     
       private Rectangle food;
     
       //Used to place food at random Coordinates
       public snakeFood()
       { 
     
         food = new Rectangle(Food_X, Food_Y, food_WIDTH, food_HEIGHT); 
         findFood(); 
         getRectangle(); 
     
         repaint(); 
         System.out.println(food); 
     
       }
       //Creates the random Coordinates
       // may need to change the xyCoordinate again. Doesn't seem to move out of the uppper left hand corner
       public void findFood()
       {
          xyCoordinate = (int) (Math.random() * RandomPosition); 
          Food_X = xyCoordinate;
          xyCoordinate = (int) (Math.random() * RandomPosition); 
          Food_Y = xyCoordinate; 
       } 
     
       public int getFood_X()
       {
          return Food_X;
       }
     
       public int getFood_Y()
       {
          return Food_Y;
       }
     
     
     
     
       public void paintComponent(Graphics g)
       {  
          Graphics2D g2 = (Graphics2D) g;
          g2.draw(food);
          g2.setColor(Color.BLUE);
          g2.fill(food);  
          repaint(); 
     
       } 
     
       public Rectangle getRectangle()
       {
          return food; 
       }
     
     
     
     
     
     
    }

    then the viewer

    import java.awt.event.*;
    import javax.swing.*;
    import java.awt.*;
     
     
    public class snakeViewer
    {  
       public static void main(String[] args)
       {   
          final JFrame frame = new snakeFrame();
     
     
          JMenuBar menuBar = new JMenuBar();     
          frame.setJMenuBar(menuBar);
          //Make the menu
          JMenu menu = new JMenu("File");
          //create and add menuItems to menu
          final JMenuItem newItem = new JMenuItem("New Game");   
          final JMenuItem exitItem = new JMenuItem("Exit");      
          menu.add(newItem);
          menu.add(exitItem);
          menuBar.add(menu); //add menu to menuBar
     
          class MenuItemListener implements ActionListener
          {
             public void actionPerformed(ActionEvent event)
             {
                if(event.getSource() == newItem )
                   System.exit(0);
                else if(event.getSource() == exitItem )
                  System.exit(99);
     
             }
          }    
          //Make listener and register sources to listener
          ActionListener listener = new MenuItemListener();
          newItem.addActionListener(listener);      
          exitItem.addActionListener(listener);     
          frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
          frame.setVisible(true);
       }
    }

    here is the body class as well and this works and will show up

    import java.awt.event.*;
    import javax.swing.*;
    import java.awt.*;
     
     
    public class snakeBody extends JComponent
    {
       private int BOX_X = 100;
       private int BOX_Y = 100;
       private int BOX_WIDTH = 10;
       private int BOX_HEIGHT = 10;
     
       private Rectangle box;
     
       public snakeBody()
       {  
     
          box = new Rectangle(BOX_X, BOX_Y, BOX_WIDTH, BOX_HEIGHT);
     
       }
     
     
       public void paintComponent(Graphics g)
       {  
          Graphics2D g2 = (Graphics2D) g;
          g2.draw(box);
          g2.setColor(Color.GREEN);
          g2.fill(box);  
     
       }
     
       // used to move the rectangle
       //Box x + dx allows us to recognize where the coordinates of the box have moved to after the translation
       public void moveRectangleBy(int dx, int dy)
       {
          BOX_X = BOX_X + dx;
          BOX_Y = BOX_Y + dy;
          box.translate(dx, dy);
          repaint();      
       }
     
       public int getBox_Y()
       {
          return BOX_Y;
     
       }
     
       public int getBox_X()
       {
          return BOX_X; 
       }
    }

    I just need to figure out why the food(blue rectangle) isn't appearing when I run the program and that's all for now. Thanks


  2. #2
    Forum VIP
    Join Date
    Jul 2010
    Posts
    1,676
    Thanks
    25
    Thanked 329 Times in 305 Posts

    Default Re: Back again with problems in my Snake Game

    Um, shouldn't this result in infinite recursion?
    public void paintComponent(Graphics g)
       {  
          Graphics2D g2 = (Graphics2D) g;
          g2.draw(food);
          g2.setColor(Color.BLUE);
          g2.fill(food);  
          repaint(); 
     
       }
    The repaint() method calls the paintComponent() method. Also, you want to call super.paintComponent(g) in the beginning of this method.
    NOTE TO NEW PEOPLE LOOKING FOR HELP ON FORUM:

    When asking for help, please follow these guidelines to receive better and more prompt help:
    1. Put your code in Java Tags. To do this, put [highlight=java] before your code and [/highlight] after your code.
    2. Give full details of errors and provide us with as much information about the situation as possible.
    3. Give us an example of what the output should look like when done correctly.

    Join the Airline Management Simulation Game to manage your own airline against other users in a virtual recreation of the United States Airline Industry. For more details, visit: http://airlinegame.orgfree.com/

  3. #3
    Member
    Join Date
    Sep 2013
    Posts
    36
    Thanks
    13
    Thanked 0 Times in 0 Posts

    Default Re: Back again with problems in my Snake Game

    Yeah I think you're right about the infinite recursion and think it was probably put in on accident and I removed it. I put in the super.paintComponent(g) and that didn't seem to work. I understand where you were coming from with that idea though because the paintComponent was being overloaded by drawing a rectangle so you have to call super but that wasn't it. Plus why would the body rectangle draw without super if this was the case so I don't think that is the issue, however I'm only a beginner.

    here is my code now just for the food part

     
       public void paintComponent(Graphics g)
       {  
          super.paintComponent(g);
          Graphics2D g2 = (Graphics2D) g;
          g2.draw(food);
          g2.setColor(Color.BLUE);
          g2.fill(food);  
          //repaint(); 
     
       }

  4. #4
    Forum VIP
    Join Date
    Jul 2010
    Posts
    1,676
    Thanks
    25
    Thanked 329 Times in 305 Posts

    Default Re: Back again with problems in my Snake Game

    Well the super call for that method is kinda important. You should always do the super.paintComponent(g) when you override the paintComponent() method. Have a look at: A Closer Look at the Paint Mechanism (The Java™ Tutorials > Creating a GUI With JFC/Swing > Performing Custom Painting)

    Well, the thing to do now would be to make sure that method is even being called. Put a print statement in the paintComponent() method, just so we know it is being called.
    NOTE TO NEW PEOPLE LOOKING FOR HELP ON FORUM:

    When asking for help, please follow these guidelines to receive better and more prompt help:
    1. Put your code in Java Tags. To do this, put [highlight=java] before your code and [/highlight] after your code.
    2. Give full details of errors and provide us with as much information about the situation as possible.
    3. Give us an example of what the output should look like when done correctly.

    Join the Airline Management Simulation Game to manage your own airline against other users in a virtual recreation of the United States Airline Industry. For more details, visit: http://airlinegame.orgfree.com/

  5. The Following User Says Thank You to aussiemcgr For This Useful Post:

    Edmacelroy (December 9th, 2013)

  6. #5
    Member
    Join Date
    Sep 2013
    Posts
    36
    Thanks
    13
    Thanked 0 Times in 0 Posts

    Default Re: Back again with problems in my Snake Game

    Ah yes that is a great idea, in fact an SI showed me this trick with my keypressed listener and I forgot about it. I will give that a shot and let you know what I figure out.

    --- Update ---

    Ok so I don't think it is being call because I added a print statement and nothing printed to screen

    here is that part
       public void paintComponent(Graphics g)
       {  
          super.paintComponent(g);
          Graphics2D g2 = (Graphics2D) g;
          g2.draw(food);
          g2.setColor(Color.BLUE);
          g2.fill(food);  
          //repaint(); 
          System.out.println("Blue Rectangle");
    }

    But I notice when running the program it is getting the coordinate from the SnakeFood and displaying that on the screen as seen here: java.awt.Rectangle[x=0,y=0,width=14,height=14]

  7. #6
    Member GoodbyeWorld's Avatar
    Join Date
    Jul 2012
    Location
    Hidden command post deep within the bowels of a hidden bunker somewhere under a nondescrip building
    Posts
    161
    My Mood
    Stressed
    Thanks
    14
    Thanked 25 Times in 25 Posts

    Default Re: Back again with problems in my Snake Game

    I think it's because of you layout. It would show the food item if you called add(food) second. It is having the type of layout, the default one, that only shows the latest component you've added.


    However, I tried changing it to FlowLayout and it showed neither.


    Your paintComponent() method of your food item is never being called.

  8. The Following User Says Thank You to GoodbyeWorld For This Useful Post:

    Edmacelroy (December 9th, 2013)

  9. #7
    Forum VIP
    Join Date
    Jul 2010
    Posts
    1,676
    Thanks
    25
    Thanked 329 Times in 305 Posts

    Default Re: Back again with problems in my Snake Game

    Ok. So, your SnakeFood rectangle printout cannot possibly be correct. Look at your width and height variables in the snakeFood class. They are set to 10, yet the printout says 14. Are you 100% sure that printout is from your snakeFood constructor?
    NOTE TO NEW PEOPLE LOOKING FOR HELP ON FORUM:

    When asking for help, please follow these guidelines to receive better and more prompt help:
    1. Put your code in Java Tags. To do this, put [highlight=java] before your code and [/highlight] after your code.
    2. Give full details of errors and provide us with as much information about the situation as possible.
    3. Give us an example of what the output should look like when done correctly.

    Join the Airline Management Simulation Game to manage your own airline against other users in a virtual recreation of the United States Airline Industry. For more details, visit: http://airlinegame.orgfree.com/

  10. #8
    Member
    Join Date
    Sep 2013
    Posts
    36
    Thanks
    13
    Thanked 0 Times in 0 Posts

    Default Re: Back again with problems in my Snake Game

    Isn't the paintComponent() of the food item being called when I return food in the getRectangle method and than call the getRectangle Method in public snakeFood() as seen here in this code

    food being returned in getRectangle() method
       public void paintComponent(Graphics g)
       {  
          Graphics2D g2 = (Graphics2D) g;
          g2.draw(food);
          g2.setColor(Color.BLUE);
          g2.fill(food);  
          repaint(); 
     
       } 
     
       public Rectangle getRectangle()
       {
          return food; 
       }

    then calling the method being done here or am I mistaken with what I'm doing

     
       public snakeFood()
       { 
     
         food = new Rectangle(Food_X, Food_Y, food_WIDTH, food_HEIGHT); 
         findFood(); 
         getRectangle();  //getRectangle Method
     
         repaint(); 
         System.out.println(food); 
     
       }



    @aussiemcgr I switched those variables to make sure that was where the program was getting the height and width from.. If I ran above program in this thread they would be 10. That's how I was making sure it was from the snakeFood constructor sorry for the confusion

  11. #9
    Forum VIP
    Join Date
    Jul 2010
    Posts
    1,676
    Thanks
    25
    Thanked 329 Times in 305 Posts

    Default Re: Back again with problems in my Snake Game

    Isn't the paintComponent() of the food item being called when I return food in the getRectangle method
    No, it should be getting called in your constructor where you have the call to: repaint()

    There must be something we are overlooking.
    Ok, so we know:
    1. You are creating a new SnakeFood object, based on the print statement
    2. You make a call to repaint() immediately before printing in your constructor
    3. You have your own paintComponent() method, which is not being called

    Have you ever used a debugger? Now would be the time to learn, lol.
    NOTE TO NEW PEOPLE LOOKING FOR HELP ON FORUM:

    When asking for help, please follow these guidelines to receive better and more prompt help:
    1. Put your code in Java Tags. To do this, put [highlight=java] before your code and [/highlight] after your code.
    2. Give full details of errors and provide us with as much information about the situation as possible.
    3. Give us an example of what the output should look like when done correctly.

    Join the Airline Management Simulation Game to manage your own airline against other users in a virtual recreation of the United States Airline Industry. For more details, visit: http://airlinegame.orgfree.com/

  12. The Following User Says Thank You to aussiemcgr For This Useful Post:

    Edmacelroy (December 9th, 2013)

  13. #10
    Member
    Join Date
    Sep 2013
    Posts
    36
    Thanks
    13
    Thanked 0 Times in 0 Posts

    Default Re: Back again with problems in my Snake Game

    No never used a debugger for java. I'm going in tonight for some help to see if the SI can help me figure it out. I'm just not understanding why it's not showing up if the other rectangle shows up just fine and is working properly. There is definitely something I have to be overlooking but this is a good start to correcting the issue. One step at a time. How does it debug a working program though, just curious because my program compiles and runs does it just point out what might be wrong with your code or ??? Just a beginner so I'm unaware of what it actually does.

  14. #11
    Forum VIP
    Join Date
    Jul 2010
    Posts
    1,676
    Thanks
    25
    Thanked 329 Times in 305 Posts

    Default Re: Back again with problems in my Snake Game

    Debuggers let you "step through the code", one statement at a time. It can be tedious, since it will take you through a bunch of silly java classes you don't care about, but that's the cost you pay to see EVERY single little method call your program makes. Generally, you put a "break point" in your code somewhere. This point indicates that this is where you want to start debugging. So when you run the code in debug mode, it will operate normally until it reaches an active break-point, where it will immediately stop what it's doing and "wait" for you to press the next button. The best way to describe it would be if you looked at each individual frame of a movie, one by one in order.
    NOTE TO NEW PEOPLE LOOKING FOR HELP ON FORUM:

    When asking for help, please follow these guidelines to receive better and more prompt help:
    1. Put your code in Java Tags. To do this, put [highlight=java] before your code and [/highlight] after your code.
    2. Give full details of errors and provide us with as much information about the situation as possible.
    3. Give us an example of what the output should look like when done correctly.

    Join the Airline Management Simulation Game to manage your own airline against other users in a virtual recreation of the United States Airline Industry. For more details, visit: http://airlinegame.orgfree.com/

  15. The Following User Says Thank You to aussiemcgr For This Useful Post:

    Edmacelroy (December 9th, 2013)

  16. #12
    Super Moderator
    Join Date
    Jun 2013
    Location
    So. Maryland, USA
    Posts
    5,517
    My Mood
    Mellow
    Thanks
    215
    Thanked 698 Times in 680 Posts

    Default Re: Back again with problems in my Snake Game

    The reason you're not seeing 2 of anything added to a JFrame is because the default layout manager for a JFrame is BorderLayout, and components added to BorderLayout are added to BorderLayout.CENTER by default. If you don't specify, that's where they go, and the last component added will cover up the previous.

    But, more importantly, your basic design is incorrect. What it should be is a main JFrame container with a JPanel added to it. All drawing should take place on the JPanel by overriding JPanel's paintComponent() method.

    Adding a component to a container is not the same thing as drawing on a JComponent's Graphics object. Adding a component to a container is ruled by that component's layout manager.

    The code can be fixed to work properly, but it will take some understanding of the correct way to do it and some time to get it done. Once the understanding is achieved, the fixing should be quick. I recommend you review the Custom Painting Tutorial to gain the understanding. Let us know if you have questions as you go through it.

  17. The Following 2 Users Say Thank You to GregBrannon For This Useful Post:

    aussiemcgr (December 9th, 2013), Edmacelroy (December 9th, 2013)

  18. #13
    Forum VIP
    Join Date
    Jul 2010
    Posts
    1,676
    Thanks
    25
    Thanked 329 Times in 305 Posts

    Default Re: Back again with problems in my Snake Game

    Oh, wow, Greg is right. I overlooked that. Instead of the classes inheriting from JComponent, they should probably be inheriting from Rectangle or some other drawable object, since you are trying to draw them onto the JPanel (or at least that's one way of doing it).
    NOTE TO NEW PEOPLE LOOKING FOR HELP ON FORUM:

    When asking for help, please follow these guidelines to receive better and more prompt help:
    1. Put your code in Java Tags. To do this, put [highlight=java] before your code and [/highlight] after your code.
    2. Give full details of errors and provide us with as much information about the situation as possible.
    3. Give us an example of what the output should look like when done correctly.

    Join the Airline Management Simulation Game to manage your own airline against other users in a virtual recreation of the United States Airline Industry. For more details, visit: http://airlinegame.orgfree.com/

  19. #14
    Member
    Join Date
    Sep 2013
    Posts
    36
    Thanks
    13
    Thanked 0 Times in 0 Posts

    Default Re: Back again with problems in my Snake Game

    OK, finally got both the rectangles to show up. Now the problem is with my if statement in the snake frame. It seems when I try to match up the two Food_X + Food_Y coordinates to the Box_X and Box_Y coordinates it's not recognizing they're colliding with each other here is the new code that can compile and run

    import java.awt.event.*;
    import javax.swing.*;
    import java.awt.*;
     
    public class snakeFrame extends JFrame
    {
       private static final int FRAME_WIDTH = 400;
       private static final int FRAME_HEIGHT = 400;
     
       // Food_x and y will be declared in find food
       private int Food_X;
       private int Food_Y;
       // size of the food
       private int food_WIDTH = 10;
       private int food_HEIGHT = 10;
       // used to create a random coordinate for food x and y
      // private int xyCoordinate; 
      // private final int RandomPosition = 10;
     
       private int BOX_X = 100;
       private int BOX_Y = 100;
       private int BOX_WIDTH = 10;
       private int BOX_HEIGHT = 10;
     
     
       private boolean right = false;
       private boolean left = false;
       private boolean up = false;
       private boolean down = false;
       private boolean wallCollision = true;
       private boolean onBoard = true; 
       private boolean newFood = true; 
     
       // calls the other classes 
       private snakeBody snake;
     
     
       private Timer t;
     
       private Rectangle food;  
       private Rectangle box;
     
     
     
     
     
     
     
       class KeyStrokeListener implements KeyListener
       {
     
          public void keyPressed(KeyEvent event) 
          {
             String key = KeyStroke.getKeyStrokeForEvent(event).toString().replace("pressed ", ""); 
             if (key.equals("DOWN"))
             {
                down = true;
                right = false;
                left = false;
                up = false;          
             }
             else if ( key.equals("UP"))
             {
                up = true;
                right = false;
                down = false;
                left = false;          
             }
             else if ( key.equals("LEFT"))
             {
                left = true;
                right = false;
                down = false;
                up = false;
     
             }
             else if (key.equals("RIGHT"))
             {
     
                right = true;
                left = false;
                down = false;
                up = false;          
             }
     
          }
          public void keyTyped(KeyEvent event) {}
          public void keyReleased(KeyEvent event) {
     
          }
     
       }
     
       public snakeFrame()
       {
     
     
          snake = new snakeBody();
     
     
     
          add(snake);
     
     
          snake.addKeyListener(new KeyStrokeListener());
          snake.setFocusable(true);
     
     
     
     
        class TimerListener implements ActionListener
        {
     
          public void actionPerformed(ActionEvent event)
          {
            if (left == true)
            {
                snake.moveRectangleBy(-5, 0);
                snake.getBox_X();
                snake.getBox_Y();    
               // System.out.println(snake.getBox_Y());
                //System.out.println(snake.getBox_X());
                snake.getFood_X();
                snake.getFood_Y();
               // System.out.println(snake.getFood_Y());
               // System.out.println(snake.getFood_X());
     
            }
     
            if (right == true)
            {
                snake.moveRectangleBy(5, 0);
                snake.getBox_X(); 
               // System.out.println(snake.getBox_X());
                snake.getBox_Y();  
                //System.out.println(snake.getBox_Y());
                snake.getFood_X();
                snake.getFood_Y();
               // System.out.println(snake.getFood_Y());
               // System.out.println(snake.getFood_X());
     
            }
            if (up == true)
            {
                snake.moveRectangleBy(0, -5);  
                snake.getBox_Y();   
                //System.out.println(snake.getBox_Y()); 
                snake.getBox_X();  
               // System.out.println(snake.getBox_X()); 
                snake.getFood_X();
                snake.getFood_Y();
                //System.out.println(snake.getFood_Y());
                //System.out.println(snake.getFood_X());  
            }
     
            if (down == true)
            {
                snake.moveRectangleBy(0, 5); 
                snake.getBox_Y(); 
                //System.out.println(snake.getBox_Y());
                snake.getBox_X();  
                //System.out.println(snake.getBox_X());
                snake.getFood_X();
                snake.getFood_Y();
               // System.out.println(snake.getFood_Y());
               // System.out.println(snake.getFood_X());
            } 
     
     
          // checks collision for snake and frame height
          if( snake.getBox_X()> FRAME_HEIGHT)
             onBoard = false; 
     
          else if (snake.getBox_X() < 0)
             onBoard = false; 
     
          else if(snake.getBox_Y() > FRAME_WIDTH)
             onBoard = false;
     
          else if(snake.getBox_Y() < 0)
             onBoard = false; 
     
          else  if(onBoard == false)
             System.out.println("Collision"); 
     
          else  if(onBoard == true)
          {
             System.out.println("On Board"); 
          }
     
     
           // checks collision for snake and food
          if( snake.getFood_X() == snake.getBox_X() && snake.getFood_Y() == snake.getBox_Y() )
             {
             newFood = false; 
             }
          //else if (snake.getFood_X() == snake.getBox_X() && snake.getFood_Y() == snake.getBox_Y())
          //newFood = false; 
     
          if(newFood == false)
          {
             System.out.println("Need new Food"); 
          }   
          if(newFood == true)
          {
                   System.out.println("Food in game"); 
          }           
         }
     
       }
     
          TimerListener listener2 = new TimerListener();
     
          final int DELAY = 100; 
          t = new Timer(DELAY, listener2);
          t.start(); 
     
     
          setSize(FRAME_WIDTH, FRAME_HEIGHT);
       } 
     
     
     
     
     
     
    }

    SnakeBody - which now contains both snakefood and snakebody

    import java.awt.event.*;
    import javax.swing.*;
    import java.awt.*;
     
     
    public class snakeBody extends JComponent
    {
       private int BOX_X = 100;
       private int BOX_Y = 100;
       private int BOX_WIDTH = 10;
       private int BOX_HEIGHT = 10;
       private int Food_X;
       private int Food_Y;
       private int xyCoordinate;
       private final int RandomPosition = 124;
       private int food_WIDTH = 10;
       private int food_HEIGHT = 10;
     
     
     
     
       private Rectangle box;
       private Rectangle food;
     
       public snakeBody()
       {  
     
     
          findFood(); 
          box = new Rectangle(BOX_X, BOX_Y, BOX_WIDTH, BOX_HEIGHT);
          food = new Rectangle(Food_X, Food_Y, food_WIDTH, food_HEIGHT);
     
     
       }
     
       public void findFood()
       {
          xyCoordinate = (int) (Math.random() * RandomPosition); 
          Food_X = xyCoordinate;
          xyCoordinate = (int) (Math.random() * RandomPosition); 
          Food_Y = xyCoordinate; 
       }
     
     
       public void paintComponent(Graphics g)
       {  
     
        Graphics2D g2 = (Graphics2D) g;
          g2.draw(food);
          g2.setColor(Color.BLUE);
          g2.fill(food);  
          repaint(); 
     
         // super.paintComponent(g); 
          Graphics2D g3 = (Graphics2D) g;
          g2.draw(box);
          g2.setColor(Color.GREEN);
          g2.fill(box);  
     
          //Graphics2D g2 = (Graphics2D) g;
          //g2.draw(box);
          //g2.setColor(Color.GREEN);
          //g2.fill(box);  
     
       }
     
       // used to move the rectangle
       //Box x + dx allows us to recognize where the coordinates of the box have moved to after the translation
       public void moveRectangleBy(int dx, int dy)
       {
          BOX_X = BOX_X + dx;
          BOX_Y = BOX_Y + dy;
          box.translate(dx, dy);
          repaint();      
       }
     
       public int getBox_Y()
       {
          return BOX_Y;
     
       }
     
       public int getBox_X()
       {
          return BOX_X; 
       }
     
       public int getFood_X()
       {
          return Food_X;
       }
     
       public int getFood_Y()
       {
          return Food_Y;
       }
     
     
    }

    than the viewer is the same
    import java.awt.event.*;
    import javax.swing.*;
    import java.awt.*;
     
     
    public class snakeViewer
    {  
       public static void main(String[] args)
       {   
          final JFrame frame = new snakeFrame();
     
     
          JMenuBar menuBar = new JMenuBar();     
          frame.setJMenuBar(menuBar);
          //Make the menu
          JMenu menu = new JMenu("File");
          //create and add menuItems to menu
          final JMenuItem newItem = new JMenuItem("New Game");   
          final JMenuItem exitItem = new JMenuItem("Exit");      
          menu.add(newItem);
          menu.add(exitItem);
          menuBar.add(menu); //add menu to menuBar
     
          class MenuItemListener implements ActionListener
          {
             public void actionPerformed(ActionEvent event)
             {
                if(event.getSource() == newItem )
                   System.exit(0);
                else if(event.getSource() == exitItem )
                  System.exit(99);
     
             }
          }    
          //Make listener and register sources to listener
          ActionListener listener = new MenuItemListener();
          newItem.addActionListener(listener);      
          exitItem.addActionListener(listener);     
          frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
          frame.setVisible(true);
       }
    }

    So now we can't get it to detect the two rectangles when they collide and display to the screen "Need new food" is it something to do with the integers I'm giving to the instance variables or is it with my if statement. I've been switching things around trying to get this part to consistently work but I'm not getting anywhere so far. I've tried changes the integers assigned to the instance variables, switch the if statement around trying new things but no dice

    Again Thank you for the help

  20. #15
    Super Moderator
    Join Date
    Jun 2013
    Location
    So. Maryland, USA
    Posts
    5,517
    My Mood
    Mellow
    Thanks
    215
    Thanked 698 Times in 680 Posts

    Default Re: Back again with problems in my Snake Game

    Rectangle has an intersects() method that you can use.

  21. The Following User Says Thank You to GregBrannon For This Useful Post:

    Edmacelroy (December 10th, 2013)

  22. #16
    Member
    Join Date
    Sep 2013
    Posts
    36
    Thanks
    13
    Thanked 0 Times in 0 Posts

    Default Re: Back again with problems in my Snake Game

    Yup needed to use the intersects() method. Thank you that solved the issue

Similar Threads

  1. Snake Game
    By sakonpure6 in forum What's Wrong With My Code?
    Replies: 1
    Last Post: September 23rd, 2013, 03:48 AM
  2. Help with Snake Game Java Code: It's Impossible to Lose the Game
    By haruspex_icis in forum What's Wrong With My Code?
    Replies: 20
    Last Post: December 17th, 2012, 12:21 PM
  3. [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
  4. [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
  5. Snake Game
    By Cuju in forum What's Wrong With My Code?
    Replies: 6
    Last Post: February 19th, 2011, 08:31 PM