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

Thread: [Snake]Help

  1. #1
    Junior Member
    Join Date
    Sep 2012
    Location
    Philippines
    Posts
    23
    My Mood
    Confused
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default [Snake]Help

    import java.awt.*;
    import javax.swing.*;
    import java.awt.event.*;
    import java.util.Random;
    import java.io.*;
    import java.awt.Color;
    import java.awt.event.ActionEvent;
     
    	public class Snakes extends JPanel implements ActionListener,KeyListener{
     
    	Timer tmr = new Timer(10, this);
    	Timer tm = new Timer(10,this);
    	static JFrame frame = new JFrame();
    	static JButton btnStart; 	
    	static JLabel ScoreLabel;
    	static int x1=20, y1=20, w1=20, h1=20;
    	static int x2=20, y2=20, w2=20, h2=20;
    	static int RandomBox = 0;
    	static int score = 0;
    	static int direction = 0;
    	Random randomGenerator = new Random();
     
    	public Snakes()
    	{
    	ScoreLabel = new JLabel ("Score:");
    	ScoreLabel.setBounds(5,445,100,20);
    	add(ScoreLabel);
    	tmr.start();
    	setLayout(null);		
    	this.requestFocus();
    	addKeyListener(this);
    	setFocusable(true);
    	setFocusTraversalKeysEnabled(false);
    	}
    public int x2Generator(int x2,Random randomGenerator,int RandomBox) {
     
    		RandomBox = randomGenerator.nextInt(5)+1;
    		if(RandomBox==1) 
    		{
    			x2 = 340;	
    		}	
     
    		else if(RandomBox==2) 
    		{
    			x2 = 135;
    		}
     
    		else if(RandomBox==3) 
    		{
    			x2 = 405;
    		}
     
    		else if(RandomBox==4) 
    		{
    			x2 = 420;
    		}
     
    		else if(RandomBox==5) 
    		{
    			x2 = 375;
    		}
     
    		return x2;
    		}
     
    public int y2Generator(int y2,Random randomGenerator,int RandomBox) {
     
    		RandomBox = randomGenerator.nextInt(5)+1;
    		if(RandomBox==1) 
    		{
    			y2 = 95;	
    		}	
     
    		else if(RandomBox==2) 
    		{
    			y2 = 400;
    		}
     
    		else if(RandomBox==3) 
    		{
    			y2 = 425;
    		}
     
    		else if(RandomBox==4) 
    		{
    			y2 = 170;
    		}
     
    		else if(RandomBox==5) 
    		{
    			y2 = 440;
    		}	
    		return y2;
    		}
     
     
     
    	public void paintComponent(Graphics g)
            {
            super.paintComponent(g);
            tm.start();
     
    		g.setColor(Color.BLACK);
    		g.fillRect(x1, y1, w1, h1);
     
    		g.setColor(Color.BLUE);
    		g.fillRect(x2, y2, w2, h2);
     
    	}
    	public void keyPressed(KeyEvent e) 
    	{
    	if(e.getKeyCode()==KeyEvent.VK_RIGHT) 
    	{
    		direction=1;
    	}
     
     
     
    	else if(e.getKeyCode()==KeyEvent.VK_LEFT) 
    	{
    		direction=2;
    	}
     
     
    	else if(e.getKeyCode()==KeyEvent.VK_UP) 
    	{
    		direction=3;
    	}
     
     
    	else if(e.getKeyCode()==KeyEvent.VK_DOWN) 
    	{
    		direction=4;
    	}
     
    	}
     
            public void keyTyped(KeyEvent e)
    	{
    	}
    	public void keyReleased(KeyEvent e)
    	{
            }
    	public void delay() 
    	{
    		try
    	{
    	Thread.sleep(100);
    	}
    	catch(Exception e)
    	{
    	}
     
    	}
     
    	public static void main (String args[]) 
    	{
              Snakes obj = new Snakes();  
              frame.setSize(500,500);
              frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              frame.setVisible(true);
              frame.add(obj);     
            }
    	public void actionPerformed(ActionEvent e)
    	{
     
    //Reset position of Snake in x and y through frame
    	if(x1<0)
    	{
    		x1=490;
    	}
    	if(x1>490)
    		{ 
    			x1=0;
    		}
    	if(y1<0) 
    	{
    		y1=460;
    	}
    	if(y1>460)
    		{
    			y1=0;
     
    		}
     
    //Snake Arrow up, down, left, right		
    	if(direction==1) 
    	{
    		x1=x1+1;	
    	}
     
    	if(direction==2) 
    	{
    		x1=x1-1;
    	}
     
    	if(direction==3) 
    	{
    		y1=y1-1;
    	}
     
    	if(direction==4) 
    	{
    		y1=y1+1;	
    	}
     
     
    //Snake and Random Box
    		if((x1==x2)&&(y1==y2)) 
    		{
    		x2 = x2Generator(x2, randomGenerator, RandomBox);
    		y2 = y2Generator(y2, randomGenerator, RandomBox);
    		score = score +1;
    		ScoreLabel.setText("Score: "+score);
    		}
    		repaint();
     
    }
    }

    Give me a hint or please just post a code how to add tail
    and please fix the score for me

    ----------------------------------------------------------------------

    After some hours my snake has a tail. I still have a problem the whole Body/Tail including the head, it can go Up, Down, Left, Right, now my problem
    is, it moves in one direction. Here's my new code.

    import java.awt.*;
    import javax.swing.*;
    import java.awt.event.*;
    import java.util.Random;
    import java.io.*;
    import java.awt.Color;
    import java.awt.event.ActionEvent;
     
    	public class Snakes extends JPanel implements ActionListener, KeyListener{
     
    	Timer tmr = new Timer(500, this);
    	Timer tm = new Timer(10,this);
    	static JFrame frame = new JFrame();
    	static JButton btnStart; 	
    	static JLabel ScoreLabel;
    	static int x1=20, y1=20, w1=20, h1=20;
    	static int x2=20, y2=20, w2=20, h2=20;
    	static int RandomBox = 0;
    	static int score = 0;
    	static int direction = 0;
    	Random randomGenerator = new Random();
     
    	public Snakes()
    	{
    	JOptionPane.showMessageDialog(null, "Start");
    	ScoreLabel = new JLabel ("Score:");
    	ScoreLabel.setBounds(5,445,100,20);
    	add(ScoreLabel);
    	setLayout(null);		
    	this.requestFocus();
    	addKeyListener(this);
    	setFocusable(true);
    	setFocusTraversalKeysEnabled(false);
    	}
    	public int x2Generator(int x2,Random randomGenerator,int RandomBox) 
    		{
     
    		RandomBox = randomGenerator.nextInt(5)+1;
    		if(RandomBox==1) 
    		{
    			x2 = 340;		
    		}	
     
    		else if(RandomBox==2) 
    		{
    			x2 = 135;
    		}
     
    		else if(RandomBox==3) 
    		{
    			x2 = 405;
    		}
     
    		else if(RandomBox==4) 
    		{
    			x2 = 420;
    		}
     
    		else if(RandomBox==5) 
    		{
    			x2 = 375;
    		}
     
    		return x2;
    		}
     
    		public int y2Generator(int y2,Random randomGenerator,int RandomBox) {
     
    		RandomBox = randomGenerator.nextInt(5)+1;
    		if(RandomBox==1) 
    		{
    			y2 = 95;	
    		}	
     
    		else if(RandomBox==2) 
    		{
    			y2 = 400;
    		}
     
    		else if(RandomBox==3) 
    		{
    			y2 = 425;
    		}
     
    		else if(RandomBox==4) 
    		{
    			y2 = 170;
    		}
     
    		else if(RandomBox==5) 
    		{
    			y2 = 440;
    		}	
    		return y2;
    		}
     
     
    	public void paintComponent(Graphics g)
        	{
            super.paintComponent(g);
            tm.start();
     
    		g.setColor(Color.BLACK);
    		g.fillOval(x1, y1, w1, h1);
     
    		g.setColor(Color.RED);
    		g.fillRect(x2, y2, w2, h2);
     
    	}
    	public void keyPressed(KeyEvent e) 
    	{
    	if(e.getKeyCode()==KeyEvent.VK_RIGHT) 
    	{
    		direction=1;
    	}
     
     
     
    	else if(e.getKeyCode()==KeyEvent.VK_LEFT) 
    	{
    		direction=2;
    	}
     
     
    	else if(e.getKeyCode()==KeyEvent.VK_UP) 
    	{
    		direction=3;
    	}
     
     
    	else if(e.getKeyCode()==KeyEvent.VK_DOWN) 
    	{
    		direction=4;
    	}
     
    	}
     
        	public void keyTyped(KeyEvent e)
    	{
    	}
    	public void keyReleased(KeyEvent e)
    	{
        	}
    	public void delay() 
    	{
    		try
    	{
    	Thread.sleep(5);
    	}
    	catch(Exception e)
    	{
    	}
     
    	}
     
    	public static void main (String args[]) 
    	{
        	Snakes obj = new Snakes();  
        	frame.setSize(500,500);
        	frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        	frame.setVisible(true);
        	frame.add(obj);     
        	}
    	public void actionPerformed(ActionEvent e)
    	{
    	//Reset position of Snake in x and y through frame
    	if(x1<0)
    	{
    		x1=490;
    	}
    	if(x1>490)
    		{ 
    			x1=0;
    		}
    	if(y1<0) 
    	{
    		y1=460;
    	}
    	if(y1>460)
    		{
    			y1=0;
     
    		}	
    	//Up, down, left, right
    	if(direction==1) 
    	{
    		x1=x1+1;
    		delay();	
    	}
     
    	if(direction==2) 
    	{
    		x1=x1-1;
    		delay();
    	}
     
    	if(direction==3) 
    	{
    		y1=y1-1;
    		delay();
    	}
     
    	if(direction==4) 
    	{
    		y1=y1+1;
    		delay();	
    	}
    		//Snake tail and Random Box
    		if(y2+h2>=y1&&x2+w2>=x1&&x2<=x1+w1&&y2<=y1||y2<=0)
    		{
    		x2 = x2Generator(x2, randomGenerator, RandomBox);
    		y2 = y2Generator(y2, randomGenerator, RandomBox);
     
    		w1=w1+20;
    		ScoreLabel.setText("Score: "+score);
    		score = score +1;
    		}
    		repaint();
     
     
    }
    }



    PS: Please give me a hint or fix the code for me
    Last edited by Totel; September 24th, 2012 at 04:39 AM. Reason: New Codes Added.

  2. #2
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,042
    Thanks
    63
    Thanked 2,708 Times in 2,658 Posts

    Default Re: [Snake]Help

    Please explain the problem with the code. What does it do or not do that you want to change?
    If you don't understand my answer, don't ignore it, ask a question.

  3. #3
    Junior Member
    Join Date
    Sep 2012
    Location
    Philippines
    Posts
    23
    My Mood
    Confused
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: [Snake]Help

    Quote Originally Posted by Norm View Post
    Please explain the problem with the code. What does it do or not do that you want to change?
    I stated my new question in my first post including my new code please help

  4. #4
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,042
    Thanks
    63
    Thanked 2,708 Times in 2,658 Posts

    Default Re: [Snake]Help

    my problem
    is, it moves in one direction
    Please explain what you want the code to do.
    If you don't understand my answer, don't ignore it, ask a question.

  5. #5
    Junior Member
    Join Date
    Sep 2012
    Location
    Philippines
    Posts
    23
    My Mood
    Confused
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: [Snake]Help

    Quote Originally Posted by Norm View Post
    Please explain what you want the code to do.
    Try to run my code and you'll understand what I am trying to explain, I'm sorry I have bad English grammar. I actually don't know how do you want me to explain it. If you ran my code, you will notice that the head of the snake don't rotate instead it moves in 1 direction. Yes it goes UP,DOWN, LEFT, RIGHT but as what I've said it only moves in 1 direction.

  6. #6
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,042
    Thanks
    63
    Thanked 2,708 Times in 2,658 Posts

    Default Re: [Snake]Help

    Sorry, I don't understand what the problem is.

    Yes it goes UP,DOWN, LEFT, RIGHT but as what I've said it only moves in 1 direction.
    If it moves in all directions, what do you want to change?

    Do you mean you want the moving shape to have a "head" that is always in front when the shape is moving? That would be done in the paintComponent() method.
    If you don't understand my answer, don't ignore it, ask a question.

  7. #7
    Junior Member
    Join Date
    Sep 2012
    Location
    Philippines
    Posts
    23
    My Mood
    Confused
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: [Snake]Help

    Quote Originally Posted by Norm View Post
    Sorry, I don't understand what the problem is.


    If it moves in all directions, what do you want to change?

    Do you mean you want the moving shape to have a "head" that is always in front when the shape is moving? That would be done in the paintComponent() method.
    Yes I want the head always be in front every time I eat the random food.
    can be done in paintComponent() ? how is that :O

  8. #8
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,042
    Thanks
    63
    Thanked 2,708 Times in 2,658 Posts

    Default Re: [Snake]Help

    You will have to tell paintComponent() what direction the shape is moving so it knows where to draw the "head". Take a piece of paper and draw on it the 4 different shapes, one shape for each direction. Then work out the code that will draw the shape for that direction. In paintComponent, test what direction the shape is moving and use the code that draws the shape with the head pointed in the correct direction.
    If you don't understand my answer, don't ignore it, ask a question.

  9. #9
    Junior Member
    Join Date
    Sep 2012
    Location
    Philippines
    Posts
    23
    My Mood
    Confused
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: [Snake]Help

    260tqia.jpg

    If you will see in the First Drawing Snake bents and the head is always in front to eat the food, while in the 2nd Drawing that's actually kinda same as mine I just used Oval in my codes instead of Rect. Now my question is how can my snake bend/rotate and make the head always in front to eat the random food.

    PS : I don't have any idea how to make it and by the way I prefer to have the 2nd
    Drawing Snake to appear in my frame.
    Last edited by Totel; September 24th, 2012 at 08:07 AM.

  10. #10
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,042
    Thanks
    63
    Thanked 2,708 Times in 2,658 Posts

    Default Re: [Snake]Help

    how can my snake bend/rotate and make the head always in front to eat the random food.
    Use a piece of paper to draw the shapes you want to see with the head in front.
    Then write the code for the paintComponent() method to draw that shape.
    If you want separate the snake to be made of more than one drawn shape, that will be more work. Save that for later.

    Start with the simpler single shape with a head on the end that the snake is moving towards. Perhaps draw in an eye to show where the head is. You have to use a piece of paper and draw the shapes on it so you get the x,y values needed for the paintComponent() method.
    If you don't understand my answer, don't ignore it, ask a question.

  11. #11
    Junior Member
    Join Date
    Sep 2012
    Location
    Philippines
    Posts
    23
    My Mood
    Confused
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: [Snake]Help

    Until now I can't get it, It sucks

  12. #12
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,042
    Thanks
    63
    Thanked 2,708 Times in 2,658 Posts

    Default Re: [Snake]Help

    Look at the drawings you made of the shape when it is going horizontally and vertically
    and then look the the fillOval() method call to see how it can be used to draw one way or the other.

    What width and height should be used for drawing each orientation? Look at your drawings.
    If you don't understand my answer, don't ignore it, ask a question.

  13. #13
    Junior Member
    Join Date
    Sep 2012
    Location
    Philippines
    Posts
    23
    My Mood
    Confused
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: [Snake]Help

    Quote Originally Posted by Norm View Post
    Look at the drawings you made of the shape when it is going horizontally and vertically
    and then look the the fillOval() method call to see how it can be used to draw one way or the other.

    What width and height should be used for drawing each orientation? Look at your drawings.
    Do I need to declare a bolean

    boolean left = false;
       boolean right = true;
         boolean up = false;
        boolean down = false;

    And add this code under public void keyPressed(KeyEvent e)
    && (!right)) 
    {
            left = true;
            up = false;
            down = false;
    }

    Sorry I still don't know what to do I need to pass this tomorrow.
    Last edited by Totel; September 25th, 2012 at 06:35 AM.

  14. #14
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,042
    Thanks
    63
    Thanked 2,708 Times in 2,658 Posts

    Default Re: [Snake]Help

    The code has a direction variable that has 4 values, one for each direction. You can us that.
    If you don't understand my answer, don't ignore it, ask a question.

  15. #15
    Junior Member
    Join Date
    Sep 2012
    Location
    Philippines
    Posts
    23
    My Mood
    Confused
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: [Snake]Help

    Quote Originally Posted by Norm View Post
    The code has a direction variable that has 4 values, one for each direction. You can us that.
    It will become like this ?

    Declaration :

    static boolean left = false;
        static boolean right = true;
        static boolean up = false;
        static boolean down = false;
    public void keyPressed(KeyEvent e) 
    	{
    	if((e.getKeyCode()==KeyEvent.VK_RIGHT) && (!right)) {
                    left = true;
                    up = false;
                    down = false;
    		direction=1;
    	}
     
     
     
    	else if((e.getKeyCode()==KeyEvent.VK_LEFT) && (!left)) {
                    right = true;
                    up = false;
                    down = false;
                    direction=2;
    	}
     
     
    	else if((e.getKeyCode()==KeyEvent.VK_UP) && (!down)) {
                    up = true;
                    right = false;
                    left = false;
                    direction=3;
    	}
     
     
    	else if((e.getKeyCode()==KeyEvent.VK_DOWN) && (!up)) {
                    down = true;
                    right = false;
                    left = false; 
    		direction=4;
    	}
     
    	}

  16. #16
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,042
    Thanks
    63
    Thanked 2,708 Times in 2,658 Posts

    Default Re: [Snake]Help

    What is wrong with the direction variable? Why do you want to add more variables?

    I would suggest that you use an enum for this:
     
       enum Direction {NONE, UP, DOWN, LEFT, RIGHT}   
     ...
    	static Direction direction = Direction.NONE;       
    ...
    	if(e.getKeyCode()==KeyEvent.VK_RIGHT) 	{
    		direction=Direction.RIGHT;    
    ...     
    	if(direction==Direction.RIGHT)     	{
    		x1=x1+1;
    Then use the value of direction in the paintComponent() to control how the shape is drawn.
    If moving horizontally, draw the length in the x direction.
    If move vertically, draw the length in the y direction.
    If you don't understand my answer, don't ignore it, ask a question.

  17. #17
    Junior Member
    Join Date
    Sep 2012
    Location
    Philippines
    Posts
    23
    My Mood
    Confused
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: [Snake]Help

    I will declare this ?
    static Direction direction = Direction.NONE;

    I don't know the use and I don't know where to put this

     public enum Direction
     {
     NONE, UP, DOWN, LEFT, RIGHT
     }

    I added this already each of my keys.
    if(e.getKeyCode()==KeyEvent.VK_RIGHT) 	{
    		direction=Direction.RIGHT;
                   }

  18. #18
    Super Moderator jps's Avatar
    Join Date
    Jul 2012
    Posts
    2,642
    My Mood
    Daring
    Thanks
    90
    Thanked 263 Times in 232 Posts

    Default Re: [Snake]Help

    Try using a search engine for keywords you find in code snippets you don't understand. Learn what the used classes and methods are for by reading through the results. There is a wealth of information available and plenty of examples if you just look for them. This one for example:
    Enum Types

  19. #19
    Junior Member
    Join Date
    Sep 2012
    Location
    Philippines
    Posts
    23
    My Mood
    Confused
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: [Snake]Help

    Quote Originally Posted by jps View Post
    Try using a search engine for keywords you find in code snippets you don't understand. Learn what the used classes and methods are for by reading through the results. There is a wealth of information available and plenty of examples if you just look for them. This one for example:
    Enum Types
    It doesn't matter now I did a trial and error in my program and I knew now the use of it.

    I don't get what Norm said
    Then use the value of direction in the paintComponent() to control how the shape is drawn. If moving horizontally, draw the length in the x direction.
    If move vertically, draw the length in the y direction.

  20. #20
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,042
    Thanks
    63
    Thanked 2,708 Times in 2,658 Posts

    Default Re: [Snake]Help

    First you need to test using the fillOval() method to see how to draw a shape that is moving in the vertical direction. The current code draws the shape moving in a horizontal direction.

    When you get that working, do something like this:
    if moving horizontally(for example direction = LEFT), draw shape in horizontal orientation
    if moving vertically(for example direction = UP), draw the shape in a vertical orientation
    If you don't understand my answer, don't ignore it, ask a question.

  21. #21
    Junior Member
    Join Date
    Sep 2012
    Location
    Philippines
    Posts
    23
    My Mood
    Confused
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: [Snake]Help

    Quote Originally Posted by Norm View Post
    First you need to test using the fillOval() method to see how to draw a shape that is moving in the vertical direction. The current code draws the shape moving in a horizontal direction.

    When you get that working, do something like this:
    if moving horizontally(for example direction = LEFT), draw shape in horizontal orientation
    if moving vertically(for example direction = UP), draw the shape in a vertical orientation
    I really can't do it. I gave up already, I think this is enough maybe my professor
    will still grade my program even with a below passing grade could be a consideration
    from the effort I did, Hehe. I really appreciated your help thank you very much even
    I didn't make it until next time dude. I will probably ask your help again I will post my
    coming projects here sooner or later.

    By the way here is my last update code in snake haha

    import java.awt.*;
    import javax.swing.*;
    import java.awt.event.*;
    import java.util.Random;
    import java.io.*;
    import java.awt.Color;
    import java.awt.event.ActionEvent;
     
    	public class Snakes extends JPanel implements ActionListener, KeyListener{
     
    	Timer tmr = new Timer(50, this);
    	Timer tm = new Timer(50,this);
    	static JFrame frame = new JFrame();	
    	static JLabel ScoreLabel;
    	static int x1=20, y1=20, w1=20, h1=20;
    	static int x2=20, y2=20, w2=20, h2=20;
    	static int RandomBox = 0;
    	static int score = 0;
    	static Direction direction = Direction.NONE;
    	Random randomGenerator = new Random();
     
    	public Snakes()
    	{
    	JOptionPane.showMessageDialog(null, "Start");
    	ScoreLabel = new JLabel ("Score:");
    	ScoreLabel.setBounds(5,445,100,20);
    	add(ScoreLabel);
    	setLayout(null);		
    	this.requestFocus();
    	addKeyListener(this);
    	setFocusable(true);
    	setFocusTraversalKeysEnabled(false);
    	}
    	public int x2Generator(int x2,Random randomGenerator,int RandomBox) 
    		{
     
    		RandomBox = randomGenerator.nextInt(5)+1;
    		if(RandomBox==1) 
    		{
    			x2 = 340;		
    		}	
     
    		else if(RandomBox==2) 
    		{
    			x2 = 135;
    		}
     
    		else if(RandomBox==3) 
    		{
    			x2 = 405;
    		}
     
    		else if(RandomBox==4) 
    		{
    			x2 = 420;
    		}
     
    		else if(RandomBox==5) 
    		{
    			x2 = 375;
    		}
     
    		return x2;
    		}
     
    		public int y2Generator(int y2,Random randomGenerator,int RandomBox) {
     
    		RandomBox = randomGenerator.nextInt(5)+1;
    		if(RandomBox==1) 
    		{
    			y2 = 95;	
    		}	
     
    		else if(RandomBox==2) 
    		{
    			y2 = 400;
    		}
     
    		else if(RandomBox==3) 
    		{
    			y2 = 425;
    		}
     
    		else if(RandomBox==4) 
    		{
    			y2 = 170;
    		}
     
    		else if(RandomBox==5) 
    		{
    			y2 = 440;
    		}	
    		return y2;
    		}
     
     
    	public void paintComponent(Graphics g)
        	{
            super.paintComponent(g);
            tm.start();
     
    		g.setColor(Color.BLACK);
    		g.fillRect(x1, y1, w1, h1);
     
    		g.setColor(Color.RED);
    		g.fillRect(x2, y2, w2, h2);
    		}
     
     
    	public enum Direction 
    	{
    	NONE, UP, DOWN, LEFT, RIGHT
    	}
    	public void keyPressed(KeyEvent e) 
    	{
    	if(e.getKeyCode()==KeyEvent.VK_RIGHT) 
    	{
    		direction=Direction.RIGHT;
    	}
     
     
    	else if(e.getKeyCode()==KeyEvent.VK_LEFT) 
    	{
    		direction=Direction.LEFT;
    	}
     
     
    	else if(e.getKeyCode()==KeyEvent.VK_UP) 
    	{
    		direction=Direction.UP;
    	}
     
     
    	else if(e.getKeyCode()==KeyEvent.VK_DOWN) 
    	{
    		direction=Direction.DOWN;
    	}
     
    	}
     
        public void keyTyped(KeyEvent e)
    	{
    	}
    	public void keyReleased(KeyEvent e)
    	{
        }
    	public void delay() 
    	{
    		try
    	{
    	Thread.sleep(50);
    	}
    	catch(Exception e)
    	{
    	}
     
    	}
     
    	public static void main (String args[]) 
    		{
        	Snakes obj = new Snakes();  
        	frame.setSize(500,500);
        	frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        	frame.setVisible(true);
        	frame.add(obj);     
        	}
    	public void actionPerformed(ActionEvent e)
    	{
    	//Reset position of Snake in x and y through frame
    	if(x1<0)
    	{
    		x1=490;
    	}
    	if(x1>490)
    		{ 
    			x1=0;
    		}
    	if(y1<0) 
    	{
    		y1=460;
    	}
    	if(y1>460)
    		{
    			y1=0;
     
    		}	
    	//Up, down, left, right
    	if(direction==Direction.RIGHT) 
    	{
    		x1=x1+5;
    		delay();
    	}
     
    	if(direction==Direction.LEFT) 
    	{
    		x1=x1-5;
    		delay();
    	}
     
    	if(direction==Direction.UP) 
    	{
    		y1=y1-5;
    		delay();
    	}
     
    	if(direction==Direction.DOWN) 
    	{
    		y1=y1+5;
    		delay();
    	}
    		//Snake tail and Random Box
    		if(y2+h2>=y1&&x2+w2>=x1&&x2<=x1+w1&&y2<=y1||y2<=0)
    		{
    		x2 = x2Generator(x2, randomGenerator, RandomBox);
    		y2 = y2Generator(y2, randomGenerator, RandomBox);
     
    		w1=w1+20;
    		ScoreLabel.setText("Score: "+score);
    		score = score +1;
    		}
    		repaint();
     
     
    }
    }

  22. #22
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,042
    Thanks
    63
    Thanked 2,708 Times in 2,658 Posts

    Default Re: [Snake]Help

    Can you code the fillRect() method to draw different rectangles?
    Write code for these two cases using a width of 20 and a length of 50
    One that is horizontally oriented (longer in the x direction)
    and one that is vertically oriented (longer in the y direction)
    Last edited by Norm; September 25th, 2012 at 10:30 AM. Reason: Rectangles now vs ovals
    If you don't understand my answer, don't ignore it, ask a question.

  23. #23
    Junior Member
    Join Date
    Sep 2012
    Location
    Philippines
    Posts
    23
    My Mood
    Confused
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: [Snake]Help

    Quote Originally Posted by Norm View Post
    Can you code the fillRect() method to draw different rectangles?
    Write code for these two cases using a width of 20 and a length of 50
    One that is horizontally oriented (longer in the x direction)
    and one that is vertically oriented (longer in the y direction)
    I'm really glad and thankful because our professor gave us another chance to finish this program until Monday next week, the sad thing is he gave us another homework which will be look like a Battle City game not really alike but, it is falling objects/shapes with 1 block on the bottom of the frame that can be move from left to right and it should fire the falling objects using "Space Bar Key" . Anyways it's not the topic here since it's about Snake Game. I need your help again, look at my updated code. I made something different and I guess it moves Horizontal and Vertical there is still a problem when I eat the Food the snake grows but when I move it to other directions the snake goes back to it's own size.

    import java.awt.*;
    import javax.swing.*;
    import java.awt.event.*;
    import java.util.Random;
    import java.io.*;
    import java.awt.Color;
    import java.awt.event.ActionEvent;
     
    	public class Snakes extends JPanel implements ActionListener, KeyListener{
     
    	Timer tmr = new Timer(50, this);
    	Timer tm = new Timer(50,this);
    	static JFrame frame = new JFrame();	
    	static JLabel ScoreLabel;
    	static int x1=20, y1=20, w1=10, h1=20;
    	static int x2=20, y2=20, w2=20, h2=20;
    	static int RandomBox = 0;
    	static int score = 0;
    	static Direction direction = Direction.NONE;
    	Random randomGenerator = new Random();
     
    	public Snakes()
    	{
    	JOptionPane.showMessageDialog(null, "Start");
    	ScoreLabel = new JLabel ("Score:");
    	ScoreLabel.setBounds(5,445,100,20);
    	add(ScoreLabel);
    	setLayout(null);		
    	this.requestFocus();
    	addKeyListener(this);
    	setFocusable(true);
    	setFocusTraversalKeysEnabled(false);
    	}
    	public int x2Generator(int x2,Random randomGenerator,int RandomBox) 
    		{
     
    		RandomBox = randomGenerator.nextInt(5)+1;
    		if(RandomBox==1) 
    		{
    			x2 = 340;		
    		}	
     
    		else if(RandomBox==2) 
    		{
    			x2 = 135;
    		}
     
    		else if(RandomBox==3) 
    		{
    			x2 = 405;
    		}
     
    		else if(RandomBox==4) 
    		{
    			x2 = 420;
    		}
     
    		else if(RandomBox==5) 
    		{
    			x2 = 375;
    		}
     
    		return x2;
    		}
     
    		public int y2Generator(int y2,Random randomGenerator,int RandomBox) {
     
    		RandomBox = randomGenerator.nextInt(5)+1;
    		if(RandomBox==1) 
    		{
    			y2 = 95;	
    		}	
     
    		else if(RandomBox==2) 
    		{
    			y2 = 400;
    		}
     
    		else if(RandomBox==3) 
    		{
    			y2 = 425;
    		}
     
    		else if(RandomBox==4) 
    		{
    			y2 = 170;
    		}
     
    		else if(RandomBox==5) 
    		{
    			y2 = 440;
    		}	
    		return y2;
    		}
     
     
    	public void paintComponent(Graphics g)
        	{
            super.paintComponent(g);
            tm.start();
     
    		g.setColor(Color.BLACK);
    		g.fillRect(x1, y1, w1, h1);
     
    		g.setColor(Color.RED);
    		g.fillRect(x2, y2, w2, h2);
    		}
     
     
    	public enum Direction 
    	{
    	NONE, UP, DOWN, LEFT, RIGHT
    	}
    	public void keyPressed(KeyEvent e) 
    	{
    	if(e.getKeyCode()==KeyEvent.VK_RIGHT) 
    	{
    		direction=Direction.RIGHT;
    		 w1=20;
    	   	 h1=10;
    	}
     
     
    	else if(e.getKeyCode()==KeyEvent.VK_LEFT) 
    	{
    		direction=Direction.LEFT;
    		w1=20;
    	        h1=10;
    	}
     
     
    	else if(e.getKeyCode()==KeyEvent.VK_UP) 
    	{
    		direction=Direction.UP;
    		w1=10;
    	        h1=20;
    	}
     
     
    	else if(e.getKeyCode()==KeyEvent.VK_DOWN) 
    	{
    		direction=Direction.DOWN;
    		w1=10;
    	        h1=20;
    	}
     
    	}
     
        public void keyTyped(KeyEvent e)
    	{
    	}
    	public void keyReleased(KeyEvent e)
    	{
        }
    	public void delay() 
    	{
    		try
    	{
    	Thread.sleep(50);
    	}
    	catch(Exception e)
    	{
    	}
     
    	}
     
    	public static void main (String args[]) 
    		{
        	Snakes obj = new Snakes();  
        	frame.setSize(500,500);
        	frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        	frame.setVisible(true);
        	frame.add(obj);     
        	}
    	public void actionPerformed(ActionEvent e)
    	{
    	//Reset position of Snake in x and y through frame
    	if(x1<0)
    	{
    		x1=490;
    	}
    	if(x1>490)
    		{ 
    			x1=0;
    		}
    	if(y1<0) 
    	{
    		y1=460;
    	}
    	if(y1>460)
    		{
    			y1=0;
     
    		}	
    	//Up, down, left, right
    	if(direction==Direction.RIGHT) 
    	{
    		x1=x1+5;
    		delay();
    	}
     
    	if(direction==Direction.LEFT) 
    	{
    		x1=x1-5;
    		delay();
    	}
     
    	if(direction==Direction.UP) 
    	{
    		y1=y1-5;
    		delay();
    	}
     
    	if(direction==Direction.DOWN) 
    	{
    		y1=y1+5;
    		delay();
    	}
    		//Snake tail and Random Box
    		if(y2+h2>=y1&&x2+w2>=x1&&x2<=x1+w1&&y2<=y1||y2<=0)
    		{
    		x2 = x2Generator(x2, randomGenerator, RandomBox);
    		y2 = y2Generator(y2, randomGenerator, RandomBox);
     
    		w1=w1+20;
    		ScoreLabel.setText("Score: "+score);
    		score = score +1;
    		}
    		repaint();
     
     
    }
    }
    Last edited by Totel; September 26th, 2012 at 07:56 AM.
    public class Newbie
    {
      public static void main (String args[])
      { 
     
    	for(int num=0;num<1;num=num+1)
    	{	
    	System.out.println("Dumb");
    	}
     
     
       }
    }

  24. #24
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,042
    Thanks
    63
    Thanked 2,708 Times in 2,658 Posts

    Default Re: [Snake]Help

    Try debugging the code by adding println statements that print out the values of the variables that are used to determine the size of the snake every time they are changed. The print out will show you where the code is doing the wrong thing.

    The variable names x1, x2 etc should be named for what they are used for: snakeX and foodX etc

    The variables for the snake should be:
    its width (a constant that does not change)
    its length (changes as food eaten)
    The paintComponent() method should use the above in the fillRect() method calls according to the direction the snake is moving.
    Last edited by Norm; September 26th, 2012 at 09:25 AM.
    If you don't understand my answer, don't ignore it, ask a question.

Similar Threads

  1. [Help] Snake algorithm
    By 123099 in forum Algorithms & Recursion
    Replies: 1
    Last Post: May 25th, 2012, 12:14 PM
  2. arraylists to store coordinates for a snake applet
    By finalfantasyfreak15 in forum What's Wrong With My Code?
    Replies: 5
    Last Post: February 19th, 2011, 10:21 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