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

Thread: [Help] Snake algorithm

  1. #1
    Junior Member
    Join Date
    Jul 2011
    Posts
    23
    Thanks
    4
    Thanked 0 Times in 0 Posts

    Default [Help] Snake algorithm

    I've been making a snake game, and everything works, tho the algorythm of the snake movement isnt that good, but its fine.
    Now, I also have an apple on the screen, and the problem is i can't figure out a way to find if the snakes head & the apple have even 1 common point.

    this is the code of the screen & apple:

    Screen:
    /*
     * To change this template, choose Tools | Templates
     * and open the template in the editor.
     */
    package Snake;
     
    import Tools.ThreadTool;
    import java.awt.*;
    import java.awt.event.KeyEvent;
    import java.awt.event.KeyListener;
    import java.util.*;
    import javax.swing.*;
     
    /**
     *
     * @author User
     */
    public class Screen extends JFrame implements Runnable,KeyListener{
    private int difficulty;    
    private int direction; //0-up 1- down 2-left 3- right
     
    private Thread t;
     
    private ArrayList<Integer> snakeX,snakeY;
     
    private panel panel;
     
    private int w,h;
     
    private Apple apple;
     
        public Screen(int difficulty,int sW,int sH){
            super("Snake");
            this.difficulty = difficulty;
     
            this.setDefaultCloseOperation(EXIT_ON_CLOSE);
            this.setSize(sW, sH);
            this.setLocationRelativeTo(null);
     
            snakeX = new ArrayList<Integer>();
            snakeY = new ArrayList<Integer>();
     
            //set width and height of snake
            w = sW/40;
            h=w;
     
            //add head
            snakeX.add(this.getWidth()/2);
            snakeY.add(this.getHeight()/2);
     
            direction = (int)(Math.random()*4);
     
            apple = new Apple(this, w, h);
            apple.generateApple();
     
            panel = new panel();
            panel.setBackground(new Color(0, 153, 51)); //dark green
            add(panel);
     
            this.addKeyListener(this);
        }
     
        @Override
        public void run() {
            while(isAlive()){ // change to alive
                    for(int i=snakeX.size();i>1 && snakeX.size() == snakeY.size();i--){
                        snakeX.set(i-1, snakeX.get(i-2));
                        snakeY.set(i-1, snakeY.get(i-2));
                    }
     
                    if(direction==0){
                        snakeY.set(0, snakeY.get(0)-h);
                        if(/*snakeX.get(0) == apple.getX() && */snakeY.get(0) == apple.getY())
                        {
                            snakeX.add(snakeX.get(snakeX.size()-1));
                            snakeY.add(snakeY.get(snakeY.size()-1)+h);
                        }
                    }
                    else if(direction==1)
                        snakeY.set(0, snakeY.get(0)+h);
                    else if(direction==2)
                            snakeX.set(0, snakeX.get(0)-w);
                    else if(direction==3)
                        snakeX.set(0, snakeX.get(0)+w);
     
     
                repaint();
                ThreadTool.sleep(t, 300/(difficulty+1));
            }
        }
     
        public void startThread(){
            t = new Thread(this);
            t.start();
        }
     
        private boolean isAlive(){
            return snakeX.get(0)>=0 && snakeX.get(0)+w<=this.getWidth() && snakeY.get(0)>=0 && snakeY.get(0)+h<=this.getHeight();
        }
     
        @Override
        public void keyTyped(KeyEvent e) {
        }
     
        @Override
        public void keyPressed(KeyEvent e) {
            if(e.getKeyCode()==KeyEvent.VK_RIGHT && direction != 2)
                direction=3;
            else if(e.getKeyCode()==KeyEvent.VK_LEFT && direction !=3)
                direction = 2;
            else if(e.getKeyCode()==KeyEvent.VK_UP && direction!=1)
                direction=0;
            else if(e.getKeyCode()==KeyEvent.VK_DOWN && direction!=0)
                direction = 1;
        }
     
        @Override
        public void keyReleased(KeyEvent e) {
        }
     
        class panel extends JPanel{
            public void paintComponent(Graphics g){
                super.paintComponent(g);
                apple.drawMe(g);
                for(int i=0;i<snakeX.size() && snakeX.size() == snakeY.size();i++){
                    g.setColor(Color.green);
                    g.fillRect(snakeX.get(i), snakeY.get(i), w, h);
                    g.setColor(Color.black);
                    g.drawRect(snakeX.get(i), snakeY.get(i), w, h);
                    System.err.println("painting at " + snakeX.get(i) + ", " + snakeY.get(i)+","+i);
                }
            }
        }
    }

    Apple:
    /*
     * To change this template, choose Tools | Templates
     * and open the template in the editor.
     */
    package Snake;
     
    import java.awt.Color;
    import java.awt.Graphics;
     
    /**
     *
     * @author User
     */
    public class Apple {
    private Screen screen;
    private int x,y;
    private int w,h;
     
        public Apple(Screen screen,int w,int h){
            this.screen = screen;
            this.w = w;
            this.h = h;
        }
     
        public void generateApple(){
            x = (int)(Math.random()*( (screen.getWidth() - w) - 0 + 1) + 0);
            y=(int)(Math.random()*( ( screen.getHeight() - h) - 0 + 1) + 0);
        }
     
        public void drawMe(Graphics g){
            g.setColor(Color.red);
            g.fillRect(x, y, w, h);
            g.setColor(Color.black);
            g.drawRect(x, y, w, h);
        }
     
        public int getX(){
            return x;
        }
     
        public int getY(){
            return y;
        }
    }


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

    Default Re: [Help] Snake algorithm

    Considering that Apple is just a rectangle, I would suggest you revise your Apple class to extend the Rectangle class (Rectangle (Java Platform SE 6)). The Graphics2D class then has 2 methods, one called draw(Shape), and another called fill(Shape). Rectangle implements the Shape Interface, and since Apple would extend Rectangle, you can send either of those two methods an Apple Object. Then, since Apple extends Rectangle, you can call one of its 4 contains() methods on Apple and send it the coordinates (or Point) of the snake's head. Those methods would return a boolean, indicating that the snake's head is somewhere inside the bounds of the Apple.

    Alternatively, you could not extend the Rectangle class and instead write your own contains() method inside your Apple class that accepts an X and Y as its arguments and returns a boolean. The bounds of your Apple is x to x+w and y to y+h (according to the drawRect() method of the Graphics class). If X is between (or equal to) x and x+w AND Y is between (or equal to) y and y+h, the method would return true. Otherwise, it would return false.
    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/

Similar Threads

  1. 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
  2. Snake Game
    By Cuju in forum What's Wrong With My Code?
    Replies: 6
    Last Post: February 19th, 2011, 08:31 PM
  3. Snake Game In Java
    By Shyamz1 in forum What's Wrong With My Code?
    Replies: 2
    Last Post: February 10th, 2011, 10:00 AM
  4. Creating a java program to "Beat" Snake web app?
    By AkOndray in forum AWT / Java Swing
    Replies: 2
    Last Post: December 5th, 2010, 12:36 AM
  5. Snake game in java
    By freaky in forum Object Oriented Programming
    Replies: 0
    Last Post: April 19th, 2010, 11:04 AM