Você está na página 1de 71

CheckMate

An Android Application for mobile players of Chess Variants

Cristina Budurean Pamela Cruz Panos Evagorou Ronnie Falcon Andrew Jack Christos Karamanos January 2014

Contents
1 Introduction 1.1 Motivation . . . . . . . . . . . 1.1.1 Chess . . . . . . . . . 1.1.2 Mobile Devices . . . . 1.2 Objectives . . . . . . . . . . . 1.2.1 User Objectives . . . . 1.2.2 Application Objectives 1.3 Introducing CheckMate . . . . 1.3.1 Chess Variants . . . . 1 1 1 1 2 2 2 2 3 5 5 5 6 13 15 15 17 17 19 22 22 23 23 24 24 26 27 28 28 29 29 30 31 31 31 32

. . . . . . . .

. . . . . . . .

. . . . . . . .

. . . . . . . .

. . . . . . . .

. . . . . . . .

. . . . . . . .

. . . . . . . .

. . . . . . . .

. . . . . . . .

. . . . . . . .

. . . . . . . .

. . . . . . . .

. . . . . . . .

. . . . . . . .

. . . . . . . .

. . . . . . . .

. . . . . . . .

. . . . . . . .

. . . . . . . .

. . . . . . . .

. . . . . . . .

. . . . . . . .

. . . . . . . .

. . . . . . . .

2 Design and Implementation 2.1 System Architecture Design . . . . . . . . . . . . . . . . 2.2 Game Logic . . . . . . . . . . . . . . . . . . . . . . . . . 2.2.1 Implementation . . . . . . . . . . . . . . . . . . . 2.2.2 Design . . . . . . . . . . . . . . . . . . . . . . . . 2.3 Game Screen - Graphics . . . . . . . . . . . . . . . . . . 2.3.1 Initial Considerations . . . . . . . . . . . . . . . . 2.3.2 Drawing . . . . . . . . . . . . . . . . . . . . . . . 2.3.3 Implementing Castling, Promotion and Animation 2.3.4 Implementing clicking in Hexagonal Chess . . . . 2.4 Android Front-End . . . . . . . . . . . . . . . . . . . . . 2.4.1 General . . . . . . . . . . . . . . . . . . . . . . . 2.4.2 Supporting multiple screen sizes . . . . . . . . . . 2.4.3 Data storage . . . . . . . . . . . . . . . . . . . . . 2.4.4 Notications . . . . . . . . . . . . . . . . . . . . . 2.4.5 Implementation . . . . . . . . . . . . . . . . . . . 2.4.6 Challenges . . . . . . . . . . . . . . . . . . . . . . 2.5 Controller . . . . . . . . . . . . . . . . . . . . . . . . . . 2.6 Backend . . . . . . . . . . . . . . . . . . . . . . . . . . . 2.6.1 Design Decisions . . . . . . . . . . . . . . . . . . 2.7 Social features - Integration with Facebook . . . . . . . . 2.7.1 Login . . . . . . . . . . . . . . . . . . . . . . . . . 2.7.2 Friend list . . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . .

3 User Interface Design 3.1 Designing with a user focus . . . . . . . . . . . . . . . . . . . . . . . . . . 3.2 Splash Screen and Main Menu . . . . . . . . . . . . . . . . . . . . . . . . . 3.3 Local / Remote Games Screens . . . . . . . . . . . . . . . . . . . . . . . .

Contents

3.4 3.5

Rules . . . . . . . . . . . . . . . My Account . . . . . . . . . . . 3.5.1 Registration / Login . . 3.5.2 Password Congurations 3.5.3 Users details . . . . . . . 3.5.4 Friends . . . . . . . . . .

. . . . . .

. . . . . .

. . . . . .

. . . . . .

. . . . . .

. . . . . .

. . . . . .

. . . . . .

. . . . . .

. . . . . .

. . . . . .

. . . . . .

. . . . . .

. . . . . .

. . . . . .

. . . . . .

. . . . . .

. . . . . .

. . . . . .

. . . . . .

. . . . . .

. . . . . .

. . . . . .

. . . . . .

34 35 36 37 37 38 39 39 39 39 40 41 41 41 42 42 42 45 46 48 48 50 50 51 52 52 52 53 54 54 54 54 55 55 55 55 55 55 55 57 58 58 59 59

4 Project Management 4.1 Team Organisation . . . . . . 4.1.1 Team Collaboration . . 4.1.2 Task Allocation . . . . 4.1.3 Tools . . . . . . . . . . 4.2 Software Design Methodology 4.2.1 Agile methodologies . 4.2.2 Testing . . . . . . . . .

. . . . . . .

. . . . . . .

. . . . . . .

. . . . . . .

. . . . . . .

. . . . . . .

. . . . . . .

. . . . . . .

. . . . . . .

. . . . . . .

. . . . . . .

. . . . . . .

. . . . . . .

. . . . . . .

. . . . . . .

. . . . . . .

. . . . . . .

. . . . . . .

. . . . . . .

. . . . . . .

. . . . . . .

. . . . . . .

. . . . . . .

. . . . . . .

. . . . . . .

5 Evaluation 5.1 Evaluating deliverables . . . . . . . . . 5.1.1 Eectiveness . . . . . . . . . . . . 5.1.2 Impact . . . . . . . . . . . . . . . 5.1.3 Eciency . . . . . . . . . . . . . 5.2 Testing . . . . . . . . . . . . . . . . . . . 5.2.1 Testing the Android Application . 5.3 Reliability . . . . . . . . . . . . . . . . . 5.4 Security . . . . . . . . . . . . . . . . . . 5.5 Overall evaluation . . . . . . . . . . . . .

. . . . . . . . .

. . . . . . . . .

. . . . . . . . .

. . . . . . . . .

. . . . . . . . .

. . . . . . . . .

. . . . . . . . .

. . . . . . . . .

. . . . . . . . .

. . . . . . . . .

. . . . . . . . .

. . . . . . . . .

. . . . . . . . .

. . . . . . . . .

. . . . . . . . .

. . . . . . . . .

. . . . . . . . .

. . . . . . . . .

. . . . . . . . .

6 Conclusion 6.1 Project Challenges . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6.2 Other Potential Directions . . . . . . . . . . . . . . . . . . . . . . . . . . . 6.3 Our personal development . . . . . . . . . . . . . . . . . . . . . . . . . . . Appendices A Chess Rules A.1 Traditional Chess . A.1.1 Objective . A.1.2 Draw . . . . A.1.3 Stalemate . A.1.4 Board . . . A.1.5 Promotion . A.1.6 En Passant A.1.7 Castling . . A.1.8 Pieces . . . A.2 Chess 960 . . . . . A.3 Capablanca Chess . A.3.1 New Pieces A.4 Grand Chess . . . . A.4.1 Specics . . ii

. . . . . . . . . . . . . .

. . . . . . . . . . . . . .

. . . . . . . . . . . . . .

. . . . . . . . . . . . . .

. . . . . . . . . . . . . .

. . . . . . . . . . . . . .

. . . . . . . . . . . . . .

. . . . . . . . . . . . . .

. . . . . . . . . . . . . .

. . . . . . . . . . . . . .

. . . . . . . . . . . . . .

. . . . . . . . . . . . . .

. . . . . . . . . . . . . .

. . . . . . . . . . . . . .

. . . . . . . . . . . . . .

. . . . . . . . . . . . . .

. . . . . . . . . . . . . .

. . . . . . . . . . . . . .

. . . . . . . . . . . . . .

. . . . . . . . . . . . . .

. . . . . . . . . . . . . .

. . . . . . . . . . . . . .

. . . . . . . . . . . . . .

. . . . . . . . . . . . . .

. . . . . . . . . . . . . .

. . . . . . . . . . . . . .

. . . . . . . . . . . . . .

. . . . . . . . . . . . . .

. . . . . . . . . . . . . .

. . . . . . . . . . . . . .

. . . . . . . . . . . . . .

Contents

A.4.2 New Pieces A.5 Glinskis Hexagonal A.5.1 Specics . . A.5.2 En Passant

. . . . Chess . . . . . . . .

. . . .

. . . .

. . . .

. . . .

. . . .

. . . .

. . . .

. . . .

. . . .

. . . .

. . . .

. . . .

. . . .

. . . .

. . . .

. . . .

. . . .

. . . .

. . . .

. . . .

. . . .

. . . .

. . . .

. . . .

. . . .

. . . .

. . . .

60 60 60 61 62 63 64 64 64 64 65 66

B Entity Relationship Diagram of Database C Matrices and Coordinates D Chess Clocks D.1 Background . . . . . D.1.1 Blitz . . . . . D.1.2 Standard . . . D.2 Our implementation Bibliography

. . . .

. . . .

. . . .

. . . .

. . . .

. . . .

. . . .

. . . .

. . . .

. . . .

. . . .

. . . .

. . . .

. . . .

. . . .

. . . .

. . . .

. . . .

. . . .

. . . .

. . . .

. . . .

. . . .

. . . .

. . . .

. . . .

. . . .

. . . .

. . . .

. . . .

iii

Executive Summary
CheckMate is a fun Android Application which enables interested users, of varying skill levels, to play Traditional Chess or Chess variants. Currently, the following Chess variants are supported: Chess960, Capablanca Chess, Grand Chess and Gliskis Hexagonal Chess. The application runs on all Android 4.1 compatible mobile devices and it will soon be available to download from Google Play. Users are able to play locally against each other on the same device, or remotely against their friends within the developing CheckMate community which is open for joining to Facebook or other users. Upon completion of a game the players receive experience points; the sum of which determines their current level within the community. Users are able to resume games that they have not nished or replay their recently nished games. The application also oers the ability to play multiple games simultaneously so that users can make all their moves while they wait for their turn to come in their active games. Furthermore, it allows users to start remote games on one device and continue them on another, giving them better control over their saved games and preferences. The main purpose of our product is to ll the gap in the market concerning people who would want to play variants of Chess on their Android mobile devices. By design, the application mainly targets professional players of Chess variants or Traditional Chess players who are eager to explore some of the existing variants. It should be noted, however, that the application does not assume that the users are already familiar with the game types supported and provides in-depth coverage of the relevant rules for each type. We have also decided to include Traditional Chess in the package in order for Chess beginners or Traditional Chess lovers to also try the application. Despite its rather specialised nature, our application still attempts to win over players of mobile games in general by providing them with an entertaining and educating experience that also has a social element. Users are thus encouraged to compete among themselves in order to enhance their experience level, and consequently elevate their skill status within the CheckMate community.

iv

Chapter 1 Introduction
1.1 Motivation

The motivation for this piece of work stems from two aspects of modern life, Chess and mobile devices.

1.1.1

Chess

Chess is a very popular strategy board game played by 600 million people worldwide[1]. Over the years, many players have created variations of the original game. The variations alter the starting positions, pieces or board shape or some combination of these. Popular variants include Grand Chess, Capablanca Chess and Gliskis Hexagonal Chess.

1.1.2

Mobile Devices

The mobile phone and tablet market has shown a continuously growing number of users[2]. Since their rst appearance these devices have matured, and are now at a point where they are powerful enough to allow users to play games with quality graphics, be used as laptop replacements[3] and be used to enable multi-party conferencing in real-time. Traditional Chess players have a plethora of applications enabling them to play Chess on the go. Currently the most popular application on the Android Play Store with 340,000 downloads for both mobile phones and tablets is Chess Free[4] with the second most popular being, Chess Live, having 50,000 downloads. This shows the dimensions of the user base of Traditional Chess as well as showing the popularity of gaming applications. We have attempted to ll the gap in the market by creating an application which enables users to play Chess variants and Traditional Chess on their mobile devices, whilst extending our skill set into the realm of mobile and tablet application development. We have focused on Android Application Development, primarily because the development tools are free, well documented and do not require a particular development platform. Moreover, there seems to be a distinct lack of applications that integrate Traditional Chess with Chess variants in the Android market as well as a huge user base. This can be estimated by the rapidly increasing number of mobile device users, the high number of gaming application downloads and the sizable number of players of Traditional Chess and Chess variants.

Chapter 1. Introduction

1.2

