You are on page 1of 6

A case study regarding the structure of a JAVA program

English 202C | Kyle Brower

Audience and Scope Throughout this document I hope to inform beginner programmers of the different segments of a snake game written in Java. More specifically this documents format works well with a college freshman in Computer Science, Information Sciences and Technology, or another related major. This student must also have some prior knowledge of Java and its syntax. Most students at Penn State take a few semesters of C++ before learning Java. They need to understand basic programming concepts from these courses in order to comprehend the snake game program. Snake, as one might remember from their old Nokia phone, makes for a simple yet addicting game. By todays standards the game lacks complexity, but looking at the source code helps solidify understanding of basic Java concepts.

Snake: A Brief Introduction Snake is an interactive application made for entertainment purposes. Programmer have written snake in several computer languages but todays document will focus on a Java implementation. Similar to most programs, how the developer creates the game can alter as well. Just keep in mind that the explanation in this document describes one programmers solution. In snake the player attempts to get as many points as possible. To do this, the player controls the movements of Left Pressed a snake. This snake, represented in figure 1 as the red and green dot chain, continuously moves. The only keys the player needs to worry about are the four arrow keys. Pressing one of these keys will move the snake in that Figure 1: Example of a traditional snake game keys direction. However, the user cannot select a direction opposite of the snakes current direction. For example hitting the right arrow key would not change the direction of a left-moving snake. Hitting an arrow key affects the head (red dot) of the snake. The remainder of the snake will follow the path the head takes. Figure 1 indicates where the snake changed direction and what key was pressed to make the change.
Left Pressed

Up Pressed

Up Pressed

To earn points a collision needs to occur between the snake head and another icon on the board (green apple in figure 1). Once the player collects an apple, the snake grows by one dot and their score increases. As the snake grows longer, the game becomes more difficult due to limited space. The game ends when one of two events occurs; the snake head hits part of the snake or the snake head hits outside the game board (hitting the wall). In the traditional version of snake, the game calculates the players score as some multiple of the number of apples collected.

The Board: Two-Dimensional Arrays Lets first look at the board of the snake program. In snake the board images are created using a twodimensional array. To understand an array, first start with the idea of a variable. In Java, a programmer can store values whether they are integers, text (Strings), or decimal numbers (doubles, floats) into elements called variables. The programmer uses these variables throughout the program after the initial declaration. An array stores multiple variables into one list. A programmer can then access any element of the array by supplying an index. For example, the programmer declares an array of five integers 0, 2, 4, 6, and 8: int myArray[] = {0, 2, 4, 6, 8};
1st Element 2nd Element 3rd Element . . .

It is possible to then use any element of the array in future code. If the programmer needs to use the 3rd element, they would write myArray[2] to use the value 4 from myArray. Arrays indices start at zero. These arrays help simplify code where hundreds or even thousands of values need to be saved. A two-dimensional array stores objects or variables in a row-column approach. Imagine a programmer declares a two-dimensional array that is five by five. He stores data at any element within the grid. Later he can access the data by providing the x and y coordinates of its location. At first a two-dimensional array may not seem useful. Why put data in row-columns when it can be accessed through a normal array? In the snake program two-dimensional arrays help in storing and displaying images, not your standard primitive data types. The 2d-array in this case relates to a small flipbook. The image only changes slightly, but when viewed back to back it looks like an animation. The program redraws the board in a matter of milliseconds, creating the smooth movement of the snake. In figure 2 the board has 20 elements in the x and y direction. There are three images that the program draws at any element on this board. They are the snake head, the snake joints (remainder of snake), and the apple. Each individual square box has a certain pixel side length. If the programmer makes the side length 10 pixels, the game boards total size comes to 200 pixels by 200 pixels. The size of the three images would need to be 10 pixels by 10 pixels as well. The position of the apple is determined by randomly generating an x-coordinate and a y-coordinate within the board. This image also gets redrawn, but only changes once an apple is collected.
Figure 2: Grid View of Snake Board

