Results 1 to 6 of 6

Thread: Snake Game

  1. #1
    FrankElliot9 is offline Member
    Join Date
    Nov 2012
    Posts
    3
    Rep Power
    0

    Default Snake Game

    Hello everybody,

    I am working on a program where I need to create a "Snake Game" program, a game where the snake grows steadily with time and the player must keep the snake from colliding with itself or a wall. I have been given three java class files to begin with, listed below:

    Java Code:
     import java.awt.Color;
    import java.awt.Font;
    import java.awt.FontMetrics;
    import java.awt.Graphics;
    import java.awt.Image;
    import java.awt.Toolkit;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.awt.event.KeyAdapter;
    import java.awt.event.KeyEvent;
    import java.util.ArrayList;
    
    import javax.swing.ImageIcon;
    import javax.swing.JOptionPane;
    import javax.swing.JPanel;
    import javax.swing.Timer;
    
    /**
     * The main game class that reads user input,
     * maintains a snake and updates game board
     * 
     *
     **/
    public class MainGame implements ActionListener {
    
    	// size of the game board (30 * 30 by default)
    	private final int WIDTH = 30;
    	private final int HEIGHT = 30;
    	
    	private final int Init_Snake_Length = 5;
    	
    	// delay of detecting user input ( in milliseconds )
    	private final int DELAY = 100;
    	
    	// grow the snake every GROWTH_INTERVAL milliseconds
    	private final int GROWTH_INTERVAL = 5000;
    	// move the snake every MOVE_INTERVAL milliseconds
    	private final int MOVE_INTERVAL = 500;
    	
    	// The snake (as a list of coordinates in the 2D board array)
    	private ArrayList<Coordinate> snake;
    	
    	// The game board object - read GameBoard.java
    	private GameBoard board; 
    	
    	// Flag variables indicating which direction is chosen
    	// by user. Only one of the four can be true at any moment
    	private boolean left = false;
    	private boolean right = true;
    	private boolean up = false;
    	private boolean down = false;
    
    	private Timer timer;
    	private long growCounter;
    	private long moveCounter;
    	
    	public MainGame() {
    		board = new GameBoard(WIDTH, HEIGHT);
    		initGame();
    		board.addKeyListener(new TAdapter());
    	}
    	
    	public static void main(String[] argv) {
    		MainGame mg = new MainGame();
    	}
    	
    	public void initGame() {
    		snake = new ArrayList<Coordinate>();
    		
    		// -------------------------------------------------------------
    		// Task 1: Initiate the snake to the center of the board
    		// by filling in the coordinates
    		//
    
    		
    		
    		// Task 1 end
    		// -------------------------------------------------------------
    		
    		board.updateSnake(snake);
    		
    		timer = new Timer(DELAY, this);
    		timer.start();
    		growCounter = 0;
    		moveCounter = 0;
    		
    		left = false;
    		right = true;
    		up = false;
    		down = false;		
    	}
    	
    	private void moveSnake() {
    
    		// -------------------------------------------------------------
    		// Task 2: Move the snake by updating the list of coordinates properly
    		// The direction to move to is given by the four flag variables (left, right, up, down)
    		//
    
    		
    		// Task 2 end
    		//--------------------------------------------------------------
    
    	}	
    	
    	private void growSnake() {
    		// -------------------------------------------------------------
    		// Task 3: Grow the snake by updating the list of coordinates properly
    		//
    
    		
    		
    		// Task 3 end
    		//--------------------------------------------------------------
    	}
    
    
    	private void checkCollision() {
    		boolean collision = false;
    		
    		// -------------------------------------------------------------
    		// Task 4: Insert code here to detect collision
    		//
    
    		
    		
    		// Task 4 end
    		//--------------------------------------------------------------		
    		
    		
    		if (collision) {
    			gameOver();
    		}
    	}
    	
    	private void gameOver() {
    		JOptionPane.showMessageDialog(board, "Game Over");
    		System.exit(0);
    	}
    	
    	/**
    	 * The actions to be performed every DELAY milliseconds
    	 */
    	public void actionPerformed(ActionEvent e) {
    		
    		if ( ++growCounter * DELAY >= GROWTH_INTERVAL) {
    			growSnake();
    			growCounter = 0;
    		} 
    		if ( ++moveCounter * DELAY >= MOVE_INTERVAL) {
    			moveSnake();
    			moveCounter = 0;
    		}
    
    		checkCollision();
    		board.resetBoard();
    		board.updateSnake(snake);
    		board.repaint();
    
    	}
    
    
    	/**
    	 * A key listener class for reading user's input.
    	 * 
    	 *
    	 */
    	private class TAdapter extends KeyAdapter {
    
    		public void keyPressed(KeyEvent e) {
    
    			int key = e.getKeyCode();
    
    			if ((key == KeyEvent.VK_LEFT) && (!right)) {
    				left = true;
    				up = false;
    				down = false;
    			}
    
    			if ((key == KeyEvent.VK_RIGHT) && (!left)) {
    				right = true;
    				up = false;
    				down = false;
    			}
    
    			if ((key == KeyEvent.VK_UP) && (!down)) {
    				up = true;
    				right = false;
    				left = false;
    			}
    
    			if ((key == KeyEvent.VK_DOWN) && (!up)) {
    				down = true;
    				right = false;
    				left = false;
    			}
    		}
    	}
    }
    Java Code:
     import java.awt.Color;
    import java.awt.Frame;
    import java.awt.Graphics;
    import java.awt.Toolkit;
    import java.awt.event.WindowAdapter;
    import java.awt.event.WindowEvent;
    import java.util.ArrayList;
    
    /**
     * This class represents the board of the snake game
     * and is responsible for drawing the board in graphical
     * mode
     * 
     *
     */
    public class GameBoard extends Frame {
    
    	private static final long serialVersionUID = 1L;
    
    	// Lists all possible types of a board item. You can add more types 
    	// such as SNAKE_HEAD or SNAKE_TAIL if you want to extend the drawing part
    	public enum BoardItem { SNAKE_PART, EMPTY };
    
    	// width & height of the board ( number of cells in 2D array. not actual number of pixels displayed)
    	private int WIDTH;
    	private int HEIGHT;
    	
    	// the 2D array to store the current board information
    	private BoardItem[][] board;
    	
    	private final int PieceSize = 10;
    	private final Color SnakeColor = Color.green;
    	
    	public GameBoard( int WIDTH, int HEIGHT ) {
    		super("COMP 110 - Snake");
    		this.WIDTH = WIDTH;
    		this.HEIGHT = HEIGHT;
    		board = new BoardItem[WIDTH][HEIGHT];
    		this.resetBoard();
    		this.setBackground(Color.black);
    		this.setFocusable(true);
    
    		this.setSize(WIDTH * PieceSize, HEIGHT * PieceSize);
    		this.setVisible(true);
    		this.setLocationRelativeTo(null);
    		this.addWindowListener(new WindowAdapter(){
    			  public void windowClosing(WindowEvent we){
    				  System.exit(0);
    			  }
    			  });
    	
    		this.setResizable(false);
    	}
    	
    	/**
    	 * reset the whole board to empty (without snake)
    	 */
    	public void resetBoard() {
    		for (int i = 0; i<WIDTH; i++)
    			for(int j = 0; j<HEIGHT; j++)
    				board[i][j]	 = BoardItem.EMPTY;
    	}
    	
    	/**
    	 * set one cell of the board to be one of the board item ( SNAKE_PART or EMPTY )
    	 * @param x board cell coordinate X
    	 * @param y board cell coordinate X
    	 * @param i board item type (BoardItem.SNAKE_PART or BoardItem.EMPTY)
    	 */
    	private void setBoardItem( int x, int y, BoardItem i) {
    		board[x][y] = i;
    	}
    	
    	/**
    	 * Accept a snake ( as a list of coordinates )
    	 * Set each coordinate in the 2D board to be of SNAKE type
    	 * @param snake
    	 */
    	public void updateSnake( ArrayList<Coordinate> snake ) {
    		for( Coordinate c : snake) {
    			this.setBoardItem(c.x, c.y, BoardItem.SNAKE_PART);
    		}
    	}
    
    	/**
    	 * draw the game board
    	 */
    	public void paint(Graphics g) {
    		super.paint(g);
    		
    		for (int i = 0; i<WIDTH; i++)
    			for(int j = 0; j<HEIGHT; j++)
    				if (board[i][j] == BoardItem.SNAKE_PART) {
    					g.setColor(SnakeColor);
    					g.fillRect(i*PieceSize, j*PieceSize, PieceSize, PieceSize);
    				}
    		
    		Toolkit.getDefaultToolkit().sync();
    		g.dispose();
    		
    	}
    	
    }
    Java Code:
     /**
     * A simple coordinate class to represent the 
     * location of an element in a 2D array.
     * 
     *
     */
    public class Coordinate {
    	public int x;
    	public int y;
    	
    	public Coordinate( int x, int y) {
    		this.x = x;
    		this.y = y;
    	}
    	
    }
    I am supposed to fill in the code for tasks 1-4 labeled in MainGame.java. Once the basic tasks are done, I should be able to play a simple snake game that looks like this.

    Normally, my first step in program design is creating an outline of the program, listing all of the major steps and the actions I need to take to fulfill them. Luckily, this is already partially done for me, as I can focus my attention on those four tasks described in MainGame.java.

    For step one, I am supposed to initiate the snake to the middle of the board. The gameboard is 30 units by 30 units, so I assume I should initialize the snake at (15,15)? And to accomplish this, should I create a snake constructor and set it to these coordinates?

  2. #2
    KevinWorkman's Avatar
    KevinWorkman is offline Crazy Cat Lady
    Join Date
    Oct 2010
    Location
    Washington, DC
    Posts
    3,963
    Rep Power
    8

    Default Re: Snake Game

    What happened when you tried that?
    How to Ask Questions the Smart Way
    Static Void Games - Play indie games, learn from game tutorials and source code, upload your own games!

  3. #3
    FrankElliot9 is offline Member
    Join Date
    Nov 2012
    Posts
    3
    Rep Power
    0

    Default Re: Snake Game

    Update on my code:

    Java Code:
     import java.util.*;
    import java.awt.Color;
    import java.awt.Font;
    import java.awt.FontMetrics;
    import java.awt.Graphics;
    import java.awt.Image;
    import java.awt.Toolkit;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.awt.event.KeyAdapter;
    import java.awt.event.KeyEvent;
    import java.util.ArrayList;
    
    import javax.swing.ImageIcon;
    import javax.swing.JOptionPane;
    import javax.swing.JPanel;
    import javax.swing.Timer;
    
    /**
     * The main game class that reads user input,
     * maintains a snake and updates game board
     * 
     *
     **/
    public class MainGame implements ActionListener {
    
    	// size of the game board (30 * 30 by default)
    	private final int WIDTH = 30;
    	private final int HEIGHT = 30;
    	
    	private final int Init_Snake_Length = 5;
    	
    	// delay of detecting user input ( in milliseconds )
    	private final int DELAY = 100;
    	
    	// grow the snake every GROWTH_INTERVAL milliseconds
    	private final int GROWTH_INTERVAL = 5000;
    	// move the snake every MOVE_INTERVAL milliseconds
    	private final int MOVE_INTERVAL = 500;
    	
    	// The snake (as a list of coordinates in the 2D board array)
    	private ArrayList<Coordinate> snake;
    	
    	// The game board object - read GameBoard.java
    	private GameBoard board; 
    	
    	// Flag variables indicating which direction is chosen
    	// by user. Only one of the four can be true at any moment
    	private boolean left = false;
    	private boolean right = true;
    	private boolean up = false;
    	private boolean down = false;
    
    	private Timer timer;
    	private long growCounter;
    	private long moveCounter;
    	
    	public MainGame() {
    		board = new GameBoard(WIDTH, HEIGHT);
    		initGame();
    		board.addKeyListener(new TAdapter());
    	}
    	
    	public static void main(String[] argv) {
    		MainGame mg = new MainGame();
    	}
    	
    	public void initGame() {
    		snake = new ArrayList<Coordinate>();
    		snake.add(new Coordinate (15,15)); // 0
    		snake.add(new Coordinate (14,15)); // 1 
    		snake.add(new Coordinate (13,15)); // 2
    		snake.add(new Coordinate (12,15)); // 3
    		snake.add(new Coordinate (11,15)); // 4
    		
    		board.updateSnake(snake);
    		
    		timer = new Timer(DELAY, this);
    		timer.start();
    		growCounter = 0;
    		moveCounter = 0;
    		
    		left = false;
    		right = true;
    		up = false;
    		down = false;		
    	}
    	
    	private void moveSnake() {
    		
    		for (int i = snake.size() - 1; i > 0; i--){
    			snake.set(i, snake.get(i-1));
    		}
    		
    		if (right == true) {
    			snake.get(0).x = snake.get(0).x + 1;
    			
    		}
    		
    		if (left == true) {
    			snake.get(0).x = snake.get(0).x-1;
    		}
    			
    		if (up == true) {
    			snake.get(0).y = snake.get(0).y-1;
    		}
    		
    		if (down == true) {
    			snake.get(0).y = snake.get(0).y+1;
    		}
    		
    	}
    I can now get the head of the snake to move around freely, however I cannot get the body of the snake to follow it. The head moves, however the other parts of the snake disappear one by one as the snake head moves. Any suggestions?

  4. #4
    Darkzombies is offline Senior Member
    Join Date
    Nov 2012
    Posts
    105
    Rep Power
    0

    Default Re: Snake Game

    Java Code:
    import java.util.*;
    import java.awt.Color;
    import java.awt.Font;
    import java.awt.FontMetrics;
    import java.awt.Graphics;
    import java.awt.Image;
    import java.awt.Toolkit;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.awt.event.KeyAdapter;
    import java.awt.event.KeyEvent;
    import java.util.ArrayList;
     
    import javax.swing.ImageIcon;
    import javax.swing.JOptionPane;
    import javax.swing.JPanel;
    import javax.swing.Timer;
    If you're going to import that much of the same thing, just do
    Java Code:
    import java.util.*;
    import java.awt.*;
    import javax.swing.*;
    and I'm just assuming, but I'm pretty sure your problem is that you used 0 instead of the variable defined in the for loop

    Java Code:
            for (int i = snake.size() - 1; i > 0; i--){
                snake.set(i, snake.get(i-1));
            }
             
            if (right == true) {
                snake.get(i).x = snake.get(i).x + 1;
                 
            }
             
            if (left == true) {
                snake.get(i).x = snake.get(i).x-1;
            }
                 
            if (up == true) {
                snake.get(i).y = snake.get(i).y-1;
            }
             
            if (down == true) {
                snake.get(i).y = snake.get(i).y+1;
            }
             
        }
    Last edited by Darkzombies; 12-03-2012 at 12:09 AM.

  5. #5
    FrankElliot9 is offline Member
    Join Date
    Nov 2012
    Posts
    3
    Rep Power
    0

    Default Re: Snake Game

    I tried that Darkzombies, however I am still having the same error. The snake shortens until only the head is left to move.

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

Similar Threads

  1. altered snake game
    By dmp in forum Android
    Replies: 1
    Last Post: 04-17-2012, 05:49 AM
  2. Snake Game
    By LuluMM in forum New To Java
    Replies: 0
    Last Post: 03-08-2012, 06:48 AM
  3. Snake Game Applet
    By Growler in forum Java Applets
    Replies: 6
    Last Post: 07-11-2010, 02:47 PM
  4. Snake game in java
    By freaky in forum New To Java
    Replies: 5
    Last Post: 04-20-2010, 06:34 PM
  5. Snake Game
    By mustachMan in forum New To Java
    Replies: 2
    Last Post: 12-10-2009, 10:35 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
  •