Objectives

The initial requirements proposed by our supervisor, Giuliano Casale, are given as follows: An Android game and a backend application for mobile chess variants - Capablanca Chess, Grand Chess, Hexagonal Board and others. Ability to play remotely Real-time playing as well as oine playing (and should handle gracefully when a user goes oine) A toy chess engine at least for one of the variants Good use of Object Oriented Programming to abstract the characteristics of the game Usability tests across a base of friends or users. Other optional requirements include the ability of participating in tournaments, assigning and tracking ranks and a web interface for the backend application manager. From these requirements we developed our user and application objectives.

1.2.1

User Objectives

The application should enable mobile Chess players to play Chess variants, as well as Traditional Chess, locally and remotely with other players. The users should be able to connect and play in real time with friends on Facebook as well as play with other aleatory users. Furthermore, they should be able to play multiple games simultaneously, without requiring the game to be completed in a single session. Users should be able to see the valid moves that a piece can make by clicking on a particular piece, which should highlight the destination cell of the moves.

1.2.2

Application Objectives

In addition to user objectives, the application also has a certain number of requirements which must be met. The application must gracefully handle constantly changing network availability and display a thoughtful use of OOP throughout the code. Moreover, the application should be developed with short iterations cycle at the end of which Usability tests are performed and feedback is used to enhance the application.

1.3

Introducing CheckMate

CheckMate has fullled the above user objectives by providing a rich user experience with the following features: Users can play Traditional Chess, Chess960, Capablanca, Grand Chess and Gliskis Hexagonal Chess. Users can pause and resume games, which enables many games to be simultaneously played over a period of time. 2

1.3. Introducing CheckMate

Users are able to replay completed games, this enables users to review and learn new strategies. Users are able to connect and play any of these variants with friends from Facebook or other randomly chosen CheckMate users. Furthermore, users are also able to play with a local opponent on a single device. Users are encouraged via an achievement system to try out new variants, gaining points for games drawn, won and lost. Therefore, this keeps users interested and engaged. An extensive description of the rules of each variant and a quick help menu in the game screen provides clear opportunities for the user to learn and play a new variant. Moreover, CheckMate also fulls the application requirements by: The use of design patterns and encapsulation to abstract the characteristics of the game. This would enable new Chess variants to be added quickly and therefore keep the application fresh and exciting. It gracefully handles network outages by carefully managing the game state through the database stored on the server. When a user goes online again, the moves can be retrieved and replayed. Employing a set of usability testing methods includingn Observation Testing and GUI Intuitiveness Testing as necessary per iteration cycle.

1.3.1

Chess Variants

Below are the main dierences between the Chess variants and the Traditional Chess: Chess 960 Chess 960 uses the same number of pieces and board size as the original chess, however the starting positions are randomised, with a few constraints in order to enable castling. There are 960 possible starting positions, hence the name.

Chapter 1. Introduction

Capablanca Chess Capablanca Chess extends the original pieces set with two extra pieces, the Chancellor and the Archbishop. The Chancellor has the combined moves of the Rook and Knight. The Archbishop has the combined moves of the Bishop and Knight. The board is extended by two les.

Grand Chess Like Capablanca Chess, it also extends the piece set with two extra pieces, the Marshal and Cardinal. The Marshal takes the combined moves of the Rook and Knight. The Cardinal takes the combined moves of the Bishop and Knight. Moreover, the starting position is altered further, as shown below.

Gliskis Hexagonal Chess Unlike the other two variants mentioned Gliskis Hexagonal Chess changes the board completely, as you can see below. However, the pieces tend to have extended behaviour. There is one more Bishop per player.

Chapter 2 Design and Implementation


In this chapter we turn our attention to the software design. We rst look at the high-level design of CheckMate, then focus on some key details.

2.1

System Architecture Design

CheckMate is a large software project. It comprises of a signicant number of Java classes (112) and PHP scripts (24). The total number of lines of code, across all components, is over 15,000. The system architecture is split into the following main components:

Figure 2.1: System Architecture The following sections describe each of the components in terms of its main features, implementation details, challenges and design decisions.

2.2

Game Logic

The following diagram depicts the relationships between the main parent classes that form the basis of the implementation of the rules of Chess, Board Representation, Game 5

Chapter 2. Design and Implementation

Engine and Players.

Figure 2.2: UML diagram of primary Game Logic Components The sections below explain how these parts were designed, implemented and interact with each other.

2.2.1

Implementation

2.2.1.1 Board One of the vital features of the game logic are the board functions and its representation. As some of the Chess variants exhibit changes to their board layout, it was important to implement the board in such a way that the code would be easily extendable for dierent types of board and we would avoid code replication. As such, we made use of the Template Method pattern, where the class AbstractBoard holds the common functionality used by any type of board, in our case rectangular board and hexagonal board.

Figure 2.3: UML diagram of Abstract Board We rst started by considering what board representation to adopt. Piece centric, cell centric or hybrid solutions are currently well known board representations[5]. A piece centric representation keeps a list, array or sets of all the pieces that are still alive on the board together with the information about the pieces position. On the other hand, a cell centric representation holds the information about the cell (in our case a square or hexagon), whether it is occupied or not. After considering these representations, we 6

2.2. Game Logic

decided to implement a hybrid solution by having a 2D array of the type Piece where the indices would identify the piece position in the board as well as having an array of Piece sets that would hold the pieces that are alive for each player and their respective position. The reason for this is that the 2D array gives a clear map from the move coordinates given by the user to the position of the piece, but relying only on the 2D array would mean that instant access to pieces would be slow as it would involve iterating through the whole board. Therefore, having a set of the pieces allows the computation time associated with nding a particular piece to be reduced. As well as the AbstractBoard holding the board representation, it is also responsible for checking for the validity of a move, making the move and updating any information needed, such as castling rights and the possibility of en passant. It also communicates to the Game about the players that are in check.

Figure 2.4: UML diagram of Board Relationships For a move to be valid a few constraints must hold, which include: the move may not put the players king in check and the move must be allowed as part of the attackable moves (the Directions and distances a piece can move to capture a piece) if the destination cell is occupied by the opponents piece. The former is checked by taking the Kings position as the starting position and all the Directions that are allowed for any piece to move within the specic board, iterating through these Directions vectors adding them to the Kings position to nd any opponents piece that the King is able to see. Upon nding the opponents piece, we then check whether the Kings position is in the range of the pieces attackable moves, if so, the move is considered to have put the player in check and therefore is invalid. The latter follows a similar procedure, we iterate through the range of ValidMoves (an object that contains a Pair of a List of Directions and an Integer to represent the distance allowed) for the attackable moves of a piece and add the Direction vectors to a set of Positions, with certain constraints. If the set of Positions contain the Position of the destination cell then the move is said to be valid. Traditional, 960, Capablanca and Grand Chess All but one Chess variant implemented in our application are played on a rectangular board, though with varying dimensions, initial piece layouts and permissible special behaviours. The Traditional Chess game is instantiated by the Game class in one of its static factory methods. It uses an 8x8 RectangularBoard and a String that holds the initial board conguration, the permissible special behaviours are taken from the default list, which allows all the existing special behaviours to be performed on the game. The implementation of Chess960 is identical to that of Tradition Chess with the exception that the initial board conguration is constructed by randomizing the conguration string under a few constraints. Both Grand Chess and Capablanca Chess add new pieces to the board 7

Chapter 2. Design and Implementation

and have their special characteristics handled primarily by the AbstractBoard and the Pieces themselves. Gliskis Hexagonal Chess

Figure 2.5: Gliskis hexagonal chess starting position (wikipedia.org) Gliskis Hexagonal Chess is played on a regular hexagonal board where each side consists of 6 cells. As shown in Figure 2.5, the boards coordinates are dened with 11 les (marked by letters a-l) and 11 ranks (marked by numbers 1-11). This way of indexing the cells is not easily translated in a software based implementation. Therefore, we had to use a dierent coordinate system suitable for the underlying algorithms and storage of the board. We had the option to choose between three coordinates systems: Oset coordinates: Oset every column in the way shown in gure 2.6.

Figure 2.6: Oset Coordinate system for Hexagonal board (redblobgames.com) Cube coordinates: This is a three dimensional coordinate system (3D), where each direction on the hexagonal board corresponds to an axis, see gure 2.7. As all the game logic for the other Chess variants were implemented for a two dimensional coordinate system (2D), using a 3D system would require us to provide another implementation for every procedure and algorithm used in the game logic. However, 8

2.2. Game Logic

a way around this would be to use coordinate conversion methods in a wrapper class around the 3D system implementation which would mean that the current implementation would still be applicable. For example the wrapper would convert cell (q,r) to cell (x,y,z) where x = q, z = r, y = -x -r.

Figure 2.7: Cubic Coordinate system for Hexagonal board (redblobgames.com) Axial coordinates: This uses only two out of the three axes from the cube coordinates system similar to the way shown in Figure 2.8. Using this 2D approach would allow us to have one game implementation for both the rectangular board and the hexagonal board based games, without the need for a wrapping class.

Figure 2.8: Axial Coordinate system for Hexagonal board (redblobgames.com) We chose to use the Axial coordinate system as it has the advantage that algorithms applied on the rectangular board can be applied on the hexagonal one as well. That would lead to a higher code reuse and better abstraction. It is also closer to the original coordinates of the Gliskis Hexagonal Board and translation between the two coordinate systems is more straightforward. 9

Chapter 2. Design and Implementation

However, the Axial coordinate system creates a point of compromise, between space and time. One could either store the board in a 2D array, or in a HashMap which would lead to space eciency. Moreover, the 2D array allows direct access to the data, whereas in the case of the HashMap, a function is required to determine the memory location, which results in a slower access time. As a result, we opted for a 2D array implementation. The basic concept behind storing the board using Axial coordinates is to take a square array, in our case a 11x11 array and to skew it so as to make a parallelogram. Two opposite corners of this parallelogram are then cut o so as to create a hexagon (as can be seen in the Figure 2.9). The skewing of the array gives a coordinate axes that is also skewed. The y-axis remains in the same direction, namely facing north. The x-axis on the other hand now has been oset by 30 degrees in the clockwise direction. This means that every cell can now be seen as having 6 adjacent neighbours, with the relative coordinates seen in Figure 2.10.

Figure 2.9: Skewing array for hexagonal board

Figure 2.10: Axial coordinates Gliskis Hexagonal Chess In this variant of chess, the pieces perform moves that can be seen as quite dierent to their rectangular board counterparts. For instance, the bishop can move in the directions 10

2.2. Game Logic

shown in Figure 2.11. It can clearly be seen that the bishop have in the hexagonal board more directions to move in. Furthermore, it is not even necessary that each piece will have its previous valid directions plus some extra directions. Continuing with the previous example, the bishop only keeps 2 of its previous directions, namely northwest and southeast as these are the only coordinates that directly translate from the rectangular board to the hexagonal one. Regarding the other moves, moving east for instance, actually is equivalent to an L shape move on a rectangular board, as this translates to adding a vector (2, 1) to the Bishops position.

Figure 2.11: Bishop moves (wikipedia.org)

2.2.1.2 Game Engine The Game class is the glue between the game logic and the controller. It contains functionality for reading a Move from the Player (as passed by the controller) and passing the move internally to be processed by the game logic. The updated status is then passed through to the Game class as a Move object once again, which contains all the information needed to update the view, for example a Piece that has been captured and the coordinates of the Piece that has captured it.

Figure 2.12: UML diagram of Board Relationships The Game is also responsible for checking whether the game is over. Every time a new Move happens, the Game checks whether any player has won or if a draw has occurred 11

Chapter 2. Design and Implementation

