top of page

Building a Snake Game in Java

  • f15eagle314
  • Jan 11, 2022
  • 2 min read

ree

One of my recent projects was to create a Classic Snake Game using only Java. At this point in time Java is the coding language that I understand the most. So I decided to take my knowledge a step further and follow a tutorial to learn how to code a simple snake game in java. This was not an original project but rather the product of following a tutorial.


One of the new things I learned to do while building this snake game was how to render graphics. This was the first time I had to render actual graphics since all of my projects before were all run and used through the terminal. Using an online tutorial I was able to learn how to render graphics using the setColor and fillRect functions.

ree

After learning how to create a basic green snake using setColor, I player around with setColor to give my snake magenta stripes which code you can see in the picture above.


This was also the first time I dealt with game mechanics such as getting to objects to move, identify other objects and to respond to specific key inputs. Following the tutorial, I was able to get the snake I rendered to move across the screen. I was also able to play around with the code and make the game harder or easier by speeding up or slowing down the snake.

ree

In order to get the snake to respond when it touches the side of the screen or the apple, I created an if statement that checks the position of the apple and the snake, or the snake and the wall.

ree

This code simply said that if the x position and the y position of the apple equaled that of the snake, then the snakes number of body parts would increase by one. To get the snake to make contact with the end of the screen, it was simply another if statement that checked to see if the coordinates of the snake were equal to the coordinates of one of the four walls.


In the past, the only key inputs I worked with were through a scanner function. Users would have to type in data and then press enter for the scanner to collect data. Any data that was inputted would simply stored and then added to another variable. For the snake game however I needed to get the snake to respond to a single instantaneous input. Through an online tutorial I was able to learn how to create a class, MyKeyAdapter, that would collect all instantaneous key presses. Using a case statement, I was able to collect the inputs of each arrow key an assign it to a single direction.

ree

At the end of this project I had a fully functional Snake Game with a few original changes that I implemented while experimenting with the code. Overall it was a fun project and I learned a lot about how powerful of a language Java can be.


Links


 
 
 

Comments


bottom of page