elizabeth.wray computerscience

47
Pencil Puzzles: Slither Link University of Manchester School of Computer Science Project Report 2010 Author: Elizabeth Wray Supervisor: Prof. Andrei Voronkov

Upload: rohit-nigam

Post on 27-Oct-2014

77 views

Category:

Documents


3 download

TRANSCRIPT

Page 1: Elizabeth.wray ComputerScience

Pencil Puzzles: Slither Link

University of Manchester School of Computer Science

Project Report 2010

Author: Elizabeth Wray Supervisor: Prof. Andrei Voronkov

Page 2: Elizabeth.wray ComputerScience

2

Abstract Pencil Puzzles: Slither Link

Pencil puzzles such as Sudoku have gained worldwide attention in recent years. This report focuses on the lesser known Slither Link puzzle, investigating mathematical theories that can be applied in order to solve the puzzle – in particular those related to Boolean satisfiablity. The main aim of the underlying project is to create a computer based tool for the playing and generation of Slither Link puzzles. In addition to this objective, this report details how design patterns and project management frameworks have been utilised in order to successfully implement a completed application within a limited timeframe. The success of implementing a solver through the use of satisfiability is analysed, and a review of additional items that could improve the resulting application if more time were available is included.

Author: Elizabeth Wray

Supervisor: Professor Andrei Voronkov

Date: May 2010

Page 3: Elizabeth.wray ComputerScience

3

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.

Page 4: Elizabeth.wray ComputerScience

4

Table of Contents

1 Introduction .................................................................................................................................... 7 1.1 The Project .............................................................................................................................. 7 1.2 Objectives................................................................................................................................ 7 1.3 Terminology ............................................................................................................................ 8 1.4 Chapter Synopsis ..................................................................................................................... 8

2 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

3 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 4 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

5 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

Page 5: Elizabeth.wray ComputerScience

5

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

Page 6: Elizabeth.wray ComputerScience

6

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

Page 7: Elizabeth.wray ComputerScience

7

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.1 The Project Recent years have seen an enthusiasm for paper based logic puzzles such as Sudoku. This project investigates the use of computer based tools in the generation and playing of such ‘pencil-puzzles’.

While Sudoku specifically has received widespread attention – now featuring in many daily newspapers, puzzle books and on-line puzzle websites, other pencil-puzzles are still relatively unknown. This project will focus on the Slither Link puzzle, and how computer based tools can be used to solve or generate the puzzle.

The project investigates different methods of solving such puzzles computationally and the current programming tools available that could be utilised in order to improve the implementation. Attention is also paid on how best to display the puzzle to improve the player’s experience.

The original project proposal can be found in Appendix I: Project Description.

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.

Page 8: Elizabeth.wray ComputerScience

8

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.

1.4 Chapter Synopsis Chapter 2 - discusses the puzzle in more detail, including its history, how to play the puzzle, tips on finding a solution, and the fundamental rules behind the puzzle.

Chapter 3 - discusses the methods that can be utilised when implementing a solver for the puzzle. It also considers the tools available in these areas and the technology platform best suited for the implementation.

Chapter 4 - details the major design decisions that were taken during the project. Attention is paid to incorporating good design practices throughout the application, as well as the design decisions taken to meet the requirements of the two main sections: the solver and the GUI.

Chapter 5 - discusses the more complex implementation details within the solver and the GUI. An overview of the eventual implementation is also provided.

Chapter 6 - analyses the results of the project. The visible results are demonstrated, and the efficiency of the underlying program analysed.

Chapter 7 - draws conclusions on the project, critically analysing how well it met its objectives, the project management skills utilised and suggestions for further work.

Page 9: Elizabeth.wray ComputerScience

9

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.

2.1 Slither Link Slither Link originates from the Japanese publisher Nikoli (1). Also know as Loop the Loop, Fences, Bridges or Sli-Lin in Japan, it was first published in Nikoli’s Puzzle magazine in 1989 (2) and has featured regularly ever since. Early versions of the game contained a number clue in every cell, which has now evolved to a random amount of cells containing numbers. Slither Link is a logic puzzle; you shouldn’t have to guess moves. Unlike Sudoku, any maths input is strictly limited – counting the number of sides surrounding a number cell is the limit to the maths required! The standard version of the game is played on a rectangular grid of cells. Each cell is either empty or filled with a number 0,1,2,3. The number represents how many lines must be drawn around a cell. Cells that are empty can have any number of lines drawn around them. The aim is to create a single loop with no crossings or loose ends. The puzzle starts with a random amount of cells entered and no sides filled in. The player must select which sides should be filled in, in order to create the loop around the grid.