and if so, it propagates this information through the controller to the view so that an appropriate action can be taken. In addition, it keeps track of whose turn it is to play. Moreover, the Game also keeps a list of Players and updates their status (alive or dead). By having a list of Players the code can be easily extendable for games that involve many players. 2.2.1.3 Pieces The Piece class is an abstract class that is the parent of all the dierent pieces on the board. Its various attributes include an enumerated type, Color, which is used to identify the player without having any direct dependencies on the Player class. In this way, the link between the specic Player and the Piece is loosely coupled. It also has a list of SpecialBehaviours (see Design section for further explanation), which is used to hold the moves that could enhance the range of valid moves of a Piece. A ag is also included to notify whether a Piece has been moved, as for some of the special behaviours there are constraints on whether the Piece has been moved. Furthermore, as dierent board geometries, for example Hexagonal, give rise to Pieces being able to move in dierent directions, the Piece must know about the BoardType. On the contrary, it does not need to specically know what Game type is being played, as this has no eect on the type of moves a Piece can do, for example a Pawn can do the exact same moves in the board used for Chess960 as in any other rectangular board. For each Piece, two dierent types of moves must be dened, namely attackable moves and allowable moves. The former represents the moves as vectors that a Piece can use to capture the opponent Players piece, whereas the latter contains the moves with which a Piece can navigate the board. By default, the attackable moves are the same as the allowable moves, but this is overriden where applicable. Each Piece must implement its own allowable moves.

Figure 2.13: UML diagram of Board Relationships Any Piece can be categorised in one of the two child classes that extend Piece: BasicPiece, which denes Pieces with primitive moves, or CombinatoryPiece, which dene Pieces whose moves are a union of one or more BasicPieces moves. The BasicPiece class takes care of the groups of moves and directions that go together. For example the Rook can move vertically and horizontally, this means that the associated Directions (an enumerated type that contains coordinates as vectors in the form, NORTH(1, 0), with 12

2.2. Game Logic

1 being the y direction and 0 being the x direction) can be added to a list to form a group, and then the associated child class can then call an appropriate method to get this list and add it to its allowable moves list, along with the distances allowed. Each CombinatoryPiece rst instantiates an object for each of the BasicPieces that it can be represented as a union of and then creates a list of all their allowable moves to be used as its own set of allowable moves. Special Behaviours To handle Castling, En Passant and Promotion in an elegant manner, we made use of the Strategy Pattern, as described later in the Design Section 2.2.2, and created a SpecialBehaviour interface. The functionalities of the SpecialBehaviour interface include the validation of the special behaviour, and the performance of any side eects that occur on the board after the special behaviour has been concluded. For example, after performing castling on the kingside the Rook moves to the square to the left of the King. Each piece contains a list of SpecialBehaviours. Although special behaviours are a characteristic of a piece, it may not be necessarily allowed in a particular game. For instance, Castling cannot be performed in Grand Chess. The Castling class, is responsible for checking whether the behaviour is allowed to be performed given a number of constraints. The possibility of En Passant is checked within the AbstractBoard class, which holds an EnPassant object containing the information about the Pawn that has just performed a double-step move and the Position of its nal destination cell. After the opponent players move, the EnPassant object becomes empty. On the other hand, Promotion varies more per game. Grand Chess has the greatest number of Promotion options. There are two checks done, when a move is attempted, rstly if Promotion is possible and secondly if promotion is obligatory. Depending on the outcome of these checks and if the user requested promotion (when this is optional), the logic either accepts the move, or informs the user that the move was not valid. 2.2.1.4 Player The Player class is used to represent a player. Its several attributes include a ag to identify the type of the player (human or computer), thus removing the need of creating a separate class to just represent an AI. A player can be categorised by two statuses, alive or dead. At the start of the game all players have their alive ag set to true, which remains true until a player is checkmated. At this point, the Game will then check if there are more than two players still alive, if not, the game is declared to be over and the player who remains alive is the winner. All the players are considered dead if the game is a draw, and in this case there are no winners. In addition, the Player class includes an enumerated type Color, which is used to identify the set of pieces associated with the player, keeping the Piece and Player class loosely coupled as explained in the Piece, see section2.2.1.

2.2.2

Design

In an application of this size it is essential to use proven design patterns and encapsulation to keep the code maintainable, to ensure extendibility with the varying specication, to 13

Chapter 2. Design and Implementation

reduce code duplication and to improve readability. Examples of this can be illustrated throughout the game logic. For instance, the Game class, which holds the game engine for the logic, extensively employs the use of static factory methods. The reason for this is that there are several chess variants, as described previously, which require a game engine. Consequently, code duplication can be avoided by containing all the functionality required for the engine within a single class, regardless of what Chess variant the engine will be for, and for each variant, writing the additional functionality required in a labelled constructor, thereby preventing the need to create several dierent derived classes of Game. Moreover, it allows the Game class to have several constructors representing the variants with the same number and type of arguments. Added to this, the Template Method pattern was eective in keeping common code in base abstract classes, to reduce code duplication. An example of this can be seen in the Piece class, which is an abstract class holding the common functionality used by each of its child classes, namely BasicPiece class and CombinatoryPiece class, which itself is also an abstract class providing the functionality for creating pieces that are purely combinations of the base pieces. For instance, the Queen can be seen as a union between the moves that can be performed by the Bishop and by the Rook. The template methods in this case for Piece include getColour() and hasMoved(). It is fairly clear that these are independent of the type of the piece, and therefore by having this common functionality in Piece, code repetition can be greatly reduced. An example of a hook method is getAllowableMoves(), which on the contrary, is completely piece dependent and therefore must be overridden. Complications would have arisen, if we had only relied on the Template Method to be completely responsible for the behaviour of each child class of Piece. This can be seen as some derived classes of the Piece class have special functionality, for example the King has a move called Castling which involves the Rook also, which can only be realised under certain conditions and is unique to the King. Having the base class, Piece, not contain this information would mean that any generic method that uses polymorphism and tests whether a piece has special moves would need to rst have to know the list of pieces that do contain special moves, then check whether the particular piece is an instance of any of these pieces, and then if so, would be able to access the special move. This is clearly a bad software engineering practice as information hiding is minimal. On the contrary, having the Piece contain a list of SpecialBehaviours, following the Strategy pattern, means that any method that needs to check whether a Piece has a special move merely has to check whether this list is not empty, and if so, it can then perform the move. In this way, no information needs to be shared about which Pieces contain the special moves and the special move itself does not need to be exposed. This also means, that if in a later iteration another piece is added or an existing piece is modied to contain a special behaviour, nothing needs to change for any method that calls these special behaviour moves, as opposed to the previous case in which these pieces would need to be added to the list of Pieces that contain special moves and the names of their special moves would also need to be known.

14

2.3. Game Screen - Graphics

2.3
2.3.1

Game Screen - Graphics


Initial Considerations

The rst important decision to make, was to decide which graphics API would be used for drawing screen. There are two options within the Android environment, Canvas and OpenGL (specically OpenGLES). The Canvas API is the simplest however, we were initially looking at implementing a 3D chess game. Canvas is a 2D only drawing API. Therefore the only option was OpenGL. Furthermore, OpenGL is an industry standard, and with hardware support within the GPU. All good Android devices have a discrete GPU, therefore we are able to take full advantage of the devices capabilities. Version 2.0 of the API was chosen as a starting point, since version 1.0 is only for 2D graphics. We would not increase the requirement without careful consideration (the app at its completion only requires version 2.0). Only very new devices support version 3.0, therefore limiting the user base of the App[6]. 2D vs 3D The rst few sprints were spent creating a 3D chess board, with the ability to move piece and update the view after a move is performed. A 3D board was successfully created, however when it was shown to the rest of the group some problems were noticed. The primary developer was testing on an emulator, where a cursor was used as the pointing device. However when the app was tested on a Nexus 7, the app would interpret a click as a drag, which would move the board instead of selecting a piece. This was caused by the clicking being interpreted as a drag since a nger press is less precise as a mouse click and any movement would be treated as a drag. It was clear that the 3D board would not provide a good user experience, and therefore support would be removed and only a 2D interface would be provided. Implementation As with every Android App, an activity is a container and manager for everything which is displayed to the user. The activity for the game screen is the GameActivity class. This creates the Controller and GLSurfaceView for the game. The controller loads the appropriate moves from either the server or the users device, should they exist. The controller then takes over the role of managing the game. GameActivity provides support for showing Toasts and windows when the game requires the user to select something, e.g. a piece when a promotion is about to take place. The Controller connects the game logic to the graphics code. Furthermore the controller either connects to the database to fetch moves or the users device. Most of these operations happen asynchronously to allow the user to continue playing. GLView (CheckMates implementation GLSurfaceView) manages the rendering and also provides an interface for the Controller to send updates it has received e.g. moves from the server. GLView captures the clicks and processes them. The Renderer GLRenderer (CheckMates implementation GLSurfaceView.Renderer) handles all the drawing using OpenGL. As per the project requirement, there has been careful design of the

15

Chapter 2. Design and Implementation

Figure 2.14: UML diagram of GameActivity components classes to make and show good use of Object Orientated Programming. This has helped tremendously when adding in the hexagonal board.

Figure 2.15: UML diagram of Renderer components The GLRenderer runs in a separate thread to GLView and only some functions can get a handle to the OpenGL Instance. These two features caused interesting problems, some of which will be discussed. The primary problem is that various objects need to be initialized with the screen size in order for the correct size and positioning of all the objects which are to be drawn. Another problem is that the method onSurfaceChanged can be called multiple times, with various parameters until the OpenGL instance has settled down. The solution is to have a eld which when any updates are made, they are cached, and fact that an update has occurred is noted. When it comes time to draw if there have been any updates which 16

2.3. Game Screen - Graphics

need attending to, they are then dealt with.

2.3.2

Drawing

All drawing, whether it is text, pieces, the board, follow a very similar pattern. Some pre-calculation of positions, and initial work loading in coordinates and images is done. Then when it comes time to draw, it can be done eciently, transferring the least amount of data possible to the GPU, in order to reduce the draw time and improving the battery life of the device. We have followed the standard OpenGL practices, for more information see Appendix C Sprites: Drawing Text and Buttons A sprite is an image which holds many other images. It reduces overhead and is faster for reusing the sub images. There are a few sprites in use, one for the pieces, text (alphanumeric characters) and buttons. All the sprites are dealt with in a similar fashion. The only textures used in the application are sprites. For each image type to be drawn, e.g. buttons, text, a Java class manages the loading and setup for drawing. The TextureManager class manages the loading of images (textures) into the OpenGL instance. This class follows the singleton pattern, to enforce that there is only one instance managing the textures. This is to make sure images are not loaded multiple times for dierent classes.

2.3.3

Implementing Castling, Promotion and Animation

Once we had a basic board working, the next requirement was to get castling and promotion working, whilst considering how to do animation. Castling and promotion are dierent to normal moves since the pieces on the board change. Notications from the GameLogic When implementing castling, promotion and especially animation it is crutial to know when the cells contents are changed. The initial design was to have a list of pairs of pieces and positions, a null piece signifying it had moved / got taken. This is an average solution, however when trying to animate it was very dicult to determine whether a piece had been taken, or where it got moved to. It was noticed that there are only ever two pieces involved in any move, the attacker and victim. Therefore when a move is performed the GLView is notied, via a move object returned, what cells have changed pieces. Therefore, it is simple to update the cells with their new pieces and animation is simply calculating the path from the original cell to the new cell. Animation Although a major write was required, animation makes the game aesthetically pleasing and more natural to play. The animation is performed once a successful move is made. First the path of of the moved pieces (maximum of two) is calculated. Next, a periodic timer is started and on each timeout, the piece(s) are moved along the path and a redraw

17

Chapter 2. Design and Implementation

is requested to update the screen. When the piece has moved along the path and at the new position, the board is updated with the new positions. The game can now continue. The piece path follows a cubic Bzier curve. A cubic Bzier curve has 4 points, a start point (P0) and an end point (P3). The other two points (P1, P2) provide direction. A cubic Bzier curve is shown below.

