Pencil Puzzles: Slither Link
Pencil Puzzles: Slither Link
University of Manchester School of Computer Science Project Report 2010 Author: Elizabeth Wray Supervisor: Prof. Andrei Voronkov
Author: Elizabeth Wray Supervisor: Professor Andrei Voronkov Date: May 2010
Acknowledgements
Thanks to my tutor, Prof. Andrei Voronkov, for his insight into the project aims and suggestions for methods that could be used to tackle it. Thanks to all that allowed me to bounce ideas off them, proof read the report and generally motivated me to get it done (as well as providing much needed distractions at times). Special thanks to Andrew Elder for continued love and support, Andrew Kirsfelds for emergency laptop support at 7am, Damian Jakusz-Gotomski for laptop supplies and the Banana Hammock Club (Aditi Aggarwal and Jonny Ray) for generally keeping me sane throughout my final year.
Table of Contents
1 Introduction .................................................................................................................................... 7 1.1 The Project .............................................................................................................................. 7 1.2 Objectives................................................................................................................................ 7 1.3 Terminology ............................................................................................................................ 8 1.4 Chapter Synopsis ..................................................................................................................... 8 Background ..................................................................................................................................... 9 2.1 Slither Link............................................................................................................................... 9 2.2 How to solve it ...................................................................................................................... 10 2.2.1 Rule 1: Number Cells ..................................................................................................... 11 2.2.2 Rule 2: Points ................................................................................................................ 11 2.2.3 Rule 3: Single Loop ........................................................................................................ 12 Technical Background ................................................................................................................... 13 3.1 Constraint Satisfaction Problems .......................................................................................... 13 3.1.1 Definition....................................................................................................................... 13 3.1.2 Solving ........................................................................................................................... 14 3.2 Boolean Satisfiability Problems............................................................................................. 15 3.2.1 Definition....................................................................................................................... 15 3.2.2 Solving ........................................................................................................................... 15 3.3 Tools Available ...................................................................................................................... 15 3.3.1 Constraint Programming ............................................................................................... 15 3.3.2 SAT Solvers .................................................................................................................... 16 3.4 Programming Languages....................................................................................................... 16 3.4.1 C++ ................................................................................................................................ 16 3.4.2 Java................................................................................................................................ 16 3.5 Technology Choice ................................................................................................................ 17 Design............................................................................................................................................ 18 4.1 The Unified Process............................................................................................................... 18 4.1.1 Iterations ....................................................................................................................... 19 4.2 Overall Design ....................................................................................................................... 20 4.2.1 Data Structures ............................................................................................................. 20 4.2.2 Core ............................................................................................................................... 20 4.2.3 Solver Interface ............................................................................................................. 21 4.2.4 Model-View-Controller ................................................................................................. 22 4.2.5 Class Diagram ................................................................................................................ 23 4.3 Solver Design ......................................................................................................................... 23 4.3.1 Rule 1: Number Cells ..................................................................................................... 23 4.3.2 Rule 2: Points ................................................................................................................ 24 4.3.3 Rule 3: Single Loop ........................................................................................................ 25 4.4 GUI Design............................................................................................................................. 25 4.4.1 Game Panel ................................................................................................................... 26 4.4.2 Button Panel and Menu Bar .......................................................................................... 27 Implementation ............................................................................................................................ 28 5.1 Solver Implementation ......................................................................................................... 28 5.1.1 Solving ........................................................................................................................... 28 5.1.2 Generation .................................................................................................................... 29 5.1.3 Check Solution............................................................................................................... 29 5.2 GUI Implementation ............................................................................................................. 29 5.2.1 Display ........................................................................................................................... 29
5.2.2 Validation ...................................................................................................................... 30 5.3 Overall Implementation ........................................................................................................ 31 6 Results ........................................................................................................................................... 32 6.1 GUI ........................................................................................................................................ 32 6.2 Solver Success ....................................................................................................................... 34 6.2.1 1st Valid .......................................................................................................................... 34 6.2.2 Total Valid ..................................................................................................................... 35 6.2.3 Total Solutions .............................................................................................................. 35 6.2.4 Solving External Puzzles ................................................................................................ 36 6.3 Generator Success ................................................................................................................ 36 6.4 Testing ................................................................................................................................... 37 7 Conclusions ................................................................................................................................... 38 7.1 Objectives.............................................................................................................................. 38 7.1.1 Ability to solve a given puzzle ....................................................................................... 38 7.1.2 Ability to generate new puzzles of different sizes with valid solutions ........................ 38 7.1.3 Ability to play a given game selecting and deselecting sides..................................... 38 7.1.4 Restart, New Game and Check Solution options .......................................................... 38 7.1.5 Able to input their own game in a logical manner........................................................ 38 7.1.6 Ability to change the grid size for different puzzles ..................................................... 38 7.2 Project Management ............................................................................................................ 39 7.3 Further Development............................................................................................................ 39 8 References .................................................................................................................................... 41 Appendix I: Project Description ............................................................................................................ 43 Appendix II: Initial Project Plan ............................................................................................................. 44 Appendix III: Project Gantt version 1 .................................................................................................... 46 Appendix IV: Project Gantt Actual ........................................................................................................ 47
Table of Figures
Figure 1: A Slither Link puzzle and its solution........................................................................................ 9 Figure 2: Different shaped Slither Link (3) ............................................................................................ 10 Figure 3: Numbered Cells in a Corner ................................................................................................... 10 Figure 4: Adjacent 3 and 0 cells ............................................................................................................ 11 Figure 5: Adjacent 3 Cells ...................................................................................................................... 11 Figure 6: Diagonal 3 Cells ...................................................................................................................... 11 Figure 7: Numbered Cells...................................................................................................................... 11 Figure 8: Valid side options from a point .............................................................................................. 11 Figure 9: Invalid side options from a point ........................................................................................... 12 Figure 10: Invalid two loop solution ..................................................................................................... 12 Figure 11: Map of Australia(6) .............................................................................................................. 13 Figure 12: Partial search tree for backtracking the map colouring problem (6). ................................. 14 Figure 13: Use Case Diagram ................................................................................................................ 19 Figure 14: Data Structure Design .......................................................................................................... 20 Figure 15: Core Class Design ................................................................................................................. 21 Figure 16: Solver Interface Design ........................................................................................................ 21 Figure 17: Model View Controller ......................................................................................................... 22 Figure 18: Controller Design ................................................................................................................. 22 Figure 19: Design Class Diagram ........................................................................................................... 23 Figure 20: Number Cell Clauses ............................................................................................................ 24 Figure 21: Point Clauses ........................................................................................................................ 24 Figure 22: GUI Design............................................................................................................................ 25 Figure 23: String Example ..................................................................................................................... 27 Figure 24: Solver Code .......................................................................................................................... 28 Figure 25: Grid Input Key Listener ........................................................................................................ 30 Figure 26: Class Diagram of Implementation........................................................................................ 31 Figure 27: Default GUI........................................................................................................................... 32 Figure 28: Incorrect Point Highlighting ................................................................................................. 33 Figure 29: Changing the Grid Size ......................................................................................................... 33 Figure 30: 1st Valid Solution Histogram................................................................................................ 34 Figure 31: Total Valid Histogram........................................................................................................... 35 Figure 32: Generator Histogram ........................................................................................................... 36
Chapter 1 1 Introduction
This chapter gives a brief overview of the project and the main objectives. Also included are an explanation of the terminology used and a synopsis of the contents of the following chapters.
1.2 Objectives
The primary objective of the project is to create a computer based tool for the playing and generation of the Slither Link puzzle. This was divided into two major aspects: the underlying logic required to generate and solve the puzzles and the GUI features required to display the logic to its full potential, allowing users to easily interact and solve the puzzle. In terms of the logic required, the basic functionality of the game is: 1. The ability to solve a given puzzle. 2. The ability to generate new puzzles of different sizes with valid solutions. In terms of the GUI features, the following requirements were identified: 1. The ability to play a given game selecting and deselecting sides. 2. Restart, New Game and Check Solution options. 3. A player is able to input their own puzzle in a logical manner. 4. The ability to change the grid size for different puzzles. The following additional items were identified as complimentary additions to the basic functionality. Upon checking a solution, if incorrect, highlight any points that are incorrect. Adding to the underlying logic in order to implement a hint tool. It was thought that this would only be useful if the hint provided was a human logical step. Simply providing a random side that should be filled in will not help the user to learn the steps of the game. Analysing the puzzles in order to add a difficulty rating to the generator. This would require a definition of what makes a Slither Link puzzle more difficult to solve in terms of the human mind and not just a computer application solving it. Deploying a web-based interface for the puzzle, with user logins and profiles, to improve the distribution of the application. A further break down of these objectives can be found in Appendix II: Initial Project Plan. 7
1.3 Terminology
For the purpose of this report: A point represents a dot on the grid. A side connects two points. Within the program this is classified as a vSide or a hSide for vertical and horizontal sides respectively. A side may be filled in or left blank. A cell is either empty or filled with a number {0, 1, 2, 3}. The grid size represents how many cells there are in the grid. For 7 rows of 7 columns, the grid size would be 7x7.
Chapter 2 2 Background
This chapter gives a more detailed background to the Slither Link puzzle, its history and the rules for playing the game.
Figure 1 demonstrates a 7x7 Slither Link game with one of its possible solutions. Slither Link comes in different sizes and difficulty ratings. On-line versions typically range from 5x5 grids up to 30x30. More advanced versions of the puzzle incorporate different shaped grids, as displayed in Figure 2.
Whilst not as widespread as Sudoku, versions of Slither Link are available for a limited number of electronic devices. Slither Link is included in the Puzzle Series Volume 5 available for the Nintendo DS; released in Japan in 2006 and North America in 2007 (4). The Numeri application for the iPhone was launched in 2009, which adapts the original game to better suit the touch screen features of the iPhone. In Numeri, there are no cells containing a 0 and instead of drawing each side of the loop yourself you start with a pre-drawn loop that you have to drag and drop around the grid to satisfy the numbers contained within the cells (5). Slither Link can also be found in one-off puzzle supplements to newspapers, but has yet to become a daily feature alongside Sudoku and crosswords.
10
Cells containing a 3 form the basis of many additional rules. For example, an adjacent 3 and 0 must always follow the pattern shown in Figure 4.
For two adjacent 3s, the side in-between them and the parallel external sides must always be filled in, as showing in Figure 5.
For diagonal threes, the outer corners will always be filled in, as shown in Figure 6.
In terms of programming a solver for Slither Link, there are three rules that must be satisfied. 2.2.1 Rule 1: Number Cells When a cell contains a number, it must be surrounded by exactly that number of lines. Empty cells may be surrounded by any number of lines. Figure 7 demonstrates the possible numbered cells that could appear.
2.2.2 Rule 2: Points For any point on the board, there must be either exactly 2 surrounding sides filled in, or exactly none. Figure 8 shows the valid options for sides filled in surrounding a point; Figure 9 demonstrates the invalid options.
11
2.2.3 Rule 3: Single Loop The solution must form a single loop. As the grid size increases, it become more likely that a possible solution that contains 2 complete loops will be found as demonstrated in Figure 10 but this is invalid.
12
As a CSP, the variables are defined as the states: WA (Western Australia), NT (Northern Territory), SA (South Australia), Q (Queensland), NSW (New South Wales), V (Victoria) and T (Tasmania). The domain of each variable is the set {red, green, blue}. The constraints require neighbouring states to have distinct colours, so for WA and NT the valid combinations are the pairs: {(red, green), (red, blue), (green, red), (green, blue), (blue, red), (blue, green)}. The valid combinations for each pair of neighbouring states form the constraints of the CSP.
13
In the case of the Slither Link puzzle, the set of variables would be the set of sides. As the domain of each variable is {true, false} (i.e. filled in or blank) then this is a finite domain CSP. The three rules described in section 2.2 would then be used as constraints between the sides. 3.1.2 Solving Two of the main methods of solving CSPs are constraint propagation and search algorithms. Constraint propagation involves modifying the CSP, ideally into one that is equivalent or easier to solve by reducing the search space at that stage. For example in the map colouring problem, if we chose a colour for WA and Q, we want to propagate this onto the constraints for NT and SA and then onto the constraint between NT and SA. It must be faster to propagate the constraint than doing a simple search (6). Search algorithms solve CSPs by exploring possible solutions. The backtracking algorithm is a search algorithm, which uses recursion to try all possibilities until a valid solution is found or the search space is exhausted. For the map colouring CSP, the back tracking algorithm chooses one variable (state) at a time and backtracks when a variable has no legal values (colours) left to assign. Figure 12 shows part of the search tree generated by the back tracking algorithm.
Figure 12: Partial search tree for backtracking the map colouring problem (6).
In reality, the back tracking algorithm alone would be very inefficient with a large number of constraints. It can be improved with methods such as look-ahead and constraint learning. There are many valid solutions to the above map colouring, one of them being: {WA = red, NT = green, Q = red, NSQ = green, V= red, SA = blue, T = red}. The Slither Link solution would be the set of assignments to the sides which satisfies all of the constraints, setting sides to true in order to form a single loop that satisfies any cells containing numbers. When more than one solution is found, choosing the best solution can be defined by an optimisation function. The investigation into what is the optimal solution for a Slither Link puzzle is outside the scope of this project.
14
15
JaCop Java Constraint Programming Solver is an open-source java library that contains constraint programming technology. It lists its advantages as: ease of maintenance, lack of memory management issues, ease of writing code, and portability (12). There are also other similar Java libraries available, such as Choco (13). Geocode similar to JaCop but a C++ implementation. Geocode prides itself in excellent performance, having won the MiniZinc challenge in 2008 and 2009 (14).
3.3.2 SAT Solvers SAT solvers determine whether it is possible to find assignments to variables that make your provided SAT problem evaluate to true. Although Satisfiability problems are NP-complete, a SAT solver will usually find a solution or prove that none exists relatively quickly. SAT solvers build on the current algorithmic solutions available for Satisfiability problems, and have improved considerably over the last 10 years. The annual SAT competitions have driven developers to refine the implementation and improve the performance of such tools. There are many open source SAT solvers available that can be embedded into the major programming languages, for example: MiniSAT - a minimalistic open source SAT solving library written in C++. It started in 2003, aiming to be a small yet efficient SAT solver with good documentation, the first version having just 600 lines of code. It prides itself in being easy to modify, designed for integration and highly efficient: having won all the industrial categories in the SAT 2005 awards (15). SAT4J - a Java SAT library, SAT4J has shipped with versions of the Eclipse development platform since 2008. SAT4J places emphasis on providing a SAT black box, enabling users to embed SAT technologies in their code without worrying about the implementation details. It includes an adaptation of the algorithms used in MiniSAT, adapted to suit Java practices (16).
view-controller component design, abstracting out the data of the component from how it is displayed on screen (21).
17
Chapter 4: 4 Design
This chapter summarises the design decisions that were made during the project. Implementation methods are discussed, and the design patterns that affected the overall structure of the project are explained. There is then a more in-depth focus on the design features related specifically to the solver and the GUI respectively.
18
4.1.1 Iterations The unified process is risk and client driven; meaning that the first features to be implemented should be those that are of the highest risk and of the most importance to the client (22). In this instance, it was decided that it would be important to start development on both the GUI and the underlying logic for a number of reasons. Firstly, without either one of these the project would not work to its potential it would be pointless to spend the entire time coding excellent solving features without the GUI to display it on and vice versa. Additionally, by having a simple GUI implemented it was easier to check output from the solver logic. Finally, by developing both alongside each other it ensured they fitted together perfectly and there were no problems trying to adapt data structures between the two. As such the following implementation order was decided: Iteration 1: Interface on which the game can be displayed. Ability to solve a given game.
Iteration 2: Interactive interface that allows the user to play the game. Ability to generate new games.
Iteration 3: Additions to interface: restart, change grid size, check solutions. Ability to enter own game.
In keeping with the unified process testing was scheduled at the end of each iteration so that the result was a correctly working subset of the overall system.
19
By all game components inheriting from the Game Feature type, they can be treated in the same manner throughout the code, avoiding the need to constantly check for type. For example a selection on the board simply calls the method to deal with that selection; no checks are needed for what type of feature the player clicked on. If they have selected a point, the method implementation will simply be empty as no action is required whereas selecting a side will either colour or clear it depending on its initial state. Additionally they can share functionality such as size and colour parameters making changes easier to implement in a single location. 4.2.2 Core In keeping with Gang of Four design patterns, a singleton factory called Core is the central creation point of the application, containing all of the information required to create: the GUI instance, the solver instance, the controller instance, and the game itself. Core is a singleton class, meaning it can only be created once as we will only ever need to have a single Core to generate the required features of the application. By using a Core factory, all the complex creation information is stored in one place.
20
Figure 15 shows a simplified design class diagram for the Core class. The setMode() method refers to the requirement for the user to be able to play or enter their own game. This results in a play or edit mode, which is controlled via the Core class.
4.2.3 Solver Interface The external SAT library is separated from the rest of the application code by a Solver Interface. This satisfies a number of design patterns. As a Protected Variation, if the inputs to the SAT4J library were to change, it would mean that changes are only required to the SAT4J implementation of the solver interface, the solver interface itself and hence the remaining code will remain unchanged. It also provides a level of indirection. Thus the method used to solve the puzzles could change without modifying code throughout the application so long as the required methods of the interface are implemented. For example, a different external SAT library could be used to implement the solver or a method for solving the puzzles that doesnt utilise a SAT solving library could be implemented without changes being required throughout the application. Figure 16 shows the Solver Interface between the Core class and the implementation of the solver using the SAT4J library.
21
4.2.4 Model-View-Controller The model-view-controller pattern is a framework developed by Trygve Reenskaug in the 1970s whilst working on the Smalltalk platform (24). The concept is well known but often overlooked, to separate the modelling of the domain, the presentation and the actions resulting from user input into three separate classes.
Model
View
Controller
Figure 17 shows the relationship between the three components. The view manages the graphical and/or textual output of the application. The controller interprets the mouse and keyboard inputs from the user, commanding the model and/or the view to change as appropriate. The model manages the behaviour of the data of the application, responds to request for information about its state (usually from the view) and responds instructions to change state (usually from the controller) (25).
Figure 18 shows how this was applied to the Slither Link application. Here the GUI class acts as the view, a specialized Controller class is used to handle user events on the GUI and the Core class acts as the model, containing all of the information about the current state of the application.
Similar principals can be found in both the GRASP design patterns (Controller coordinates system operation from the UI layer) and Gang of Four patterns (Observer provides a level of indirection between UI events and the system). There are a number of benefits to the level of separation achieved from the model-view-controller architecture. From a development point of view, it facilitates more straightforward testing as errors are easier to isolate to a particular component. Testing of each component can also be more thorough, as the functionality is clearly identifiable as opposed to being distributed across various classes throughout the application.
22
Within the lifetime of the application, the level of separation allows the application to accommodate changes to the user interface. As the core model does not depend on the view, adding a new type of view to the application does not affect the model. This facilitates the possible future addition of a web interface for the application, as discussed in section 7.3. 4.2.5 Class Diagram Figure 19 shows the resulting design for the overall system incorporating the design features discussed above, concluding the discussion of the overall design.
Figure 20 displays the resulting clauses that are added to the expression wherever a cell containing a number is found. If a cell contains a 3: S1 v S2 v S3 v S4 S1 v S2 S1 v S3 S1 v S4 S2 v S3 S2 v S4 S3 v S4 If a cell contains a 2: S1 v S2 v S3 v S4 S1 v S2 v S3 v S4 S1 v S2 v S3 v S4 S1 v S2 v S3 v S4 S1 v S2 v S3 v S4 S1 v S2 v S3 v S4 S1 v S2 v S3 v S4 S1 v S2 v S3 v S4 S1 v S2 v S3 v S4 S1 v S2 v S3 v S4 If a cell contains a 0: S1 S2 S3 S4
If a cell contains a 1: S1 v S2 v S3 v S4 S1 v S2 S1 v S3 S1 v S4 S2 v S3 S2 v S4 S3 v S4
4.3.2 Rule 2: Points For any point on the board, there must be either exactly 2 surrounding sides filled in, or exactly none. However not all points have 4 sides leading out of them, corner points only have 2 and points along an external edge have 3. Therefore the clauses differ based on these 3 types of point. For a point with 4 sides, the same clauses are added as for a cell containing a 2 minus the clause preventing 0 sides being true as this would be valid in this situation. Truth tables were used to determine the clauses for points with 3 or 2 sides. Figure 21 shows the clauses for points surrounded by 4, 3 or 2 sides. A point with 4 sides: S1 v S2 v S3 v S4 S1 v S2 v S3 v S4 S1 v S2 v S3 v S4 S1 v S2 v S3 v S4 S1 v S2 v S3 v S4 S1 v S2 v S3 v S4 S1 v S2 v S3 v S4 S1 v S2 v S3 v S4 S1 v S2 v S3 v S4 A point with 2 sides: S1 v S2 S1 v S2 A point with 3 sides: S1 v S2 v S3 S1 v S2 v S3 S1 v S2 v S3 S1 v S2 v S3
24
4.3.3 Rule 3: Single Loop The solution must form a single loop. Considerable time was spent attempting to encode this into Boolean propositional formulae in conjunctive normal form, but unfortunately no successful encoding was found within the time constraints of the project. Instead a hybrid solution was designed; whereby the constraints for numbered cells and points are solved using satisfiability methods and then the possible solutions that meet these two constraints are checked until a solution is found that satisfies the single loop constraint. In order to check a single loop is formed, the following pseudo code was implemented: For each side in the puzzle: If side filled in, add to total count. For a random start side that is filled in Until current side = start side Move to next filled in side (without going to previous side) Add to current count If current count = total count Success! Single loop formed Else Solution invalid more than one loop formed.
Care was taken in the design of each section to ensure the best practices in human computer interaction were met.
25
4.4.1 Game Panel The game panel displays the Slither Link puzzle. The following requirements were established for the game section of the user interface: The user must be able to make and undo a move. The user must be able to enter their own puzzles.
There were a number of options for user interaction with the game panel. Firstly, with the aim of playing the game, the user could either: Drag around a pre-drawn complete loop on the grid until it lays in a pattern that satisfies the puzzle. This would need the loop to grow and shrink as required. This method is implemented by the Numeri application on the iPhone, which is a similar concept to Slither Link and has received mixed reviews. Select each side in turn by clicking on it until a complete loop has been formed.
It was decided that the user should select each side. The drag and drop of the pre-drawn loop was determined to be more suitable to touch screen applications such as the iPhone. Additionally, by clicking each side, undoing a move is easier to implement and you can also add functionality for the player to denote sides that cannot be filled in, aiding their game playing strategy. For the second requirement, the user needed to be able to interact with the game panel in order to enter their own puzzles. It was decided that the user should be able to either enter their puzzle via the grid or by typing in some form of string representation of the puzzle. It was predicted that string input would be a faster method, possibly for when users wish to find a solution to a puzzle from another source. Entering via the grid was predicted to be used more for a user to try and create their own puzzles. Again there were a number of options for entering a game via the grid. The user could: Select a cell and type in the number (input validation would need to be used to prevent anything other than {0, 1, 2, 3}). Drag the required number from an Edit Panel into the cell. Divide each cell into quarters for each valid option, and the user clicks on the option within the cell they want.
It was decided that selecting the cell and typing in the number would be the best option. Again, the drag and drop function appeared more suited for a touch screen. Whilst dividing the cell into quarters would have eliminated the need for keyboard input, for larger grid sizes the cells may become smaller and hence subdividing them would make each quarter harder to read. On prototype game panels, it was also felt that this option made it less obvious that some of the cells should remain empty when creating a puzzle. In order for the user to implement a game using an input string, a format had to be decided that represented a Slither Link puzzle in string format. The most obvious option was decided to be where each cell had a value and the string is read in rows from left to right starting at the top left. The character x denotes an empty cell and any cells containing a number are denoted by that number. Whilst this method means that the string length grows as the puzzle grid size increases, it was decided to offer the most clarity. Representing the number of blank cells with an alphabetical character to denote the number of blank cells was considered (a=1, b=2, etc) but it was decided that this would be less obvious for speedy entry, with the player being required to know the number equivalent of the alphabetic characters. Thus the puzzle displayed in Figure 23 would be represented by the string xx21xxx2x0123xxxxx1xx2xx0.
26
4.4.2 Button Panel and Menu Bar The button panel and menu bars contain all of the options available to the user other than selecting and deselecting sides on the puzzle. The following requirements were identified for the button panel: Check Answer: if an incorrect solution has been submitted, points of failure should be highlighted on the game panel. Find Solution: displays a solution, removing any sides currently selected by the user. Restart Game: clears any sides selected by the user but keeps the current puzzle. New Game: generates and displays a new puzzle. Input own game: needs to give the user the option between string or grid input. Change grid size: needs to give the user the option between 5x5, 7x7 and 9x9.
It was decided that it would be too much functionality to add all of the above features to the immediately visible buttons in the button panel alongside the game panel. Therefore a menu bar was added so that just the functionality that is directly related to the user playing the current game is in the button panel. Thus the button panel contains the options for: Check Answer, Find Solution, Restart and New Game. The options to input your own game and change the grid size were moved to the menu bar. This worked well, as drop down menus could then be used for the further selections required after each of these options.
27
Chapter 5 5 Implementation
This chapter details the implementation of the main features of the application. The implementation is divided into two sections: the implementation of the solver and the implementation of the graphical user interface. The overall implementation of the application is then summarised with the help of a design class diagram detailing the resulting system.
14 //Loop over possible solutions, performing single check 15 while (problem.isSatisfiable() && count<500){ 16 count++; 17 model = problem.model(); 18 19 if (singleCheck()){ 20 return model; 21 } 22 } 23 //If no valid solution found before timeout, return null. 24 return null;
Figure 24: Solver Code
28
The point and number cell clauses generated from the current puzzle are then added to the solver instance (Figure 24 lines 4-9). In order to do this, the clauses must be converted from an Array List into the VecInt type. The VecInt type is an internal type in the SAT4J library. The application deliberately doesnt generate the clauses as the internal VecInt type so as to maintain a level of indirection between the application and the external SAT4J library. Next, an instance of the IProblem interface (from the SAT4J library) is used to create a solution (Figure 24 line 11). As discussed in section 4.3.3; the single loop constraint could not be encoded into the clauses to be added to the solver instance, so the models returned may be invalid in that they form more than one loop. Thus the models returned by the problem instance are iterated over, each one being checked as to whether it forms a single loop until either: A valid solution is found There are no more models The 500 iteration loop timeout occurs. In the cases that no valid solution is found, the puzzle is declared to be unsolvable. The timeout is set to 500 iterations as it was found that above this a visible time lag can be seen when waiting for the solver to complete. Section 6.2 analyses when the first valid solution is found and whether the timeout is ever met. 5.1.2 Generation Research was carried out into how many cells are typically filled in per grid size via freely available online puzzles. It was found that overall this is a random number somewhere between twice and three times the grid size. In order to generate a new puzzle, a random loop is first drawn on the grid. Certain restrictions are placed on this loop to ensure that a suitable game is generated, such as the minimum number of lines that it has to contain and that it cant form a loop that follows the external edges of the board. Once the loop is generated, a random number of cells are populated. As a final check, the resulting puzzle is input into the solver to check that a valid solution can be found out before the timeout. If not, a new puzzle is generated. Section 6.3 analyses how many times a new puzzle has to be generated because a valid solution could not be found before the timeout. 5.1.3 Check Solution The check solution methodology does not use the SAT4J library, in case of the situation where the solver times out before it finds the specific solution submitted by a user. In this instance if we had used the SAT4J library, the application would have incorrectly indicated a valid solution submitted by the player was incorrect. Instead, a simple loop over the game structure is made that checks that any numbered cells are correctly surrounded and that there are no loose ends or crossings at any of the points. The singleCheck() method is then used to ensure a single loop has been formed, and the player is informed as to whether their solution is correct or not. In the instance that an invalid solution is entered, this is highlighted on the playing board via red outlines of the points or cells that are incorrect.
into different classes in order to maintain high cohesion within each class. A GUI object then contains an instance of both the game panel and the button panel in order to group them together for display. As each of the components of the game (cells, points and sides) use polymorphism to inherit from the generic type Game Feature, they can all be based on the same graphical representation. A JPanel from the Java Swing library is used for all features and then extended for the different requirements such as differing sizes. There are then some additional features for certain components, for example: a point has its background colour filled in, a cell has a text field that can contain a number, and a side can be selected or deselected changing its background colour. A flexible layout manager was required to ensure that different sized puzzle grids could be accommodated within the GUI, as well as enabling a certain amount of resizing of the GUI based upon the users preference. The Java Spring layout was found to work excellently for this application. Using spring layout, you define directional constraints between components. Thus a grid like structure made up of JPanels of different sizes was created for the Slither Link puzzle to be displayed on. The Java Spring layout can be found at (28). 5.2.2 Validation When the player is inputting their own game, strict validation was important to prevent any unexpected errors, which can be difficult to pick up on when testing due user input being unpredictable. For the string input method validation checks are run when the user submits their input. The length is checked against the current grid size, and the string can only contain a valid number {0, 1, 2, 3} or an x to indicate a empty cell. Any failed validation from the string input will display an error message detailing what failed and then return the user to the Input String dialog. When validating the users input via the grid a key listener was used. By implementing the Key Typed method of the key listener, validation checks could be made every time the user attempted to type into the grid (as displayed in Figure 25). If they attempt to type anything in a cell other than a valid number {0, 1, 2, 3} or a delete action then the input will be deleted and an error sound is emitted (Figure 25 lines 6-10). The length of the input is also checked to ensure they dont enter more than a single character (Figure 25 lines 11-15). 1 2 3 4 5 6 7 //Validate input to be a single 0,1,2,3 char c = e.getKeyChar(); JTextField textField = (JTextField) e.getSource(); String content = textField.getText();
//Check input is a valid character if ( c!='0' && c!= '1' && c!='2' && c!='3' && c!=KeyEvent.VK_BACK_SPACE && c!=KeyEvent.VK_DELETE){ 8 getToolkit().beep(); 9 e.consume(); 10 } 11 12 //Check input is correct length 13 if (content.length() != 0){ 14 getToolkit().beep(); 15 e.consume(); 16 }
Figure 25: Grid Input Key Listener
30
31
Chapter 6 6 Results
This chapter details the results of the project. First, the features of the graphical user interface are displayed. There is then some analysis of the solver implementation: detailing how efficient it is across the available grid sizes as well as success at solving external puzzles. The generation method is also analysed. The end of this chapter then goes on to detail any additional testing that was carried out on the application.
6.1 GUI
This section displays the main features of the graphical user interface for the Slither Link application. The GUI loads with a default 5x5 grid, as show in Figure 27.
The user can select or deselect a side by a single left click on that side. When selected, the cell is filled with a gray colour. By right clicking a side, the user can mark it as a side that cant be filled in. When the user clicks Check Answer, a dialogue box displays a message telling them if their solution is correct. If it is incorrect, any cells or points that dont satisfy the constraints for the game are highlighted in red, as showing in Figure 28.
32
The user can change the size of the grid using the radio buttons in the menu bar, as displayed in Figure 29.
There are two options for the user to create their own puzzle. If they select to Enter using String from the Create menu bar option, a dialog box allows them to input the string format of the puzzle. If they select to Enter via grid an empty editable grid is loaded. Validation is applied to both of these methods to prevent invalid games being entered.
33
5x5
100 80 60 40 20 0 1 2 3 4 5 6 7 8 9 More 100 80 60 40 20 0 Frequency Frequency
7x7
1st Valid
9x9
100 80 60 40 20 0 1 2 3 4 5 6 7 8 9 More 1st Valid
Figure 30: 1st Valid Solution Histogram
As displayed in the histograms for each size category in Figure 30, for a large proportion of cases the first model returned from the SAT solver was valid. A trend can however be seen that as the grid size increases, the likeliness that the first model returned will be valid decreases; 77% for 5x5 compared to 28% for 9x9 grids. For the 9x9 grid, 70% of valid solutions were found before the program had looped 9 times. The test runs demonstrated that the application never reaches the 500 loop timeout, a valid solution was always returned before this limit within these grid size ranges.
34
Frequency
6.2.2 Total Valid This section analyses how many of the solutions returned from the SAT library are valid in comparison to the total number of solutions returned.
5x5
40 30 20 10 0 10% 20% 30% 40% 50% 60% 70% 80% 90% 100% 40 30 20 10 0 Frequency Frequency
7x7
Valid
9x9
40 30 20 10 0 10% 20% 30% 40% 50% 60% 70% 80% 90% 100% Valid
Figure 31: Total Valid Histogram
The histograms in Figure 31 display what percentage of returned models from the SAT library are valid solutions within the application across the grid sizes 5x5, 7x7 and 9x9 over 100 runs. As can be seen by the trends on the histograms, the smaller the grid size the more likely the returned model is a valid one. For 31 out of 100 puzzles generated on a 5x5 grid, 100% of the models returned by the SAT library were valid solutions compared to only 3 out of 100 puzzles generated on a 9x9 grid that had 100% validity of solutions returned by the SAT libraries. 6.2.3 Total Solutions This section analyses the total number of models returned from the SAT library (note that not all of these will form valid solutions for the model due to the missing constraint). The application is set to timeout when 500 models returned from the SAT library have been looped through, to avoid it continually looping through models returned for a puzzle that doesnt have a single loop solution. Out of 100 runs, a 5x5 grid only reached 500 returned models from the SAT library (the default max) 6 times. On average 85 models were returned in total for a 5x5 grid. In comparison, a 7x7 grid only had 5 out of 100 runs where the 500 max was not reached, and none of the runs for a 9x9 grid returned less than the 500 max from the SAT library. However, it is not believed to be beneficial to increase the maximum number of times the application loops through the returned models from the library looking for a valid solution, as the analysis into the 1st valid solution returned found that for the 9x9 grid a valid solution was discovered within the first 9 loops 70% of the time.
35
Frequency
10% 20% 30% 40% 50% 60% 70% 80% 90% 100% Valid
The number of solutions returned by the SAT library may however provide an insight into the analysis of the proportion of valid solutions returned. As more models are returned the greater the grid size, it becomes less likely that 100% of these models will form a valid solutions. This was demonstrated in section 6.2.3 Total Solutions. 6.2.4 Solving External Puzzles To check that the solver is capable of handling difficult rated puzzles from other applications, puzzles from a range of on-line sources were input into the Slither Link application for it to attempt to solve. This proved very successful. 25 difficult rated puzzles were input for each of the 3 grid sizes and the application was able to solve all of them.
5x5
80 60 40 20 0 1 2 3 4 5 6 7 8 9 More 80 60 40 20 0 Frequency Frequency
7x7
9x9
80 60 40 20 0 1 2 3 4 5 6 7 8 9 More
Figure 32: Generator Histogram
Figure 32 shows how many times the generator method has to restart because a solution could not be found before the time out across each grid size. In common with the other analysis, the performance is better for smaller grid sizes. On a 5x5 grid, a puzzle was generated on the first loop 61% of the time compared to 38% of the time for a 9x9 grid. However across all grid sizes, the vast
36
Frequency
1 2 3 4 5 6 7 8 9 More
majority of puzzles were generated within 5 loops indicating that the generator is not dramatically worse for larger grid sizes.
6.4 Testing
The previous sections detail testing the effectiveness of the methods used to solve and generate puzzles. Other forms of testing were required to ensure that the application met the requirements and no unexpected behaviour was displayed. As the implementation was incremental, unit testing of each component at the end of each iteration suited the structure of the project. Testing of an application such as this is relatively straight forwards and was not overly time consuming. The main tests that were carried out had the aim of checking that the implemented section behaved as expected. So for example, any modifications to the graphical user interface could quickly be tested. Similarly, the implementation of a solver method was simple tested by repeatedly using the functionality to check that it consistently solved puzzles with no errors across the grid sizes. On-top of the incremental unit tests, time was also dedicated to a final system test before the application was demonstrated. The motivation behind this was to check that the resulting application met the original requirements, as well as ensuring that no unexpected behaviour had unwittingly been created in features developed and tested in earlier iterations. As user input is limited to the input of their own puzzles, which is strictly validated, the user interface is on the whole straightforward to test. Attention was paid to following different routes through the application, to ensure consistency. For example, checking what would happen when changing the grid size when in the edit mode it should remain in the edit mode not default back to the play mode.
37
Chapter 7 7 Conclusions
This chapter evaluates the success of the project. How the original objectives were achieved is examined, as is the project management process that was followed. Finally, recommendations for extensions to the project if more time was available are made.
7.1 Objectives
The basic objectives of the project were identified in 1.2 Objectives. This section analyses each objective, detailing whether it was achieved and how well the implementation worked. 7.1.1 Ability to solve a given puzzle Analysis of the solver implementation showed it to be capable of solving a range of puzzles available from other sources. However, the looping nature of the solver implementation is not ideal. Whilst it did not occur within the test data set, it is feasible for the solver implementation to time out before it finds a valid solution when a valid solution does in fact exist. 7.1.2 Ability to generate new puzzles of different sizes with valid solutions The application demonstrated itself to be capable of generating new puzzles. However the requirement to iterate over the generator method until a puzzle was created that could be solved before the solver timeout is once again not an ideal implementation. 7.1.3 Ability to play a given game selecting and deselecting sides This was a relatively straight forward GUI implementation. Effort was however spent ensuring that the selections appeared in a manner that was pleasing to the user. 7.1.4 Restart, New Game and Check Solution options These options were once again relatively simple to implement once the underlying solving and generating functionality had been implemented. 7.1.5 Able to input their own game in a logical manner Two methods were implemented to meet this objective: string or grid inputs. As the puzzle proved to be successful at solving puzzles available from on-line sources, this feature gives the application a potential use as a solving tool for puzzles generated elsewhere. 7.1.6 Ability to change the grid size for different puzzles This objective was achieved. However it is thought that more flexibility could have been implemented within this objective, to allow different shaped or larger grids than the three options that were made available. In conclusion, whilst the basic objectives were met the results section has indicated that improvements could have been made to the methods used to implement the solving functionality. The difficulty faced encoding the final constraint, that the solution must form a single loop, meant that most of the solving functionality has to iterate over models. Had the final constraint successfully been encoded in conjunctive normal form and added to the expression solved by the external SAT4J library, this looping would have been avoided. A vast array of additional features, as discussed in the subsequent section 7.3, would also have improved the project had time allowed.
38
39
The ability to add a Hint tool would also have been desirable feature. This would require a different approach to be taken in relation to the puzzles as the next human step cannot be found using the Boolean propositional formulae that are currently used to solve the puzzle. The final feature that was a point of interest would be some analysis for a difficulty rating. It is currently unknown what makes a Slither Link puzzle more difficult whether it is the number of cells that contain a number or the number of possible steps after each move.
40
8 References
1. Nikoli. Slitherlink. Nikoli Puzzles. [Online] http://www.nikoli.co.jp/en/puzzles/slitherlink/index_text.htm. 2. Conceptis Ltd. Slitherlink History. Conceptis Puzzles. [Online] http://www.conceptispuzzles.com/index.aspx?uri=puzzle/slitherlink/history. 3. Bumgardner, Jim. Free Slitherlink Puzzles from KrazyDad. KrazyDad. [Online] http://www.krazydad.com/slitherlink/. 4. Agetec Inc. Brain Buster Puzzle Pak. Agetec. [Online] http://www.agetec.com/catalog/product_info.php?products_id=37. 5. Beam, Jennifer. Numeri is Slitherlink Reinvented for iPhone. AppCraver. [Online] http://www.appcraver.com/numeri/. 6. Stuart Russel, Peter Norvig. Artificial Intelligence: A Modern Approach. Chapter 6: Constraint Satisfaction Problems. s.l. : Pearson, 2009. 7. Cook, Stephen. The Complexity of Theorem Proving Procedures. 1971. 8. Fact-Index. NP-Complete. Fact-Index. [Online] http://www.factindex.com/n/np/np_complete_1.html. 9. VisWiki. DPLL Algorithm. VisWiki. [Online] http://www.viswiki.com/en/DPLL_algorithm. 10. SAT Research Group, Princeton University. zChaff. Chaff. [Online] http://www.princeton.edu/~chaff/zchaff.html. 11. J.R.Fisher. Prolog:-tutorial. csuomona. [Online] http://www.csupomona.edu/~jrfisher/www/prolog_tutorial/intro.html. 12. JaCop. JaCoP Overview. JaCoP. [Online] http://jacop.osolpro.com/index.php?option=com_content&view=article&id=19&Itemid=27. 13. ChocoSolver. ChocoSolver. ChocoSolver. [Online] http://www.emn.fr/z-info/choco-solver/. 14. GeoCode. GeoCode. GeoCode. [Online] http://www.gecode.org/. 15. Een, Niklas and Soresson, Niklas. The MiniSat Page. MiniSat. [Online] http://minisat.se/MiniSat.html. 16. OW2 Consortium. SAT4: Bringing the power of SAT technology to the Java Platform. SAT4J. [Online] http://www.sat4j.org/. 17. Stroustrup, Bjarne. The C++ Programming Language. Bjarne Stroustrup's Homepage. [Online] http://www2.research.att.com/~bs/C++.html. 18. . Bjarne Stroustrup's FAQ. When was C++ Invented. [Online] http://public.research.att.com/~bs/bs_faq.html#invention.
41
19. Howard, Toby. COMP20072: Computer Graphics and Image Processing. School of Computer Science Intranet. [Online] https://www.cs.manchester.ac.uk/csonly/courses/COMP20072/manuals/opengl.pdf. 20. Oracle. The History of Java Technology. Java. [Online] http://www.java.com/en/javahistory/. 21. O'Reilly Media, Inc. Why the Excitement About Swing? O'Reilly On Java. [Online] http://www.oreillynet.com/pub/a/oreilly/java/news/swing_0998.html. 22. Larman, Craig. Applying UML and Patterns. Westford, Massachusetts : Prentice Hall, 2008. 23. Gamma, Helm, Johnson, Vlissides. Design Patterns. Introduction. Westford, Massachusetts : Addison-Wesley, 2008. 24. Reenskaug, Trygve. MVC. Pages of Trygve M. H. Reenskaug. [Online] http://heim.ifi.uio.no/~trygver/themes/mvc/mvc-index.html. 25. Burbeck, Steve. How to use Model-View-Controller (MVC). Applications Programming in Smalltalk-80. [Online] http://st-www.cs.illinois.edu/users/smarch/st-docs/mvc.html. 26. Voronkov, Andrei. Vampire's Home Page. VProver. [Online] http://www.vprover.org/. 27. OW2 Consortium. SAT4J Core Download. GForge. [Online] http://forge.ow2.org/project/showfiles.php?group_id=228. 28. Oracle Corporation. How to Use SpringLayout. The Java Tutorials. [Online] http://java.sun.com/docs/books/tutorial/uiswing/layout/spring.html.
42
43
Presentation Results
Description A4 Poster giving a brief outline of the project. Formal presentation of results to project supervisor and additional marker. Should cover either the problem and a general solution or just focus on a specific aspect of the project. of Demonstration at a computer terminal of you project to the laboratory manager and your project supervisor. Should show what your aims were and how you implemented them. Deadline for stopping all technical work on the project. A permanent record of the project and its technical content.
5.) Background Reading The following sites have been an essential source of the types of puzzles described here: http://www.puzzle-loop.com http://www.nikoli.co.jp/en/puzzles/slitherlink/index_text.htm. http://www.krazydad.com/slitherlink/.
45
47