Figure 1: A Slither Link puzzle and its solution

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.

Page 10: Elizabeth.wray ComputerScience

10

Figure 2: Different shaped Slither Link (3)

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.

2.2 How to solve it In terms of the human mind tackling the puzzle, there are some simple patterns that can be spotted. The more puzzles you play, the more patterns you find to help you decide on a next step. Some of the simplest patterns are as follow:

When a number is in a corner, there are a limited number of options depending on the number. For a corner cell containing a 1, neither of the sides from the corner point can be filled in. A corner cell containing a 2 must have the following two external sides filled in. A corner cell containing a 3 must have the 2 sides from the corner point filled in. This is illustrated by Figure 3.

Figure 3: Numbered Cells in a Corner

Page 11: Elizabeth.wray ComputerScience

11

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.

Figure 4: Adjacent 3 and 0 cells

For two adjacent 3s, the side in-between them and the parallel external sides must always be filled in, as showing in Figure 5.

Figure 5: Adjacent 3 Cells

For diagonal threes, the outer corners will always be filled in, as shown in Figure 6.

Figure 6: Diagonal 3 Cells

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.

Figure 7: Numbered Cells

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.

Figure 8: Valid side options from a point

Page 12: Elizabeth.wray ComputerScience

12

Figure 9: Invalid side options from a point

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.

Figure 10: Invalid two loop solution

Page 13: Elizabeth.wray ComputerScience

13

Chapter 3:

3 Technical Background This chapter details the technical research that was done before work on the design of the application commenced. It starts with an explanation of Constraint Satisfaction Problems and Satisfiability problems, detailing how the methods within these fields can be applied to the Slither Link puzzle. Research is then presented into the tools available to aid in the solving of such problems, and the languages suited to this application. This is then summarised into the technical choices made for the implementation of the application.

3.1 Constraint Satisfaction Problems

3.1.1 Definition The Slither Link puzzle can be seen as a constraint satisfaction problem. A constraint satisfaction problem (CSP) is defined by a set of variables, X1, X2,...,X and a set of constraints, C1, C2,...,C. Each variable Xi has a nonempty domain Di of possible values. A solution to the CSP is found when an assignment is made to every variable (complete assignment) that satisfies all of the constraints (6).

The map colouring problem is an excellent example of a constraint satisfaction problem. Suppose we are given a map of Australia, as in Figure 11. The aim is to colour each state red, green or blue so that no neighbouring states have the same colour.

Figure 11: Map of Australia(6)

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.

Page 14: Elizabeth.wray ComputerScience

14

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.

Page 15: Elizabeth.wray ComputerScience

15

3.2 Boolean Satisfiability Problems

3.2.1 Definition Satisfiability (SAT) is the problem of determining whether there are a set of assignments to the variables of a Boolean formula that make the formula evaluate to true. In order to utilise the theories related to SAT when solving the Slither Link puzzle, the puzzle would need to be converted into a set of propositional formula. A proposition is anything that can be either true or false, so a propositional formula is a type of formula that has a truth value.

SAT is a well known NP-Complete decision problem, as proved by Stephen Cook in 1971 (7). Solutions to NP-Complete problems can be verified quickly but there is no known way to efficiently find that solution. The time required to solve the problem increases as the size of the problem grows (8). While there is no known polynomial time algorithm to solve NP-complete problems, there have been many efficient and scalable algorithms developed to solve SAT instances in recent years. As the computational power of processors has increased, the field of finding a solution to NP-Complete problems has continued to be widely researched.

3.2.2 Solving Many solving algorithms require the SAT instance to be in conjunctive normal form (CNF). In conjunctive normal form, an expression is made up of a conjunction of clauses. A clause is a disjunction of literals where a literal is a variable or its negation. For example, our literals are the four variables S1, S2, S3, and S4. A negation is preceded by ¬. A clause can be made up of a disjunction of these literals or their negation, for example S1 \/ ¬ S2. An expression in CNF is then a conjunction of such clauses, for example (S1 \/ ¬ S2) /\ (S3 \/ ¬ S4).