Figure 2.16: Bezier Curve (Wikipedia) The equation, which this line represents is, B(t) = (1 t)3 P0 + 3(1 t)2 tP1 + 3(1 t)t2 P2 + t3 P3 , t [0, 1]. The parameter t is incremented on each frame of the animation to make the piece move from the start point, P0, to the destination point, P3. The values of P{0-3} depend on the type of the move and the piece type. Pieces always move from the center of the start cell to the center of the destination cell. Horizontal, Vertical and Diagonal P0, P1 are equal to the start point and P2, P3 equal to the end point. L-Shape An L-Shaped move, like that of a Knight, has the following values: P0, P1 are equal to the start points and P2 is (Start.row, Destination.column), P3 is the end point. Take For a move when a piece is taken, the captured piece must move into the captured pieces set, below the players name. The points for the path are: P0, P1 are equal to the start, P2 (width / 2, 0), and P3 the destination cell of capture board. Castling Castling provided an opportunity to make a fun animation. The idea was to have the King hop over the Rook as the Rook moves horizontally. Therefore, the path for the Rook, is as given above. The King needs to move up, along then down. To do this the following points are required: P0: Start 18

2.3. Game Screen - Graphics

P1: (Start.x + 1.5 cellwidth, Start.y + 1.5 * cellheight) P2: (Destination.x + 1.5 cellwidth, Destination.y + 1.5 * cellheight) P3: Destination The 1.5 value is specially chosen to make sure the King does not touch the Rook. Replay Mode Since we have animation for the moves, a natural progression was to create a replay mode. The animation makes the moves appear more natural, instead of jumping from one position to another, without any transition. Users can replay completed games, therefore they can see good positions and learn from mistakes.

2.3.4

Implementing clicking in Hexagonal Chess

Implementing clicking for the hexagonal board was not as trivial as that of the rectangular board. Patels resource [7] provided great assistance in solving this probem. There is no native support in OpenGLES for determining the object clicked, an algorithm had to be developed in order to determine the object which was clicked. There are two possible solutions: Colour. This method assigns unique colours to all clickable objects. Then rerenders the scene, and checks which colour is at the location clicked. Algorithmically. In this methed an algorithm is used which converts the coordinates of the user click into a way of determining the object clicked. The colour method, is not a good solution, as (1) all objects need a unique colour, this requires managing which colours already have been used, (2) the entire scene has to be rerendered, which is inecient. Therefore, the algorithm method was used. The Hexagon The following diagram shows properties used throughout the following description.

Figure 2.17: Diagram of hexagon properties

Converting click coordinates to a Hexagon index A few steps were required to convert a cartesian, e.g. (x, y), coordinate to the correct hexagon index.

19

Chapter 2. Design and Implementation

Cartesian coordinate to approximate Hexagon It is easier to explain this conversion in reverse, i.e. converting a hexagon to a set of pixels. We chose to use Axial coordinates, since it makes the manipulation easier. Given a xed origin, the position of all hexagons on the board can be determined using two vectors Q and R, the basis vectors. This is shown in gure 2.18.

Figure 2.18: Base Vectors Therefore, all hexagon cells are given an axial coordinate: (q, r) where q, r Z. By varying, a, b [0, 1), in (q + a, r + b), all pixels contained within a given hexagon, (q, r), can be determined. Given, (q + a, r + b), the cartesian coordinate (x, y ) need to be calculated. For the horizontal axis: only Q has a component in this axis. x= 3 width q 4 3 = size 2 q 4 3 = size q 2

20

2.3. Game Screen - Graphics

For the vertical axis: Q and R both have components in this axis. y =A+B where, 3 A= width r 2 3 = size 2 r 2 = 3 size r 3 q width B= 2 2 q 3 size 2 = 2 2 q = 3 size 2 therefore, q y = 3 size (r ) 2 As previously noted, the above conversion, given a cartesian coordinate (x, y ), needs to be inverted in order to determine the approximate hexagon clicked. Inverting x and y above gives: x size 1 1 3y 3 x r = 3 size
2 3

q =

Hexagon Rounding However, the full conversion is not yet complete. The (q , r ) axial coordinate represents the (q + a, r + b) coordinate above. In order to get the correct axial coordinate the a and b need to be removed. Patel[7] recommends a method he calls hexagon rounding. Hexagon rounding, removes the a and b, via mathematical rounding and xing a constraint. Patel provides the algorithm for doing this, however he uses cubic coordinates, therefore the Axial coordinates need to be converted, see section 2.2.1. function rx = ry = rz = hex_round(Cube(x, y, z)): round(x) round(y) round(z)

x_diff = abs(rx - x) y_diff = abs(ry - y) z_diff = abs(rz - z) if x_diff > y_diff and x_diff > z_diff: rx = -ry-rz 21

Chapter 2. Design and Implementation

else if y_diff > z_diff: ry = -rx-rz else: rz = -rx-ry return Cube(rx, ry, rz) Finally, the coordinates returned from hex_round, are converted back to axial coordinates. Axial Coordinates to Hexagon Cell Index There are two issues with the coordinates generated from the above process. Firstly, some of the coordinates generated are not valid positions on the board. These cells can be seen in gure 2.19.

Figure 2.19: Hexagonal Board in green with the red invalid regions Secondly, the origin is in the bottom left hand corner of the screen. The chosen origin can be seen in gure 2.20, this allows the (q, r) coordinates to be directly used as the index to a 2D array of hexagonal cells. Both of these problems can be simply solved. For each column from the center (either way) remove 1 row from the y coordinate. If afterwards the coordinates are out of bounds of the array, then the coordinate is invalid.

2.4
2.4.1

Android Front-End
General

CheckMate was designed with regards to the ocial Android documentation (Android Developers), following some of the Best Practices advices. We also used some design paradigms from the book Sams Teach Yourself: Android Development in 24 Hours in order to build a user friendly, ecient application whose look and overall structure matches similar applications in the Android market. Firstly, we designed and implemented a basic user interface that would enable us to test the actual game. On each iteration we kept adding features by rst creating the 22

2.4. Android Front-End

Figure 2.20: Hexagonal Board Origin Location layout of the various screens and then writing the code that implemented the features. On the nal iterations we focused on making the user interface more attractive. Having a good design from the early stages of development was denitely a plus as it enhanced clarity and cohesion between classes and reduced code repetition. For example, by following the books advice we created a hierarchy of classes where the root contained all constants, settings and functions that were going to be used in multiple other classes. This well-dened structure allowed us to reduce the level of refactoring that needed to be done at the later stages.

2.4.2

Supporting multiple screen sizes

Aligned with the industrys standard, CheckMate is suitable to both phones and tablets. For that reason we carefully designed the layouts of the screens so that they would make good use of the available area, avoiding thus the need to design separate layouts for each screen size and orientation. An example of this is the use of multiple dimension XML resources: instead of declaring a width to have a specic size we set it equal to the title width, a resource identier that is dened in both values/dimens.xml and valuessw600dp/dimens.xml to have the value of 20sp and 40sp for phones and tablets (scale independent pixels) respectively. The Android OS will load automatically the denition that matches best the screen size and orientation of the actual device.

2.4.3

Data storage

Data storage posed a design dilemma: should we store the games state on the device or on the server? The former would mean that the retrieval of these data would be fast and the device wouldnt need an internet connection to operate. On the other hand, the latter would mean that the user could access the data by logging on a dierent device too. Moreover, the state of the games between remote players would have a higher probability of being in a valid and consistent form. Taking all these considerations into account we decided to follow the middle path: store data about local games on the devices storage and data about remote games on the server. 23

Chapter 2. Design and Implementation

2.4.4

Notications

Informing the user when certain events take place (such as when the opponent has made his move, has abandoned the game or the user was invited to a new game) could be implemented in two ways: by creating an application widget or by using the notications manager. The former would require that the user explicitly decides to add the widget in a specic area of the Widgets screen; however this area is typically small due to the limited number of available cells in the screen, a fact that would limit the amount of information we could display there. Moreover, it would require the user to check frequently the screen to see if there are any updates. On the other hand, issuing notications to inform the user of certain events was a more compelling solution as it would allow CheckMate to post multiple, variable length messages that can be viewed by the user at any screen. We thus decided to adopt the second design. The gure 2.21 illustrates the nal form of this service:

Figure 2.21: Screen shot of notications

2.4.5

Implementation

We used Eclipse as the IDE for Java with the Android Development Tools plug-in to build the application for two reasons: (1) we all had previous experience with it and (2) it is the tool that is recommended by Google for Android development as currently the alternative Android Studio is available only as an early access preview. This according to Google means that several features are either incomplete or not implemented and you may encounter bugs. We decided to build CheckMate from scratch using our own frontend and backend, essentially managing users and controlling remote games via a database and a collection of PHP scripts. The alternative was to use the Google Play Game Services SDK that was released last May. This would provide us with many ready-made features like real-time multiplayer via game lobbies and invitations, leader boards, awards, Google+ integration 24

2.4. Android Front-End

and cloud storage. While these sounded very exciting at rst, upon closer examination of this service we decided to reject it on the basis that it does not currently support turn-based games. This meant that as soon as a player disconnected from a game (either intentionally or unintentionally) the game would end. As Chess is by its nature a turn-based game that can take hours (or days) to complete, the only valid development approach was the rst one. Each screen of the user interface is implemented as an Android Activity. Activities are special classes that display a certain layout of graphical elements on the screen while at the same time they provide the code that utilizes the features associated with each screen. When the user navigates through the application they are essentially starting (or resuming) new activities and stopping old ones. Dialogs are used to capture user input and output information. Furthermore, Toasts1 are used to provide feedback to the user. Serialization An important implementation aspect in this project concerns object serialization: converting Java objects to strings so that they can be saved on the local disk or be transmitted to the server. Specically, we needed an ecient way to save the game state so that it can be resumed at a later time. In addition, serialization is also required when an object is needed to be passed from one Activity to another. We examined three possible solutions to address this requirement: 1. Implement the interface Serializable in all classes that need to be serialised. This would be simple (as it does not require the implementation of any methods) but it would provide poor performance. Also it would not allow us to customize this behaviour where this would be needed. 2. Implement the interface Parcelable in all classes that need to be serialised. This would give a good performance but it would require the implementation of a set of methods in each class to explicitly say how an object is going to be serialised. 3. Use Googles Gson library. This is a powerful utility that provides a very simple interface for converting an object to a JSON string and vice versa. It also provides good performance, supports recursive serialization and generics and allows custom behaviour to be specied where needed. For all these reasons we decided to adopt this solution. Resuming Games Regarding the feature of resuming games, the rst idea was to implement this by serialising (and storing) and deserializing all Java objects associated with a specic game. As work on the Game Logic progressed however, these objects became more and more in number, causing storage overhead as well as time overhead (especially in transferring their serialised form from the server to the device). We thus decided to change the implementation: to resume a game the application simply starts a new game and replays all existing moves before showing the board to the user. The space overhead is signicantly smaller as the only things that need to be saved now are the games type, the players names, the initial order of the players in the game and the list of all the moves up to now.
1

messages that appear on the bottom of the screen for a short duration

25

Chapter 2. Design and Implementation

Moreover, this approach gave us one more signicant benet compared to the initial one: the implementation of the replay mode could now be greatly simplied. CheckMate resumes a completed game, by just remaking all moves one by one with a small delay in between. Notications CheckMate (active or inactive) provides the user with notications by creating an Android Service that starts every one minute (provided that the user is signed in), checks in the background if there are any updates for the specied user in the database, creates any notications and then stops itself.

2.4.6

Challenges

During the course of the project we encountered a signicant number of technical challenges with the Android Front-End. Some of them are: Serializing abstract types Gson provides an easy interface to serialize and deserialize Java objects but it also has some serious limitations. One of them is that it cannot recreate objects which contain references to interfaces and abstract classes, a serious problem for us since our entire design is based on good object-oriented principles. The problem arises from the fact that at the point of deserialization it does not know the actual type of the object it needs to restore and calling new() on an abstract type breaks the program. To x this issue we (1) narrowed the range of classes and elds we need to serialize in the app in order to reduce the abstract types Gson has to manage to minimum and (2) we implemented functions that convert an abstract type to a concrete type that contains an enumerated value describing its actual type before serialization, and we use this information to regenerate the correct object after deserialization. Handling asynchronous tasks The Android Development Tools impose the programming paradigm that all network operations must run on a background thread. This has the advantage that the UI thread remains responsive to the user at all times. On the other hand, because these tasks run asynchronously with respect to the main UI thread, it is more dicult to manage them when something in the UI changes. For example, if the user clicks on the Back button immediately after an asynchronous task starts, the operations will still be carried out even if (1) there is no such need now as the user has left the Activity responsible for this operation or (2) executing these operations will break the program (the latter happens when a dialog is scheduled to appear at the end of the task but because the parent Activity is now gone the dialog causes the application to crash). To solve these issues we enforced the following: If the operations of the task are not crucial we cancel all pending messages of the threads event queue as soon as the user moves away from the current Activity. If the operations still need to be done at all cases, we either make sure that we do not allow the user to move out of the Activity before the task nishes or we allow 26