Timers: Speed of the Snake When programmers create games in Java they use timers to simulate movement. A simple example entails a ball falling down a screen. A programmer creates an image at a certain height. He specifies in the code to have the ball move down five pixels for an iteration of the timer. The programmer gives the timer a value of one second. This would cause the ball to move very slowly down the screen. It would look choppy as well because the large timer delay. In the snake program the timer equals 140ms; roughly one seventh of a second. So after every one seventh of a second, the snake head, its body, and the apple (whether it moves or not) gets redrawn. The smaller delay makes the movement appear smoother. However, a smaller delay makes the game much harder because the speed of the snake increases. The Snake: Movement Algorithms Like mentioned in the introduction the player controls the head of the snake. Each segment of the snake after the head follows the previous segment. So the second segment would end up in the heads position after the timer delay, the third segment in the seconds position, and so on. Figure 3 shows the method used to move the snake after each timer delay. x[z] dictates the x-position of the zth element of the snake whereas y[z] the y-position. x[0] and y[0] : used to indicate the position of the snake head. x[1] and y[1] : the second segment. x[dots] y[dots] : the last segment of the snake.

Figure 3: move function in snake program

The for-loop assigns the position of the non-head portion of the snake. It starts at the end of the snake, and goes towards the head. To determine the position of the head, there are four if statements. The names left, right, up, and down are Boolean variables (either true or false). Other logic in the code determines which direction has a true state. Given the direction, the position of the head moves accordingly. This move function is called after each timer delay. The move function provides the location of each part of the snake game. A separate function called paint physically draws the images on the board. It uses a for loop for each x[z] any y[z] pair to draw an image at that location.

Collisions: Keeping Score and Game Over Collisions occur when the head of the snake has the same position as another non-empty element on the board. In the traditional snake game this happens after one of a few things: The position of the snake head exceeds the size of the board. If the board was 20 by 20 as in figure 2, the game would be over if x[0] > 20, x[0] < 0, y[0] > 20, or y[0] < 0. The position of the snake head is the same as the position of the apple. The position of the snake head is the snake as another element of the snake.

The program must check if either of these events happens after every timer delay. Conditional if statements would be used for checking if the snake is within the board. The same approach would be used to see if the player hit the apple. To see if the snake hit itself the programmer would use a for loop similar to the one in the move method. This loop would check if the position of the head is equal to any of the other snake segments. If the snake hits the wall or itself, the game is over. The programmer provides logic to print a message on the screen telling the player their fate. If an apple is collected, the players score variable updates with the new total score. The program calls the locateApple() method to create a new apple on the board. Conclusion How do all of these parts come together? The program supplies an initial position of the snake and the first apple. Once the game begins, the snake begins to move in the default direction. Once the player hits a new key, the move function will take it into account and change the direction of the snake head. Every one-seventh of a second the board is redrawn with the new snake position, the apple, and the score. The program will also pick up any arrow key input after the delay and adjust accordingly. After each timer delay the program goes through a large list of checks to see whether the apple was collected, the player hit the wall, or the player hit themselves. If the player collects an apple, the program calls the method to generate a new random position for the apple and the program redraws the apple on the board. If any other type of collision occurs, the game ends and the program exits to the main menu.

Works Cited Bodnar, Jan. "Snake." Snake. Jan Bodnar, n.d. Web. 17 Oct. 2012. <http://zetcode.com/tutorials/javagamestutorial/snake/>. "Snake Movement (Game Development Forum at JavaRanch)." Snake Movement (Game Development Forum at JavaRanch). N.p., n.d. Web. 19 Oct. 2012. <http://www.coderanch.com/t/200897/GameDevelopment/java/Snake-movement>. "Snake (video Game)." Wikipedia. Wikimedia Foundation, 10 Nov. 2012. Web. 19 Oct. 2012. <http://en.wikipedia.org/wiki/Snake_(video_game)>.

Images http://wpuploads.appadvice.com/wp-content/uploads/2012/10/110.gif http://zetcode.com/img/gfx/javagames/snake.png http://books.mozdev.org/html/figs/moz_1209.png

You might also like