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

Recreate the sport with Java

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

Are you aware the fundamentals of Java or Processing and wish to begin creating your personal video games or possibly simply recreate one of many classics? This text describes the method of constructing the basic Snake sport utilizing Processing.

Wikipedia (2022) describes Processing as a graphical library and built-in growth setting (IDE). The library is constructed on Java and gives extra courses and simplifications (Wikipedia, 2022). To obtain and set up Processing, go to processing.org/download and obtain the installable matching the popular platform.

1.1 Utility Stream

Processing gives many strategies to regulate the circulate of an utility, for instance, to regulate key occasions, initialization, or steady conduct. Two necessary strategies to know to get began with Processing are the strategies setup() and draw(). One other built-in methodology, the article is introducing later is keyPressed(). The conduct of the three strategies is:

  • setup() is known as one time when the applying begins (Processing, 2022a).
  • draw() executes perpetually and is known as a lot of occasions matching the framerate (Processing, 2022b).
  • keyPressed() executes when a key’s pressed, and the secret is saved in a variable named key (Processing, 2022c).

1.2 Graphical Interface

Processing additionally gives a graphical interface the place the purpose (x, y) = (0, 0) is on the left prime nook (see determine 1). Drawing shapes inside Processing could be very easy as a result of the library gives the 2D primitive strategies resembling rect(x, y, w, h), circle(x, y, r), or line(x1, y1, x2, y2) . Discover extra 2D primitive strategies at processing.org/reference.

Determine 1: Show the route of the horizontal axis (x) and vertical axis (y) inside Processing’s graphical interface.

As with each challenge, it may be a terrific concept to determine a few necessities to set the route and description an outline of vital options. Part 2.1, due to this fact, describes the necessities of the sport which is adopted by a piece describing the code.

2.1 Necessities

The necessities for the sport are:

  1. The snake and goal are drawn utilizing rectangles.
  2. The primary rectangle of the snake represents the pinnacle of the snake and it is just the pinnacle that may set off collision occasions with the target and tail.
  3. When the snake reaches the display screen’s border, it’s teleported to the alternative place.
  4. The target will get a brand new random place when it collides with the snake’s head.
  5. The sport ends if the snake’s head collides with its tail.
  6. The rating will increase every time the snake collides with the target.

2.2 Coding the sport

To maintain the article easy, the next part is split into totally different steps of coding the sport.

2.2.1 Including properties

Step one is so as to add world properties that may retailer details about measurement, positions, and so forth. The primary two properties so as to add is gameover and s (see determine 2). The boolean variable gameover is used to test if the participant has misplaced the sport and the float variable s is a basic measurement specifying the dimensions of the rectangles representing the target and the snake.

Determine 2: Show the primary two properties of the sport.

Now, when the overall properties are in place it’s time so as to add the properties for the snake. The snake would require a property specifying the place of every rectangle representing the snake’s tail and head. It’ll additionally require a property specifying the route of the snake. To retailer the positions of the snake’s rectangles, add a property referred to as snakePositions of the kind ArrayList<PVector> , and to retailer details about the snake’s route, add a property referred to as snakeDirection of the kind PVector (see determine 3).

Determine 3: Exhibits the properties of the snake.

The final property, the sport requires, is a variable specifying the positions of the target. Add a property referred to as objPosition of the kind PVector (see determine 4).

Determine 4: Exhibits the property of the target.

2.2.2 Property knowledge varieties

Part 2.2.1, including properties, introduces a few knowledge varieties which may be unfamiliar to freshmen. boolean and float are primitive knowledge varieties, boolean refers to a worth that may be both true or false, and float refers to a quantity that not like an integer can specify a complete quantity and a decimal half. ArrayList<T> and PVector are composite knowledge varieties, ArrayList<T> refers to an inventory of different knowledge varieties that may be dynamically resized, PVector refers to a 2 or third-dimensional vector.

2.2.3 Including customized helper strategies

The subsequent part covers a few helper strategies used to assist simplify the reason of the sport. The primary methodology is used to test if the place of two factors overlaps (see determine 5).

The process of the strategy could be outlined as follows:

  1. Count on two vectors specifying the highest left nook of a rectangle.
  2. Discover the middle place of the rectangle utilizing its measurement (s).
  3. Return true if the space between the middle positions is lower than the dimensions.
Determine 5: Exhibits an implementation of a way that returns true if two factors overlap.

The subsequent methodology is used to provide a vector a random place (see determine 6).

The process of the strategy is as follows:

  1. Set the horizontal property (x) to a random float inside a and b .
  2. Set the vertical property (y) to a random float inside a and b .
Determine 6: Exhibits a way that provides a vector a random place inside the given boundaries.

The final two helper strategies are reset() and endgame() . reset() is used to set the properties of the sport to the identical state as in the beginning of the applying and endgame() is used to begin the top sport performance.

The process of endgame() is:

  1. Set the gameover property to true to sign the sport is ended.
  2. Override the present content material with a black background.
  3. Reset the fill colour to set the textual content colour to white.
  4. Show a textual content saying “Gameover”.

The process of reset() is:

  1. Set the gameover property to true to sign the sport is NOT ended.
  2. Take away all saved positions from the snakePositions property.
  3. Outline a vector with the place of the display screen’s heart.
  4. Add the vector to the snakePositions property to outline the snake’s head.
  5. Set the target’s place to a random place inside the display screen’s borders.
Determine 7: Exhibits the implementation of a way used to finish the sport and one other used to reset the properties of the sport.

2.2.4 Add the built-in methodology: setup