2.5. Controller

him to do so but we make the result silent (for example, by avoiding to show the dialogs that would appear upon task completion).

2.5

Controller

The most important Activity in CheckMate is the GameActivity which actually allows the user to play (or review) a game. This class initializes the Controller (the object responsible for managing the various inter system-component communication) and the View and sets up the game. It contains an instance of a Game object (the Model), and it is the only object that can directly communicate with it. The following diagram describes how these components communicate to allow the user to play the game:

Figure 2.22: Application of MVC When the user makes a move, the GLView noties the Controller. The Controller asks the Game for verication, and if it is successful, it updates the GLView and sends the move to the server via the ClientWeb object (if the game is between remote players). Then if the game is between local players the GLView is ready to accept moves from the next player, otherwise it stays in an idle state until the Controller receives a move from the server. We decided to separate the game logic (the model) from the rest of the app by applying the MVC design pattern for the following reasons: The model does not depend on the user interface. We can actually reuse the code for playing chess variants in dierent applications with dierent visual representations. In fact, when the GUI was being designed, a text based interface interface for playing chess was used for testing purposes. This was still used on occasion to determine the source of bugs. The separation of concerns allowed each one of us to work on a specic component of the application, which would interact with the others through well-dened interfaces. What this meant in practice is that we did not have to write code in each others classes, and therefore fragility of code was reduced.

27

Chapter 2. Design and Implementation

2.6
2.6.1

Backend
Design Decisions

The backend consists of two major components, the database and PHP scripts that query and manipulate it. The database stores the users details and any relevant data concerning the games. Our choice for DBMS was PostgreSQL as it is a powerful, open source and cross platform database system. We also considered MySQL which the most widely used, but decided to reject it, as it is not as expressive as PostgreSQL and also has some drawbacks such as the lack of boolean types. The database was installed on a virtual machine provided to us by the Department of Computing. The Entity-Relationship diagram in the Appendix B illustrates the databases tables and the links between them. For handling requests to the server we decided to use PHP scripts. PHP is a widely used language that many web servers support. Therefore, we would not encounter diculties to host the Backend. PHP also has built-in PostgreSQL database manipulation functionality so no additional drivers are required. Finally, PHP provides support for JSON message format which was used for client-server communication. The interface between the Controller and the server is implemented by the frontend class WebInterface, which hides the underlying complexity of the large number of scripts that are used and the parameters each one needs. Thus creating an abstraction for accessing the server from the rest of the application which simplies the frontend development. In addition, WebInterface is extended by ClientWeb and FBClientWeb which are used according to the way that the user decides to log into the application. Using this instance the Controller can make requests to the server by calling methods on it without the need to setup connections or give the server the required user details for authentication as the WebInterface takes care of that.

Figure 2.23: Client-Server communication diagram Regarding the communication between device and server, we had two options: either create a persistent connection between the two, or make the device poll the server whenever required to fetch data. Keeping a persistent connection for each device is not a scalable solution as the server would have a signicant number of such connections opened simultaneously and this would aect its performance and responsiveness. This is especially true since we are currently using DoC resources for the backend. Therefore we decided to only use polling to check for events on the server. Games Each game consists of: 28

2.7. Social features - Integration with Facebook

A record in the Games table specifying the game type, the players turn and the game status, one of active, nished, abandoned or cancelled. Records for each player in GamesPlayers the order in which they play. One record for each move performed in the Moves table. A new game is created in two dierent ways: by matching two users that ask for the same type of game based on their points or by creating a game after a game invitation has been accepted. In the rst case when a user asks for a game with a random opponent, a game is created in Games plus a record in GamesPlayers giving the relation of that user within the game. When another user requests a game of the same type with a random opponent, the server checks if there has been a new game created with no opponent assigned yet, if so, it will allocate the user to that game. A game can be resumed or replayed by fetching all the moves of that game and perform them one by one on the device. This was preferred than actually storing the whole board state as it would require to either calculate it on the server, which would mean extra processing and complexity for the server, or require the device to send the whole game state to the server whenever a move is performed. The latter would lead to extra load for the connection. Events Events are used to represent notications that each user should receive. Events are stored on the server, until the user for whom they are intended for retrieves them. Events are added for each user in the following cases: BUDDY REQUEST: A user has requested to become your friend BUDDY ACCEPT: A user has accepted your friend request BUDDY DECLINE: A user has declined your friend request GAME INVITE: One of your friends invited you to a game GAME ACCEPT: A friend of yours accepted your game invitation GAME DECLINE: A friend of yours declined your game invitation GAME OVER: A game you were playing has ended TURN: It is your turn to play in an active game All events contain the required data for all relevant front end functionality.

2.7
2.7.1

Social features - Integration with Facebook


Login

For the login process, we chose between two main implementation options. The rst one was to integrate a Login button in our application which is positioned in the Main Activity and changes its state if a user logs in or out. The second one, was to oer a Login Flow 29

Chapter 2. Design and Implementation

that opens a separate login screen outside of the Main Activity. As CheckMate oers more than one way of registering to the application, we decided to implement the second option. The Login Flow is a FacebookSDK object that upon creation, oers the login button and registration form. When a user enters their Facebook login details, a Facebook session is opened. During this session, we access the users public prole and user friend list (through the SDK) that have been authorized by the user. During the opened session, we use the users rst name and Facebook ID to create a CheckMate user which we can then use it to handle the registration / login as a normal CheckMate user. This implementation decision prevented the need of a sophisticated authentication process designed specically for Facebook and created the means for a fast integration with other SDK (like Google+ for example) in the future.

2.7.2

Friend list

Users that have registered with their Facebook account can start a game against their Facebook friends. In order to fetch the users friends, as soon as the user logins, we get all their friends ids, with the exception of those who have not yet registered to the application by checking against the database data held for the users.

30

Chapter 3 User Interface Design


In this section we outline and discuss our design decisions and how we kept the user central to our design, through user stories and usability tests. The subsequent sections take an indepth look at some of the ner implementation issues and details.

3.1

Designing with a user focus

As a key principle, we tried to ensure that our design decisions, in particular the user interface, would provide a good user experience. We researched the prole of our typical player and analysed how to provide a good game experience. As a result, we concluded that the most important elements are a user friendly and intuitive UI design and a completely functional application. Throughout the process of designing CheckMate, we constantly sought feedback from our users and incorporated this into our work. We initially started with paper prototypes of the user interface, leading to usability tests once we had a small but working set of features. Moreover, we kept a consistent layout design in order to oer the same user experience across the local and remote play modes.

3.2

Splash Screen and Main Menu

31

Chapter 3. User Interface Design

When CheckMate launches the rst screen that shows up is the Splash Screen. This is a simple screen that aims to provide a smooth switch from the Android Application view to our application. After a very small delay the Main Menu Screen appears. This is the root of the navigation tree shown below. From here the user is no further than three clicks away from any functionality they wish to access.

Figure 3.1: Software Architecture for the UI

3.3

Local / Remote Games Screens

Figure 3.2: Local and Remote Games Screen When a user clicks on the Play Oine or Play Online option they are taken to the Local Games Screen and to the Remote Games Screen respectively which gives them the option to: Start a new game of Chess, or one of the Chess variants. Resume one of the active games. Replay one of the last 5 completed games. 32

3.3. Local / Remote Games Screens

All three options cause a switch to the Game Screen. We enforce a limit on the current number of active games. After starting more than 10 active games in the local play mode or 20 in the remote play mode, a user is prompted to delete (abandon) one of them rst. The user can delete a game by a long click on a selected game and conrming this operation. In the remote mode, when a user wishes to play a game, they are presented with two options, either to play against a random opponent or a friend. If the user chooses to play against a random player the user has to wait until a suitable opponent has been found. A suitable opponent is a user that requested to join the same Chess variant game and is waiting for a random opponent himself. If no suitable opponent appears within 30 seconds then the application will exit the board game screen and add another game record to the active games list marked as Waiting for an opponent. Once a suitable opponent arrives, he will get assigned to this game and the rst player will get a notication telling him that the game can now begin. However, If the user chooses to play against a friend, then a list of his friends appears and the user is free to pick any of them. The list of friends are either Facebook friends (if the user has subscribed using his Facebook account) who are CheckMate users or the friends the user has specically added. When the user selects a friend, a notication is sent to this friends phone inviting them to play, should the user accept, CheckMate will create a new game. Finally, the Invitations button in the Remote Games Screen shows all the games that the user has been invited to. Specically, it shows the Chess variant type, the name and level of the player who invited them. The user can accept an invitation or decline it.

Figure 3.3: Game invitations The Game Screen is shown when the user starts, resumes or replays a game, either through the Local Games Screen or the Remote Games Screen. A player can make a move by clicking on a piece and then selecting a cell from the set of valid destinations which is shown on the board. He can also make special moves like castling and promotion by a 33

Chapter 3. User Interface Design

Figure 3.4: Game Screen (Hexagonal Board) and Timer on Grand Chess long click on a piece and selecting one of the options. Each players set of captured pieces is displayed under his name. Users can also turn the sound eects on or o or view the how to play dialogs by clicking on the appropriate help button on the top right corner. The Game Screen can accommodate for both game and move timed games between two players on the same device (local mode). The actual parameters for both are set before the game starts. For more information on how CheckMates clock works see Appendix D. A player can abandon the current game by clicking on the trash icon on the top left button. This will cause a dialog to popup on the other players screen to inform him of this event, as shown in gure 3.5. Clicking on the question mark icon will open a help dialogue which provides explanation about the touch gestures available to move pieces across the board. Furthermore, when the Game Screen is on replay mode, the user can pause and resume this process by clicking on the pause button at the bottom. Replay mode allows the user to see the entire history of moves made in a game, a feature that was requested by many users in the usability testing.

3.4

Rules

CheckMate is targeted also to users that do not know how to play Chess or any Chess variants. Therefore, it is important to provide clear games instructions. The Rules Screen provides the users with information about the rules for all supported chess variants. The screen provides a uent way of navigating through the various game types by swiping across the screen.

34

3.5. My Account

Figure 3.5: Screen shot of quick help dialog and Level Up

Figure 3.6: Rules Screen

3.5

My Account

The My Account screen provides the user with the means to: Sign in with a CheckMate or Facebook account. This is required for playing against a remote player.

35

Chapter 3. User Interface Design

Figure 3.7: My account screen Register for a CheckMate account. Change their password. Reset their password. View details of their account including statistics and current experience level. View their friends and friend requests. Log out of the game.

3.5.1

Registration / Login

CheckMate allows users to register or login in two ways: 1. As a CheckMate user - which requires the user to ll in their name, email address and choose a password. 2. Using their Facebook account - which only requires users to ll in their existing Facebook details. We decided to add the Facebook registration option due to several dierent reasons which include the popularity of Facebook and its integration in the Android game industry as it helps to advertise the application to more users. In addition, Facebook was also highly suggested during our usability tests as users wanted the option to play against their Facebook friends and also not have the need to remember another account details. The Facebook login and logout options can be accessed from the main menu by clicking on My Account and then Log in/out with Facebook.

36

3.5. My Account

Figure 3.8: Screen shots of native login and Facebook login Once the users Facebook account was veried, they are requested to allow CheckMate to use their public prole and friends list. Upon approval, the user is automatically registered as a CheckMate user. When a user wants to logout (for both Facebook user and CheckMate user), they can do so by accessing the My Account screen in the Main Menu and clicking on Logout.

3.5.2

Password Congurations

