Facebook Twitter Instagram
    Saturday, May 21
    Trending
    • John Travolta-Led Movie Acquired By Saban Films
    • What is TXT Heardle And How To Play It?
    • Lyon’s Champions League title win vs Barcelona reaffirms its status
    • Apple display supplier could lose out on large iPhone 14 order after it was reportedly caught cutting corners
    • To War Criminals With Impunity, Think Again
    • Ronald Reagan Washington National Airport renumbers its gates
    • You Can Check In – And Check Bags – Closer To Departure Than American Airlines Says On Its Website
    • Spain eases Covid entry for unvaccinated tourists
    Facebook Twitter Instagram Pinterest VKontakte
    Swave Digest
    • Home
    • World News
    • Technology
      • Smartphones
      • Computers
      • Programming
      • Automobiles
    • Entertainment
      • Music
      • Anime
      • Movies
    • Sports
      • Football
      • Basketball
      • Tennis
    • Business
      • Crypto
      • Stocks
      • NFT
    • Lifestyle
      • Fashion
      • Health
      • Travel
    • Shop
    Swave Digest
    Home»Technology»Programming»Create the Classic Snake Game With Processing Library and Java | by Nicolai B. Andersen | May, 2022
    Programming

    Create the Classic Snake Game With Processing Library and Java | by Nicolai B. Andersen | May, 2022

    Swave DigestBy Swave DigestMay 14, 2022No Comments10 Mins Read
    Facebook Twitter Pinterest LinkedIn Tumblr Email
    Create the Classic Snake Game With Processing Library and Java | by Nicolai B. Andersen | May, 2022 1*59fa2uIitTgnWmUairelIA
    Share
    Facebook Twitter LinkedIn Pinterest Email

    Table of Contents

    • Recreate the game with Java
    • 1.1 Application Flow
    • 1.2 Graphical Interface
    • 2.1 Requirements
    • 2.2 Coding the game

    Recreate the game with Java

    A GIF displaying the Snake game from the article.
    A GIF displaying the Snake game from the article.

    Do you know the basics of Java or Processing and want to start developing your own games or maybe just recreate one of the classics? This article describes the process of building the classic Snake game using Processing.

    Wikipedia (2022) describes Processing as a graphical library and integrated development environment (IDE). The library is built on Java and provides additional classes and simplifications (Wikipedia, 2022). To download and install Processing, go to processing.org/download and download the installable matching the preferred platform.

    1.1 Application Flow

    Processing provides many methods to control the flow of an application, for example, to control key events, initialization, or continuous behavior. Two important methods to know to get started with Processing are the methods setup() and draw(). Another built-in method, the article is introducing later is keyPressed(). The behavior of the three methods is:

    • setup() is called one time when the application starts (Processing, 2022a).
    • draw() executes forever and is called a number of times matching the framerate (Processing, 2022b).
    • keyPressed() executes when a key is pressed, and the key is stored in a variable named key (Processing, 2022c).

    1.2 Graphical Interface

    Processing also provides a graphical interface where the point (x, y) = (0, 0) is at the left top corner (see figure 1). Drawing shapes within Processing is very simple because the library provides the 2D primitive methods such as rect(x, y, w, h), circle(x, y, r)or line(x1, y1, x2, y2) . Find more 2D primitive methods at processing.org/reference.

    Create the Classic Snake Game With Processing Library and Java | by Nicolai B. Andersen | May, 2022 1* WmEnrcZqEueHi3NIYve8w
    Figure 1: Display the direction of the horizontal axis (x) and vertical axis (y) within Processing’s graphical interface.

    As with every project, it can be a great idea to establish a couple of requirements to set the direction and outline an overview of necessary features. Section 2.1, therefore, describes the requirements of the game which is followed by a section describing the code.

    2.1 Requirements

    The requirements for the game are:

    1. The snake and objective are drawn using rectangles.
    2. The first rectangle of the snake represents the head of the snake and it is only the head that can trigger collision events with the objective and tail.
    3. When the snake reaches the screen’s border, it is teleported to the opposite position.
    4. The objective gets a new random position when it collides with the snake’s head.
    5. The game ends if the snake’s head collides with its tail.
    6. The score increases whenever the snake collides with the objective.

    2.2 Coding the game

    To keep the article simple, the following section is divided into different steps of coding the game.

    2.2.1 Adding properties

    The first step is to add global properties that can store information about size, positions, etc. The first two properties to add is gameover and s (see figure 2). The boolean variable gameover is used to check if the player has lost the game and the float variable s is a general size specifying the size of the rectangles representing the objective and the snake.

    Figure 2: Display the first two properties of the game.

    Now, when the general properties are in place it’s time to add the properties for the snake. The snake will require a property specifying the position of each rectangle representing the snake’s tail and head. It will also require a property specifying the direction of the snake. To store the positions of the snake’s rectangles, add a property called snakePositions of the type ArrayList<PVector> and to store information about the snake’s direction, add a property called snakeDirection of the type PVector (see figure 3).

    Figure 3: Shows the properties of the snake.

    The last property, the game requires, is a variable specifying the positions of the objective. Add a property called objPosition of the type PVector (see figure 4).

    Figure 4: Shows the property of the objective.

    2.2.2 Property data types

    Section 2.2.1, adding properties, introduces a couple of data types that may be unfamiliar to beginners. boolean and float are primitive data types, boolean refers to a value that can be either true or falseand float refers to a number that unlike an integer can specify a whole number and a decimal part. ArrayList<T> and PVector are composite data types, ArrayList<T> refers to a list of other data types that can be dynamically resized, PVector refers to a 2 or 3-dimensional vector.

    2.2.3 Adding custom helper methods

    The next section covers a couple of helper methods used to help simplify the explanation of the game. The first method is used to check if the position of two points overlaps (see figure 5).

    The procedure of the method can be defined as follows:

    1. Expect two vectors specifying the top left corner of a rectangle.
    2. Find the center position of the rectangle using its size (s).
    3. Return true if the distance between the center positions is less than the size.
    Figure 5: Shows an implementation of a method that returns true if two points overlap.

    The next method is used to give a vector a random position (see figure 6).

    The procedure of the method is as follows:

    1. Set the horizontal property (x) to a random float within a and b .
    2. Set the vertical property (y) to a random float within a and b .
    Figure 6: Shows a method that gives a vector a random position within the given boundaries.

    The last two helper methods are reset() and endgame() . reset() is used to set the properties of the game to the same state as at the start of the application and endgame() is used to start the end game functionality.

    The procedure of endgame() is:

    1. Set the gameover property to true to signal the game is ended.
    2. Override the current content with a black background.
    3. Reset the fill color to set the text color to white.
    4. Display a text saying “Gameover”.

    The procedure of reset() is:

    1. Set the gameover property to true to signal the game is NOT ended.
    2. Remove all saved positions from the snakePositions property.
    3. Define a vector with the position of the screen’s center.
    4. Add the vector to the snakePositions property to define the snake’s head.
    5. Set the objective’s position to a random position within the screen’s borders.
    Figure 7: Shows the implementation of a method used to end the game and another used to reset the properties of the game.

    2.2.4 Add the built-in method: setup

    The next method, the game requires, is the built-in setup method which is called once when the application starts.

    The procedure of the method is as follows:

    1. Set the screen size to 250×250 pixels.
    2. Set the frame rate to 25 frames pr. second.
    3. Reset the properties of the game using the helper method: reset
    Figure 8: Shows the implementation of the built-in method: setup.

    2.2.5 Add the built-in method: draw

    The built-in method draw()is called continuously until the application is stopped. The code within the draw() method is a bit more complex than other methods presented in the article and the code is, therefore, divided into several parts in the following section.

    The procedure of the code presented in figure 9 can be described as follows:

    1. Set the screen’s background to black.
    2. If the propertygameover is true, which means the game is ended, wait 5 seconds, and reset the game.
    3. Set the fill color to white.
    4. Display a text saying “Score: x” at (x, y) = (10, 20).
    5. Set the fill color to black and stroke color to white.
    6. Draw the objective.
    7. Loop the snakePositions property in reversed order.
    8. Get the current position.
    9. Check if the current index is equal to the head’s index to define behavior for the snake’s head, and add an else statement used to define the behavior for the snake’s tail.
    10. Draw a rectangle at the current position representing the snake’s tail or head.
    Figure 9: Display the implementation of the built-in method: draw.

    Why loop the snakePositions from the end to the start? The reason is related to the movement of the snake. Whenever the head of the snake moves one time in some direction, each rectangle of the tail also has to be moved one time.

    The code is, therefore, designed as follows:

    1. Start by selecting the last element and set its position to the second last element’s position.
    2. Select the second last element and set its position to the third last element’s position.
    3. Continue to select an element, and set its position to the position of the element before it, until the first element is reached.
    4. When the first element is reached, move the position of that element one time towards the direction specified in the property called snakeDirection.
    Figure 10: Display the implementation of the movement of the snake.

    The draw() method currently moves the position of the snake, checks if the game is ended, and draws the snake and the objective. But it still needs some functionality handling what should happen when the snake reaches the screen’s borders and some other functionality handling when the snake’s head overlaps with the objective or its own tail.

    The procedure for when the snake reaches the screen’s borders (L 14–18, figure 11):

    1. If the horizontal property (x) of the snake is less than zero, set the property to the screen’s width.
    2. If the horizontal property (x) of the snake is greater than the screen’s width, set the property to zero.
    3. If the vertical property (y) of the snake is less than zero, set the property to the screen’s height.
    4. If the vertical property (y) of the snake is greater than the screen’s height, set the property to zero.

    The procedure for when the snake’s head overlaps with the objective (L 22–29, figure 11):

    1. If the position of the snake’s head overlaps with the position of the objective.
    2. Set the position of the objective to a new random position.
    3. Get the position of the snake’s last tail element.
    4. Define a position behind the last tail element.
    5. Add that position as the new last tail element.

    The procedure for when the snake’s head overlaps with one of its tail elements (L 34–39, figure 11):

    1. If the tail element is not directly attached to the head and overlaps with the head.
    2. End the game.
    3. Stop the loop.
    4. If the tail element doesn’t overlap, set the position of the tail element.
    Figure 11: Display the implementation of the functionality handling whenever the snake reaches the screen’s borders and handling overlaps between the snake’s head and tail.

    2.2.6 Add the built-in method: keyPressed

    The last functionality the game requires is something handling key events.

    The directions the snake can move can be defined as follows:

    • Left — (x, y) = (-1, 0)
    • Right — (x, y) = (1, 0)
    • Up — (x, y) = (0, -1)
    • Down — (x, y) = (0, 1)

    The procedure for the keyPressed() method is:

    1. If the ‘a’-key is pressed and if the snake is not moving right set the direction to left.
    2. If the ‘d’-key is pressed and if the snake is not moving left set the direction to right.
    3. If the ‘s’-key is pressed and if the snake is not moving up set the direction to down.
    4. If the ‘w’-key is pressed and if the snake is not moving down set the direction to up.
    Figure 12: Display the implementation of the method handling keypress.

    A Github Gist with a full example of the code for the game can be found at this link.

    Processing is a graphical library and a development environment (IDE). It provides a graphical interface that can be used to draw different shapes and text. setup(), draw()and keyPressed() are built-in Processing methods used to handle initialization, continuous behavior, and keypress events. ArrayList<T> can be used to create a dynamically sized list andPVector specifies a vector, and provides methods to calculate the distance between vectors. The movement of the snake is created by looping the snakePositions in reversed order and assigning the position of each element to the position of the element before reaching the snake’s head which is moved towards the direction specified in snakeDirection.

    En.wikipedia.org. 2022. Processing (programming language) — Wikipedia. [online] Available at: [Accessed 30 April 2022].

    Processing.org. 2022a. [online] Available at: [Accessed 30 April 2022].

    Processing.org. 2022b. [online] Available at: [Accessed 30 April 2022].

    Processing.org. 2022c. [online] Available at: [Accessed 30 April 2022].

    2022 and andersen classic create game java library may nicolai processing programming snake the with
    Share. Facebook Twitter Pinterest LinkedIn Tumblr Email
    Swave Digest
    • Website
    • Twitter
    • Pinterest

    Related Posts

    What is TXT Heardle And How To Play It?

    May 21, 2022

    To War Criminals With Impunity, Think Again

    May 21, 2022

    You Can Check In – And Check Bags – Closer To Departure Than American Airlines Says On Its Website

    May 21, 2022

    Family demand answers as eight people arrested for trafficking teen girl from Dallas NBA game to Oklahoma

    May 21, 2022
    Add A Comment

    Leave A Reply Cancel Reply

    Twitter Instagram Pinterest
    • Home
    • Privacy Policy
    • Terms & Conditions
    • Contact Us
    © 2022 Swave Digest. All Rights Reserved.

    Type above and press Enter to search. Press Esc to cancel.