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

Thread: Snake Game

  1. #1
    Junior Member
    Join Date
    Feb 2010
    Location
    Canada
    Posts
    25
    Thanks
    2
    Thanked 0 Times in 0 Posts

    Default Snake Game

    I'm working on creating a snake game for fun. I've got a rough version of it going now which is basically just the snake moving around and boxes appearing on the screen. I just revamped the whole thing so it's a lot better. I'm wondering what the best method is to decide how you tell if the player hits their tail? And also the best way to increase the size of the snake, right now the snake currently stays at 1 box since I haven't gotten that far?

    Also I need help figuring out how to get the tail to follow the path of the first cube, a lot more difficult than I first thought!

    /Edit

    Change the delay timer to make it quicker, it's slow atm for testing purposes

    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.awt.Toolkit.*;
    import java.util.*;
    import java.util.Random;
     
     
    public class SnakeGame extends JPanel
    implements KeyListener{	
     
     
     
    char shape = 'r';
    JLabel ScoreLabel;
    JPanel panel1;
    int RandomBox = 0;
    int BoxX = 145;
    int BoxY = 280;
    int SnakeX = 340;
    int SnakeY = 300;
    int direction = 0;
    int score = 0;
    Random randomGenerator = new Random();
     
     
    public SnakeGame() {
     
    setFocusable(true);
    addKeyListener(this);;	
     
     
    }
     
    public static void main(String args[]) {
     
    JFrame frame = new JFrame("Drawing Canvas");	
    SnakeGame canvas = new SnakeGame();
    canvas.makeGUI();
    frame.getContentPane().add(canvas);
    frame.setSize(700,700);
    frame.addWindowListener(new WindowAdapter(){
     
    	public void WindowClosing(WindowEvent e) {
    		System.exit(0);
    	}
    });
    frame.setVisible(true);
    }
     
    public void makeGUI() {	
     
    	panel1 = new JPanel();
     
     	ScoreLabel = new JLabel("Score: " + score);	
     
        panel1.add(ScoreLabel);   
     
        //add panels
        add(panel1);
     
     
    }
     
    public int BoxXGenerator(int BoxX,Random randomGenerator,int RandomBox) {
     
    RandomBox = randomGenerator.nextInt(5)+1;
     
    if(RandomBox==1) {
    	BoxX = 340;	
    }	
     
    else if(RandomBox==2) {
    	BoxX = 135;
    }
     
    else if(RandomBox==3) {
    	BoxX = 505;
    }
     
    else if(RandomBox==4) {
    	BoxX = 520;
    }
     
    else if(RandomBox==5) {
    	BoxX = 375;
    }
     
    return BoxX;
     
     
    }
     
    public int BoxYGenerator(int BoxY,Random randomGenerator,int RandomBox) {
     
    RandomBox = randomGenerator.nextInt(5)+1;
     
    if(RandomBox==1) {
    	BoxY = 95;	
    }	
     
    else if(RandomBox==2) {
    	BoxY = 400;
    }
     
    else if(RandomBox==3) {
    	BoxY = 425;
    }
     
    else if(RandomBox==4) {
    	BoxY = 170;
    }
     
    else if(RandomBox==5) {
    	BoxY = 560;
    }
     
    return BoxY;
     
     
    }
     
    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;
    }
     
     
    shape = e.getKeyChar();	
    repaint();
     
    }
     
    public void keyReleased(KeyEvent e) {
     
    }
     
    public void keyTyped(KeyEvent e) {
     
    }
     
    public void delay() {
     
    try{
    	Thread.sleep(100);
    }
    catch(Exception e){
    }
     
    }
     
    public void paintComponent(Graphics g) {
     
    g.setColor(Color.WHITE);
    Dimension d = getSize();
    g.fillRect(0,0, d.width, d.height);
     
    // g.translate(x,y);
     
    //each line is 520
     
    	g.setColor(Color.BLACK);
    //Top Border	
    	g.drawLine(80,80,600,80);
    //Right Border
    	g.drawLine(600,80,600,600);
    //Bottom Border
    	g.drawLine(600,600,80,600);
    //Left Border
    	g.drawLine(80,80,80,600);
     
    	// y-max is 600
    	// y-min is 80
    	// x-max is 600
    	// x-min is 80
     
    	//Reset position if X/Y goes past border
    	if(SnakeX<80){
    		SnakeX=600;
    	}
     
    	if(SnakeX>600){
    		SnakeX=80;
    	}
     
    	if(SnakeY<80) {
    		SnakeY=600;
    	}
     
    	if(SnakeY>600) {
    		SnakeY=80;
    	}
     
    	//Up, down, left, right
    	if(direction==1) {
    		SnakeX=SnakeX+5;	
    		repaint();
    		delay();
    	}
     
    	if(direction==2) {
    		SnakeX=SnakeX-5;	
    		repaint();
    		delay();
    	}
     
    	if(direction==3) {
    		SnakeY=SnakeY-5;
    		repaint();
    		delay();
    	}
     
    	if(direction==4) {
    		SnakeY=SnakeY+5;	
    		repaint();
    		delay();
    	}
     
     
     
    //Collision detection
    if(SnakeX==BoxX&&SnakeY==BoxY) {
     
     
    BoxX = BoxXGenerator(BoxX,randomGenerator,RandomBox);
    BoxY = BoxYGenerator(BoxY,randomGenerator,RandomBox);
    score = score + 1;
    ScoreLabel.setText("Score: "+score);
    }
     
     
    System.out.println(SnakeX + "," + SnakeY);
    g.fillRect(BoxX,BoxY,15,15);
    //Snake
    	g.setColor(Color.RED);
    	g.fillRect(SnakeX,SnakeY,15,15);
     
     
     
     
     
    }	
    }
    Last edited by Cuju; March 24th, 2010 at 11:21 PM.


  2. #2
    Super Moderator helloworld922's Avatar
    Join Date
    Jun 2009
    Posts
    2,896
    Thanks
    23
    Thanked 619 Times in 561 Posts
    Blog Entries
    18

    Default Re: Snake Game

    Looks nice

    I wrote a snake-like game a while back and used a doubly-linked list to keep track of all the points. I didn't use Java's LinkedList class, though. A simple node which can link backwards and forwards worked much better for me (there were several issues with the using Java's LinkedList).

    To check for collisions, You will have to compare the head to everything it could possibly collide with. There's not much you can do to get around this.

  3. #3
    Junior Member
    Join Date
    Feb 2010
    Location
    Canada
    Posts
    25
    Thanks
    2
    Thanked 0 Times in 0 Posts

    Default Re: Snake Game

    Quote Originally Posted by helloworld922 View Post
    Looks nice

    To check for collisions, You will have to compare the head to everything it could possibly collide with. There's not much you can do to get around this.
    Thank ya, and yeah that's what I thought I'd have to do ugh.

    Any suggestions on how to get the tails behind the lead cube to follow its path, this is my main concern atm?

  4. #4
    Super Moderator helloworld922's Avatar
    Join Date
    Jun 2009
    Posts
    2,896
    Thanks
    23
    Thanked 619 Times in 561 Posts
    Blog Entries
    18

    Default Re: Snake Game

    Yeah, using a queue is probably the easiest way. Simply add points on where would the head should be moving to. At the other end, you can remove points from the queue which represents where the tail was.

    I used my own doubly-linked node and managed the queue manually because I just couldn't find the performance I wanted in any of Java's API collections. However, I did have thousands to tens of thousands of points. If you limit how many points you have, it's probably possible to get away with Java's LinkedList.

  5. #5
    Member Faz's Avatar
    Join Date
    Mar 2010
    Posts
    97
    Thanks
    5
    Thanked 14 Times in 14 Posts

    Default Re: Snake Game

    Sounds interesting I will have to take a look at it later.

    I would think that maybe rather then have the whole snake move I would just move the head and delete the tail(the position where the head was is now part of the body). I guess the problem is how you define the tail I would think each part of the body would have a count down timer to when it dissapears when it does it will inevitably be the tail. This is how I think I would do it anyways. I'll have a proper read over the code when I'm not so busy.

  6. #6
    Junior Member
    Join Date
    Feb 2010
    Location
    Canada
    Posts
    25
    Thanks
    2
    Thanked 0 Times in 0 Posts

    Default Re: Snake Game

    Quote Originally Posted by helloworld922 View Post
    Yeah, using a queue is probably the easiest way. Simply add points on where would the head should be moving to. At the other end, you can remove points from the queue which represents where the tail was.

    I used my own doubly-linked node and managed the queue manually because I just couldn't find the performance I wanted in any of Java's API collections. However, I did have thousands to tens of thousands of points. If you limit how many points you have, it's probably possible to get away with Java's LinkedList.
    I'm still a java noob so my knowledge of that stuff is pretty much nothing.

    I'm having a hard time understanding how to get the the tail pieces to follow the heads path. I've tried storing the heads path as a seperate value then delaying when the tail is drawn so it looks like it's following the head... doesn't seem to work

  7. #7
    Junior Member
    Join Date
    Feb 2011
    Posts
    7
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Snake Game

    i'm also making a snake game and i've heard that i needed to use an arraylist to store the coordinates.

Similar Threads

  1. DOS board game
    By SageNTitled in forum Java Theory & Questions
    Replies: 5
    Last Post: March 4th, 2010, 02:53 PM
  2. Game 3x3
    By Koren3 in forum Algorithms & Recursion
    Replies: 1
    Last Post: December 20th, 2009, 07:43 PM
  3. invisible box game
    By new2java in forum Loops & Control Statements
    Replies: 1
    Last Post: September 27th, 2009, 12:46 PM
  4. Job offers to program Hobo Wars
    By MooncakeZ in forum Paid Java Projects
    Replies: 7
    Last Post: September 17th, 2009, 09:41 PM
  5. [SOLVED] Fixing of bug for Pong game
    By phoenix in forum What's Wrong With My Code?
    Replies: 11
    Last Post: July 14th, 2009, 01:19 PM