Forgot password Users who have forgotten their password can retrieve it via the Forgot password tab in the My Account Menu if the user is not logged in. Upon submitting their username and email address, the system will email them a new password (which they can then change via the Change Password screen). Change Password A registered user can change their password by clicking on Change Password via the My Account screen. The user must submit his old password followed by his new password and only if the users old password is correct, then the new password may be used for this account.

3.5.3

Users details

Once a user signs in, they can see how many games they have won, lost or drawn as well as their experience points, their current level and the remaining amount of points left for

37

Chapter 3. User Interface Design

them to proceed to the next level. Having opponents labeled with a specic level allows players to choose who they want to face based on how challenging a game they would like. Experience points concern only games against remote players and are awarded according to the following scheme: victory (20), draw (10), defeat (5). If a player abandons a game, it is counted as a defeat but they do not earn any points, whereas the opponent gets the victory points. The users level is initially set to 1 and is incremented when the amount of experience points reaches:
l1

50 1.25r
r=0

where l is the current level. This makes it increasingly harder for a user to proceed to the next level.

3.5.4

Friends

The user can see the list of his friends, add new friends and handle friend requests sent to him by clicking on the View Friends and View friend requests buttons as shown below:

Figure 3.9: Screen shots of Friend List and Friend Request dialogs

38

Chapter 4 Project Management


4.1
4.1.1

Team Organisation
Team Collaboration

Meetings We strived to hold weekly team meetings in order to discuss ideas for the future iterations and give feedback about the progress on the current iteration. We then used the feedback to estimate the amount of time and manpower needed to carry out the tasks of the next iteration and dene the project direction. At the times when the group could not meet in person, we would communicate via Google Hangout sessions or through posts on a private Facebook group. The team meetings, alongside regular meetings with the supervisor, provided us with a way to collaboratively make decisions about tasks and set milestone deadlines, as well as ensuring that all the members were aware of the current state of the project and that our supervisor was in agreement with the decisions taken by the group. Development Sessions We frequently developed alongside other members of the group, which enabled everyone to have an overall understanding of the application and increased the groups work exibility. Pair programming was also employed due to the nature by which the tasks of the project were assigned (See section 4.1.2). The benet of this was that members of a pair were able to advise each other and discuss about alternative implementations and design patterns, thus increasing the probability of good quality code.

4.1.2

Task Allocation

At the initial planning meeting members of the team were allocated to tasks according to their skill set and interests. However these allocations were not strict as members could change and help on other tasks depending on the task priorities. For instance Panos Evagorou, who was working on the backend, was able to help with the design of the hexagonal board for the game logic. The allocation was given as follows: Andrew Jack implemented and designed the graphics for the boards for each variant using OpenGLES as well as adding animation, to make the game more intellectually

39

Chapter 4. Project Management

stimulating and aesthetically pleasing. He also contributed to xing a number of issues on the Game Logic and the Android Client. Christos Karamanos designed and implemented the applications Android Client. He was responsible for creating the user interface as well as the applications logic so that the game logic would correctly be integrated with the graphics and the backend. He had the responsibility of making sure that the nal application supported all the features discussed in Section 1.3 Panos Evagorou designed and implemented the applications backend, which is the database schema and the server-side scripts. He also contributed on the implementation of the Hexagonal Board. Ronnie Falcon worked on the interaction of the application with Facebook including the Facebook login and the ability to play against a Facebook player. Was in charge of initially integrating the game logic with the Frontend and on some of the client server communications. Cristina Budurean worked on the appearance of the application. She also contributed to the Game Logic with implementing pieces functionality, variants, developing tests within the JUnit testing framework and creating code for various rules of the game. Pamela Cruz worked extensively on the Game Logic by employing Test Driven Development and various Design Patterns in the implementation of the rules of Chess, Board representation and Game Engine.

4.1.3

Tools

Version Control Version control is fundamental to software development, as it allows members of a team to develop in parallel in an organised way, track all the changes at a specic time, revert changes or switch back to a stable version, if necessary. Git is a very well known version control system. It allows every team member to have a complete copy of the repository data stored locally, thus making access to le history extremely fast, as well as allowing certain functionality when disconnected from the network. It also enables the creation of branches which is extremely useful for the development of isolated features that can be later integrated or discarded. Given all the above mentioned benets and our previous experience with Git, it was our chosen tool for version control. We took great advantage of Gits branching system by creating a separate branch to every subgroup within the team, namely: android_client, game_logic, back_end and graphics. This enabled us to concurrently develop features and by merging frequently to the master branch, we iteratively added the functionality required for our application. In addition, we chose to use GitLab as a frontend and management tool for our Git repository. GitLab provides a simple graphical user interface, which enables viewing of the updates of the repository for each member in a timeline. In addition, it provides a way to communicate between the members through the assignment of issues, line comments on the code and wiki pages. We extensively used GitLab for tracking progress, to see the code other members had written without having to checkout their branches and compare branches and commits.

40

4.2. Software Design Methodology

Trello Trello is a web based project management application which uses boards to represent projects containing lists of tasks, where tasks are made up of cards. Cards can contain les, checklists, due date and can be assigned to a particular member. List of tasks can be labelled and cards can be moved between them. For instance, we created 5 lists of tasks: Could, ToDo, InProgress, Testing, Done. At the planning stage of our project, we used Trello to allocate tasks to each team member and from then, we tracked the progress of each task and updated them to the appropriate list. Facebook We also communicated via a private group on Facebook as it allowed us to take advantage of instant messaging, access history of conversations easily and lead discussions on a specic topic of the project. Google Drive We used Google Drive for cooperatively writing description of project requirements, reports and drawing of design specication, as it promotes collaboration through real time editing and allows remote access to les.

4.2
4.2.1

Software Design Methodology


Agile methodologies

On the planning stage of our project we opted to follow an Agile software design approach. This meant that we were able to deliver features incrementally. For example, before implementing other Chess variants we ensured that the basic rules for the Traditional Chess were fully functional. Furthermore, an iterative development helped us to ensure the quality of our code by testing throughout the lifecycle and allowed us to be exible to changes to our project requirements. As a group we set milestones in order to keep track of the progress of the group and individual team members . This helped us along the development process to change requirement priorities when we had fallen behind schedule and to restructure the allocation of tasks. The tasks per milestone and their respective priorities were consistent with the requirements set at our meetings with the supervisor. Setting milestones enabled us to ensure that the project would be delivered on time. At team meetings, we assigned members of the group to a task. This gave the team the opportunity to discuss ideas and clarify the requirements and the role of each team member. Progress of the tasks during an iteration were tracked via Trello, where each team member could see which tasks they were assigned to and give an update of the task by moving it to the correct labelled list.

4.2.2

Testing

Test Driven Development Test Driven Development was heavily used, especially within Game Logic. For a full description of how this technique was implemented in practice see section 5.2.1. 41

Chapter 5 Evaluation
5.1 Evaluating deliverables

We evaluated CheckMate throughout its development and at its completion because we wanted to know quantitatively if the program works, how ecient and eective it is and what the impact is on the users. We did a substantial number of usability tests with experienced players. We showed them how to use our application and we took into consideration their feedback, spending many hours developing an application that provides a great user experience. We know how many people are interested in our application out of the surveyed users, but we do not know how many people will actually be interested in our game and will carry on playing after the release of our application (impact). Our users were attracted by our GUIs intuitiveness and the Help Dialog for the features (for example the suggested legal moves), but we are still not sure whether these are eective ways of making our application appealing to them (eectiveness). Lastly, now that we have the nal version of the application with a stable set of features, we wish to know whether the time spent in developing this has been worthwhile in terms of our initial goals (eciency). We will now present how we have quantitatively evaluated these aspects.

5.1.1

Eectiveness

To start o, we selected a set of aspects and features that we wished to evaluate our application with, in regards to eectiveness. The features are: Highlighted moves Drag and Drop The GUIs intuitiveness Highlighted Moves Testing From our initial testing with users we found out that they did not know the rules of some of the variants. This caused them issues and many got frustrated with the game as they constantly attempted to make incorrect moves. Therefore, we decided to implement a UI which displays the various legal moves for each piece. In order to evaluate its usefulness we decided to test this feature by the following: We had three rounds with 6 users in each round. At the rst round (the control round) each user was asked to play at most 16 moves without the highlighted moves. Following 42

5.1. Evaluating deliverables

Figure 5.1: Highlighted moves of a Knight this, at the second round the users had the valid moves highlighted. Finally, for the third round the users played without the highlighted moves. During each round we counted the number of incorrect moves. Our hypothesis is that the number of incorrect moves should decrease after the user has played a game with the highlighted moves visible. If this is the case then the highlighted moves is proved useful. Moreover, if observed that users struggle in making moves, then it should be permanently turned on. Below we present our results from all the rounds for Gliskis Hexagonal Chess only, as this is the one out of the variants implemented that most diers from Traditional Chess. Player Round 1 Round 2 Round 3 Change from rounds 1 and 3 1 77% 0% 67% 10 % 2 84% 0% 81% 3% 3 56% 0% 49% 7% 4 73% 0% 68% 5% 5 69% 0% 61% 8% 6 77% 0% 59% 12 % From our test results, we found out that having the highlighted moves for Chess960, was not so helpful, as the only dierence from Traditional Chess is the conguration at the start of the game, but the pieces remain the same. However, for both Capablanca, Grand and Gliskis Hexagonal Chess, having the highlighted moves proved to be extremely important as the number of incorrect moves decreased signicantly from round 1 to round 3. An explanation for this can be given based on the fact that Gliskis Hexagonal Chess changed the board layout, and so the behaviour of the pieces are very dierent than Traditional Chess. On the other hand Capablanca and Grand chess add new pieces, but keep the same board shape as Traditional Chess. Drag and Drop As part of our goals and further emphasised by a few users during our usability tests, there was a desire to make the game as realistic as possible in order to give a better user experience. One of the ways we found that we could provide this feature was to allow users to make moves by dragging and dropping. 43

Chapter 5. Evaluation

After implementing this feature, we had to ensure that this provided the realistic twist that was requested. To do this, we asked the same users who suggested the feature to play the game using drag and drop to perform moves. As they played, we did observation testing and after a couple of moves, we noticed a few problems with this feature. Firstly, it was proved to be more likely for a player to make an unintended move, as the player may drop the piece at a neighbouring cell and not on the intended cell. Lastly, we realised that for beginners, it would teach the incorrect concept with respect to jumping over a piece, which is a prohibited move for all pieces except the knight. We could not automate this test, as we cannot distinguish automatically between an intended or unintended move. As the table below shows, we performed this test with four people, where we documented the number of aborted moves, the number of unintended destinations and the number of incorrect moves by jumping over a piece out of 35 moves. From the data, we can see that for player number 4, a beginner in chess variant, 20% of his moves were incorrect as he tried to move over a piece. Furthermore, as there were 15% unintended destinations, we were led to think that the precision of where a player needs to drop the piece needs to be very accurate. Therefore, we concluded that this feature should be removed, as it would provide an increase in the number of erroneous moves. This will make the game less realistic, but adding this feature makes the game harder to play and increases the probability of incorrect moves being made, especially, on a small device. As a result we opted to only allow the players to make moves via clicking on the source cell and then the destination cell. Player 1 2 3 4 Average Number of unitended destinations 14% 17% 23% 6% 15% Number of incorrect moves by jumping over a piece 8% 5% 11% 20% 11% The GUIs intuitiveness testing A crucial aspect of any user interactive application is the way it looks and how easy and intuitive it is for users to navigate and use it. During the development stage we made a simple, yet functional GUI, which we presented to users for usability tests, together with some paper prototypes for some parts of the user interface that had not yet been implemented. While users interacted with the application we logged the way they navigated through the dierent sections, by recording the consecutive events (the buttons clicked) since the user started the application. This test was done with 6 users. At the time of this test, two members of the team were absent, therefore we decided to use a ow visualisation[8] graph to present the data so that we could easily analyse the feedback given and evaluate our GUI accordingly with all the members of the team. From the graph (Figure 5.2), we found out that the users seemed to be missing out on the registration when playing remotely as shown by the grey funnel between Main Menu and Play Oine (Local Mode), which shows that a much larger proportion of users clicked on Play Online (Remote Mode) rather than on Registration. From this, we realised that we had not made it intuitive enough for the new users that they had to register before playing. Therefore, we added a screen exclusively for Account management (My Account) and we inform the user that he needs to be signed in at the point where he tries to access the Play Vs Remote Player screen.