The subsequent methodology, the sport requires, is the built-in setup methodology which is known as as soon as when the applying begins.

The process of the strategy is as follows:

  1. Set the display screen measurement to 250×250 pixels.
  2. Set the body charge to 25 frames pr. second.
  3. Reset the properties of the sport utilizing the helper methodology: reset
Determine 8: Exhibits the implementation of the built-in methodology: setup.

2.2.5 Add the built-in methodology: draw

The built-in methodology draw()is known as repeatedly till the applying is stopped. The code inside the draw() methodology is a little more advanced than different strategies introduced within the article and the code is, due to this fact, divided into a number of components within the following part.

The process of the code introduced in determine 9 could be described as follows:

  1. Set the display screen’s background to black.
  2. If the propertygameover is true, which implies the sport is ended, wait 5 seconds, and reset the sport.
  3. Set the fill colour to white.
  4. Show a textual content saying “Rating: x” at (x, y) = (10, 20).
  5. Set the fill colour to black and stroke colour to white.
  6. Draw the target.
  7. Loop the snakePositions property in reversed order.
  8. Get the present place.
  9. Verify if the present index is the same as the pinnacle’s index to outline conduct for the snake’s head, and add an else assertion used to outline the conduct for the snake’s tail.
  10. Draw a rectangle on the present place representing the snake’s tail or head.
Determine 9: Show the implementation of the built-in methodology: draw.

Why loop the snakePositions from the top to the beginning? The reason being associated to the motion of the snake. At any time when the pinnacle of the snake strikes one time in some route, every rectangle of the tail additionally needs to be moved one time.

The code is, due to this fact, designed as follows:

  1. Begin by choosing the final ingredient and set its place to the second final ingredient’s place.
  2. Choose the second final ingredient and set its place to the third final ingredient’s place.
  3. Proceed to pick a component, and set its place to the place of the ingredient earlier than it, till the primary ingredient is reached.
  4. When the primary ingredient is reached, transfer the place of that ingredient one time in the direction of the route specified within the property referred to as snakeDirection.
Determine 10: Show the implementation of the motion of the snake.

The draw() methodology at present strikes the place of the snake, checks if the sport is ended, and attracts the snake and the target. However it nonetheless wants some performance dealing with what ought to occur when the snake reaches the display screen’s borders and another performance dealing with when the snake’s head overlaps with the target or its personal tail.

The process for when the snake reaches the display screen’s borders (L 14–18, determine 11):

  1. If the horizontal property (x) of the snake is lower than zero, set the property to the display screen’s width.
  2. If the horizontal property (x) of the snake is larger than the display screen’s width, set the property to zero.
  3. If the vertical property (y) of the snake is lower than zero, set the property to the display screen’s peak.
  4. If the vertical property (y) of the snake is larger than the display screen’s peak, set the property to zero.

The process for when the snake’s head overlaps with the target (L 22–29, determine 11):

  1. If the place of the snake’s head overlaps with the place of the target.
  2. Set the place of the target to a brand new random place.
  3. Get the place of the snake’s final tail ingredient.
  4. Outline a place behind the final tail ingredient.
  5. Add that place as the brand new final tail ingredient.

The process for when the snake’s head overlaps with one in every of its tail parts (L 34–39, determine 11):

  1. If the tail ingredient just isn’t instantly hooked up to the pinnacle and overlaps with the pinnacle.
  2. Finish the sport.
  3. Cease the loop.
  4. If the tail ingredient doesn’t overlap, set the place of the tail ingredient.
Determine 11: Show the implementation of the performance dealing with every time the snake reaches the display screen’s borders and dealing with overlaps between the snake’s head and tail.

2.2.6 Add the built-in methodology: keyPressed

The final performance the sport requires is one thing dealing with key occasions.

The instructions the snake can transfer could be outlined as follows:

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

The process for the keyPressed() methodology is:

  1. If the ‘a’-key is pressed and if the snake just isn’t transferring proper , set the route to left.
  2. If the ‘d’-key is pressed and if the snake just isn’t transferring left , set the route to proper.
  3. If the ‘s’-key is pressed and if the snake just isn’t transferring up , set the route to down.
  4. If the ‘w’-key is pressed and if the snake just isn’t transferring down , set the route to up.
Determine 12: Show the implementation of the strategy dealing with keypress.

A Github Gist with a full instance of the code for the sport could be discovered at this link.

Processing is a graphical library and a growth setting (IDE). It gives a graphical interface that can be utilized to attract totally different shapes and textual content. setup(), draw(), and keyPressed() are built-in Processing strategies used to deal with initialization, steady conduct, and keypress occasions. ArrayList<T> can be utilized to create a dynamically sized record andPVector specifies a vector, and gives strategies to calculate the space between vectors. The motion of the snake is created by looping the snakePositions in reversed order and assigning the place of every ingredient to the place of the ingredient earlier than reaching the snake’s head which is moved in the direction of the route laid out in snakeDirection.

En.wikipedia.org. 2022. Processing (programming language) — Wikipedia. [online] Accessible at: <https://en.wikipedia.org/wiki/Processing_(programming_language)> [Accessed 30 April 2022].

Processing.org. 2022a. [online] Accessible at: <https://processing.org/reference/setup_.html> [Accessed 30 April 2022].

Processing.org. 2022b. [online] Accessible at: <https://processing.org/reference/draw_.html> [Accessed 30 April 2022].

Processing.org. 2022c. [online] Accessible at: <https://processing.org/reference/keyPressed_.html> [Accessed 30 April 2022].

More Posts