Home
Projects

Snake Icon Java Logo Snake

The classic Nokia phone game from the mid 90's. Steer a snake around a board, eating food and avoiding obstacles.

Features

  • High-score system
  • Custom graphics and sound
  • Autoplay option with rudimentary (greedy) pathfinding

Skills Applied

  • OOP
  • Algorithms
  • Data structures (LinkedList, HashMap)
  • File I/O
  • UI/Graphic Design
Screenshot 1 Screenshot 2

Background

This project began as a CLI game written in C++. I wrote it in C++ as a way to get some practice working with data structures in that language, before I decided that Snake could be a decent portfolio project. My Java Application Programming course gave me plenty of practice using Java’s Swing library, so I decided to use that.


What I learned

The main thing that I learned in the course of writing this program was how a game loop (specifically delta-time) works. I defined a default FPS that the game would run at, and defined a default delay between each frame (or delta, ∆) as 1000 divided by the FPS. For this reason, the speed of the game is tied to the frames per second, which I learned is actually quite common in game development. Each frame, the game calculates the next position of each element (via updateGame()), and then renders each element at its determined position.

I included in my game loop a sort of rudimentary pathfinding algorithm, which was actually quite useful in testing the high score system when it came time to write that. The method moveTowardFood() determines which direction the food is in relative to the Snake’s head by subtracting the food’s x/y pos by the Snake head’s x/y pos. The next cell on the x and y axes are then checked for safety using isSafe(), passing the x coord and signum of y and vice versa. If the move is safe (i.e., the next cell is not a wall) then the Snake is moved in that direction.

The high-score system was something that I knew wouldn’t be too much trouble as I have worked with file I/O extensively in my coursework. The high score system first checks for a high score file to read from (a plain .txt file). If it doesn’t find one, it will create one the next time the game is played. If it does find one, it parses and loads the file into local memory, to be displayed as a list of high scores.

The Snake is represented as a Linked List of Point objects. I have written Linked Lists in C as practice, but had not had a need to use them in a project before now. At the end of the updateGame() method, the Linked List is iterated over and each cell that the snake occupies is set as a Snake cell, which is used by the display() method to determine how to render each cell of the game area.


Source Code: View on Github

Download (via GitHub release): Download .jar

Instructions: Requires Java 17 or later. Run java -jar Snake 1.x.jar, where x is replaced by the current build version.

© Home 2025