44

5.1. Evaluating deliverables

Figure 5.2: Flow visualisation of CheckMate

5.1.2

Impact

To estimate the games impact, we decided to assess how many regular users we have at this point. For the purposes of this test we decided to dene that a regular user is one that has participated on at least 10 games in ve days. We carried usability tests (by installing the application on 12 user devices). After a period of 5 days, we looked at the database to get an idea of how many of those users actually continued to use CheckMate after the experiment. The data is summarised below: Number of games initiated or joined by each of the 12 users: Player 1 2 3 4 5 6 7 8 9 10 11 12 Total Games Initiated 7 16 9 0 22 13 0 10 4 11 0 8 The average of games per user is given by: the number of total games initiated by all users 100 = the total number of users 12 = 8.33 The percentage of regular users is given by: number of users which have participated in at least 10 games in ve days 5 = the total number of users 12 = 41.66% From this experiment, we saw that on average users seem to have carried on playing, which shows that they were actually interested in our application over time.

45

Chapter 5. Evaluation

5.1.3

Eciency

Finally, we chose a set of aspects to assess our eciency, which are: Development Velocity Group collaboration Development Velocity A great indication of our performance is our velocity. We dene velocity as the sum of W (where W is the number of tasks x weight of each task) we managed to complete at each iteration out of the total number of tasks that we had to complete based on our MoSCoW list below. Must Normal chess Chess 960: a variant of normal chess where the starting positions are randomised. Capablanca chess: normal chess with additional pieces: Chancellor and Archbishop Grand Chess: an extension to Capablanca chess, which adds a Chancellor and an Archbishop Hexagonal Chess: the cells of normal chess are hexagonal Good intuitive user interface. Good use of OOP to abstract the characteristics of the game. Should Social integration e.g. Facebook / G+ Handles well when a user goes oine Help dialog a user can access during the game to help him move the pieces if he nds it non-intuitive Could Upload the game to play store. Implement an AI for a single player game Wont Focus on implementing AI for all variants. Build an iOS version. Millennium 3D Chess

46

5.1. Evaluating deliverables

We dened the weight as a number between 1 and 10, where a small weight (1-3) is given to tasks that are easy to complete, a medium weight (4-7) is denoted to tasks that are challenging to complete and a high weight (8-10) is given to tasks that are very challenging to complete. An initial weight was assigned to each task in our group meetings (by voting for its approximate weight range). Then, the group member that the task was assigned to, was responsible to further investigate the complexity of the task and report back to the team if we had not considered some aspects in the weighting process. Our velocity is shown in the table below, and we can see that the performance changes between iterations. Our performance is strictly related to the amount of time we had to spend on the project at each iteration. We can see that during the rst iteration, when we had a lot of time, we managed to complete many heavy-weighted tasks. However, in the second iteration when coursework deadlines and other responsibilities came up, we managed to complete fewer tasks. We tried to catch up during the third iteration, however during the fourth, fth and sixth iterations the velocity slowed down again as we had other courseworks. The seventh, eighth and ninth iterations were clearly aected by the exam period. Finally, during our winter break we managed to complete the remaining tasks and bring the project to a nal working state. Iteration Tasks Completed Total Weight 1 5 40 2 3 23 3 8 35 4 6 29 5 4 27 6 5 30 7 (Exam Period) 1 50 8 (Exam Period) 0 0 9 (Exam Period) 0 0 10 (Winter Break) 6 39 11 (Winter Break) 9 60 12 (Winter Break) 6 54 13 (Winter Break) 8 67 We have completed 409 of our weight out of the 467 overall weight denoted to the total amount of tasks. We can see that our average velocity is 31.4. Comparing it with the suggested velocity of spending the equivalent of one day per week on the project, we are condent that this value fullls (at the very least) the expectation of making regular progress each week. Cutting The Scope At the beginning of the fth week we evaluated our velocity and decided to cut some features out in order to meet the deadline. These features include items which were on the Should have or Could have sections of the MoSCoW list, such as four-player chess, advanced AI mode and integration with Google+. We let our supervisor know about this decision, and in particular we made sure all requirements set by him were still within the projects scope. The burndown chart, in gure 5.3 illustrates the number of tasks (taken out of the MoSCoW list of requirements) that were left to do at each iteration:

47

Chapter 5. Evaluation

Figure 5.3: Burn Down Chart The graph allowed us to see that although we had an approximately constant velocity in terms of tasks completed per week, we would probably have run out of time before completing all the tasks. This showed that we had initially underestimated the time needed to complete the requirements in our MoSCoW list, and thus we needed to take action and reschedule our work. Hence, we decided to reduce the number of tasks that we had initially planned to complete by week 9. By using extrapolation, we estimated that we would be able to nish the code during Christmas. We believe we beneted from using the Burndown Chart as it helped us to avoid risking not delivering the required tasks by the deadline. Retrospective meetings We held retrospective meetings regularly in order to assess how we worked as a group. During the winter break, we held meetings on Google Hangouts. To do this we listed the good point of our work side by side to the to improve points, as shown in gure 5.4. As an example, during the third iteration we noticed some problems such as (1) we were getting a lot of merge conicts, (2) some of the members were working on code that was not up-to-date and (3) some of the commit messages in Git were too general or covered a wide range of changes. On that weeks retrospective meeting we decided to address these issues by (a) committing small changes more frequently and (b) merging more often. This allowed us to progress faster in the development of the application as we managed to reduce the time spent on merge conicts and on asking other members to describe what they changed when their commits covered a lot of changes.

5.2
5.2.1

Testing
Testing the Android Application

CheckMate was tested by mock games on various Android devices and on emulators. This was needed in order to assure the correctness of the game and that it handled dierent 48

5.2. Testing

Figure 5.4: Photo of a retrospective meeting screen sizes appropriately. Test Driven Development To help ensure correctness, Test Driven Development (TDD) was used on the game logic (the Model) part of the project. As Kent Beck (who is credited with developing or rediscovering the technique) stated, TDD encourages simple designs and inspires condence. It provided a clear and safe way to control the development of the game by splitting it into its rules. For every rule of the basic chess game, a unit test was created at rst, after which followed the implementation of that rule. This was very important for the correctness of the game as later on variants of Chess were implemented and there needed to be a guarantee that the basic rules were still being followed. This assured the correctness of the game as it indicated many bugs that were introduced when new code was added or existing code was modied. Without having the tests written, some of these bugs could have remained for a long time, possibly being discovered later on in the development process when it would be more dicult and time consuming to debug and x them. Furthermore, the names of the tests followed a Behaviour-Driven Development approach so that they could act as an executable specication for the game, documenting its behaviour. TDD was applicable in the case of game logic because the rules of Chess and variants are well established, which enabled us to know the set of functionalities that needed to be tested. The other subsections of this project (Android client, Back End and Graphics) generally entailed research before the code was implemented, especially for the android client as the team members responsible for that had no previous relevant experience. The specications for tasks in these sections were therefore constantly changing as the members acquired knowledge about which features could be developed in practice. This constant change in the exact specication made TDD harder to implement. A test for checking that the capablanca games new piece the chancellor can move as it is designed to is given by the following:

49

Chapter 5. Evaluation

@Test public void chancellorCanMoveLikeKnight() throws InvalidMoveException, AskUserForPieceSelection { Game game = constructGame(); Board board = game.getBoard(); Piece beforeMove = board.getPieceAt(Position.newCharToInt(1, h)); game.move(new Move(Position.newCharToInt(1, h), Position.newCharToInt(3, g))); Piece afterMove = board.getPieceAt(Position.newCharToInt(3, g)); assertTrue(beforeMove == afterMove); } Apart from TDD, we have used other forms of testing to ensure correctness. Specically JUnit tests have been written for game logic and the Android app via the standard testing environment provided by Eclipse. A few Android instrument tests have been written as well in order to test how dierent Activities interact with each other (e.g. testing that LoginActivity transits smoothly to MainMenuActivity upon successful login). Finally, we also used the DDMS perspective in Eclipse to simulate events like receiving a call while using the application, to see if it handled such events properly.

5.3

Reliability

One of the requirements which were set by the supervisor was that the application should handle gracefully the situation where a user goes oine. From the testing we performed, we can say with condence that we managed to fulll this objective by ensuring the integrity of the state of an active game. This was achieved by storing the game state on the server and giving the DBMS the sole responsibility of manipulating this in a transactional manner. Moreover in case of a connection failure while the player is making a move, the state of the game is fetched from the server when the connection is reestablished and the pieces and players turns are set as they were before the connection was lost. This way, any incompatibility between the server and the client is elegantly handled.

5.4

Security

To ensure that a security mechanism has been put in place, it was enforced that access to the database is only possible through certain PHP scripts that allow specic operations to be carried out. Also, any parameters passed on to the server are sanitized to prevent SQL injection attacks on the database. In order to restrict users from accessing any data not relevant to their account information on the server, a users identity is validated using a unique token based on their encrypted password, which is encrypted on the client before being sent to the server; this is required every time a connection is established with the server. We thus believe we have successfully reduced the vulnerability of our system to a reasonable degree.

50

5.5. Overall evaluation

5.5

Overall evaluation

As a group we are satised with the project given the time constraints and other course commitments. Through discussions with the supervisor and the perspective users of the application, we are condent that we created a game which satisies to a great extent the requirements in an ecient and correct way.

51

Chapter 6 Conclusion
6.1 Project Challenges

The nal stable version of CheckMate is fast, responsive, and has a user friendly interface, for a full list of our achievements see section 1.3. It has been tested throughout its development on a variety of Android devices. We came across and overcame many challenges during the implementation of the project, which included: The adaptation of the axial system to support the Hexagonal Board in the Game Logic. The serialization and deserialization of Java objects to represent the game state in the face of references to interfaces and abstract classes. For the Graphics subsection, implementing Hexagonal Board and required components such as determining the cell a player has clicked for a move. Android enforces asynchronous behaviour for network communications, which posed a challenge when implementing the client-server module. Regarding the feature of timed games, we decided to integrate it in the local mode only, for several reasons. If we assume that the player will be connected throughout the entire game, we would still need to cater for the case in which the players device cannot send or receive moves due to a lack of connection to the server. Consequently, stopping the timers at a loss of connection would give the players the opportunity to take advantage of this, by deliberately disconnecting from the internet, in order to increase their thinking time. On the contrary, if the timer is not stopped when the player disconnects, the device will not be able to send the move, and therefore the controller will be unable to correctly determine the game state. Both of these cases can result in an unfair game for either player.

6.2

Other Potential Directions

Although we have added many features to CheckMate, there are other features which could be added. Some of which we considered but for various reasons we opted not implemented them at this point in time. For example, we decided to leave out the implementation of an AI for several reasons. Firstly, we estimated that we would not have 52

6.3. Our personal development

time to do a sophisticated AI. A simple one would not be useful, especially since our main target group is experienced chess players. Secondly due to time constraints we negotiated with our supervisor and agreed to focus on the social interaction aspects of the application. Therefore we added the ability to replay completed games and integrated Facebook, so that users could play against their Facebook friends. Other features not currently supported, due to time constraints, include, tournaments between the players giving awards to the winners and integration into other social networks like Google+. In addition, an implementation direction that we did not take was to use a mobile development framework like PhoneGap. In this framework, one can program an application using Javascript and HTML5 and it automatically deploys it to dierent platforms. Therefore, that would have been useful if we were considering to build a cross platform application on Android and iOS.

6.3

Our personal development