The DPLL (Davis-Putman-Logemann-Loveland) is one such algorithm, based on backtracking to solve SAT problems in conjunctive normal form. DPLL uses unit propagation to simplify the clauses and pure literal elimination in order to improve on the standard backtracking algorithm. First introduced in the 1960s, the DPLL algorithm is the basis of many other algorithms and SAT solvers (9). For example, the Chaff algorithm from Princeton University builds on the DPLL principal. The most recent implementation of Chaff, zChaff, has had success in solving problems with more than a million variables and ten million clauses (10).

3.3 Tools Available The previous chapters have examined how the Slither Link puzzle could be solved by either modelling it as a constraint satisfaction problem or as a satisfiability problem and the algorithms that could be used to solve them. There are however a number of tools available that automate the process of solving the problem once it has been converted into either a CSP or SAT problem. These are largely classified into constraint programming or utilising external libraries that implement a SAT solver. The concept behind these tools is that it should be sufficient to clearly define the problem and then allow a black box method to solve it without getting into the details of how this is done.

3.3.1 Constraint Programming In constraint programming, the user specifies a set of constraints and the system solves them. You do not need to specify the steps needed to solve the problem, just accurately describe the problem itself and the system will solve it. There are a number of options available within the constraint programming field:

Prolog – a high level, declarative language that is popular within theorem proving and automated deduction systems. It began in the 1970s with Marseile Prolog and most modern Prolog systems ship with a constraint solver – for example GNU Prolog which includes extensions to Prolog to enable constraint programming (11).

Page 16: Elizabeth.wray ComputerScience

16

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).

3.4 Programming Languages Given that the availability of the above tools is largely based within C++ and Java languages, it was decided to research these in order to make a decision on which language the application would be best implemented in.

3.4.1 C++ C++ started development in 1979 by Bjarne Stroustrup at the Bell Labs (17). Originally called “C with classes” (18), C++ built on the C language to make it object oriented. C++ is known as a superset of C – any valid C program is also a valid C++ program. C++ is said to be a middle level language, as whilst it is high level in most features (i.e. it has a strong abstraction from the machine language), it still allows low level control over aspects such as memory management.

OpenGL is a specification of an Application Programming Interface for computer graphics programming. Two utility libraries extend the functionality of OpenGL; GLU provides function for drawing more complex primitives, and GLUT facilitates interaction (19). Mesa 3D provides a generic OpenGL implementation that can be used with C to create a graphical user interface.

3.4.2 Java Java was developed by a group of Sun engineers called the “Green Team” lead by James Gosling in 1991. It wasn’t until the growth of the internet and the release of the Internet Browser Netscape Navigator in 1995 that the language really started to take off. With a similar syntax to C and C++, Java is an object oriented language that simplifies features that may have bogged down other object oriented languages such as C++. Portability is a major feature of Java – with its “write once, run everywhere” philosophy (20). The Java Swing components contain everything that is needed to build a graphical user interface. Part of the Java Foundation Classes, Swing is platform independent with many powerful components that are fully customisable and can be written in just a few lines of code. Swing employs the mode-

Page 17: Elizabeth.wray ComputerScience

17

view-controller component design, abstracting out the data of the component from how it is displayed on screen (21).

3.5 Technology Choice After analysis of the methods that could be used to solve the Slither Link puzzle, it was decided that the use of Satisfiability and SAT solvers would be an interesting approach to take. As Slither Link is an NP Complete puzzle, it was feared that attempting to design and optimize an efficient algorithm from scratch could take over the entire project, distracting away from other interesting features such as creating a GUI that displays the puzzle in an impressive manner and hopefully some more in-depth analysis of the puzzle in order to create hints or difficulty ratings.

After analysis of the SAT libraries available, it was decided to code the project using Java. The primary aim of this project is not to learn a new language. As such coding in Java avoided the learning curve of a new technology and allowed the project to make progress much faster in the initial stages than if C++ had been chosen. Additionally, simple internet research into the Java Swing libraries showed them to be very well documented and apparently flexible and straight forward to use. Research into SAT libraries showed those implemented in Java – such as SAT4J to be just as effective on this scale as the C++ alternatives such as MiniSat.

Page 18: Elizabeth.wray ComputerScience

18

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.

4.1 The Unified Process A major aim of the project was to efficiently manage the implementation of a project within a limited time period. With this in mind, some time was spent investigating software development processes that could help structure the project to make the best use of the time available. The Unified Process stood out as the most relevant to this application due to its iterative nature and suitability to Object Oriented Design (22), which also supported the decision to code the project using Java. The Unified Process provides a flexible framework, which could be easily adapted to suit the changing structure of the project. The Unified Process supports dividing a project into time boxed iterations, meaning that progress was visible after each iteration and making it easier to monitor the progress of the project as a whole. The breakdown of tasks for this project also proved to fit iterative development well.

