Page 1 of 2 12 LastLast
Results 1 to 20 of 21
  1. #1
    Join Date
    Mar 2009
    Posts
    13
    Rep Power
    0

    Default How to make my snake grow?

    Hi everyone!
    I´m currently working on a snake game. But i got 1 problem too deal with. When the snake is moving and the body comes along, it´s suppose to erase the last body peace and place it where the head just been. How am I suppose do to that?
    Here is the code:
    Main:
    Java Code:
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    
    public class GregerSnake extends JFrame{
    private Board field = new Board();
    private JButton[] button = new JButton[4];
    private String[] buttonText ={"New Game","Menu","Com", "Cancel"};
    private JButton info;
    private JPanel u, downPanel;
    private JLabel o;      //o är titeln
    
        public GregerSnake(){
    
            u = new JPanel();
            downPanel = new JPanel();
            downPanel.setBackground(Color.lightGray);
            u.setBackground(Color.lightGray);
    
            o = new JLabel("GregerSnake");
            o.setFont(new Font("Arial", Font.BOLD, 40));
            u.add(o);
            
            MyListener myL = new MyListener();
    
            for(int i=0;i<button.length;i++){
                button[i] = new JButton();
                button[i].setText(buttonText[i]);
                button[i].addActionListener(myL);
                u.add(button[i]);
            }
    
            info = new JButton();
            info.setText("Info");
            info.addActionListener(myL);
            downPanel.add(info);
    
            Container c = getContentPane();
            c.add(u, BorderLayout.NORTH);
            c.add(field, BorderLayout.CENTER);
            c.add(downPanel, BorderLayout.SOUTH);
    
            field.startGame();
        }
    
        class MyListener implements ActionListener{
            public void actionPerformed(ActionEvent ae){
                field.requestFocus();
                if(ae.getSource() == button[0]){
                    field.newGame();
                }
                else if(ae.getSource() == button[1]){
                //    field.startMenu();
                }
                else if(ae.getSource() == button[2]){
                    field.killCom();
                }
                else if(ae.getSource() == button[3]){
                    System.exit(0);
                }
                else if(ae.getSource() == info){
                    System.out.println("INFO");
                }
            }
        }
    
        public static void main(String[] args) {
            GregerSnake gt = new GregerSnake();
    	gt.setVisible(true);
            gt.setSize(586, 585);
            gt.setTitle("GregerSnake");
    	gt.setDefaultCloseOperation(EXIT_ON_CLOSE);
            gt.setResizable(false);
            gt.setLocationRelativeTo(null);
        }
    
    }
    And the board:
    Java Code:
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    
    public class Board extends JPanel implements ActionListener{
    Timer time = new Timer(150, this);  //Timern
    private int x, y, xq, yq, xa, ya;   //Ormen, datorn, päronet.
    private int yMax = 460;
    private int xMax = 580;
    private int antal;            //Antal päron.
    private int s = 20;           //Storlek och steglängd'
    private int[] xR = new int[25];     //Bredden *20.
    private int[] yR = new int[23];     //Längden *20.
    private boolean rand;
    private int l;
    private boolean[][] fieldP = new boolean[xR.length*24][yR.length*24];
    private static boolean up, right, left, down, comSnake;
    
        public void add(){
            antal++;
          //      fieldP[x-20][y+20] = true;
        }
    
        public void newGame(){
            time.stop();
            setFalse();
            x = 240;
            y = 280;
            xq = 300;
            yq = 420;
            antal = 0;
            random();
            up = false;
            right = false;
            left = false;
            down = false;
            comSnake = true;
            time.start();
        }
    
        public void killCom(){
            if(comSnake == true){
                comSnake = false;
            }
            else if(comSnake == false){
                comSnake = true;
            }
        }
    
        public void comSnake(){
            if(comSnake == true){
                if(xq > xa){            //Vänster
                    if(xMax-xq+xa < xq-xa){
                        if(xq+s >= xMax){
                            xq = -20;
                        }
                        xq = xq+s;
                    }
                    else{
                        xq = xq-s;
                    }
                }
    
                else if(xq < xa){       //Höger
                    if(xq+(xMax-xa) < xa-xq){
                        if(xq-s <= -20){
                            xq = xMax;
                        }
                        xq = xq-s;
                    }
                    else{
                    xq = xq+s;
                    }
                }
    
    
                else if(yq < ya){       //Nedåt
                    if(yq+(yMax-ya) < ya-yq){
                        if(yq-s < -20){
                            yq = yMax;
                        }
                        yq = yq-s;
                    }
                    else{
                        yq = yq+s;
                    }
                }
    
                else if(yq > ya){   //Uppåt
                    if(yMax-yq+ya < yq-ya){
                        if(yq+s > yMax){
                            yq = -20;
                        }
                        yq = yq+s;
                    }
                    else{
                        yq = yq-s;
                    }
                }
            }
        }
    
        public void eat(){
            if(xa == x && ya == y){
                add();
                System.out.println(antal);
                random();
            }
            else if(xq == xa && yq == ya){
                random();
            }
        }
    
        public void random(){
            rand = true;
            while(rand == true){
                xa = xR[(int)(Math.random() * 24 + 1)];
                ya = yR[(int)(Math.random() * 22 + 1)];
                if(fieldP[xa][ya] == false){
                    rand = false;
                }
            }
        }
    
        public void last(){
            l = 0;
            for(int m=0; m<xR.length*24; m++){
               for(int n=0; n<yR.length*24; n++){
                    if(fieldP[m][n] == false){
                        l++;
                    }
               }
            }
        }
    
        public void setFalse(){
            for(int m=0; m<xR.length*24; m++){
                for(int n=0; n<yR.length*24; n++){
                    fieldP[m][n] = false;
                }
            }
            fieldP[240][300] = true;
            fieldP[240][320] = true;
            fieldP[240][340] = true;
        }
    
        public void startGame(){
            time.start();
          //  newGame();
    
            for(int i=0; i<xR.length; i++){
                xR[i] = i*20;
                for(int m=0; m<yR.length; m++){
                    yR[m] = m*20;
                }
            }
            newGame();
            random();
    
            addKeyListener(new KeyAdapter(){
                public void keyPressed(KeyEvent e){
                    if((e.getKeyCode() == KeyEvent.VK_UP) && !down){
                           left = false;
                           right = false;
                           up = true;
                    }
                    else if((e.getKeyCode() == KeyEvent.VK_DOWN) && !up){
                            left = false;
                            right = false;
                            down = true;
                    }
                    else if((e.getKeyCode() == KeyEvent.VK_LEFT) && !right){
                            up = false;
                            down = false;
                            left = true;
                    }
                    else if((e.getKeyCode() == KeyEvent.VK_RIGHT) && !left){
                            right = true;
                            up = false;
                            down = false;
                    }
                    else if(e.getKeyCode() == KeyEvent.VK_C){
                        killCom();
                    }
                repaint();
                }
            });
        }
    
        public void actionPerformed(ActionEvent e){
            fieldP[x][y] = true;
            if(up == true){           //Uppåt
                if(y-s <= -20){
                    y = yMax;
                }
                y = y-s;
            }
            else if(right == true){    //Höger
                if(x+s >= xMax){
                    x = -20;
                }
                x = x+s;
            }
            else if(left == true){      //Vänster
                if(x-s <= -20){
                    x = xMax;
                }
                x = x-s;
            }
            else if(down == true){     //Neråt
                if(y+s >= yMax){
                    y = 0;
                }
                y = y+s;
            }
            
            comSnake();     //Datorn
            eat();          //Kollar om den äter ett päron
            repaint();
        }
    
        @Override public void paintComponent(Graphics g){
            super.paintComponent(g);
            g.setColor(Color.red);
            g.fillRect(x, y, s, s);
            g.setColor(Color.orange);
          //  for(int i=0; i<antal; i++){
                for(int m=0; m<xR.length*24; m++){
                    for(int n=0; n<yR.length*24; n++){
                        if(fieldP[m][n] == true){
                            g.fillRect(m, n, s, s);
                        }
                    }
                }
           // }
            g.setColor(Color.green);
            g.fillRect(xa, ya, s, s);
            g.setColor(Color.magenta);
            g.fillRect(xq, yq, s, s);
        }
     }
    Thanks!

  2. #2
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    26

    Default

    That's an awful lot of code to ask volunteers to go through, and this may be preventing you from getting a timely answer. You may wish to simplify your problem a bit.

  3. #3
    zweibieren is offline Senior Member
    Join Date
    Aug 2009
    Location
    Pittsburgh, PA
    Posts
    284
    Rep Power
    6

    Default How to make snake not grow

    It looks like the snake will always get longer. To delete the last piece of the snake the program must know where it is. This could be done by searching for the end of the snake. Better would be to consult a record of the places the snake occupies.

    One way to remember the snake is to store each added cell onto a queue. Then when it is time to delete the end of the snake, the first cell on the queue is the cell to delete. The queue might be declared as
    ArrayDeque<Point> q = new ArrayDeque<Point>();
    and then a new cell would be added with
    q.add(newPoint(x,y));
    and the cell to delete is
    Point victim = q.remove();

  4. #4
    Join Date
    Mar 2009
    Posts
    13
    Rep Power
    0

    Default

    I´ve never used an Array like that before, do you know any tutorial or can you help and explain it to me? Thanks!

  5. #5
    zweibieren is offline Senior Member
    Join Date
    Aug 2009
    Location
    Pittsburgh, PA
    Posts
    284
    Rep Power
    6

    Default

    Googling "deque tutorial java" gave lots of hits.
    One of the useful ones is A tutorial on Queues (with examples and Java code)

    In the case above, the ArrayDeque is being used entirely as a queue. Items are inserted at one end and removed from the other. Thus appears come out in the same order they went in. The entire snake at any given time is in the queue. After inserting a new element at the "add" end of the queue, the last element can gotten from the "remove" end of the queue.

  6. #6
    Join Date
    Mar 2009
    Posts
    13
    Rep Power
    0

    Default

    I've been looking in some tutorials, thanks! It's been useful! But I'm not sure exactly how I should use deque to do it? How am I suppose to know which one is the last peace of the snake?

  7. #7
    zweibieren is offline Senior Member
    Join Date
    Aug 2009
    Location
    Pittsburgh, PA
    Posts
    284
    Rep Power
    6

    Default

    Don't worry about "deque" concepts. Just use ArrayDeque as a queue.
    Use the add() and remove() methods.

    How am I suppose to know which one is the last peace of the snake?
    As it begins, the program will one-by-one insert each piece of snake
    onto the board. It should do this starting with the tail end of the snake.
    As each piece is inserted, it goes into the queue with add().

    Whenever the program inserts a new piece of snake on the front,
    it goes into the queue with add().
    Now the queue is in order with the oldest piece of snake at the front.
    Whenever the program wants to take a piece off the tail of the snake,
    all it has to do is take the first piece emerging from the queue with remove().

  8. #8
    Join Date
    Mar 2009
    Posts
    13
    Rep Power
    0

    Default

    Doesn't it need to be an 2 dimensional array in the queue? I mean, the position must have 1 y-worth and 1 x-worth?

  9. #9
    zweibieren is offline Senior Member
    Join Date
    Aug 2009
    Location
    Pittsburgh, PA
    Posts
    284
    Rep Power
    6

    Default

    Think. Isn't there some sort of object you could store in the queue that would hold an x and a y value? (BTW, Deque requires that its elements be objects.)

    I hope this message is to the Point :D

  10. #10
    Join Date
    Mar 2009
    Posts
    13
    Rep Power
    0

    Default

    I guess that I´m asking for more help than I would :P But I have no idea of how to use Point. I´ve tried to work it out. Heeelp (a)

  11. #11
    zweibieren is offline Senior Member
    Join Date
    Aug 2009
    Location
    Pittsburgh, PA
    Posts
    284
    Rep Power
    6

    Default

    Java Code:
    // import the Point class
    import java.awt.Point;
    
    // storing x and y into the queue:
    Point p = new Point (x,y);
    queue.add(p);
    
    ...
    // retrieving x and y from the queue:
    Point t = (Point)queue.remove();
    x = t.x;
    y = t.y;
    Now do you get the Point ?-)

  12. #12
    Join Date
    Mar 2009
    Posts
    13
    Rep Power
    0

    Default

    Yeah I think so :D So many thanks!!

  13. #13
    Join Date
    Mar 2009
    Posts
    13
    Rep Power
    0

    Default

    Do I need a new sign for each Point I save? Is there a smart way to keep control over them all, if I have like 30 Points saved?

  14. #14
    zweibieren is offline Senior Member
    Join Date
    Aug 2009
    Location
    Pittsburgh, PA
    Posts
    284
    Rep Power
    6

    Default

    Questions:
    Do I need a new sign for each Point I save?
    Is there a smart way to keep control over them all,
    if I have like 30 Points saved?
    Answers: no and yes, but why?

    As it removes a Point from the queue,
    the code could shove it on another.
    Then when a new Point is needed,
    it can be snatched from that second queue.

    "But why?"
    The coding effort to introduce an optimization
    will far exceed any savings from using cached data.

    In general:
    • Optimize only after poor performance is apparent.

    (That is, do as I say and not as I do. Sigh.)

  15. #15
    Join Date
    Mar 2009
    Posts
    13
    Rep Power
    0

    Default

    You know. I exually think I understands the thing. Can´t say how thankful I´m. But.. how can I create more Point variables? Musn´t all the Point be created in the beginning (private Point g = New Point(); ) ?

  16. #16
    zweibieren is offline Senior Member
    Join Date
    Aug 2009
    Location
    Pittsburgh, PA
    Posts
    284
    Rep Power
    6

    Default

    An object value can be created at any time, not just in a declaration.
    One might write: new Point(5,3).x = 7;
    This creates a point, initializes its fields to 5 and 3, resets the x value to 7,
    and then forgets about the whole thing.
    One can write
    Java Code:
                ArrayDeque<Point> points = new ArrayDeque<Point>();
                ...
                points.add(new Point(6,7));
    which creates a Point and pushes it onto a queue from which it can later be retrieved.
    Through the magic of the garbage collector,
    the Point will remain in memory as long as it can be accessed from a variable,
    and not too much longer.

  17. #17
    Join Date
    Mar 2009
    Posts
    13
    Rep Power
    0

    Default

    In order too be able too use ArrayDeque, you most declar import java.util.*; (?). But when I add the contenst an error messages on the line with the Timer adds up..?

  18. #18
    zweibieren is offline Senior Member
    Join Date
    Aug 2009
    Location
    Pittsburgh, PA
    Posts
    284
    Rep Power
    6

    Default

    Just import java.util.ArrayDeque.

    There are Timer classes in java.util, javax.swing, javax,management.timer, and sun.misc.
    The code should probably be written to refer explicitly to one of these. e.g.,
    javax.swing.Timer myTimer = new javax.swing.Timer(delay, listener);

  19. #19
    Join Date
    Mar 2009
    Posts
    13
    Rep Power
    0

    Default

    I can´t really say how grateful I am. Just 1 little little last thing. Think this is the last in the puzzel. Lets say the body is 5 pieces long, how do I g.fillRect(x, y, s, s); all of them?

  20. #20
    zweibieren is offline Senior Member
    Join Date
    Aug 2009
    Location
    Pittsburgh, PA
    Posts
    284
    Rep Power
    6

    Default

    ArrayDeque has methods to traverse the queue without removing elements.

Page 1 of 2 12 LastLast

Similar Threads

  1. Make it just A, Help me please
    By yuuchan in forum New To Java
    Replies: 3
    Last Post: 04-25-2009, 03:09 PM
  2. How to make a function?
    By mephisto772 in forum New To Java
    Replies: 5
    Last Post: 02-23-2009, 10:51 AM
  3. Snake game movement
    By BeerMonkey in forum New To Java
    Replies: 9
    Last Post: 11-27-2008, 01:48 PM
  4. How do you make a jar file
    By alex_cunningham in forum New To Java
    Replies: 3
    Last Post: 07-15-2008, 04:56 AM
  5. How to grow an array
    By Java Tip in forum java.lang
    Replies: 0
    Last Post: 04-14-2008, 09:49 PM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •