Docsity

The Snake Game Java Case Study, Study notes of Design

Toggle sidebar
bg1
The Snake Game Java Case Study
John Latham
January 22, 2016
Contents
1 Introduction 2
2 Learning outcomes 2
3 Description of the game 2
4 The classes of the program 4
5 The laboratory exercise and optional extra features 6
6 High level design, and development approach 6
7 Concept: model, view and control 8
8 Separating behaviour and image: design policy 9
9 Development of Direction 12
9.1 Variable and method interface designs . . . . . . . . . . . . . . . . . . . . . . 12
9.2 Code for
Direction
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13
10 Development of Cell and CellImage 15
10.1 Variable and method interface designs . . . . . . . . . . . . . . . . . . . . . . 17
10.2 Code for
Cell
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20
11 Development of Game and GameImage 25
11.1 Method interface designs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25
12 Development of SpeedController
and SpeedControllerImage 28
12.1 Variable and method interface designs . . . . . . . . . . . . . . . . . . . . . . 29
13 Development of AboutBox 30
14 Development of GameGUI 30
14.1 Method interface designs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30
15 Development of the top level class Snake 30
16 Conclusion 31
1
pf3
pf4
pf5
pf8
pf9
pfa
pfd
pfe
pff
pf12
pf13
pf14
pf15
pf16
pf17
pf18
pf19
pf1a
pf1b
pf1c
pf1d
pf1e
pf1f
pf20
pf21
pf22
pf23

Partial preview of the text

Download The Snake Game Java Case Study and more Study notes Design in PDF only on Docsity!

The Snake Game Java Case Study

 - January 22, John Latham 
  • 1 Introduction Contents
  • 2 Learning outcomes
  • 3 Description of the game
  • 4 The classes of the program
  • 5 The laboratory exercise and optional extra features
  • 6 High level design, and development approach
  • 7 Concept: model, view and control
  • 8 Separating behaviour and image: design policy
  • 9 Development of Direction
    • 9.1 Variable and method interface designs
    • 9.2 Code for Direction
  • 10 Development of Cell and CellImage
    • 10.1 Variable and method interface designs
    • 10.2 Code for Cell
  • 11 Development of Game and GameImage
    • 11.1 Method interface designs
    • and SpeedControllerImage 12 Development of SpeedController
    • 12.1 Variable and method interface designs
  • 13 Development of AboutBox
  • 14 Development of GameGUI
    • 14.1 Method interface designs
  • 15 Development of the top level class Snake
  • 16 Conclusion

1 Introduction

This case study presents much of the development of a program to play a snake game, similar to that found on certain old mobile phones. The core game playing functionality is actually left as a staged laboratory exercise.

2 Learning outcomes

The intentions of this case study are as follows.

  • To reinforce many of the Java and programming concepts you have already met.
  • To provide valuable experience of the design and implementation of a large program.
  • To provide a framework for a more challenging, and thus rewarding, laboratory exercise.

Whilst there is no substitute for writing your own programs, watching the development of another’s is still an extremely effective way of collecting design and programming experience, particularly as the programs can be a little more challenging than those you would be able to write yourself at this stage. (Caveat: this is only true for case studies that you are not supposed to be doing yourself – watching someone else develop code that you are supposed to be doing on your own is disastrous for your learning!)

How much you get from this case study depends on how much you put in. Ideally you should carefully follow every part of it and check your depth of understanding at every opportunity. All confusions or misunderstandings which it may reveal must be dealt with immediately.

3 Description of the game

The game is similar to snake on mobile phones (which is similar to a game played on Unix over 30 years ago), but with some ‘improvements’.

The game is played by one player, who has the objective of obtaining the highest score possible. The player is in control of a snake which is constantly moving around a square field of cells. The length of the snake is a whole number of cells. At any time, the snake moves in one of the 4 directions, parallel to a side of the square, and the player can change the direction using the 4 arrow keys of the keyboard. If the snake crashes into a side, or into itself, then it is dead, and the game stops.

Also in the field is a single piece of food. When the head of the snake hits this, the food is eaten, and the snake becomes one cell longer. This event increases the score of the player. At

Figure 1: A screen dump of a game. The optional extra feature of a gutter trail is visible behind the snake.

4 The classes of the program

As is usual in the object oriented approach, the program will be developed as a number of separate classes. Identifying the appropriate classes of a program is really an art which can slowly be learned from experience. And like the result of any art, the quality of any choice of classes is subjective (although most people will agree there are many more bad choices then good ones!).

By thinking about our understanding of the game, we can form a list of classes which will appear in the program.

Class list for Snake Game: main model classes

Class Description Cell The game grid is made up of cells. Each cell has a type and a number of attributes. For example, a cell could be clear, or it could be a snake head facing in a particular direction, etc.. Direction The snake in the game moves in one of four directions. This non-instantiable class provides those four directions, and various methods to manipulate them (such as obtaining the opposite of a direction). Game This is the main behaviour of the game play. Its primary purpose is to provide a method for making one move of the game.

We will also require some other classes to support the operating framework, including the following.

Class list for Snake Game: operating support classes

Class Description GameGUI This will provide a user interface so that the player can see the snake and the food, etc., and be able to operate the game via the keyboard. It will also be the driving force for the game, that is, it shall contain a method to play the game by repeatedly invoking the move method from the Game class. SpeedController A speed controller is something which controls the speed of the game, to make it easier or harder for the player as they choose. This will be achieved rather simply by the program calling a method to cause a delay between every move. A controller will have various speed settings, the ability to increase or decrease speed, and to pause and resume the game. AboutBox This will provide a pop-up box which can display information about the program and help on how to use it.

Finally, we shall need a class to contain the main method.

Class list for Snake Game: top level class

Class Description Snake This is the top level class, containing only the main method. This shall simply create an instance of GameGUI, invoke its game playing method and print out the score once the game has finished.

set initial game state while user has not asked to quit { speedController.delay(by some amount) moveValue = some function of (speedController.getCurrentSpeed()) game.move(moveValue) update the game’s image } return game.getScore()

A GameGUI will also interpret the key presses from the player, and invoke the appropriate methods: e.g, to get the SpeedController to change speed or pause and resume; to create and show the AboutBox, to change the direction of the snake in the Game, etc..

A Game will primarily offer the method move(). This will cause the game to change state, progressing by one move. The new state will depend on the settings of the old state. Where is the head of the snake? What direction is it facing? Where is the food? Etc.. There will also be a method setSnakeDirection() which will be called from the GameGUI when the player presses one of the arrow keys. There will be other methods too, such as getScore(), cheat() and toggleTrees(). The state of the game will be represented by a number of instance variables, the most obvious one being a 2-dimensional array of Cells to make up the field.

A SpeedController will have a number of methods, such as speedUp(), slowDown(), pause(), resume() and, most importantly, delay().

A Cell will store information, such as is there a piece of snake in the cell? If so, what direction is it facing? Or, is there a piece of food here? Or a tree? Etc.. It will have accessor method s to access and mutator method s to mutate the information it stores, so the state of a cell can be seen and changed.

The Direction class will be non-instantiable, it will simply provide 4 directions, and some useful methods to manipulate them. For example, the method xDelta() will return what value you need to add to an x coordinate, if you want to make a movement in a certain direction given as its argument. (The amount returned will be -1, 0 or 1.) This combined with the similar yDelta() will make the new position of the head of the snake easy to compute from the direction it is facing.

An AboutBox will simply pop up to display some text given to it when it is created, and provide a dismiss button to make it go away. This will be used to provide some help to the player.

Let us analyse the anticipated dependencies between these classes.

  • Snake is the top level class. This will build an instance of GameGUI.
  • GameGUI will need an AboutBox to show help text, a SpeedController to regulate the speed of the game, and a Game to play.
  • AboutBox will not require any other of these classes.
  • SpeedController will not require any other of these classes.
  • Game will require Cell for the field of cells and Direction for the direction of the snake.
  • Cell will require Direction so it can store which direction the pieces of snake are facing.
  • Direction will not require any other of these classes.

So, we plan to develop the classes in the following order: Direction, Cell, Game, SpeedController, AboutBox, GameGUI, and finally Snake.

7 Concept: model, view and control

In general, programs have some kind of behaviour and an interface connecting the behaviour to the outside world. The behaviour is often referred to as the model , as it is this that must implement the real world functionality required of the program.

The interface to a program can be divided into two categories: output and input, often referred to as view and control , respectively.

There is much debate in the O.O. world about these three functions of a program. The so-called M.V.C. argument (standing for model , view and control ) suggests there is much to be gained by separating the 3 functions into different classes in the final program. On the other hand, some people prefer to combine them – there are no hard and fast rules.

Perhaps the main reason for separating the parts is that it more easily allows certain parts to be changed without affecting the others. For example, somebody might find a better way of modelling the real world requirements, but is quite happy with the existing user interface. Or someone might make a better interface for an existing program which is otherwise quite ac- ceptable. The inherent flexibility can be exploited from the initial design too. For example, a program might have a number of different interfaces to support different operating envi- ronments, whilst having only one model part. Perhaps the most obvious examples are those programs which have both a text and a graphical interface.

The most persuasive argument for separating the model from the other two parts in a learning environment is that it permits us to study quite complex programs long before we need to discover the details of complex graphical user interfaces: we can simply hide the specifics of the control and view parts of the program at this point in time.

Class list for Snake Game: image classes

Class Description SpeedControllerImage Provides the image and control for speed controllers.

Having made the decision to develop separate classes for model and view, we next must figure out the way we would like to do it. For example, for each instance of Cell which we create, we will also need to create an instance of CellImage. We must decide on a strategy for keeping track of the relationship between corresponding instances of these classes. There are numerous ways we could do this. The approach we have chosen in this case study has actually been taken so that you can develop the Game class without having to worry about view and control classes! So, if we were not in such a learning context, we might have taken a different approach.

Here is the policy we shall use in this case study.

  • An instance of GameGUI will be created by the main method. This will create an instance of Game and then also an instance of GameImage. A reference to the game instance will be passed to the instance of the game image, so that the game image knows which game to provide a view for.
  • The instance of GameImage will construct an instance of CellImage for every cell in the game it has been given. It will keep track of all these cell images, and also combine them to produce the image of the game.
  • When an instance of CellImage is created, it is passed a reference to the instance of Cell for which it must provide an image.
  • The instance of the class GameImage will have an update() method. This will be in- voked after every move, and at other times, by the instance of GameGUI. This method will invoke a similar update() method on each instance of CellImage, which will repaint the image of the corresponding cell, if the cell has been changed since the image was last painted.

As suggested above, the attraction of this strategy is that the model classes for the game and the cells need to have absolutely no knowledge of the image classes. This is particularly persuasive given that the Game class is to be written by you!

A second attraction is that we can also hide most of the details of the image and control classes for this current discussion.

Figure 2 shows how the classes will be used in the program. The diagram is simplified, and in particular ignores the class Direction.



 



 



 



 



 

 



 



 



 

 

 



 



 



 

 

 



 



 



 



 



 



 



 





 



 



 



 





 



 



 



 



 



 



 



 



 



 



 



 

SpeedControllerImage

image

Game

Snake game

GameGUI

gameGUI

SpeedController

speedController

AboutBox

helpBox

CellImage

cellImage ...

GameImage

gameImage

Cell

Cell [] [] grid

Figure 2: Simplified diagram showing the most significant classes of the program. The class Direction is not shown.

Method interfaces for class Direction.

Method Return Arguments Description yDelta int int Static (class) method that takes an integer represent- ing a direction, and returns -1, 0, or 1: this being the change needed to the y component of a cell co-ordinate in order to move in the given direction. rightTurn int int Static (class) method that takes an integer represent- ing a direction, and returns the integer representing the direction that is a right turn from the given one. leftTurn int int Static (class) method that takes an integer represent- ing a direction, and returns the integer representing the direction that is a left turn from the given one.

9.2 Code for Direction

Next we develop the code for the class. We need to choose an integer to represent each of the direction values we need to provide. The most common way of doing this is simply to count upwards from 0, directly assigning the values to each variable.

public class Direction { public static final int NONE = 0; public static final int NORTH = 1; public static final int EAST = 2; public static final int SOUTH = 3; public static final int WEST = 4;

The method to find the opposite of a direction simply requires 5 cases.

public static int opposite(int direction) { switch (direction) { case NORTH: return SOUTH; case SOUTH: return NORTH; case WEST: return EAST; case EAST: return WEST; default: return direction; } // switch } // opposite

We could instead have used a formula exploiting the actual values of the directions – see if you can figure out what it would be.

The method to find the x delta to move in a certain direction also simply requires 5 cases. It is at this point that we need to fix the relationship between coordinates and directions. We arbitrarily choose to have cell coordinates in the form (x,y), with (0,0) as the top left corner cell, and with the direction NORTH being upwards, SOUTH being downwards, WEST being leftwards and finally EAST being rightwards.

public static int xDelta(int direction) { switch (direction) { case NORTH: return 0; case SOUTH: return 0; case WEST: return -1; case EAST: return 1; default: return 0; } // switch } // xDelta

The method to find the y delta is similar.

public static int yDelta(int direction) { switch (direction) { case NORTH: return -1; case SOUTH: return 1; case WEST: return 0; case EAST: return 0; default: return 0; } // switch } // yDelta

Turning left or right again involves 5 cases.

public static int rightTurn(int direction) { switch (direction) { case NORTH: return EAST; case EAST: return SOUTH;

Figure 3: A sneak preview of all 16 combinations of in and out directions of snake heads.

SNAKE BODY This is for a cell that has part of the body of the snake in it. This also has the same 3 attributes as a SNAKE HEAD cell. The snakeBloody boolean is true if and only if the snake is ‘dead’ at this point, usually because the head of the snake has crashed into this part of the body. The snakeOutDirection states in which direction the next piece of snake, nearer to the head, can be found; the snakeInDirection states in which direction the previous piece of snake, nearer to the tail, can be found. You can think of a piece of snake as being like a joint of 2 bones. The 2 bones can swivel at the joint, and each bone is fixed to a bone in the next part of the snake. The two directions are stating which way the 2 bones are facing.

SNAKE TAIL This is for a cell that has the tail of the snake in it. This also has the same 3 attributes. The snakeBloody boolean is true if and only if the snake is ‘dead’ at the tail, usually because the head of the snake has crashed into it. The snakeOutDirection states in which direction the next piece of snake, nearer to the head, can be found; the

snakeInDirection states in which direction the tail of the snake has just come from.

FOOD This is for a cell that has the food in it.

TREE This is for a cell that has a tree in it.

OTHER This is for a cell that can be used for optional extra features. It has 1 attribute the otherLevel which is an integer between -255 and 255 inclusive. The image of such a cell will always be a shade of the background colour, with the brightness proportional to the level: a negative number is darker than the background, and 0 is the same colour as the background. In practice there may not be 511 different shades of the background colour available, so some values will look the same. For example, if the background colour is pure green at a value of 100, that is the red, green, blue triple is (0, 100, 0), then there will be 255 different shades brighter than this, but only 100 shades darker. So - will be shown as the colour (0, 0, 0) which is black, but so will all the values less than -100. 255 will be shown as the colour (255, 255, 255) which is white – no longer a green really.

10.1 Variable and method interface designs

Cell will have the following public variables.

Variable interfaces for class Cell.

Variable Type Description int NEW A static final integer value representing the type of cell which is a newly created cell. int CLEAR A static final integer value representing the type of cell which has nothing in it. int SNAKE HEAD A static final integer value representing the type of cell which con- tains a snake head. int SNAKE BODY A static final integer value representing the type of cell which con- tains a part of snake body. int SNAKE TAIL A static final integer value representing the type of cell which con- tains a snake tail. int FOOD A static final integer value representing the type of cell which con- tains a piece of food. int TREE A static final integer value representing the type of cell which con- tains a tree. int OTHER A static final integer value representing the type of cell for optional extra cell types.

The class will also have the following public methods.

Method interfaces for class Cell.

Method Return Arguments Description clone Object Makes a new cell which has the same type and attributes as this one, and re- turns a reference to it. equals boolean Cell Compares 2 cells for an exact match of type and all attributes, returning true if and only if they match.

The class CellImage will have the following public methods.

Method interfaces for class CellImage.

Method Return Arguments Description Constructor Cell, int Builds a cell image object, to provide the image of the given Cell, this image being a square of pixels of the given in- teger size. paint void Graphics Paints the actual image of the cell asso- ciated with the cell image object. getPreferredSize Dimension Returns the desired size of the image, as an instance of the class Dimension. update void The cell is compared with the value it had last time the image was painted, and causes a repaint if it has changed.

Let us make some observations about this list of methods.

  • paint() and getPreferredSize() are used by the Java GUI mechanisms, and we are not going to study the details of them here.
  • update() will be called from GameImage as part of its update() method.
  • update() will use the clone() and equals() methods of the Cell class, to keep a copy of the previous value of a cell, and compare the current one to it, respectively.

10.2 Code for Cell

We can now develop the code for the Cell class. The class has 8 static (class) variables, one each for the different types of cell. Each instance will have 5 private instance variables, to store the type and the associated attributes of the cell.

public class Cell { // Values for cell type public static final int NEW = 0; public static final int CLEAR = 1; public static final int SNAKE_HEAD = 2; public static final int SNAKE_BODY = 3; public static final int SNAKE_TAIL = 4; public static final int FOOD = 5; public static final int TREE = 6; public static final int OTHER = 7;

// Current cell type private int cellType;

// Attributes used if cellType is a snake type:

// Is the snake bloody (dead) at this cell? private boolean snakeBloody;

// What are the incoming and outgoing directions of the snake? private int snakeInDirection; private int snakeOutDirection;

// Attribute used if cellType is OTHER:

// A level from -255 to 255 private int otherLevel;

The constructor takes no arguments, and builds a new cell with the type NEW.

public Cell() { cellType = NEW; } // Cell

Next we write the accessor method for the cell type. The purpose of accessor method s is to permit public read access to private instance variables.