As the first step of the unified process the overall basic requirements were outlined. This was done through the use of use cases. Figure 13 shows the use cases that were identified, which are described below.

Play Game: the user needs to be able to play the game by selecting sides on a grid until they have formed a loop. They should also be able to undo selections, and mark sides that can’t be filled in.

Check Solution: the user needs to check their solution is correct. The application should provide feedback on whether it is correct, or highlight any points that make it incorrect.

Find Solution: if a user can’t solve a puzzle, the application needs to be able to display a correct solution. This will require the external SAT library.

Restart: the user should be able to restart a puzzle, which clears any sides they have selected but leaves the puzzle the same.

New Game: the user should be able to indicate they want a new game to be generated. This will require the external SAT library.

Input Own Game: the user should be able to input their own puzzles. This could be for them to attempt to create their own puzzle, or they may be trying to input a puzzle from another source in order to use the Find Solution functionality.

Change Grid Size: the user should be able to change the grid size of the puzzle.

Page 19: Elizabeth.wray ComputerScience

19

Figure 13: Use Case Diagram

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.

Page 20: Elizabeth.wray ComputerScience

20

4.2 Overall Design Before coding could begin on the first iteration, a whiteboard session was used to draw up an outline of the data structures required as well as the underlying structure of the project as a whole. In keeping with following the Unified Process, good Object Oriented design practices were considered when designing the underlying structures. In order to do this, a combination of GRASP and Gang of Four design patterns were used throughout the system design in order to ensure that it remained flexible and to avoid unknown issues that may cause problems later on in the implementation. Design patterns describe simple and elegant solutions to specific problems in object oriented design (23). They do not express new ideas; simply capture solutions that have evolved over time. The Gang of Four design patterns refer to the set of patterns described in (23) by the four authors: Erich Gamma, Richard Helm, Ralph Johnson, and John Vlissides. GRASP stands for General Responsibility Assignment Software Patterns, as described by Craig Larman in (22). The two sets of patterns overlap; a selection of those that are most relevant to this application are described below.

4.2.1 Data Structures The underlying data structure is that of the game itself, which is made up of cells, points and sides. It was decided that the Polymorphism GRASP pattern should be used so that all of these types inherit from the generic type Game Feature, as shown in Figure 14.

Figure 14: Data Structure Design

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.

Page 21: Elizabeth.wray ComputerScience

21

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.

Figure 15: Core Class Design

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 doesn’t 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.

Figure 16: Solver Interface Design

Page 22: Elizabeth.wray ComputerScience

22

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.

Figure 17: 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.

Figure 18: Controller Design

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.

Model

ControllerView

Page 23: Elizabeth.wray ComputerScience

23

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 19: Design Class Diagram

4.3 Solver Design When designing the solver, the following requirements had to be met:

Ability to solve a given puzzle.

Ability to generate new puzzles.

Ability to check a player’s submitted solution is valid.

In order to use the SAT4J libraries, the Slither Link puzzle first needed to be converted into conjunctive normal form. The sides of the puzzle formed the literals of the CNF – true indicating they were filled in and false indicating they were left blank. In the following sections, the literals are listed as a numbered side {S1, S2, S3, S4}. A negated literal (false side) is preceded by ¬. A clause is then made up of a disjunction of literals, indicated by ‘v’, for example ‘S1 v ¬S2’.

4.3.1 Rule 1: Number Cells If a cell contains a number, exactly this number of the surrounding sides must be filled in. All of the cells within a grid are surrounded by 4 sides, so clauses are needed for 3 sides out of 4, 2 sides out of 4, 1 side out of 4 and 0 sides out of 4 in conjunctive normal form.

The simplest here is 0 sides out of 4, where 4 clauses of each side negated are added to the expression. A cell containing a 1 is the inverse of a cell containing a 3. The Vampire tool (26) was used to help generate the clauses where a cell contains a 2 in conjunctive normal form, based on the rule that an even number of variables need to be true with the addition of clauses to prevent 0 or 4 sides being true: leaving 2 as the only option. Truth tables were used to verify that these clauses created the required output.

Page 24: Elizabeth.wray ComputerScience

24