Upon concluding our project, we feel that we acquired many new skills and improved in others. In terms of the technical development, working on this project taught each one of us about new technologies, tools and techniques. As such, we gained knowledge about Android Development, Facebook SDK and OpenGLES. We also found out about the usefulness of the utility functions provided by PHP for querying and manipulating databases as well as expanded our knowledge of OO design. In terms of the team collaboration, we adopted a few management, communication and progress tracking tools, such as Trello for management and progress tracking and Google Hangout for communication. This project also helped us to improve our teamwork skills and to learn how to communicate better with each other. Finally, we believe that we have learned a lot by successfully following the Agile methodologies. The most important aspect which we have practiced was task management: By compiling a set of game functionalities, sorting them by their importance and splitting them into several implementation sprints, we managed to keep track of our progress and deliver a working version of the game on a regular basis. During the rst couple of sprints, we focused on the essential features and managed to build a basic version of the game. Then, in each new sprint we incrementally added more and more game features until we reached the complete version we have presented in this report. We also practiced Agile methodologies when managing the project, when prioritising our tasks and when interacting with our supervisor or other potential end users.

53

Appendix A Chess Rules


This following description is based on content from the following websites: www.chess.com www.fide.com www.chessvariants.org en.wikipedia.org/wiki/Chess

A.1

Traditional Chess

Figure A.1: Traditional Chess Starting Positions The game of Chess is played between two opponents who move their pieces alternately on a square board called a chessboard. The player with the white pieces commences the game. A player is said to have the move, when his opponents move has been made.

A.1.1

Objective

The objective of each player is to place the opponents king under attack in such a way that the opponent has no legal move. The player who achieves this goal is said to have checkmated the opponents king and to have won the game. Leaving ones own king under attack, exposing ones own king to attack and also capturing the opponents king are not allowed. The opponent whose king has been checkmated has lost the game. 54

A.1. Traditional Chess

A.1.2

Draw

If the position is such that neither player can possibly checkmate, the game is drawn.

A.1.3

Stalemate

A position counting as a draw, in which a player is not in check but cannot move except into check.

A.1.4

Board

The board is composed of a 10 x 8 grid of 80 equal squares alternately light (the white squares) and dark (the black squares). At the beginning of the game one player has 20 light-coloured pieces (the white pieces); the other has 20 dark-coloured pieces (the black pieces).

A.1.5

Promotion

Promotion is a rule describing the transformation of a pawn that reaches the nal rank (either the 8th rank for the White player or the 1st rank for the Black player) into the players choice of a queen, knight, rook, or bishop of the same color. The new piece replaces the pawn on the same square and is part of the move. Promotion is not limited to pieces that have already been captured. Every pawn that reaches its eighth rank must be promoted.

A.1.6

En Passant

A pawn attacking a square crossed by an opponents pawn which has advanced two squares in one move from its original square may capture this opponents pawn as though the latter had been moved only one square. This capture is only legal on the move following this advance and is called an en passant capture.

A.1.7

Castling

This is a move of the king and either rook of the same colour along the players rst rank, counting as a single move of the king and executed as follows: the king is transferred from its original square two squares towards the rook on its original square, then that rook is transferred to the square the king has just crossed.

A.1.8
King

Pieces

There are two dierent ways of moving the king: by moving to any adjoining square not attacked by one or more of the opponents pieces or castling (unless it is a grand or hexagonal chess game).

55

Appendix A. Chess Rules

Figure A.2: Traditional Chess: King moves Queen The queen may move to any square along the le, the rank or a diagonal on which it stands.

Figure A.3: Traditional Chess: Queen moves

Rook The rook may move to any square along the le or the rank on which it stands.

Figure A.4: Traditional Chess: Rook moves

Bishop The bishop may move to any square along a diagonal on which it stands. When making these moves the bishop, rook or queen may not move over any intervening pieces. Knight The knight moves to any of the closest squares that are not on the same rank, le, or diagonal, thus the move forms an L-shape: two squares vertically and one square horizontally, or two squares horizontally and one square vertically. The knight is the only piece that can leap over other pieces.

56

A.2. Chess 960

Figure A.5: Traditional Chess: King moves

Figure A.6: Traditional Chess: Knight moves Pawn The pawn may move forward to the unoccupied square immediately in front of it on the same le, or on its rst move it may advance two squares along the same le provided both squares are unoccupied (black circles in the diagram); or the pawn may capture an opponents piece on a square diagonally in front of it on an adjacent le, by moving to that square (black xs). The pawn has two special moves: the en passant capture and pawn promotion.

Figure A.7: Traditional Chess: Pawn moves

A.2

Chess 960

Chess960 (or Fischer Random Chess) is a variant of chess invented and advocated by former World Chess Champion Bobby Fischer, publicly announced on June 19, 1996 in Buenos Aires, Argentina. It employs the same board and pieces as standard chess; however, the starting position of the pieces on the players home ranks is randomized. The random setup renders the prospect of obtaining an advantage through the memorization of opening lines impracticable, compelling players to rely on their talent and creativity. The player with the white pieces commences the game. A player is said to have the move, when his opponents move has been made.

57

Appendix A. Chess Rules

Figure A.8: A possible Chess 960 board conguration

A.3

Capablanca Chess

Figure A.9: Capablanca Chess Starting Positions Capablanca chess (or Capablancas chess) is a chess variant invented in the 1920s by former World Chess Champion Jose Raul Capablanca. It incorporates two new pieces and is played on a 10 x 8 board. Capablanca proposed the variant while World Champion, and not as a sour grapes rationalization after losing his title as some critics have asserted. He believed that chess would be played out in a few decades and games between grandmasters would always end in draws. The threat of draw death for chess was his main motivation for creating a more complex and richer version of the game. The player with the white pieces commences the game. A player is said to have the move, when his opponents move has been made.

A.3.1

New Pieces

Figure A.10: Additional pieces in Capablanca Chess The new pieces have properties that enrich the game. a Chancellor that moves as both a rook and a knight 58

A.4. Grand Chess

an Archbishop that moves as both a bishop and a knight. This piece would be able to deliver checkmate on its own, which none of the conventional pieces can do; however, checkmate cannot be forced without the help of its own king.

A.4

Grand Chess

Figure A.11: Grand Chess Starting Positions Grand Chess is a popular large-board chess variant invented by Dutch games designer Christian Freeling in 1984. It is played on a 10 x 10 board, with each side having two additional pawns and two new pieces. The player with the White pieces commences the game. A player is said to have the move, when his opponents move has been made.

A.4.1
Pawns

Specics

Has an initial two-step move option and are subject to en passant capture. En Passant A pawn attacking a square crossed by an opponents pawn which has advanced two squares in one move from its original square may capture this opponents pawn as though the latter had been moved only one square. This capture is only legal on the move following this advance and is called an en passant capture. Castling Castling is not possible. Promotion A Pawn may promote on reaching the penultimate or the antepenultimate rank (either the 8th or the 9th rank for the White player or the 2nd or the 3rd rank for the Black player). A Pawn must promote on reaching the nal rank. A Pawn can promote only to a friendly piece that has been captured, and for which it is exchanged. If no friendly 59

Appendix A. Chess Rules

piece has been captured, then a Pawn may not move beyond the 9th furthest rank. An immobile Pawn on the 9th furthest rank can still give check.

A.4.2

New Pieces

Figure A.12: Additional pieces in Grand Chess The new pieces have properties that enrich the game. a Marshal that moves as both a rook and a knight a Cardinal that moves as both a bishop and a knight. This piece would be able to deliver checkmate on its own, which none of the conventional pieces can do; however, checkmate cannot be forced without the help of its own king.

A.5

Glinskis Hexagonal Chess

Figure A.13: Hexagonal Chess Starting Positions Glinskis Hexagonal Chess, invented by Wladyslaw Glinski in 1936 and rst launched in Britain in 1949, is probably the most widely played of the hexagonal chess variants. The game is played on a regular hexagonal board with 91 hex cells having three colors (light, dark, and mid-tone), with the middle cell (or hex) usually mid-tone. The usual set of chess pieces is increased by one bishop and one pawn. The array is ordered so that each piece is initially free to move. Also noteworthy is the fact that both the King and Queen defend all three Bishops.

A.5.1
Pawns

Specics

Pawns have an initial two-step move option. En passant captures are allowed. A capturing Pawn, which arrives on a friendly Pawns starting square, regains its initial two-step move 60

A.5. Glinskis Hexagonal Chess

option. Pawns promote when they arrive on one of the eleven hexes that dene the opposite borders of the board. Castling Castling is not possible. Stalemate Stalemate earns 3/4 points for the player delivering it and 1/4 point for the player stalemated.

A.5.2

En Passant

A pawn attacking a square crossed by an opponents pawn which has advanced two squares in one move from its original square may capture this opponents pawn as though the latter had been moved only one square. This capture is only legal on the move following this advance and is called an en passant capture.

61

Appendix B Entity Relationship Diagram of Database

62

Appendix C Matrices and Coordinates


All objects to be drawn are created in their own coordinate system. All of the objects vertices are within a 3D cell with x, y, z [1, 1]. The center of the object is at (0, 0, 0). In order to view the object these are transformed by three separate matrices. The rst matrix is the model matrix. This places the object into the correct place in the world and with the correct transformations (e.g. scaling, rotation). The second matrix, the view matrix, which is in eect the camera. It positions where the user is looking, by moving the world to the correct place. The nal matrix, projection, manipulates the image to t into the window. We use an orthographic projection since it is a 2D App.

63

Appendix D Chess Clocks


The following section is based on a wikipedia article: http://en.wikipedia.org/wiki/ Chess_tournament

D.1

Background

There are many dierent variations of timed chess games each one having dierent rules. Some of them are:

D.1.1

Blitz

In blitz chess (also known as sudden death chess) each player starts with a xed amount of time to spend on their moves of the game. Bullet: one or two minutes per side Blitz: less than 15 minutes per side (often 5 minutes), sometimes with a small time increment every move Rapid: 1560 minutes per side (often 25 minutes), sometimes with a small time increment every move. Armageddon: a single game guaranteed to produce a result, because the Black side has draw odds (that is, for Black, a draw is equal to a victory). To compensate, White has more time on the clock. Blitz time controls increase the odds that one would lose on time, meaning a forfeiture of the game due to the expiration of ones chess clock. Blitz tournaments are often documented with the notation G/5 or G/15, meaning game in 5 and game in 15, respectively.

D.1.2

Standard

Standard time controls (STC) are ones in which a player has a set amount of time to complete a specied number of moves. If the specied number of moves is met, the players time will rejuvenate. The rst standard time controls, introduced in 1861, were 24 moves in two hours, with the average game lasting ve hours. In the mid-1980s, a new format, 40 moves in two hours, proved popular because few games lasted over 60 moves. 64

D.2. Our implementation

D.2

Our implementation

Before the introduction of chess clocks in the mid 1950s chess club rapid transit tournaments had a referee who every ten seconds called out for each move, so we decided to use a similar variation to this where you have 1 minute for each move otherwise you lose. In addition, we implemented the Rapid Chess with the option of a 10 and 20 minute per side having a ten second increment per move. In both cases, when a player runs out of time then he immediately loses the game.

65

Bibliography
[1] ChessManic Bill Wall. How many chess players? http://www.chessmaniac.com/ index.php/2012/12/27/how-many-chess-players/, December 2012. [Online; accessed 2014-01-09]. [2] AP. World has about 6 billion cell phone subscribers, according to u.n. telecom agency report. http://www.huffingtonpost.com/2012/10/11/ cell-phones-world-subscribers-six-billion_n_1957173.html, November 2012. [Online; accessed 2014-01-09]. [3] Canonical. Ubuntu for android ubuntu for phones ubuntu. http://www.ubuntu. com/phone/ubuntu-for-android, 2014. [Online; accessed 2014-01-09]. [4] Google Play. Google play. http://play.google.com, 2014. [Online; accessed 201401-09]. [5] Chees Programming Authors. chessprogramming. http://chessprogramming. wikispaces.com, 2014. [Online; accessed 2014-01-09]. [6] Khronos Group. Opengles. http://www.khronos.org/opengles/, 2014. [Online; accessed 2014-01-09]. [7] Amit Patel. Hexagonal grids. http://www.redblobgames.com/grids/hexagons, March 2013. [Online; accessed 2014-01-09]. [8] Google Analytics team Phil Mui. Introducing ow visualization: visualizing visitor ow. http://analytics.blogspot.co.uk/2011/10/ introducing-flow-visualization.html, October 2011. [Online; accessed 2014-01-09].

66

Você também pode gostar