Snake Game – Java In 10 Minutes

Snake game is famous classic game, starting from handset mobile to latest mobile, it always has its own admirers.

The goal of the game is the snake needs to catch its food and grow to a maximum.

In this example we will see how we can implement the logic in Java.

SnakeGame Java Screen

Logic:

The game follows the below logic

  1. Create a board of width & height
  2. Create a List to store the points(x,y) of snake.
  3. Create a direction(LEFT, RIGHT, TOP, BOTTOM) and for each step(screen refresh or repaint()) add a movement to points of x,y based on direction
  4. Based on arrow button press,
    1. Create a new Point(x,y) based on direction, add it to the top of the List.
    2. Remove the last point in the List.(if no food taken)
  5. If the snake eats food,
    • Increment all the current points of snake in list. (based on Direction)
    • add one more points to Snake List copying the point of head before increment(top of array) -> (list.add(point)
  6. Else
    • Just increment all the current points of snake in list. (based on Direction)

Leave a Comment

Your email address will not be published. Required fields are marked *