Figure 20 displays the resulting clauses that are added to the expression wherever a cell containing a number is found.

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 3 sides: ¬S1 v S2 v S3

S1 v ¬S2 v S3 S1 v S2 v ¬S3 ¬S1 v ¬S2 v ¬S3

A point with 2 sides: S1 v ¬S2

¬S1 v S2

Figure 21: Point Clauses

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 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

If a cell contains a 0: ¬S1

¬S2

¬S3

¬S4

Figure 20: Number Cell Clauses

Page 25: Elizabeth.wray ComputerScience

25

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.

4.4 GUI Design The GUI design was split into three main areas: the game panel, the button panel and the menu bar as shown in Figure 22. The game panel is used to display the Slither Link puzzle itself. The button panel and the menu bar both contain the necessary options to navigate round the application such as restart, changing the size and checking solutions.

Figure 22: GUI Design

Care was taken in the design of each section to ensure the best practices in human computer interaction were met.

Page 26: Elizabeth.wray ComputerScience

26

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’.

Page 27: Elizabeth.wray ComputerScience

27

Figure 23: String Example

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.

Page 28: Elizabeth.wray ComputerScience

28

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.

5.1 Solver Implementation The solver was implemented with the use of the SAT4J Core libraries, which are available under the GNU LGPL licence at (27).

5.1.1 Solving In order to solve a given puzzle a ‘light’ instance of the SAT4J solver interface is created (Figure 24 line 2). The light solver is used as the Slither Link puzzle is a relatively small SAT problem which will be efficiently solved by the ‘light’ version, avoiding the overheads of the default solver.

1 //Create solver instance

2 ISolver solver = new ModelIterator(SolverFactory.newLight());

3 solver.setTimeout(3600);

4 //An iterator is used to read the clauses into the solver.

5 Iterator c_it = clauses.iterator();

6 while (c_it.hasNext()){

7 int [] clause = (int[])c_it.next();

8 solver.addClause(new VecInt(clause));

9 }

10 //Problem instance holds the possible solutions 11 IProblem problem = solver; 12 int count = 0; 13 int [] model = null;

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

Page 29: Elizabeth.wray ComputerScience

29

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 doesn’t 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 can’t 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.

5.2 GUI Implementation

5.2.1 Display The GUI is implemented using Java Swing functionality. There are two main areas of the GUI: a game panel on which the puzzle is displayed and played, and a button panel which contains the required buttons to give the user the functionality they require. The implementation of these areas is split

Page 30: Elizabeth.wray ComputerScience

30

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 don’t enter more than a single character (Figure 25 lines 11-15).

Figure 25: Grid Input Key Listener

1 //Validate input to be a single 0,1,2,3

2 char c = e.getKeyChar();

3 JTextField textField = (JTextField) e.getSource();

4 String content = textField.getText();

5

6 //Check input is a valid character

7 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 }

Page 31: Elizabeth.wray ComputerScience

31

5.3 Overall Implementation The final implementation follows the designed class structure very closely (see section 4.2.5 for the original design). One additional class was added – the ClauseFunctions class. This class contains all of the methods required to generate the encoding of the puzzle in conjunctive normal form. It is a Pure Fabrication method as it doesn’t relate to a concept within the domain of the Slither Link application, but is required to maintain high cohesion within the Solver class.

Figure 26 displays the final class diagram, with the methods required for the main functionality listed.

Figure 26: Class Diagram of Implementation

Page 32: Elizabeth.wray ComputerScience

32

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.

Figure 27: Default GUI

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 can’t 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 don’t satisfy the constraints for the game are highlighted in red, as showing in Figure 28.

Page 33: Elizabeth.wray ComputerScience

33

Figure 28: Incorrect Point Highlighting

The user can change the size of the grid using the radio buttons in the menu bar, as displayed in Figure 29.

Figure 29: Changing the Grid Size

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.

Page 34: Elizabeth.wray ComputerScience

34

6.2 Solver Success This section analyses the frequency of results generated by the application when attempting to solve puzzles using a combination of the external SAT library and internal algorithms as detailed in the Design and Implementation chapters.

As previously discussed, the SAT solver returns models that satisfy the first two constraints of the Slither Link puzzle: the number of sides surrounding a cell and the number of lines from each point to prevent crossings and dead ends. The final constraint (that the solution must form a single loop) is then determined via an internal method, as this could not be encoded into the conjunctive normal form format required by the SAT library. This has the implication that the application needs to loop through the models returned from the SAT library until it finds a ‘valid’ solution. The application is set to timeout after looping 500 times and declare the puzzle unsolvable.

6.2.1 1st Valid This section details how many of the models returned by the SAT library are looped over before a valid (single-loop) solution is found for the grid sizes 5x5, 7x7 and 9x9. The data was collected over 100 puzzles generated by the application in each size category.

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.

020406080

100

1 2 3 4 5 6 7 8 9

Mo

re

Fre

qu

en

cy

1st Valid

5x5

020406080

100

1 2 3 4 5 6 7 8 9

Mo

re

Fre

qu

en

cy

1st Valid

7x7

020406080

100

1 2 3 4 5 6 7 8 9

Mo

re

Fre

qu

en

cy

1st Valid

9x9

Page 35: Elizabeth.wray ComputerScience

35

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.

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 doesn’t 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.

0

10

20

30

40

10

%

20

%

30

%

40

%

50

%

60

%

70

%

80

%

90

%

10

0%

Fre

qu

en

cy

Valid

5x5

0

10

20

30

40

10

%

20

%

30

%

40

%

50

%

60

%

70

%

80

%

90

%

10

0%

Fre

qu

en

cy

Valid

7x7

0

10

20

30

40

10

%

20

%

30

%

40

%

50

%

60

%

70

%

80

%

90

%

10

0%

Fre

qu

en

cy

Valid

9x9

Page 36: Elizabeth.wray ComputerScience

36

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.

6.3 Generator Success This section analyses the generator method, which is used on the launch of the application and whenever the player selects ‘New Game’. The generator works by drawing a random loop, filling in certain cells and then checking that the solver can find a valid solution before it times out (as detailed in the Implementation section). If the solver can’t find the valid solution before the timeout (500 loops), a new puzzle is generated and the checks run again.

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

0

20

40

60

80

1 2 3 4 5 6 7 8 9

Mo

re

Fre

qu

en

cy

5x5

0

20

40

60

801 2 3 4 5 6 7 8 9

Mo

re

Fre

qu

en

cy7x7

0

20

40

60

80

1 2 3 4 5 6 7 8 9

Mo

re

Fre

qu

en

cy

9x9

Page 37: Elizabeth.wray ComputerScience

37

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.

Page 38: Elizabeth.wray ComputerScience

38

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.

Page 39: Elizabeth.wray ComputerScience

39

7.2 Project Management As discussed in Chapter 4: Design, careful consideration was given on how to best structure the implementation of the project within the limited time period available. The project Gantt chart was regularly updated throughout the year to ensure it remained realistic and thus helpful to the progress of the project. The project plan was reviewed post Christmas in light of the delays caused by attempting encode the final constraint in conjunctive normal form in order for it to be inputted into the external SAT library.

The Gantt chart that was created post-seminar (when the objectives of the project were clearer due to more detailed background research being carried out) is shown in Appendix III: Project Gantt version 1. The actual implementation is shown in Appendix IV: Project Gantt Actual. As demonstrated from these Gantt charts, the implementation of the solver ran well over schedule, cutting into any time available to implement additional features.

Whilst the implementation of the solver overran, it is still felt there were some positive points to the project management methods applied to this project with skills developed that will be useful for future projects.

Following the Unified Process (UP) had a number of benefits. As the UP advocates iterative development, the project plan could be adapted to suit discoveries made during previous iterations. It was found that short iterations suited the working methods applied to this project, enabling the project to be broken down into manageable chunks that were achievable alongside other third year commitments.

The UP is risk and client driven. This shaped the contents of the first two iterations – ensuring that priority was given to creating the core functionality of solving and displaying the game early on in development. This proved to be advantageous when the solver implementation overran, as whilst no additional features were implemented the project did successfully meet its main objectives. Even though it was felt that more functionality could have been added, it is still seen as a plus side of the project that the basic functionality was thoroughly completed.

The agile practices of the Unified Process meant the project evolved as more was discovered about the methods involved – which allowed the project plan to be adapted following feedback from the seminar.

In conclusion, whilst the implementation of the solver overran and prevented additional features from being implemented, it is thought that good project management skills were exhibited in order to create a well tested application with all of the basic functionality.

7.3 Further Development There are a number of additional items that would have improved the project. Given more time, the first to be implemented would have been adding a web interface onto the Slither Link application. It is felt that adding a web interface to the application would make it more accessible to different users. There would also be a number of additional features that could be added in the web application. For example:

By adding user logins data could be stored about the user to ensure they were never presented with the same puzzle twice.

A score board feature could be added, possibly based on the time taken to solve the puzzle.

Had a web application with an underlying database been implemented, it is also likely that a store of generated puzzles would be created, instead of generating each puzzle on demand. This should speed up the players experience, by removing the possible iterations over the generate method as the application attempts to create a valid puzzle.

Page 40: Elizabeth.wray ComputerScience

40

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.

Page 41: Elizabeth.wray ComputerScience

41

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.fact-index.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.

Page 42: Elizabeth.wray ComputerScience

42

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.

Page 43: Elizabeth.wray ComputerScience

43

Appendices

Appendix I: Project Description

Pencil puzzles of a Sudoku-type, including "Loop-the-loop" and "Bridges" etc. There has been a tremendous craze in this country for paper-based logical puzzles, the main one being Sudoku, which is now present in most national papers and rivals the crossword in popularity. Other puzzles of a similar type (but more topological than numerical) have also increased in popularity - puzzles such as "Loop-the-loop" and "Bridges". The project is to produce computer-based tools to help in the generation, analysis and playing of such puzzles. Amongst the tools are:

(1) Generation of initial boards, and (unique!) solutions (2) Generation of solutions to given boards (3) "Play-analysis" tools - these provide guidance on what-and-why in a play and give explanations of appropriate moves. To do the latter, we need to represent the deductive aspects of the puzzle and follow and display deductive traces. There is already some analysis of the kinds of deductive traces that are associated with Sudoku (do a websearch!).

There are two other areas for development:

(A) Assessing the difficulty rating of puzzles (B) Producing a `teaching tool' to help players become proficient in the puzzle.

We will be concerned with the puzzles other than Sudoku such as those named above.

Page 44: Elizabeth.wray ComputerScience

44

Appendix II: Initial Project Plan

Pencil puzzles of a Sudoku-type (Including "Loop-the-loop" and "Bridges" etc.) 1.) Brief I aim to create a computer based tool to help in the generation, analysis and playing of puzzles such as loop the loop. There are currently available on the internet a number of sites that allow the playing and solving of these puzzles, but none seem to follow a logic understandable to humans, and therefore they can’t provide features such as ‘next step’ tools to aid in teaching how the puzzle is played. 2.) Project Aims I aim to create a computer based tool to generate, analyse and solve Slither Link puzzles. Important aspects of this that I plan to focus upon are:

2.1 The logic behind these puzzles: I have spent some time playing these puzzles to increase my understanding of the steps taken, as well as to see the various levels of difficulty that are suitable. I see the next step when starting this project is to try and translate this knowledge into logical steps that can be programmed in order to:

Generate Initial Boards and unique solutions

Generate solutions to initial boards

Provide play analysis tools to help teach new users how the games are played.

2.2 The GUI features required to play them: I see the GUI as being very important in this project as without a fully functioning interface then even the most accurate implementation of the logic cannot be displayed to its full ability. Areas that I aim to develop in the GUI are:

Starting from a generated board, allow users to make and undo selections, restart the game, start another game and finish the game to see if their solution is correct.

Allowing a user to easily enter their own game onto the grid and the program to provide a solution if there is one available.

Implementing hints and play analysis tools to demonstrate how the puzzle should be created.

3.) Proposed System Features

3.1 Essentials

Generate Unique Puzzles (and solutions)

A user interface to complete puzzles (allowing users to draw lines, mark out invalid moves etc.)

A solution checker, that highlights were (if anywhere) the player is wrong)

A user interface for the player to enter a puzzle of their own, and the ability for the program to solve this.

Ability to change the size of the grid.

3.2 Wish-List

Difficulty Rating for the puzzles

Hints for the next move / teaching tool.

Web Interface.

4.) Deliverables

Page 45: Elizabeth.wray ComputerScience

45

Date Item Description

11th November 2009 Poster A4 Poster giving a brief outline of the project.

18th Nov – 8th Dec 2009 Seminar 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.

10th March – 23rd March 2009 Presentation of Results

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.

29th March 2009 End of Coding Deadline for stopping all technical work on the project.

5th May 2009 Project Report 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/.

Page 46: Elizabeth.wray ComputerScience

Appendix III: Project Gantt version 1

Page 47: Elizabeth.wray ComputerScience

47

Appendix IV: Project Gantt Actual