Implementing a Chess Coach

Total Page:16

File Type:pdf, Size:1020Kb

Implementing a Chess Coach Implementing a Chess Coach registration: 4861469 (Supervisor: Dr Barry Theobald) Abstract The core component of every chess engine is it’s AI (Artificial Intelligence). AI has been an area of constant interest and research since the dawn of modern computing, holding interest for a number of important fields including not only computing but also, among others, philosophy, psychology and neurology. In this project, a chess program capable of fielding a game between two players was designed and implemented. Prominent methods of achieving both this and a chess engine capable of providing a challenging game experience to a player were discussed, and the methods used in this instance were justified. The program underwent user testing to ascertain it’s performance, and the results were discussed. Acknowledgements I would like to extend my sincere thanks to my supervisor, Dr Barry J. Theobald, for providing me with invaluable guidance and support throughout this challenging project. I would also like to express my gratitude to all of the users that provided me with helpful and constructive feedback. CMPC3P2Y Contents Contents 1 Introduction 8 1.1 Background and History of Computer Chess Engines . .8 1.2 Aims . 10 2 Representing a Chess Board 11 2.1 Arrays . 11 2.2 Bitboards . 11 3 Tree Search Algorithms 14 3.1 Best-First Search . 14 3.2 Breadth-First Search . 16 3.3 Depth-First Search . 16 3.4 Machine Learning Approaches . 20 4 Evaluating a Chessboard 21 4.1 Heuristics . 21 4.2 Piece-Square Tables . 21 5 Weaknesses of Current Generation Chess Engines 23 6 Design and Implementation 24 6.1 Program Structure . 25 6.2 Board Representation . 27 6.3 Artificial Intelligence . 33 7 Testing 37 7.1 Framework . 37 7.2 Profiling . 38 7.3 Summary of Test Results . 38 Reg: 4861469 3 CMPC3P2Y Contents 8 Conclusions and Future Work 41 8.1 Future Work . 41 Reg: 4861469 4 CMPC3P2Y List of Figures List of Figures 1.1 Estimated likelyhood of winning a game of chess based on the differ- ence in Elo rank between the two players. Given a difference of approx- imately 450 Elo between top humans and top computers, this shows that a top human player would have only approximately a 5% chance of defeating a top computer. Sourced from (Moser, 2010). .9 2.1 An example bitboard representing white pawns at the start of a chess game, formatted into the shape of a chessboard for ease of understand- ing. Each ‘1’ represents represents a white pawn. 12 2.2 An illustration of the process of determining whether any of the posi- tions a white knight can attack contain a black piece. 12 2.3 An example attack bitboard representing the possible lines of attack for a knight on square C3. ‘x’ represents the knight’s position and ‘1’ rep- resents a square that can be attacked by the knight. 13 3.1 A demonstration of the order of node expansion when traversing a tree structure using breadth-first search. 16 3.2 A demonstration of the order of node expansion when traversing a tree structure using depth-first search. 17 3.3 An example minimax tree, searching 4 ply deep. The nodes highlighted in grey demonstrate the path through the tree that the algorithm will determine to be the best available move after completion. 19 3.4 An example alpha-beta tree, searching 5 ply deep and building upon the minimax algorithm by eliminating subtrees that cannot provide a better score than another subtree that has already been evaluated. The eliminated subtrees are highlighted in grey. 20 4.1 Example piece-square tables for white pawns, left, and white knights, right. 22 6.1 Illustration of the cycle of the model-view-controller design pattern. This approach is used to help make large and complex programs modu- lar and maintainable. 24 6.2 The hex values used to initialise the board at the start of a game. 27 Reg: 4861469 5 CMPC3P2Y List of Figures 6.3 Flowchart demonstrating the process of a human white player attempt- ing to make a move. 28 6.4 Flowchart demonstrating the validation process that is applied to any attempted move with a pawn. 29 6.5 An illustration of the process of determining whether the position under test contains a white pawn. 30 6.6 Demonstration of the use of the text-based input/output system used for early testing purposes. A text file showing the numerical values of each board position was implemented to aid usability. 31 6.7 Demonstration of the capabilities of the final GUI implementation. Se- lected friendly squares are highlighted green, unoccupied attackable squares are highlighted in light blue, and attackable squares occupied by opposing pieces are highlighted in red. Chessboard texture sourced from http://assets.freeprintable.com/images/item/original/ blank-chess-board.gif, chesspiece textures sourced from http: //www.wpclipart.com/recreation/games/chess/chess_set_ symbols.jpg............................... 32 6.8 Illustration of the recursive minimax search function traversing the game tree to determine the best possible move. 34 7.1 Results from profiling the memory usage of the program. The greatest source of memory usage is shown to be the allocation of Chessboard objects. This result is unexpected, as Chessboard objects individually use very little memory and should not be created in substantial enough numbers to use the indicated amount of memory. 39 7.2 Results from profiling the CPU usage of the program. The greatest source of CPU usage is shown to be Thread.sleep(), which is not used while other operations are ongoing. All logic-heavy operations, such as move validation, use very little CPU-time, and so can be con- sidered efficient. 40 Reg: 4861469 6 CMPC3P2Y List of Tables List of Tables 6.1 Classes associated with the program’s framework . 26 Reg: 4861469 7 CMPC3P2Y 1 Introduction 1 Introduction 1.1 Background and History of Computer Chess Engines The development of computer chess engines first began as an effort to improve AI tech- niques, led by the belief that the only way for a chess engine to attain any noteworthy level of ‘skill’ would be to strengthen the AI driving the engine. Many of the people involved believed that the successful creation of such an AI would irrefutably prove that human thinking can be artificially modelled, since chess was and still is widely regarded as the ultimate game of wits and cunning (Hsu et al., 1990). The original belief that only improved AI could sufficiently strengthen a chess engine for it to be a formidable opponent has proven false over the years, with the main point of progress being the constant and significant increase in the raw speed of the hardware running chess engines. The most notable example of this is Deep Blue, the computer purpose-built by IBM for playing chess that in 1997 famously defeated the then world chess champion Garry Kasparov. The computer was capable of evaluating 200 million positions per second and regularly searched over 20 ply deep, a feat impossible for any human player (Campbell et al., 2002). This degree of brute force easily compensated for it’s inferior tactical and strategic abilities, resulting in the first ever instance of a computer defeating a chess world champion. Contrast this computational power to the first fully-fledged chess computer, written by Alex Bernstein in 1957, which took 3 hours to search 4 ply deep. A second area in which chess programs have grown significantly more advanced over time is in the optimisation of their search algorithms. As hardware has grown faster, search algorithms have become less dependent upon hardware speed. In the last 10 years, chess programs have become increasingly viable on affordable, commercially available hardware. Modern mobile devices are now capable of playing chess well enough to easily overcome casual players, and where once supercomputers were re- quired to defeat grandmaster chess players, it is likely to eventually become the case that even mobile devices are capable of defeating them. In 1988, Kasparov was asked if he thought a computer would be able to defeat a chess grandmaster before the year 2000, to which he confidently replied ‘No way’ (Hsu et al., Reg: 4861469 8 CMPC3P2Y 1 Introduction 1990). It is testament to the astonishingly rapid progress of computer chess engines that an expert in the field like Kasparov could be proven so dramatically wrong, with grand- master Bent Larsen losing to Deep Thought just 10 months later (Simon and Schaeffer, 1990). Chess is a game of perfect information, a state in game theory where players ob- serve all previous moves, and can therefore determine all possible future game-states (Von Neumann and Morgenstern, 2007). The possession of perfect information allows the development of optimal strategies. However, there are far too many possible game- states in chess to compute a solution in a reasonable amount of time, if at all. The most powerful modern chess engines are all but untouchable to even the strongest human players. The required Elo (a ranking system used to measure the relative strengths of players in two-player games (Elo, 1978)) rating to qualify as a grandmaster is 2400, with the highest ever human Elo rating being 2851, belonging to Kasparov. Comparing this to the rating of the current strongest computer chess engine in the world, RYBKA 4, which has an unconfirmed but estimated 3300 Elo, the difference in playing strength between top humans and top computers becomes apparent. This fact is illustrated in Figure 1.1. Figure 1.1: Estimated likelyhood of winning a game of chess based on the difference in Elo rank between the two players.
Recommended publications
  • New Architectures in Computer Chess Ii New Architectures in Computer Chess
    New Architectures in Computer Chess ii New Architectures in Computer Chess PROEFSCHRIFT ter verkrijging van de graad van doctor aan de Universiteit van Tilburg, op gezag van de rector magnificus, prof. dr. Ph. Eijlander, in het openbaar te verdedigen ten overstaan van een door het college voor promoties aangewezen commissie in de aula van de Universiteit op woensdag 17 juni 2009 om 10.15 uur door Fritz Max Heinrich Reul geboren op 30 september 1977 te Hanau, Duitsland Promotor: Prof. dr. H.J.vandenHerik Copromotor: Dr. ir. J.W.H.M. Uiterwijk Promotiecommissie: Prof. dr. A.P.J. van den Bosch Prof. dr. A. de Bruin Prof. dr. H.C. Bunt Prof. dr. A.J. van Zanten Dr. U. Lorenz Dr. A. Plaat Dissertation Series No. 2009-16 The research reported in this thesis has been carried out under the auspices of SIKS, the Dutch Research School for Information and Knowledge Systems. ISBN 9789490122249 Printed by Gildeprint © 2009 Fritz M.H. Reul All rights reserved. No part of this publication may be reproduced, stored in a retrieval system, or transmitted, in any form or by any means, electronically, mechanically, photocopying, recording or otherwise, without prior permission of the author. Preface About five years ago I completed my diploma project about computer chess at the University of Applied Sciences in Friedberg, Germany. Immediately after- wards I continued in 2004 with the R&D of my computer-chess engine Loop. In 2005 I started my Ph.D. project ”New Architectures in Computer Chess” at the Maastricht University. In the first year of my R&D I concentrated on the redesign of a computer-chess architecture for 32-bit computer environments.
    [Show full text]
  • COMP30191 the Theory of Games and Game Models
    COMP30191 The Theory of Games and Game Models Andrea Schalk [email protected] School of Computer Science University of Manchester August 7, 2008 About this course This is an introduction into the theory of games and the use of games to model a variety of situations. While it is directed at third year computer science students it is also suitable for students of mathematics, and possibly of physics. It contains some proofs but does not require advanced knowledge of mathematics. The course goes beyond what is classically understood as game theory (the basics of which are covered in Sections 1 and 2) by making connections with computer programs for games such as Chess, and using games to model scenarios in sociology or biology. This course has been taught in the past as CS3191 and CS3192. What this course is about Games have been used with great success to describe a variety of situations where one or more entities referred to as players interact with each other according to various rules. Because the concept is so broad, it is very flexible and that is the reason why applications range from the social sciences and economics to biology and mathematics or computer science (games correspond to proofs in logic, to statements regarding the `fairness' of concurrent systems, they are used to give a semantics for programs and to establish the bisimulation property for processes). As such the theory of games has proved to be particularly fruitful for areas which are notoriously inaccessible to other methods of mathematical analysis. There is no set of equations which describes the goings-on of the stock-market (or if there is, it's far too complicated to be easily discoverable).
    [Show full text]
  • Exploring Modern Chess Engine Architectures
    Vrije Universiteit Amsterdam Bachelor Thesis Exploring modern chess engine architectures Author: Pieter Bijl (2647306) Author: Anh Phi Tiet (2638026) 1st supervisor: Prof. Dr. W.J. Fokkink 2nd reader: Prof. Dr. ir. H.E. Bal A thesis submitted in fulfillment of the requirements for the VU Bachelor of Science degree in Computer Science July 5, 2021 CONTENTS I Introduction 3 II Basics of chess engine architecture 3 II-A Board representation . .3 II-B Move generation . .6 II-C Search . .9 II-D Evaluation . 12 III Methodology 17 IV Results 18 IV-A Results . 18 IV-B Result analysis . 19 V Conclusion 20 VI Discussion 20 References 23 Appendix 23 2 Abstract—The game of chess is over 1000 years old and is move generator is often the limiting factor, and in a regular still not optimally played in the 21st century. This thesis aims to alpha beta style search. The first research question here is explore the technical history of chess computing over the last 40 as follows: Which approach to board representation is the years. Various techniques that have been employed throughout that time are implemented and tested to determine their perfor- fastest for move generation, which suits a full general purpose mance differences. Similarly, classical evaluation functions that chess engine, and in which subroutines of the engine is the attempt to score a position based on handcrafted, human-like choice of board representation most critical? We hypothesize chess features are broken down and their parameters tuned. that magic and PEXT bitboards will beat the others in both In conclusion, implementations of both array centric board scenarios, where PEXT bitboards perform slightly better.
    [Show full text]
  • A Complete Chess Engine Parallelized Using Lazy SMP
    A Complete Chess Engine Parallelized Using Lazy SMP Emil Fredrik Østensen Thesis submitted for the degree of Master in programming and networks 60 credits Department of informatics Faculty of mathematics and natural sciences UNIVERSITY OF OSLO Autumn 2016 A Complete Chess Engine Parallelized Using Lazy SMP Emil Fredrik Østensen © 2016 Emil Fredrik Østensen A Complete Chess Engine Parallelized Using Lazy SMP http://www.duo.uio.no/ Printed: Reprosentralen, University of Oslo Abstract The aim of the thesis was to build a complete chess engine and parallelize it using the lazy SMP algorithm. The chess engine implemented in the thesis ended up with an estimated ELO rating of 2238. The lazy SMP algorithm was successfully implemented, doubling the engines search speed using 4 threads on a multicore processor. Another aim of this thesis was to act as a starting compendium for aspiring chess programmers. In chapter 2 Components of a Chess Engine many of the techniques and algorithms used in modern chess engines are discussed and presented in a digestible way, in a try to make the topics understandable. The information there is presented in chronological order in relation to how a chess engine can be programmed. i ii Contents 1 Introduction 1 1.1 The History of Chess Computers . .2 1.1.1 The Beginning of Chess Playing Machines . .2 1.1.2 The Age of Computers . .3 1.1.3 The First Chess Computer . .5 1.1.4 The Interest in Chess Computers Grow . .6 1.1.5 Man versus Machine . .6 1.1.6 Shannon’s Type A versus Shannon’s Type B Chess Computers .
    [Show full text]
  • The Design and Implementation of an Adaptive Chess Game
    California State University, San Bernardino CSUSB ScholarWorks Electronic Theses, Projects, and Dissertations Office of aduateGr Studies 9-2015 THE DESIGN AND IMPLEMENTATION OF AN ADAPTIVE CHESS GAME Mehdi Peiravi mehdi peiravi Follow this and additional works at: https://scholarworks.lib.csusb.edu/etd Part of the Robotics Commons Recommended Citation Peiravi, Mehdi, "THE DESIGN AND IMPLEMENTATION OF AN ADAPTIVE CHESS GAME" (2015). Electronic Theses, Projects, and Dissertations. 228. https://scholarworks.lib.csusb.edu/etd/228 This Project is brought to you for free and open access by the Office of aduateGr Studies at CSUSB ScholarWorks. It has been accepted for inclusion in Electronic Theses, Projects, and Dissertations by an authorized administrator of CSUSB ScholarWorks. For more information, please contact [email protected]. THE DESIGN AND IMPLEMENTATION OF AN ADAPTIVE CHESS GAME A Project Presented to the Faculty of California State University, San Bernardino In Partial Fulfillment of the Requirements for the Degree Master of Science in Computer Science by Mehdi Peiravi September 2015 THE DESIGN AND IMPLEMENTATION OF AN ADAPTIVE CHESS GAME A Project Presented to the Faculty of California State University, San Bernardino by Mehdi Peiravi September 2015 Approved by: Haiyan Qiao, Committee Chair, Computer Science Kerstin Voigt, Committee Member Ernesto Gomez, Committee Member © 2015 Mehdi Peiravi ABSTRACT In recent years, computer games have become a common form of entertainment. Fast advancement in computer technology and internet speed have helped entertainment software developers to create graphical games that keep a variety of players’ interest. The emergence of artificial intelligence systems has evolved computer gaming technology in new and profound ways.
    [Show full text]
  • FPGA Multiprocessor for Game Tree Searches Thesis to Obtain The
    FPGA Multiprocessor for Game Tree Searches António Pedro Santos Coelho Thesis to obtain the Master of Science Degree in Electrical and Computer Engineering Supervisor: Prof. Horácio Cláudio de Campos Neto Examination Committee Chairperson: Prof. Nuno Cavaco Gomes Horta Supervisor: Prof. Horácio Cláudio de Campos Neto Members of the Committee: Prof. João Paulo Baptista de Carvalho May 2016 In the past Grandmasters came to our computer tournaments to laugh. Today they come to watch. Soon they will come to learn. Monty Newborn, computer chess tournament organizer, 1977 Acknowledgements I want to thank my supervisor Prof. Horácio Neto for his help and guiding me in the correct direction. I also want to thank my colleges and family for the massive support they have given me for so long. i Abstract This thesis explores the development of a hardware/software system that implements an algorithm for game tree searches, applied to the game of Chess. The system architecture consists of a general purpose processor that executes the software part, and by a dedicated hardware unit that implements a move generator for the game of Chess. Move generation speed is a crucial part of a game tree search algorithm. The faster the move generator, the more tree nodes can be visited per time unit, thus finding more information to help choose the next move. Even though the hardware move generator proved itself to be much faster than the software move generator in the Faile chess engine, the system has a bottleneck in making the moves available to the game engine, so future work is needed to extract the full potential from the designed hardware.
    [Show full text]
  • Data Structures
    Data structures PDF generated using the open source mwlib toolkit. See http://code.pediapress.com/ for more information. PDF generated at: Thu, 17 Nov 2011 20:55:22 UTC Contents Articles Introduction 1 Data structure 1 Linked data structure 3 Succinct data structure 5 Implicit data structure 7 Compressed data structure 8 Search data structure 9 Persistent data structure 11 Concurrent data structure 15 Abstract data types 18 Abstract data type 18 List 26 Stack 29 Queue 57 Deque 60 Priority queue 63 Map 67 Bidirectional map 70 Multimap 71 Set 72 Tree 76 Arrays 79 Array data structure 79 Row-major order 84 Dope vector 86 Iliffe vector 87 Dynamic array 88 Hashed array tree 91 Gap buffer 92 Circular buffer 94 Sparse array 109 Bit array 110 Bitboard 115 Parallel array 119 Lookup table 121 Lists 127 Linked list 127 XOR linked list 143 Unrolled linked list 145 VList 147 Skip list 149 Self-organizing list 154 Binary trees 158 Binary tree 158 Binary search tree 166 Self-balancing binary search tree 176 Tree rotation 178 Weight-balanced tree 181 Threaded binary tree 182 AVL tree 188 Red-black tree 192 AA tree 207 Scapegoat tree 212 Splay tree 216 T-tree 230 Rope 233 Top Trees 238 Tango Trees 242 van Emde Boas tree 264 Cartesian tree 268 Treap 273 B-trees 276 B-tree 276 B+ tree 287 Dancing tree 291 2-3 tree 292 2-3-4 tree 293 Queaps 295 Fusion tree 299 Bx-tree 299 Heaps 303 Heap 303 Binary heap 305 Binomial heap 311 Fibonacci heap 316 2-3 heap 321 Pairing heap 321 Beap 324 Leftist tree 325 Skew heap 328 Soft heap 331 d-ary heap 333 Tries 335 Trie
    [Show full text]
  • CS3191 Section 4 Large Games
    CS3191 Section 4 Large Games Andrea Schalk Department of Computer Science, University of Manchester Andrea Schalk: CS3191 Section 4 – p. 1/44 These games have very large game trees—typically far too large to be held in memory entirely, and certainly too large to try to find all strategies. In fact, even the methods in the previous section will not work on such games—the game trees are so large that carrying out alpha-beta search would take far too long to return a value and thus a good move. There are three problems which have to be solved to write such a program which we will discuss in some detail. Finally we will have a look at how Chess-playing programs developed, since Chess is the game for which the most effort has been made when it comes to writing programs. Large games Section 4 covers how computer programs for games such as Chess, Go, Othello, Checkers and similar games work. Andrea Schalk: CS3191 Section 4 – p. 2/44 In fact, even the methods in the previous section will not work on such games—the game trees are so large that carrying out alpha-beta search would take far too long to return a value and thus a good move. There are three problems which have to be solved to write such a program which we will discuss in some detail. Finally we will have a look at how Chess-playing programs developed, since Chess is the game for which the most effort has been made when it comes to writing programs.
    [Show full text]
  • Anatomia De Um Motor De Xadrez
    Instito de Matemática e Estatística Universidade de São Paulo Anatomia de um Motor de Xadrez Autor: Supervisor: Hugo Vinicius Mori Dantas Santana José Coelho de Pina 01 de Dezembro de 2014 Sumário Sumário 1 1 Introdução 2 2 História 3 3 Anatomia 4 4 Comunicação 6 5 Representação do tabuleiro8 6 Busca 17 7 Avaliação 28 8 Pulse 35 9 Disciplinas relacionadas 45 10 Comentários finais 46 1 Capítulo 1 Introdução O xadrez é um jogo de tabuleiro de natureza recreativa e competitiva para dois jogadores. Este jogo é um dos mais populares do mundo e é praticado em diversos lugares como escolas, clubes, torneios ou pela internet [39]. Desde a invenção do xadrez, os enxadristas tentam buscar a melhor estratégia e tática para vencer uma partida. Muitos pesquisadores desenvolveram teorias ou máquinas para este jogo durante muitos anos [28]. Nas décadas de 1940 e 1950, houve um súbito avanço na pesquisa sobre xadrez. Isto foi possível graças à invenção do computador. Um grande número de enxadristas, percebendo o poder do computador, iniciaram o seu trabalho relacionado ao motor de xadrez (chess engine)[28]. O primeiro torneio de xadrez foi realizado em Londres, 1851. Em especial, o primeiro torneio de mo- tores de xadrez ocorreu na cidade de Nova York, em 1970. Desde então, estas competições são realizadas regularmente. O objetivo deste trabalho é apresentar as teorias relacionadas ao xadrez por computador e mostrar como poderiam ser implementadas estas estratégias num computador na forma de motor de xadrez e, finalmente, mostrar as relações deste assunto com as disciplinas oferecidas no curso de bacharelado em ciência da com- putação.
    [Show full text]