





























Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
This page cannot be seen from the preview
Don't miss anything!






























II
Abstract The first focus of this project is creating an implementation of the game Dots and Boxes. This implementation is then used as a testbed for multiple advanced computer players. Some complex computer players have been created, including a Minimax player and a Monte Carlo Tree Search player.
The computer players created were made to compete against each other in tournaments on different sizes of game board, in order to obtain a ranking of the players. The game has also been analysed using these players to determine some important properties of the game.
A ranking of the players shows their relative strengths and weaknesses as well as highlighting key areas for improvement.
The game and all of the players are implemented with Python, using the PyQt5 module for graphics.
Table of Contents
2
Important Outcomes There are a number of important specific outcomes for this project based on the aims and objectives.
Background Dots and Boxes Dots and Boxes, first puďlished iŶ ϭϴϵϱ as ͚ La Pipopipette͛ ďLJ Édouard LuĐas (2), is a pencil and paper game for two players.
The game is played on a grid of dots, commonly ranging from 3x3 to 5x grids. Two players take turns drawing horizontal or vertical lines to connect adjacent dots. When a player completes the fourth side of a square and encloses the space inside, they ͚Đlaiŵ͛ that ďodž for theŵselǀes, usually marking the box with their initial or their player number. An additional rule that is crucial to the complexity of the game is that when a player draws a line to complete a box, they must take another turn afterwards. Players cannot skip turns. The game is finished when all of the lines have been drawn. The winner is the player who claimed the most boxes. (3) Figure 1 - Full game example of Dots and Boxes on a 3x3 grid. (25)
3
Figure 1 shows a full game of dots and boxes on a 3x3 grid, completed in 9 turns. Player B is initially mirroring player A͛s ŵoǀes , until turn 8 where they claim a box and so get an extra move. With this extra move they play another line which opens the board for player A. Player A then claims the remaining three boxes and wins the game.
Dots and Boxes is a good game to analyse from an Artificial Intelligence standpoint as it is a ͚ĐoŵďiŶatorial͛ gaŵe, ǁhiĐh ŵeaŶs that is has the following properties: (4)
Dots and Boxes has already been previously solved for some smaller board sizes, as shown in (1). (5) also presents a winning strategy for player 2 on a 4x4 board. Boards that are larger than 5x5 have not yet been solved, so it is not known if either player can be guaranteed a win on these boards and there is Ŷo kŶoǁŶ strategLJ for ͚ perfeĐt plaLJ͛.
Dots and Boxes is classically played on a grid with all of the lines unfilled, to be played by the player. This is kŶoǁŶ ďLJ soŵe as aŶ ͚ AŵeriĐaŶ ďoard͛. There is aŶother popular ǀariaŶt kŶoǁŶ as a ͚ Sǁedish ďoard͛ , in which the lines that make up the edge of the board are filled in from the start. This can lead to more interesting play and quicker games. (6) As ǁell as these tǁo ǀersioŶs of the gaŵe, the author proposes a third ǀariaŶt, a ͚ raŶdoŵ ďoard͛. This version of the game will start with a number of the lines filled in from the start, chosen at random. This variant is inconsequential to the analysis of the game – it͛s simply fun and interesting.
Algorithms The algorithms chosen and implemented have been picked to help analyse the game itself, and also to demonstrate how effective different strategies can be in the game of dots and boxes.
The minimax theorem is a mathematical theorem in the area of game theory, first proven and published in 1928 by John von Neumann. The minimax theorem provides conditions that guarantee that the max–min inequality is also an equality (7).
The minimax algorithm is a game playing algorithm for n-player games that is based on this theorem. The minimax algorithm is designed to minimise the potential loss in any scenario, whilst maximising potential gain. Minimax was originally designed for n-player zero sum games with perfect information and has more recently been extended to complex games and general decision making in the presence of uncertainty. As Dots and Boxes is an n-player zero sum game with perfect information, minimax is a very good fit for this scenario.
5
Figure 3 - Minimax state tree diagram
The Minimax algorithm described in Figure 2 is a very basic version of the game playing minimax algorithm.
Figure 4 shows a simplified version of Minimax that exploits the property ܾ,ܽሺ ݔܽܯ ሻ ≡ −ܯ𥠀݊ሺ− ,ܽ−ܾሻ This leads to the NegaMax algorithm, which simply negates the value returned from the recursive call to NegaMax. In the case of a game in which players strictly make alternate moves this produces the exact same result as Minimax. This simplifies the algorithm as it removes the need for separate MinMove and MaxMove functions. This algorithm also introduces the concept of a depth variable. This allows the calling function to control the depth of the search in the game tree. When NegaMax is called it will be passed a positive integer, when NegaMax is called again, the depth is lowered by 1. When the depth value reaches 0 an evaluation of the game state is made and returned. This is the version of the algorithm that will be adapted for use in this project. Figure 4 - 'NegaMax' algorithm pseudocode
6
There are further optimisations that can be made to the Minimax algorithm. Two of these will be disĐussed later iŶ the ͚ iŵpleŵeŶtatioŶ͛ seĐtioŶ.
Monte Carlo Tree Search is a heuristic search algorithm for decision processes, most notably employed in game playing software. Monte Carlo Tree Search has been used in the famous ͚AlphaGo͛ prograŵ for plaLJiŶg the ďoard gaŵe Go (8), other board games like Chess and Shogi (9) and in turn based strategy games such as Total War: Rome II (10).
The Monte Carlo Method is a method which dates back to the 1940s that uses randomness to help solve difficult deterministic problems. The method relies on repeatedly using random sampling to find approximate results in problem spaces; as such, the accuracy often increases with increased numbers of samples. (11)
In 1987, Bruce Abramson modified the Minimax search algorithm to use an expected outcome model based on random game playouts – a Monte Carlo method – instead of the usual static evaluation function. (12) This method of searching was developed further to include recursive rolling out and backtracking and later introduced the Upper Confidence Bound (UCB) heuristic for constructing trees. (13) In 2006, Rémi Coulom coined the term Monte Carlo Tree Search (MCTS) when he applied Monte Carlo search to game trees. (14)
The principle of operation of MCTS is to analyse the best moves that are available to the player. A state tree is constructed with nodes corresponding to potential moves that can be made. These moves are discovered by the selection process and analysed by random playout. The selection of moves is made using the UCB formula for exploitation and exploration. The formula for calculating UCB for each individual move is;
𩀀𥠀 𦰀𥠀 ܿ+ √
ln 𠐀𥠀 𦰀𥠀 where;
This calculates a value for UCB with two parameters. The first parameter is the exploitation parameter, which is simply a ratio of how many winning states have been discovered after this node and how many times this node has been visited. The second parameter is the exploration parameter, which factors in how many times this node has been visited in total compared to its parent node. The exploration parameter is scaled by c, which allows the algorithm to be tuned to explore more or explore less depending on the use case. (15)
One iteration of the MCTS algorithm includes four steps;
8
request. When a player takes a turn in dots and boxes it will not modify the game directly, it will request to make a move and the game will either make the move if it can and modify itself or reject the move if it is illegal. Inheritance in OOP is the ability to define new classes of objects based on other classes of objects. When one object inherits from another, it takes all of the data and code from the parent object and can then expand on it. This leads to hierarchies of objects going froŵ ͚ geŶeral͛ at the top of the hierarĐhLJ to ͚ speĐifiĐ͛ at the ďottoŵ. IŶ the Đase of th is projeĐt, a ͚ geŶeral͛ oďjeĐt will be an abstract ͚plaLJer͛ oďjeĐt. This will represent any type of player and will define the interface that the game and GUI can have ǁith a plaLJer oďjeĐt. More speĐifiĐ oďjeĐts that iŶherit froŵ ͚ plaLJer͛ will be ͚Minimax PlaLJer͛ aŶd ͚ Monte Carlo PlaLJer͛. This leads oŶ to polLJŵorphisŵ. Polymorphism is a property that objects can have that means one part of a program does not need to know what it is interacting with, simply how to interact with it. This means that the program can be interacting with any type of player, it does not know which, and it will still be able to interact with it effectively. In the case of this program, each player can be asked to produce a move to be made in the game and the methods to decide which move is selected can be vastly different from one another, yet the game does not need to know how this move is produced.
AŶother iŵportaŶt ĐoŶĐept used is the ͚ faĐtorLJ patterŶ͛. Th is ŵethod siŵplifies the ĐreatioŶ of objects and promotes polymorphism. To use this creation pattern, an interface must be defined that a part of the program knows how to interact with. This interface will be common to all of the objects created by the factory. The factory can then provide concrete objects for the program, without the program knowing the specific implementation of the object or how to create the object itself. (18) In this project a factory pattern will be used to create different types of player. When instantiating the game and the players, the controlling code will not know how to create each different type of player. The controlling code will be provided with a factory which knows how to create players and the controlling code can then ͚ask͛ the faĐtorLJ for a tLJpe of plaLJer. WheŶ asked, the faĐ torLJ ǁill Đreate the player and return it to the program under a common player interface. This will reduce program complexity and code duplication, as the code for creating specific player types is only in one place, in the factory. The code will not need to be duplicated in every place that players need to be created.
9
Implementation The general structure of the program is described in this UML class diagram:
Figure 6 - UML Class Diagram for Dots and Boxes
This diagram describes the structure and interactions between each class in the program. The basic operation of the program is as follows:
11
box – are at the same index but are in the next array. This led to the structure in figure 7. The red horizontal lines are indexed first left to right and then top to bottom. The green vertical lines are indexed top to bottom and then left to right. These are placed in a three-dimensional array, with the first index representing the horizontal or vertical collections of lines.
It was decided to represent the boxes using a simple two-dimensional array starting from the top left. This means that when accessing the boxes it is easy to find the lines that the box is dependent on. The line to the top of any box (i, j) will be at index (0, i, j), the bottom at (0, i+1, j), the left at (1, j, i) and the right at (1, j+1, i).
To play the game the players must make moves and these moves equate to the lines in the game. This means making a move is the same as choosing a line. The simple solution to making moves was to simply send the index of the line to play to the game. This means moves are made by sending tuples to the game in the form (o, i, j). When the game receives a move it first checks if the move is legal. If it is a legal move then the line that has been selected ǁill haǀe its ͚ oǁŶer͛ propertLJ set to the Ŷuŵďer of t he plaLJer takiŶg the move. After this, the game will check the boxes associated with this line to see if they have been fully enclosed by lines. This is done by looking at the index of the move and calling the check_completed method of the one or two boxes that are connected to this line. As each Box object stores a reference to the four lines it is comprised of it can check all four of them to see if they have all been claimed. If no box has been completed this turn then the internal player counter will change to the next player. If a box has been completed then the rules state that the same player gets another turn, so the internal player counter will not increment. This process of making moves, checking boxes and incrementing the player counter encompasses all of the rules of the game. Players can make moves if they are legal, the boxes are claimed as points for each player, and players can take turns in the order they should.
The process of checking if a submitted move is legal or not is simple; the game has an internal list of all of the possible legal moves that can be made and if a move is in this list, it is legal. This list of legal moves is generated at the start of the game when the grid is created. When moves are successfully made they are removed from the list. This method of saving all of the legal moves at the start of the game and then removing them from the list as they are made is a time saving effort. If it were necessary to check all of the moves to see if the current move is legal every time then the entire grid of lines would need to be checked every turn.
To make the representation of the game as lightweight as possible, the game itself does not have anything to do with the display of the game or the GUI. This initially made development difficult as the GUI was created after the game was finished. To aid development and debugging the game includes a method print_grid, which prints a simple ascii representation of the game grid. This can be seen in Figure 9, where the first grid is an empty starting grid and the second grid has had 4 moves made, (0, 0, 0), (0, 1, 0), (1, 0, 0) and (1, 1, 0). These moves claim the top-left box in index (0, 0) for player two.
As the game was being developed for complex computer players to play, it required a method of returning a deep copy of itself. This is a copy of the game in exactly the same state, but completely separate from the original so that modifying the copy does not affect the original. As this method may be called many times whilst a computer player is calculating their move,
Figure 8 - Example of game print_grid method
12
this method needed to be as fast as possible. For this reason a game can be constructed initially with only a height and a width input and can also be constructed using a number of input parameters. When a copy is made it will send the current player value, list of legal moves and the arrays of lines and boxes to the copy. The copy will then construct itself using a different constructor method that copies the owner values of the lines and boxes, rather than using the same arrays.
GUI The GUI was developed after the game had already been implemented. This means the GUI could be made to be dependent on the game whilst the game is not dependent on the GUI at all. The GUI consists of two main components; the Start Frame and the Game Frame. The Start Frame is the first window that comes up when the game is launched and allows the user to pick all of the options that are available for the game.
The specific inputs have been chosen so as to eliminate the possibility of a user entering bad data. The inputs that control grid size are integer only and can only be between 3 and 10. The player choice inputs are dropdowns that are populated by stored values in the player factory. When selecting an advanced computer player – either minimax or monte carlo – inputs appear to change the parameters for these specific types of player. There are also colour pickers which are completely cosmetic choices that simply make the game feel nicer, and a variant radio box group, which can switch between the different variants of the game.
Figure 9 - Start Frame GUI
14
Player System The player system is based on the hierarchy of players that can be seen in figure 6. Every type of player inherits from the generic class PlayerBase, meaning they can share a common interface. The HumanPlayer class is an empty implementation, with the only difference being that its ͚isHuman͛ method returns True. The ComputerPlayer class acts as a parent class for all of the computer players, which return False from their isHuman method.
The code for the Player Factory – shown in Figure 13 – mostly consists of a simple if-elif-else statement that can switch between the different string representations of each player. If the ͚plaLJerTLJpe͛ ǀariaďle passed iŶto ŵakePlaLJer is Ŷot iŶ the iŶterŶal list of plaLJers the faĐtorLJ siŵplLJ returns a default Human Player. This prevents the program from crashing if the factory receives a bad input. The factory can construct each different type of player along with the parameters they require and returns this from the makePlayer method. Because of this, any type of player can be made while only requiring the string name and an index. The factory can fill in any missing parameters if they are needed. As the factory also holds the list of player types hard coded, the dropdown selection boxes in the StartFrame GUI can be populated directly with these. This allows new player types to be added and removed only by updating the factory, without needing to change the GUI.
Figure 13 - Code for Player Factory
Players There are 5 player types in the game. These are Human, Random, In-order, Minimax and Monte Carlo. The Human player class is an empty class. It needs no implementation as the GUI simply lets the human click the button they want. The Random player class is a basic computer player. When its chooseMove method is called and it is passed a copy of the game, it uses PLJthoŶ͛s built-in random module to return a random choice from the list of legal moves.
15
The In-order player is also a basic computer player. It simply returns a move from the list of legal moves, from a predetermined index. This is the most basic strategy but can be modified by changing the order in which moves are returned. The Random and In-order players serve as basic first steps in creating the more advanced players, and also serve as benchmarks for testing and comparing the more advanced players.
The Minimax player was made by learning from and modifying an implementation demonstrated in a lecture series for an Artificial Intelligence module. The original implementation that was used to teach was for the game Pacman, written in Java. (19)
This player was a basic Minimax player, consisting of chooseMove, MinMove, MaxMove and Evaluation methods. However, it was quickly understood that this approach would not work for Dots and Boxes due to the irregular turn order that the rules create. Figure ϯ shoǁs aŶ ͚ ordiŶarLJ͛ MiŶiŵ ax game tree, in which the players take alternate turns. The game tree for a particular game of Dots and Boxes however looks more like Figure 14. Rather than having strict alternating turns, some moves are capturing moves. These moves, marked with an asterisk in the diagram, are moves where the player captures a square, meaning the capturing player gets another turn. This makes the minimax implementation more complex as the same depth of game tree can contain moves from either player.
This problem of inconsistent turn order was solved by using and adapting the NegaMax algorithm shown in Figure 4. The NegaMax algorithm uses one recursive method to explore the game tree, rather than the two methods used in the basic Minimax algorithm. The NegaMax algorithm will simply negate the value returned from its recursive calls, causing the Min and Max steps to alternate. The solution used in the Dots and Boxes implementation takes this and introduces a conditional step in order to determine whether or not the returned value should be minimised or
Figure 14 - Minimax state tree for Dots and Boxes