Creating Snake using Java

11,104

Solution 1

To answer your postscript, set a background color or make a JPanel behind everything else with a painted color.

To progress with the project, consider making it an exercise in the MVC framework. What is happening now is that your Model and View are linked in the same class - this makes it hard to follow the logic behind everything.

What you can do is first separate your Snake from anything to do with the view - make a snake with an ArrayList<Integer[]> segmentLocations or something, to represent the (x,y) of each of the segment locations on a board that you define - you can use absolute coordinates or you can make an arbitrary grid and change to absolute coordinates in your View (this typifies the MVC relationship better). Snake should also have a field for the direction the snake is facing - I would use an enum Direction {N, S, E, W}, but you have options on that, as you could also have an integer representing direction, or a variety of other ways.

Your Snake would then also have ways to update itself - move(), shifting the location of all of the segments based on the current direction for the initial segment and causing all of the other segments to follow the movement of the one before it (this is pretty easy if you consider it for a couple of minutes).

Your view could be a JFrame with a GridLayout consisting of JPanels which poll your Snake instance and see if there is a segment in the location and if so, draw it, or a multitude of other options.

Your controller would be the KeyAdapter that sends the updates in direction to your Snake when the arrow keys are pressed.

Small hint, to make your life easier: when you add a new segment, just have it at the location of the last segment of the Snake. The next time it moves, the new segment will be in the same location, and the rest of the Snake should have move accordingly.

Solution 2

Your paintComponent(...) only draws one rectangle. Instead if you want to draw multiple rectangles or ovals, or whatever, give your class a List<Point> or List<Rectangle2D>, and in your Swing Timer, remove the tail from the list and add a new head. then have paintComponent() use a for loop to iterate through a list, drawing all the rectangles held by the list.

Also you will probably want to use key bindings rather than a KeyListener to get the user's key presses as this will work better when other components steal the focus.

Solution 3

Given a class defining a segment's geometry,

class Segment {
    private int x, y, d;

    public Segment(int x, int y, int r) {
        this.x = x - r;
        this.y = y - r;
        this.d = 2 * r;
    }
}

Consider a queue of segments,

Queue<Segment> snake = new LinkedList<Segment>();

Then each iteration is simply

snake.remove();
snake.add(new Segment(...));

And paintComponent() includes this loop

@Override
public void paintComponent(Graphics g) {
    ...
    for (Segment s : snake) {
        g.fillXxxx(s.x, s.y, s.d, s.d);
    }
    ...
}
Share:
11,104
corecase
Author by

corecase

Updated on October 02, 2022

Comments

  • corecase
    corecase over 1 year

    I decided to re-create Snake using Java, but I'm sort of stuck. At the moment, I have a square that the user can move around the screen using the arrow keys. When you press LEFT once, the square begins to move left using a timer.. You don't need to hold down the key or keep pressing it; it changes direction when you press any of the other keys that are set(Right, Up, Down). My goal is to use an ArrayList to hold the squares that make up the snake. At the moment, I've created an ArrayList with just one Snake object inside, if I add a second Snake object to the list and add it to the frame(with the first), only one Snake object is visible and the keys to move it don't function. I'm looking for some ideas as to how I can progress with this project - please don't give me the full answer, because I'd like to figure out most of it on my own; I just need some direction. Thanks in advance - code is below.

    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    
    public class Snake extends JPanel implements KeyListener, ActionListener
    {
    int x = 0, y = 0, velx = 0, vely = 0;
    Timer t = new Timer(250, this);
    
    
    public Snake(int num1, int num2)
    {
        t.start();
        addKeyListener(this);
        setFocusable(true);
        setFocusTraversalKeysEnabled(true);
        x = num1;
        y = num2;
    }
    public void paintComponent(Graphics g)
    {   
        super.paintComponent(g);
    
        g.setColor(Color.blue);
        g.fillRect(x, y, 20, 20);
    }
    public void actionPerformed(ActionEvent e)
    {
        repaint();
        x += velx;
        y += vely;
    }
    public void up()
    {
        vely = -20;
        velx = 0;
    }
    public void down()
    {
        vely = 20;
        velx = 0;
    }
    public void left()
    {
        vely = 0;
        velx = -20;
    }
    public void right()
    {
        vely = 0;
        velx = 20;
    }
    public void keyPressed(KeyEvent e)
    {
        int code = e.getKeyCode();
    
        if(code == KeyEvent.VK_UP)
            up();
        else if(code == KeyEvent.VK_DOWN)
            down();
        else if(code == KeyEvent.VK_RIGHT)
            right();
        else if(code == KeyEvent.VK_LEFT)
            left();
    
    }
    public void keyReleased(KeyEvent e)
    {
    
    }
    public void keyTyped(KeyEvent e)
    {
    
    }
    }
    //Driver Class
    import javax.swing.*;
    import java.awt.event.*;
    import java.awt.*;
    import java.util.*;
    
    public class UserClass
    {
    private static JFrame frame = new JFrame("Snake");
    private static ArrayList<Snake> mySnake = new ArrayList<Snake>();
    
    public static void main(String[] args)
    {
        frame.setSize(500,500);
        frame.setBackground(Color.black);
        frame.setVisible(true);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    
        mySnake.add(new Snake(20,20));
        frame.add(mySnake.get(0));
    }
    }
    

    P.S When I put this same exact code in Eclipse on my Mac, the background of my frame is black, but on Windows it's light gray... Anyone know why? Thanks.

  • corecase
    corecase almost 12 years
    Thanks a lot; that definitely helped clarify things.
  • corecase
    corecase almost 12 years
    Wouldn't the instance variables x, y, d within the Segment class have to be public for this to work? Since paintComponent is accessing those varibles?
  • Michael
    Michael almost 12 years
    Just make a get method for each variable if you don't like having public data members. (getX() etc.)
  • trashgod
    trashgod almost 12 years
    Yes, the original was private static Segment. See also Bloch, Effective Java, 2nd ed, "Item 13: Minimize the accessibility of classes and members."