scieee AI-readable full text Open interactive document viewer

Methodologies and Tools for Creating Competitive Poker Playing Agents

Luís Filipe Guimarães Teófilo

Full text

Methodologies and Tools for Creating Competitive Poker Playing Agents Luís Filipe Guimarães Teófilo PROGRAMA DOUTORAL EM ENGENHARIA INFORMÁTICA Supervisor: Luís Paulo Gonçalves dos Reis (Ph.D.) Co-supervisor: Henrique Daniel de Avelar Lopes Cardoso (Ph.D.) 2016, January © Luís Filipe Guimarães Teófilo i Abstract Many researchers have devoted their time to develop software agents intended for strategic games. These agents obtained outstanding results in popular games such as Chess in which current agents cannot be consistently beaten by the best human players. However, for stochastic games with incomplete information there are still no optimal solutions, especially for games with large search spaces, where research is limited by current hardware. Poker is a game that is frequently used to measure progress in this domain, given its key features: simplicity; large number of decision points; hidden cards. Major scientific advances have already been achieved: agents are unbeatable in Head’s up Limit Poker. However, in more popular Poker variants, agents are still far from perfect. In this thesis Poker is approached in-depth by addressing all necessary aspects to create Poker software agents, both in scientific and engineering terms. First, new tools for creating and testing agents are shown, namely a tool for automatic online playing. Next, advances on abstraction techniques are shown, namely a new no-domain specific method. Finally, techniques to enhance game play and decision making are analysed and compared. This includes agent architectures based on expert knowledge and optimizations in the usage of the current state-of-the-art algorithm for game playing (Counterfactual Regret Minimization). All developed methodologies were validated on simulated games or real games. Simulations show great efficiency improvements on current techniques. In real games the developed agents achieved a good result on the AAAI Annual Computer Poker Competition (2nd place in the Kuhn track) and, for the first time reported, they were also profitable in real money multiplayer online matches, against human players. Keywords: Poker; Game Theory; Opponent Modelling; Simulation; Bot; General Game Playing; Game Description Languages. iii Resumo Muitos investigadores dedicam tempo a desenvolver agentes destinados a jogos estratégicos. Estes obtiveram excelentes resultados em jogos populares como Xadrez, tendo ultrapassando o desempenho de jogadores humanos. No entanto, nos jogos estocásticos de informação incompleta não existem soluções ideais, especialmente para jogos com grande espaço de pesquisa, devido a limitações de hardware. O póquer é atualmente o jogo mais popular para medir os avanços nesta área pois tem regras simples, elevado número de pontos de decisão e cartas escondidas. Avanços científicos relevantes foram alcançados onde, inclusivamente, foram criados agentes imbatíveis na variante Head’s up Limit. No entanto, em variantes mais populares, os agentes ainda não são perfeitos. Nesta tese são abordados todos os aspetos essenciais para a criação de agentes póquer, tanto em termos científicos como da engenharia da solução. Primeiro, foram criadas novas ferramentas para criar e testar agentes, com destaque para um programa que permite aos agentes jogarem online. De seguida, são abordadas técnicas de abstração, incluindo um novo método independente do domínio do jogo. Por fim, demonstram-se técnicas para melhorar a tomada de decisão, baseadas em arquiteturas de agentes com base no conhecimento de especialistas e otimizações no uso do algoritmo Counterfactual Regret Minimization, abordagem com melhores resultados teóricos nesta área atualmente. As metodologias desenvolvidas foram validadas via simulação e jogos reais. Nas simulações foi possível observar melhoramento da velocidade dos algoritmos. Nos testes em ambiente real, os agentes obtiveram bons resultados na competição do AAAI (2º lugar em Kuhn) e nos jogos online, demonstrando-se que um agente pode ser rentável a jogar contra humanos. Palavras-chave: Póquer; Teoria de Jogos; Modelação de Oponentes; Simulação; Agentes Automáticos; Jogos Genéricos; Linguagens de Descrição de Jogos. v Acknowledgments I would like to express my appreciation towards my supervisors: Luís Paulo Reis and Henrique Lopes Cardoso, for all the support over the last years: Luís gave me the opportunity to extend my previous Master Thesis work as a Ph.D., again under his supervision, and helped me to get funding for this project; Henrique always gave me the best advice and very good revisions on my work. I would like to thank to Professor Eugénio Oliveira for giving me good advice on scientific work and for helping me to get work resources (equipment, conferences). I also give my thanks to the students that finished their master theses under my supervision. The contribution of their work for this thesis was crucial. On a more personal note, I would like to thank to my beloved girlfriend Rita. She was very important to cheer me up in a difficult phase of my life, where I had to reconcile my job with the writing of this thesis and a house moving. Finally, and most importantly, I would like to thank to my family members, in particular to my parents and sister. They were and they will always be there for me. They have encouraged me in pursuing Ph.D. studies and they helped become who I am. They have also always supported me on the most difficult times of my life. This work was supported by the Portuguese Foundation for Science and Technology (FCT), under Doctoral Grant with reference SFRH/BD/71598/2010. Luís Filipe Guimarães Teófilo vii “Where there's a will there's a way” Samuel Smiles xiv Figure 22 – ACPC Poker Server – User interface. ........................................................... 69 Figure 23 – Open Meerkat Poker Test bed..................................................................... 70 Figure 24 – WinHoldEm graphical interface ................................................................... 72 Figure 25 – Poker Agents class model. ........................................................................... 78 Figure 26 – Communication between the Socket Agent and the External agent. ......... 79 Figure 27 – Poker Simulation System Architecture. ....................................................... 80 Figure 28 – Game moves database class model. ............................................................ 82 Figure 29 – Poker simulation module. ............................................................................ 84 Figure 30 - LIACC Poker Simulator .................................................................................. 85 Figure 31 –LIACC Poker Simulator 2D visualizer ............................................................. 85 Figure 32 – Evolutionary simulation module. ................................................................ 86 Figure 33 – PGDL Specification ....................................................................................... 95 Figure 34 – PDGL Builder System workflow. ................................................................ 100 Figure 35 – PGDL GUI Games Module .......................................................................... 108 Figure 36 – PGDL GUI Rounds Module ......................................................................... 108 Figure 37 – PGDL GUI Deck Module ............................................................................. 108 Figure 38 – Card position recognition – the chips occluded the third card ................. 112 Figure 39 – Detecting cards regions algorithm ............................................................ 112 Figure 40 – Cutting the card for recognition. ............................................................... 113 Figure 41 – Detecting the card template...................................................................... 114 Figure 42 – Detecting the dealer button position ........................................................ 116 Figure 43 – Chips representation in the casino interface software. ............................ 116 Figure 44 – Action representation in the casino interface software. .......................... 117 Figure 45 – Action and bet amounts detection. ........................................................... 117 Figure 46 – Average detection rate per scale factor .................................................... 118 Figure 47 – Bezier curve example between points A and B (degree = 2). ................... 119 Figure 48 – Computing the mouse movement trajectory from one point the other .. 120 Figure 49 – Poker Bot user interface ............................................................................ 122 Figure 50 – ARS tables lookup process and architecture. ............................................ 129 Figure 51 – Average rank strength VS E[HS] heat maps at River ................................. 131 Figure 52 – Reduced game utility abstraction .............................................................. 133 xv Figure 53 – Hand Strength relative distribution observed from the dataset in the Pre- Flop round. ................................................................................................................... 136 Figure 54 – Hand Strength relative distribution observed from the dataset in Post-Flop rounds. .......................................................................................................................... 136 Figure 55 – Betting distributions for Pre-Flop round. .................................................. 137 Figure 56 – Betting distributions for Post-Flop rounds. ............................................... 137 Figure 57 – CFR recursive implementation for generic Poker variants ........................ 141 Figure 58 – Kuhn Poker’s strategy into sparse arrays. ................................................. 144 Figure 59 – GetStrategy function (CFR implementation) is the function that updates the actual strategy probabilities taking into account the current accumulated regrets. .. 145 Figure 60 – Liner CFR algorithm ................................................................................... 146 Figure 61 – Building the CFR actions tree (C++) ........................................................... 149 Figure 62 – Eliminating search nodes based on actions dominance (C++) .................. 150 Figure 63 – Lucifer’s Architecture ................................................................................. 151 Figure 64 – Main parts of Lucifer’s source code (C++) ................................................. 154 Figure 65 – K-Current-Best-Utility strategy selection example for K=3 ....................... 155 Figure 66 – Hermes’s decision workflow. ..................................................................... 156 Figure 67 – Hermes’s architecture. .............................................................................. 156 Figure 68 – Hermes equity computation algorithm ..................................................... 159 Figure 69 – Hermes expected return algorithm. .......................................................... 160 Figure 70 – Hermes game playing algorithm................................................................ 161 Figure 71 – Hermes’s all time profit ............................................................................. 165 Figure 72 – Hermes’s stealing blinds results ................................................................ 169 Figure 73 – AAAI Computer Poker Competition 2014 – highest ranked teams in the Kuhn 3P track. ............................................................................................................... 174 xvii List of Tables Table 1 – Rock Paper Scissors represented in normal-form .......................................... 12 Table 2 – Examples of games and their respective classifications. ................................ 17 Table 3 – Poker Hand Ranks ........................................................................................... 21 Table 4 – The size (number of information sets) of simplified versions of Poker .......... 22 Table 5 – Summarized description of some notable Poker Agents ............................... 46 Table 6 - Tight Aggressive Players. ................................................................................. 62 Table 7 – Nit/Rock players. ............................................................................................. 62 Table 8 – Loose Aggressive Players. ............................................................................... 62 Table 9 – Manic/Aggro Donk players. ............................................................................ 63 Table 10 – Calling station player..................................................................................... 63 Table 11 – Short stacker player. ..................................................................................... 63 Table 12 – Loose passive player. .................................................................................... 63 Table 13 – Sklansky and Malmuth groups ...................................................................... 65 Table 14 – Hand Ranking Server Commands.................................................................. 81 Table 15 – Player statistical indicators. .......................................................................... 87 Table 16 – Simulator benchmark test results for 1.000 tries with 100.000 games and four players. .................................................................................................................... 88 Table 17 – Poker Simulators Comparison table. ............................................................ 88 Table 18 – Differences between Poker Variants ............................................................ 94 Table 19 – PGDL in-built agent's strategy..................................................................... 106 Table 20 – PGDL usability tests ..................................................................................... 109 Table 21 – Card detection rates ................................................................................... 115 Table 22 – Amount detection rates .............................................................................. 118 Table 23 – Identify mouse movement.......................................................................... 121 xviii Table 24 – Hand rank function benchmark .................................................................. 125 Table 25 – Hand rank comparison ................................................................................ 126 Table 26 – Sampling board cards in E[HS] algorithm ................................................... 127 Table 27 – Benchmarking Average Rank Strength ....................................................... 130 Table 28 – Reduced game utility abstraction tests in mili big blinds/h ........................ 134 Table 29 – PokerLang strategy inferring accuracy. ...................................................... 140 Table 30 – Recursive CFR vs Linear CFR (time in seconds) ........................................... 147 Table 31 – Recursive CFR vs Linear CFR (memory usage in MB) .................................. 147 Table 32 – Possible game state abstractions considered by Hermes ........................... 159 Table 33 – Starting cards classification for Hermes. 1 for top scored hands and 8 for low scored hands. Hands without classification in this table are considered unplayable thus Hermes folds immediately when holding such hands. ................................................. 160 Table 34 – Some statistics about the hand played by the Hermes agent. ................... 164 Table 35 – Hermes’s playing style statistics ................................................................. 168 Table 36 – Hermes’s defending and stealing blinds statistics ...................................... 169 Table 37 – Hermes’s against the 10 most profitable opponents ................................. 171 Table 38 – Hermes’s against the 10 less profitable opponents ................................... 171 Table 39 – Results from the top scored teams in the 2014 three player Kuhn poker AAAI competition. ........................................................................................................ 175 Table 40 – Played matches results in the 2014 three player Kuhn poker AAAI competition. ................................................................................................................. 175 Table 41 – Global compressed results by team from the top scored teams in the 2014 three player Kuhn poker AAAI competition. ................................................................ 176 xix Abbreviations and Acronyms AAAI – Association for the Advancement of Artificial Intelligence. ACPC – Annual Computer Poker Competition (organized in the AAAI conference). AI – Artificial Intelligence. CIG – Complete Information Games CFR – Counterfactual Regret Minimization. CPRG – Computer Poker Research Group (University Alberta, Canada). DEI – Informatics Engineering Department (FEUP). EGT – Evolutionary game theory (EGT) FAI – Fake Artificial Intelligence FCT – Foundation for Science and Technology FEUP – Faculty of Engineering, University of Porto GDL – Game Description Language IIG – Incomplete Information Games IRC – Internet Relay Chat LIACC – Artificial Intelligence and Computer Science Laboratory NE – Nash-Equilibrium UP – University of Porto xx 1 Chapter 1 Introduction This chapter provides an overview of this thesis and all the developed work that led to its writing. First, the context and motivation of the work are presented in order to justify it. To further emphasize the work’s motivation, the main scientific challenges of this kind of work are also listed. Next, the main objectives and contributions of this thesis are described. The chapter is finalized by outlining the structure of this thesis. 1.1 Context Artificial intelligence (AI) research is a field of study aimed at developing pieces of software and/or hardware that can replace or assist human beings in performing tasks that require intelligence i.e. tasks that are not methodical and that require expert knowledge about on how to deal with unforeseen events. This is contrary to common machines (such as appliances 1 ) or software (such as Notepad) whose aim is the systematic fulfilment of tasks that are composed by sets of instructions. Software applications or machines with intelligence also have the capacity to make decisions and control other systematic systems. In the beginning, the main goal of AI research was to create a Strong AI: an intelligence that imitates brain functions or human behaviour, with the goal of creating intellects that match or exceed humans’ one – towards a technological singularity 2 [1]. As years and research went by it was verified that such project was impracticable at 1 Some modern appliances can perform intelligent tasks such as heat controlling. 2 A time when machines are so smart that they are able to create smarter versions of themselves. Chapter 1 – Introduction 2 the time, so AI researchers focused on solving particular problems, with that being known as weak AI. However this paradigm might change in a recent future, as the capacity of CPUs progresses at geometric rate [2]. Projects, such as the Blue Brain 3 – which is an attempt to replicate a synthetic brain by reverse-engineering the mammalian brain down to the molecular level [3] – clearly support the research on strong AIs. However, weak AI research has achieved far greater results than strong AI research. One of the most explored fields within weak AI research is the development of game playing software agents 4 – autonomous software entities that perform intelligent tasks without human intervention. It is important to differentiate game playing agents from some types of “intelligent” game strategies. In most games with AIs, the software responsible for playing as the computer has access to more information than the human, can control human avatars or control the seeds of the supposedly random events – this AIs are known as Fake AIs (FAIs). Good examples of FAIs can be found in several Texas Hold’em videogames – the FAIs know which cards their human opponents have and they shuffle the cards in a controlled manner to benefit themselves, especially in harder difficulties. This thesis focuses on weak AI for games, but only on game playing agents rather than fake AIs, since despite the great utility of fake AIs, they do not pose any challenge to science and thus not allowing the achievement of this research’s goal – the primary goal of researching games is to transport the acquired knowledge to solve other, potentially and arguably more beneficial, real-life problems. 1.2 Motivation There are many games that pose interesting challenges for AI. Classic games such as chess or checkers serve as a test bed to test AI problems in well-defined domains, with the goal to adapt the developed expertise to real-life problems. Significant results were achieved when developing game playing agents – the most well-known example is the Deep Blue computer, which was the first machine to ever defeat a human chess 3 Project website: http://bluebrain.epfl.ch/ 4 Software agents are also known as the robots Chapter 1 – Introduction 3 world champion [4]. Nowadays, current chess programs have completely surpassed human players thus diminishing down the scientific challenge in this kind of games – complete information games (CIG). Moreover, solving games like chess or checkers also greatly differs from solving real-file problems, due to the lack of incomplete information and stochasticity. As John von Neumann says: Real life is not like that. Real life consists of bluffing, of little tactics of deception, of asking yourself what is the other man going to think I mean to do. And that is what games are about in my theory. John von Neumann 5 Therefore, incomplete information games (IIG) provide a much richer domain to study AI and adapt the developed methodologies to other domains. One great example of such games is Poker. Poker is probably the most popular card betting game in the world. It is played by millions around the world and has become a very profitable industry 6 , with massive media coverage 7 . Given its popularity and the amounts of money involved (in the order of billions of dollars each year), Poker also became a research subject in other domains such as Economics (the economic impact of gambling [5]) or Phycology (studies of addictive behaviour [6], [7]). Poker’s key features such as incomplete knowledge, risk management, need for opponent modelling and dealing with unreliable information, turned this game into an important topic in Computer Science, especially for AI. These features make it possible to use this game as an easy tool to measure progress in AI research itself. This is so given the fact that in order to assess new approaches one only has to test them against the former ones – these tests can be easily performed by running simulations (the easiness of simulation is actually one of the main advantages of using games). Dedicated Poker research started about 20 years ago [8]. Even before that, the well-known scientist John Forbes Nash, also used Poker games to demonstrate his also well-known concept of Nash-Equilibrium (NE) [9], which granted him a Nobel Prize and is nowadays a fundamental concept in the Game Theory. Poker presents a radically 5 In this statement John von Neumann was referring to Chess. 6 Growth of Poker industry in the news: http://www.newsweek.com/going-all-online-poker-117991 7 One good example is a TV channel exclusively dedicated to Poker: The Poker Channel 2 – Background 10 Many known scientists dedicated their time to develop game playing agents with intelligent strategies for games like chess because those games have a clearly defined set of rules and goals which allows them to be an easy domain to experiment on [8] – the main benefit resides on the fact that it is relatively easy to validate new approaches, especially through simulation of game plays. This presents an advantage as it a form of low cost validation of new AI approaches as it is possible to accurately measure the degree of success of a particular approach just by comparing results of many games played against programs based on other approaches or human players – the results are usually measured in terms of agent’s average utility growth. This means that games have a well-defined metric for measuring the development progress – in other words, it is possible to determine with more certainty if one is approaching (or not) a more optimal solution to solve a given problem. Another advantage of games research is that the knowledge gained from solving them can and has been used to solve other AI-related problems. These and other features like the fact of games having a “recreational factor” and a great impact in the entertainment industry today, make games an extremely important challenge for AI. 2.2 Game Theory Game Theory is a branch of applied mathematics that models strategic situations – games – in which one’s success depends on one’s opponents choices [13]. This field of research was initially introduced by John von Neumann in 1928 [14]. Game Theory models problems or situations as a game. A game is any strategic situation that can be described by the following features (for more details on these features see Section 2.3):  Set of players or actors (at least 2);  Set of possible moves (decisions) for each player;  Set of strategies;  Set of rules; 2 – Background 11  State;  Utility (game’s payoff). The game players are the entities that participate in the situation. Each one can follow its own strategy in a competitive environment with the objective of maximizing the utility (score obtained by the player at the end of the game). For instance, in a game like Poker, the utility would be the money balance of the player at the end of the game. The winning player(s) always have a positive balance, getting for that reason a positive utility. In contrast, the losing players get a negative utility. A game also has a state that represents the current value of the variables involved in the game. Any game move made by any player may alter the game state and the current state may terminate the game, depending on the game’s rules. 2.2.1 Strategies in games In a game, the agents’ behaviour is described by their strategies – a function that receives as parameter a game state or information set – in the case of incomplete information games – and returns an action (or decision). Commonly, in game theory, three types of game strategies are considered:  Pure Strategy: for each specific game state, the players always make the same move;  Mixed Strategy: the player assigns a probability to each pure strategy and stochastically picks one;  Totally Mixed Strategy: a particular type of mixed strategy. It consists of a set of pure strategies where each has a strictly positive probability of being chosen. It should be noted that in game theory each player has its own strategy set which is smaller than the set of all possible strategies for the game in question. 2.2.2 Extensive-form games An extensive-form game is a representation of a game in game theory in a form of a game tree. This representation allows for the demonstration of certain games’ 2 – Background 12 important aspects, like the sequencing of players' possible moves or their possible choices at every decision point. One example of such representation of a simple game (Rock Paper Scissors) can be seen in Figure 1. The numbers on the bottom of the game tree represent the game’s payoff for each player. The letters R, P and S represent the possible game’s actions, respectively actions Rock, Paper and Scissors. P (0, 0) (-1, +1) (+1, -1) (+1, -1) (0, 0) (-1, +1) (-1, +1) (+1, -1) (0, 0) P P Player 1 decides Player 2 decides Figure 1 – Rock Paper Scissors represented in extensive-form Table 1 – Rock Paper Scissors represented in normal-form Player 2 Player 1 Rock Paper Scissors Rock (0, 0) (-1, +1) (+1, -1) Paper (+1, -1) (0, 0) (-1, +1) Scissors (-1, +1) (+1, -1) (0, 0) 2 – Background 13 2.2.3 Normal-form game representation The normal-form game is a matrix representation of the game, which shows the players, strategies and the final payoffs. One example of that representation of a simple game (Rock Paper Scissors) can be seen in Table 1. Each matrix position contains the payoffs for both players considering the chosen actions. 2.2.4 Nash-equilibrium in Game Theory John Forbes Nash is a mathematician who did remarkable research in the area of game theory. He introduced the famous Nash-Equilibrium-Theory [9] in 1950. The Nash- Equilibrium represents a set of mixed strategies in a game where if any player i were to change its strategy, it would decrease its overall utility. This change is sole, i.e. it assumes that every other player maintains its strategy. A set of Nash-equilibrium strategies usually provides a very stable solution, especially for developing game playing agents for 2 player games. Usually, a Nash- Equilibrium is computed by self-play 11 algorithms or linear programming which results in two strategies (one for player 1 and the other for player 2). Then, the idea is for the game playing agent to use player 1’s strategy when it is in the player 1 position, otherwise it uses the strategy of player 2. This way, an agent can assure a minimum average utility against any opponent. The biggest disadvantage of this method is that it is conservative – it does not optimize results against particular players. When the game is unsolvable, an approach of this type may even not guarantee positive utility – it only warrants that the utility will not go below or above a certain threshold. One example of such a game is Kuhn Poker for 3 players (see 2.5.3). Nash-Equilibrium can be formally defined as follows: ∀𝑖,𝑥𝑖∈𝑆𝑖,𝑥𝑖≠𝑥𝑖∗:𝑓𝑖(𝑥𝑖∗,𝑥−𝑖 ∗)≥𝑓𝑖(𝑥𝑖,𝑥−𝑖 ∗) EQ1 11 It is a type of reinforcement learning algorithm for games. It consists of an approach where the game playing agent optimizes its strategy over time by playing several games against itself. 2 – Background 14 The notation for EQ1 is defined below: (S, f) is a game with n players, where:  i player  𝑥𝑖 a mixed strategy profile 12 for player i.  𝑥𝑖∗ a mixed strategy profile for player i that is in Nash-Equilibrium.  𝑆𝑖 the set of all possible strategy profiles for player i.  -i an opponent  fi a function that takes two strategy profiles as arguments and returns the average utility for player i in matches between those strategy profiles. The equation formalizes that if player i deviates from his * profile (Nashequilibrium) strategy, its utility will never increase. 2.2.5 Evolutionary Game Theory Evolutionary game theory (EGT) is a branch of game theory that studies games in a biological context base on Charles Darwin and Herbert Spender principle: “The Survival of the Fittest”. Thus, EGT is based on the idea of natural selection: over time the population evolves and during that evolution the stronger individuals will survive and the weaker ones will perish. In other words, the population always evolves in order to adapt to the environment that it is in, therefore optimizing its processes taking into account the available resources. Evolutionary game theory was first introduced [15] by John Maynard Smith in 1973. He found that the fitness of a strategy should not be measured in isolation; it should be measured in interaction with other strategies. Thus, EGT analyses the payoff of a set of strategies rather than individual payoffs, thus focusing on the dynamics of strategy shifting within a population. 12 Strategy profile - it is a tuple of probabilities of a given player performing each game’s possible action: the sum of the tuple’s elements is always 1. 2 – Background 15 2.3 Formalizing Extensive-form Games An extensive-form game is a generic representation of a sequential decision problem in form of a tree where each edge represents a decision and each node represents a sequence of performed actions (history). The history is hereinafter denoted by h considering that h ∈ H, being H the set of all possible game sequences according to the game’s rules. Also consider h’ a history-prefix where h = h’ || x. Therefore, a game G can be represented as the following tuple: 𝐺=<𝐻,𝑍,𝑁,𝐴,𝑎,𝑢,𝑝>|𝑍⊂𝐻 𝑤ℎ𝑒𝑟𝑒 𝑎:𝐻→𝐴′:𝐴′⊆𝐴 𝑢:𝑁×𝑍→ℚ 𝑝:𝐻→𝑁 EQ2 Z is a subset of H and represents the game’s terminal nodes i.e. the nodes where the game ends. N represents the set of players in the game and A is the set of all possible actions. An extensive-form game also requires the definition of three functions. Function a gives the set of all possible actions for a given node (or history) A’ (that is a subset of A) where for any particular node z ∈ Z we have that a(z) = ∅ and for any particular node h ∈ H\Z we have that a(h) ≠ ∅. Function p returns the acting player of any game sequence. Finally, function u returns the utility (or score) of a given player at a terminal node. 2.4 Game Classification Games can be classified taking into account different aspects such as visibility of the game state, duration of the game and the occurrence of random events. Some possible game classifications will now be presented. It is possible to classify games taking into account the visibility of the game state: 2 – Background 16  Complete Information Games – when the state of the game is always available to every player. Most board games are complete information games.  Incomplete Information Games – when the state of the game is hidden or partially hidden. Most card games are incomplete information games. There are two types of classifications regarding the existence of a playing history:  Sequential Games – when the game has sequences of actions and its players play in turns (not necessarily rotated). In this kind of games, players can take into account past opponents’ decisions because their actions are observable.  Simultaneous Games – there is no history, the players decide simultaneously. There are two types of classifications regarding cooperation between players:  Cooperative Games – the players’ utility could be shared, i.e. each player does not depend on its individual success but rather its group’s success. Not to be confused with each player’s individual notion of utility.  Non Cooperative Games – the utility is individual, i.e. the players are only interested on their own individual success. Taking into account the duration of the game, it is possibly to classify it as:  Finitely Long Game – game that cannot last forever.  Infinitely Long Game – game that can last forever – they can loop forever between the same states. There are two types of games regarding the sum of payoffs at the end:  Zero-sum Games – the sum of all players payoff is 0, which means that for a player to win a certain amount of points, one or more players must lose the same amount.  Non-zero-sum Games – the sum of all players payoffs is not 0. One good example is the Casino commissions on Poker or Blackjack games, which turn Zero-sum games into non-zero sum games. 2 – Background 17 Regarding the occurrence of random events, there are two types of games:  Deterministic Games – no occurrence of random events;  Stochastic Games – occurrence of random events (e.g. dice roll). 2.4.1 Examples of games In order to better understand the types of games described previously, Table 2 is presented – it contains examples of several well-known games and their classification (Blank – it has the opposite classification, ✓ – it has that classification, ? – it may have both classifications, depending on the version of game’s rules). Table 2 – Examples of games and their respective classifications. Game Complete Inf. Sequential Cooperative Finite Zero-sum Deterministic Poker ✓ ✓ ?13 Stock Market ✓ ? ✓ Minesweeper ✓ ✓ Backgammon ✓ ✓ ✓ ✓ Checkers ✓ ✓ ✓ ✓ ✓ Go ✓ ✓ ✓ ✓ ✓ Chess ✓ ✓ ✓ ✓ ✓ Prisoner's dilemma ? ✓ ✓ Monopoly ✓ ✓ ✓ Go-Fish ✓ ✓ Football ✓ ✓ ✓ ✓ ✓ Diplomacy ✓ ✓ ✓ 13 Poker is not zero-sum in casinos. 2 – Background 18 2.5 Poker “Poker is a generic name for literally hundreds of games, but they all fall within a few interrelated types” [16]. David Sklansky 14 Poker is a card game in which players bet that their current hand is stronger than the hands of their opponents. All bets throughout the game are placed in the pot and, at the end of the game, the player with the highest ranked hand wins. Alternatively, it is also possible to win the game by forcing the opponents to fold their hands by making bets that they are not willing to match. For this reason, since the players do not know the cards of the opponents, it is possible to win the game with a hand with lower score, by convincing the opponents that one’s hand is the highest ranked. 2.5.1 Poker Game Classification By using the classifications presented in Section 2.4, most Poker games can be classified as follows:  Incomplete Information: because the player does not know the opponents’ cards.  Non Cooperative: in Poker there is no cooperation between players. Each player wants to maximize his/her profit. Also, cooperation in Poker is considered cheating.  Finitely Long: a Poker game cannot last forever, because each player has a finite amount of cash. Even if players were continuously raising, they would eventually run out of money which means that they would be forced to go all-in.  Zero-sum: the money won by any player is lost by others, so the sum of gains and losses is always 0. However, when played in casinos, Poker is no longer a zero sum game because the casino is entitled to a percentage of the pot. 14 David Sklansky – an well-known and renowned expert in gambling. 2 – Background 19  Stochastic: the cards are randomly dealt to all players.  Sequential: in Poker, players play sequentially. Typically the history sequences are very large as discussed in [10]. 2.5.2 Texas Hold’em Poker Texas Hold’em is a Poker variation that uses community cards. This variant of Poker was chosen because its rules have specific characteristics that allow new developed methodologies to be adapted to other Poker variations with reduced effort [17]. 2.5.2.1 Rules At the beginning of every game, two cards are dealt to each player. The dealer player is assigned and marked with a dealer button. The dealer position rotates clockwise from game to game. After that, the two players to the left of dealer post the blind bets. The first player is called small blind, and the other one is called big blind. They respectively post half of minimum and the minimum bet. The player that starts the game is the one on the left of the big blind. One example of an initial table configuration is shown in Figure 2. The dealer is the player at seat F and the small and big blind players are respectively the A and B seats. Figure 2 - Poker table layout (from [18]) The first player to act is the player to the left of the big blind (player C) and the next player is the closest one to the left of the current player. Each player can choose one of the following actions:  Call: match the current highest bet. If it is not necessary to put more money in the pot, this action is also known as Check. 2 – Background 26 game. Function c returns the value of the current maximum bet. Function v returns the visible shared cards for a given history. Finally, r is the function that determines the set of remaining players for a given history (it excludes the players that have folded). Given these functions, we can determine the utility of a player. The value of the pot in ℎ∈𝐻 is ∑𝑏(𝑖,ℎ) 𝑁 𝑖 then, given Texas Hold’em Poker rules, player i’s utility in a terminal node z is given by EQ6. 𝑢(𝑖,𝑧)∈{−𝑏(𝑖,𝑧),∑𝑏(𝑗,𝑧) 𝑁𝑗−𝑏(𝑖,𝑧)}|𝑖∈𝑁∧𝑧∈𝑍 EQ6 Given these definitions we can also detail the a function, which given a history returns the possible betting amounts. The No Limit variant of Texas Hold’em Poker is characterized for having no limits in bets – the players can raise up to their remaining money (see EQ7), where 0 corresponds to a fold action, the lower limit min(𝑠(𝑝(ℎ),ℎ),𝑐(ℎ)−𝑏(𝑝(ℎ),ℎ)) to a call and the higher limit 𝑠(𝑝(ℎ),ℎ) to an allin. The lower and the upper limit might be equal, if the player doesn’t have enough cash to call – in that case, the player goes all-in. ∀ℎ∈𝐻:𝑎(ℎ)∈[min(𝑠(𝑝(ℎ),ℎ),𝑐(ℎ)−𝑏(𝑝(ℎ),ℎ)), 𝑠(𝑝(ℎ),ℎ)]∪{0}∧𝐴=ℚ≥0 EQ7 2.5.4.3 Information sets An information set is the name of a decision point in Poker; contrarily to complete information games, a player in Poker does not have the full game state information. Poker information sets 𝐼𝑖,ℎ={ℎ,𝑃𝑖,𝑣(ℎ)}|𝐼𝑖,ℎ∈𝐼 are composed of the game’s action sequence, the player’s private cards and the visible community cards. Other features can be extrapolated from the basic features, such as the Hand Strength measure, later described in this thesis. 2 – Background 27 2.6 Summary In this chapter this thesis’s domain was presented by clarifying several basic concepts about game theory and research in games. The game object of this study – Poker – was also introduced by explaining its most important rules and motivation for its research. The main Poker variants used in this thesis were also presented, namely Kuhn, Leduc and Texas Hold’em Poker. 29 Chapter 3 Literature Review This chapter describes the current tools, trends, techniques and approaches into building artificial intelligent programs capable of playing Poker. Some brief summaries of areas that may be required for the development of this thesis work are also presented: Section 3.1 gives a brief overview about what is being done in this thesis domain and by whom; Section 3.2 summarizes the current algorithms used by the research community. Section 3.3 presents the main agents that were developed until today. Section 3.4 presents ways on how to efficiently compute ranks of sets of cards. Section 3.5 presents algorithms for computing estimators to aid Poker game playing. Sections 3.6 and 3.7 present expert knowledge. Sections 3.8 and 3.9 present the tools for respectively simulating games and having agent playing online; finally on Section 3.10 a brief summary about emotional agents is given. 3.1 Computer Poker Research Research on computer Poker has been active over the past 20 years, which is evidenced by the relatively high number of publications in top conferences [19]–[23] and journals [17], [24], as well as master and doctoral theses [25]–[27]. However, none of these works focused on creating Poker players to match with humans. Besides Darse Billings work [25], most of the approaches focused more on the theoretical aspects of game-playing, making them only valid on more theoretical scenarios with theoretical environments. An exception to this is a recent achievement, where a perfect agent was Chapter 3 – Literature Review 30 created for Texas Hold’em Head’s On Limit [24]. However, the described approach is (currently) unfeasible for multiplayer no-limit Poker, due to memory and CPU capacity constraints. For this reason there is still a long way to go to create a Poker agent that is capable of consistently beating the best human players, especially in multi-player environments. 3.1.1 Research Groups The most relevant work in the area was mainly done by research groups exclusively dedicated to Computer Poker. These are the most relevant institutions that produce relevant research work in the area:  Computer Poker Research Group (CPRG) at University Alberta 16 – CPRG is probably the most active group on computer Poker research in the world today. They have produced the first Ph.D. thesis [25] about computer Poker, many other master theses with quite relevant advances and have published several papers in the top artificial intelligence conferences. Most of the research conducted in this group emphasizes on game theory applied to Poker. In most editions they achieve medals in the Annual Computer Poker competition as well (especially on the Limit competitions) [28]. To start exploring this domain, it is very important to thoroughly study the work done by this group.  Carnegie Mellon University 17 – CMU does not have a research group exclusively dedicated to Computer Poker. However, some CMU students, coordinated by Professor Tuomas Sandholm, developed several winning agents at the Annual Computer Poker competition, especially in the No- Limit competition (they developed several abstraction techniques for nolimit Poker).  Faculdade de Engenharia da Universidade do Porto / LIACC – Research in computer Poker started at FEUP around 2008 with two Master theses. Like CMU, there is no research group just for Poker. However, several 16 CPRG homepage: http://poker.cs.ualberta.ca 17 See some CMU Poker papers at http://www.cs.cmu.edu/~sandholm/ Chapter 3 – Literature Review 31 publications were made during the last years (see Appendix A for examples). 3.1.2 Conferences and competitions The most relevant work in the domain of Computer Poker can be found in the following conferences. These conferences are top conferences in the area of artificial intelligence, with very low acceptance rates (on average < 10%):  AAMAS – International Conference on Autonomous Agents and Multi Agent Systems  AAAI – International Conference on Artificial Intelligence  IJCAI – International Joint Conference on Artificial Intelligence There is also relevant work in top journals such as:  Artificial Intelligence Journal  The International Computer Games Association Journal  Science Most of the work is tested and validated in agent competitions. The most relevant competitions are organized by the CPRG:  CPRG Annual Poker Bot Competition 18 [28] – The Annual Computer Poker Competition has run since 2006. The competition takes place each summer at the AAAI or IJCAI Conferences. The event attracts competitors, both academics and hobbyists alike, from countries all over the world. The main focus of the competition is on developing a further understanding of how poker research can benefit artificial intelligence. The competition has four tracks (not all tracks run every year): o Limit Texas Hold’em Poker (2 Players) – the goal of this competition is to assess agents in game theory applied to large and sequential games. 18 Official website: http://www.computerpokercompetition.org/ Chapter 3 – Literature Review 32 o Limit Texas Hold’em Poker (3 Players) – same goal as the 2 player competition but with and even larger game and the multi-player facet, which makes it hard to use Nash-Equilibrium based strategies. Moreover, the existence of a third player greatly reduces the strength of the playing hands. o No-limit Texas Hold'em Poker (2 Players) – the main challenge of this competition is to assess abstraction techniques. Given the fact that No-Limit variants of Poker are much larger, abstraction techniques are essential to make a good game playing agent. o Kuhn Poker (3 Players) – the main challenge of this competition is to assess opponent modelling capabilities in the agents. Given that this variant of Poker is much smaller than the others (as explained in Section 2.5.3), agents must model their opponents to maximize their utility.  Bot VS Human competition – three competitions between agents and very good human players were held. The first competition that opposed poker agents and professional players was in 2007 19 . At this competition, an agent defeated for the first time a professional Poker player in a group of matches in Limit Poker, but lost the series. On the same competition in the following year 20 , the competing agent was able to win by a low margin. Finally and more recently in 2015, the competition Brain Vs AI 21 was held. It was the first competition in the No-Limit variant between agents and humans. In this competition, humans managed to get more cash but it is stated that scientifically it was a tied competition. 19 http://webdocs.cs.ualberta.ca/~games/poker/man-machine/2007/ 20 http://webdocs.cs.ualberta.ca/~games/poker/man-machine/ 21 https://www.cs.cmu.edu/brains-vs-ai Chapter 3 – Literature Review 33 3.2 Current Approaches There are several different approaches for building artificial poker players such as Heuristic-based, Simulation-based, Pattern Matching-based and Monte Carlo Search Tree-based approaches. In the following sub-sections, the main approaches to create Poker agents will be presented and discussed. 3.2.1 Rule Based A rule based approach is the most direct and simple approach to start developing Poker agents. It consists in defining the agent’s behaviour with a set of conditional ifthen-else rules, which means selecting an action for a given information set. A hypothetical rule-based approach is shown on Figure 4. In this particular example the player will fold with a probability of 20%, call with a probability of 30% and raise with a probability of 50%, if the pot value and the hand score is high. Action flopAction(Hand hand, GameState state){ if(state.pot > 100 && hand.score > 3000 && state.numActivePlayers <= 2){ return new Action(0.20, 0.30, 0.50); } else if... } Figure 4 – A hypothetical rule within a rule-based system for Texas Hold’em Poker (based on Figure 1 in [29]) This approach is very intuitive but has several limitations. First, it requires expert knowledge. Moreover, even with expert knowledge, manually abstracting very large variants of Poker such as Texas Hold’em cannot capture several strategy nuances that expert players use with their intuition, which makes it very hard to formalize. 3.2.2 Simulation Based Simulation based approaches for Poker game playing consist in generating many random possible match outcomes in order to obtain empirically the statistical average best response for a given game state – Monte Carlo Simulation. Monte Carlo Chapter 3 – Literature Review 34 Simulations rely on simulating the opponents’ behaviour when their playing nodes are reached; using random action sampling for every node not only uses a large number of iterations but also could produce not very accurate predictions in games of incomplete information. In order to speed-up the sampling process, the sampling is biased taking into account the opponent profile (pre-established profiles learned from, for instance, game logs [30]) . One of such techniques is called selective sampling [31], which combines this with reinforcement learning, which goal is to maximize the information gain – in this work selective bias was introduced in private cards i.e. instead of just considering the opponent’s possible private cards, a weighted table with the frequency of those cards is maintained throughout the game and it is filled by all observable actions. A similar technique was also applied to the game of Scrabble [32]. This approach has good practical results in small games, but for very large games such as Poker, the lack of information and observations (only about 10% of the hands provide information about the cards of the opponents) makes the agent play just based on card probabilities, which makes it very predictable. One particular case of a simulation based approach is the Monte-Carlo Tree Search algorithm (MCTS). The MCTS is a simulation based algorithm that is adapted for sequential problems – it estimates the values of moves by sampling them in a game tree [33]. It consists of applying Monte Carlo Methods on game trees, by selecting random branches of possible outcomes and then selecting the branch that will likely produce the best results. The accuracy of this algorithm greatly depends on the number of simulations: the more simulations, the better the estimate. The algorithm starts by initializing the game tree, creating a single root node with the current game state. After that, the following steps (see Figure 5 and Figure 6) are repeated a fixed number of times:  Selection: consists on selecting the leaf node of the tree to be expanded;  Expansion: add child nodes to the selected node;  Simulation: game simulation until the leaf node of the game tree is reached; Chapter 3 – Literature Review 35  Backpropagation: the final value of the simulation is stored on the nodes that define the followed path. Figure 5 - The Monte Carlo Tree Search algorithm (from [46]). In this work [33] the author created a complete Poker agent that combines typical player clusters (previously extracted) to predict card holdings and the MCTS algorithm, as explained in Figure 5. The results produced by this algorithm worked well against agents with static strategies but event against those, sometimes problems related with local maxima occurred which prevented the algorithm to properly model the opponents, thus the average winnings were not optimized. Other relevant works about the MCTS algorithm and its applications in Poker are [34], [35]. Figure 6 – Poker Agent Architecture that combines MCTS and Clustering (from [46]). 3.2.3 Nash-Equilibrium A Nash Equilibrium, as defined in Section 2.2.4, is an equilibrium point between a set of mixed strategies, for the game participants, where each one cannot perform better Chapter 3 – Literature Review 42 described in [45]. The generic approach of this language allows for its easy adaptation to other domains. The language root starts by defining the concept of strategy: a strategy is a set of tactics each of which is a tuple composed by an activation condition and a behavior for that tactic. The activation condition consists of abstracting decision points or information to define I’. They correspond to a set of verifications of the visible game features (through evaluators) or predictions about uncertain events (through predictors). A tactic’s behaviour is the procedure followed by the player when the activation condition is met (the behavior itself has a second layer of verifications that can abstract the information set even further). The tactic’s behaviour could be either user-defined or language predefined (based on common expert tactics). In the next sub-sections we describe PokerLang’s main language concepts. Below the main elements of this language are presented, in the BNF notation. <STRATEGY>::= {<TACTIC>} <TACTIC>::= <ACTIVATION_CONDITION> <TACTIC_BEHAVIOUR> <ACTIVATION_CONDITION>::= {<EVALUATOR>} <TACTIC_BEHAVIOUR>::= <PREDEFINED_BEHAVIOUR>|<BEHAVIOUR> <PREDEFINED_BEHAVIOUR>::= loose_agressive|loose_passive| tight_agressive|tight_passive <BEHAVIOUR>::= {<RULE>} <RULE>::= {<EVALUATOR> | <PREDICTOR>} <ACTION> <VALUE> <ACTION>::={<PREDEFINED_ACTION><PERC>| <DEFINED_ACTION><PERC>} __________________ Language: BNF To allow the easy creation of Poker-Lang document, an interface was also created. This interface is called PokerBuilder and its appearance can be seen on Figure 9. With a smooth interface and simple features, PokerBuilder is accessible to any user that understands the main concepts of poker. Chapter 3 – Literature Review 43 Figure 9 – Poker Builder (from [45]) 3.2.6 Other approaches Several other approaches were used for building poker playing software agents but with less scientific significance. However, some of the agents developed with such approaches actually got some very good results in practice, often surpassing more theoretical approaches (with emphasis for a Case Based Reasoning Bot that got 2nd and 3rd places at the Computer Poker Competition even against Nash-Equilibrium agents). These approaches are:  Miximax and miximix– these algorithms were presented on [46], [47] and they can be considered to be versions of the minimax algorithm adapted to incomplete information games. These algorithms are adaptive: they assume Chapter 3 – Literature Review 44 the existence of opponent profiles with online information from the games assigning one of the profiles to the current opponents. This will enable to better estimate the probabilities of all actions on a given information set thus permitting the agent to traverse the game tree with much more accuracy. This approach is closer to what real players do, thus having the disadvantage of needing a strong starting database in order to properly estimate how the opponents will proceed in order to select the best possible action. Another problem is the predictability of this kind of approach, after the opponent learns which models we know.  Teams of Computer Programs – This approach is in reality an aggregation of several methodologies – it consists of using several agents at the same time. Each agent has strengths and weaknesses. When facing an unknown opponent, there is no information regarding which strategy should be used. An approximation to a Nash-Equilibrium is not likely to lose, but it is always possible and it was already explained that the goal is to earn as much as possible. Therefore using heuristics to switch strategy during the game (if one is not performing well) is a good option, with very good results demonstrated empirically [30], [48]. The agent that is responsible for changing the strategy is called coach agent. It observes the conditions of the game and decides which of the game playing agents is going to play.  Pattern Matching Methods – pattern matching methods consist of creating agents that adapt their strategies based on past experience. The idea of these methods is to model the game, by defining which game variables represent a strategy and then build statistical models of past game data based on those variables. For instance, the work described in [18] showed that it is possible to build a Poker agent that behaves like a human player, using supervised learning methods. The author defined game variables and then used game logs of past games between human players to copy their strategies. The agent is also able to combine different tactics from different human players. This way, the agent does not have a static strategy; therefore it can confuse the opponent modelling mechanics of its opponents. Another similar approach [49] used the expectation-maximization (EM) algorithm to build cluster models, where a Chapter 3 – Literature Review 45 cluster model is a mixture model of players. This approach focused on learning quickly instead of learning accurately because if a player wants to win against an opponent that it has never seen, it has to learn fast before losing its chips. This approach performed well in short term games, outperforming agents based on Bayesian methodologies.  Case-Based Reasoning (CBR) – is a group of learning algorithms that consist on having a set of previously observed cases as a knowledge base to aid in the decisions during the game. In the case of Poker it uses classified game logs as a knowledge base, with each play classified as being good or bad. When the agent has to decide which action it is going to take it searches on the knowledge base for the case that more reassembles the current game state. The decided action is similar to the one that was taken in the past (if the action was good in the past). The most successful applications of CBR to Poker were Casey[50], Casper[51] and Sartre[52]. They got very good standings in the ACPC competition (including a 3rd place in No-Limit). 3.3 Poker Agents The number of poker software agents has been increasing in the last years. Many have been created during, and as a part of, academic research but as this research matures and becomes widespread, so does the number of individuals tackling and researching on this subject. This section provides a brief description and resources for the most popular poker agents at this time, with emphasis on the ones that participated in the Annual Computer Poker Competition or that produced some academic results. There is not much info about other potential agents that are being used in Online Poker. The limitations imposed by casino clients in their use makes them being hidden to the general public. However, there is strong belief among Poker professionals that bots are playing everywhere online. Chapter 3 – Literature Review 46 Table 5 – Summarized description of some notable Poker Agents Year Name Type 1997 Loki Rule Based Loki [53] was the first agent made by the CPRG. Loki uses a rule based approach which was made by game experts. Its decisions were mainly based on profile opponent models based on expert knowledge and Effective Hand Strength computation. This approach was not very successful in online matches (on IRC) against low/mid-level opponents. Also it was not very accurate with opponent modelling and it had a huge exploitability. When CFR agents emerged, Loki became quickly deprecated. 1999 Poki Rule Based Poki [46] is the new version of Loki, completely revised. It was the first agent to feature the miximax and miximix techniques. This version had a revised opponent modelling system which made it rather successful in IRC matches. It also won the 2008 ACPC 6 players limit competition – even against CFR agents. This happened because currently CFR agents are not yet proficient in multiplayer. In games with lower number of players, this agent can be easily beaten by a CFR. Even so, it is still an important agent, with potential applicability for online game playing against humans. 2002 PsOpti/Sparbot Nash-Equilibrium / Linear Prog. PsOpti [54] was the first one to use a Nash-Equilibrium based approach with abstraction. This agent only played Texas Hold’em Pre-Flop. Even so, tests indicated that it outperformed some human players (on IRC) and all agents developed until then. However, the winning rates of this agent were low, because it did not possess any opponent modelling capabilities. It participated in the ACPC competition in 2006 and won the Head’s on Limit competition under the name of Hyperborean 06. Its code was also included in the Poker Academy software under the name of Sparbot. 2003 Vexbot / BRPlayer Adaptive game tree search Vexbot [55] uses context tree data structures to store the opponent models. These models disregard chance nodes and only store betting sequences. It was the bot that firstly stored decisions with abstracted game betting sequences as the key for retrieving the probabilities to play on given information sets. This agent was also the first to be able to detect weaknesses in a Nash-Equilibrium strategy by exploiting the older PsOpti versions. 2006 Hyperborean CFR / Nash-Equilibrium Hyperborean [41] first emerged as a team of poker programs composed by all PsOpti agents. It participated and won the first ACPC competition on Limit Poker variant. Furthermore, this agent marked the introduction of the CFR algorithm as the state of the art algorithm to create Near-Equilibrium agents. 2007 Polaris CFR / Restricted Nash Response Polaris [36] innovated by using the restricted Nash response technique described in Section 3.2.3. It was the first game playing agent to have reported wins against some of the best human Poker players in the first Human VS Machine competition. 2007 Hyperborean (No-Limit) CFR / Restricted Nash Response Hyperborean (no-limit) [56] was the first bot to apply the CFR and Nash-Equilibrium approach to a No-Limit Poker version. This agent was the first that needed to explore an extra step required for game abstraction, called translation. The translation was Chapter 3 – Literature Review 47 required to correct the betting amounts between the abstracted and the real game because in No-Limit Poker the betting amounts are continuous. 2009 Hyperborean (Ring) Data biased response Hyperborean (ring) [42] was the first one based on the CFR algorithm that performed well in multiplayer games. Despite the lack of theoretical guarantees that CFR produces Nash-Equilibrium strategies for multiplayer games, this agent is the proof that the generated strategies are still very robust for game play. 2015 Cepheus CFR+ Cepheus was the first agent [24] to solve the Limit Texas Hold’em variant of Texas Hold’em without abstraction. Despite having the problems of still not being able to optimize winnings against specific players, it is unbeatable in the long run, because its exploitability is almost zero. The main issue is that the used algorithm (CFR+) requires a lot of computational power and memory to deal with such large variants of Poker. 2006 Casey Case Based Reasoning Casey [50] is a case based reasoning bot that starts off with an empty knowledge base. It starts playing with random decisions and recording all of them. The more it plays the more it learns. This version made some erratic assumptions of the game without an initial training period. 2007 Casper Case Based Reasoning Casper [51] is another Poker agent that can play in a Full Texas Hold’em Poker table which demonstrates the usefulness of these approaches over more theoretical approaches when it comes to multiplayer Poker. This agent does not learn from scratch like Casey, it uses game logs from playing against Poker Academy to learn new cases to make its decisions. This agent did well against the agents at Poker Academy and also against humans with fake money, but it did not do as well against humans in real money tables with very small stakes. 2009 / 2010 Sartre Case Based Reasoning Sartre [52] is the updated version of Casper but Nash-Equilibrium based agents. In 2010 it got the 3rd place in the Limit competition of the ACPC and the 2nd place in the No-Limit variant. 2006 / 2007 GS Family Nash-Equilibrium GS is bot similar to PsOpti that uses the Game Shrink system. That algorithm, given a description of the game tree is capable of generating a Near-Nash Equilibrium solution using lossless or lossy abstractions. This agent also combines offline and real-time game solving, using offline learning for the Pre-Flop and Flop rounds of the game and for the other the solution is computed online. 2007 / 2015 Tartanian Evolutionary game theory Tartanian is a group of game playing agents that innovated by their abstraction techniques on No-Limit versions of Poker. It is also the first reported agent that applies EGT to Equilibrium solution learning, by breeding and merging different equilibrium profiles to speed-up reaching a more stable solution. It placed 2nd at the 2007 ACPC competition. 2010 HoldemML Pattern Matching HoldemML is a group of No-Limit Texas Hold’em game playing agents that used pattern matching to build their behaviour from game logs [48]. The results demonstrated that these agents imitated well their human counterparts but the lack of Chapter 3 – Literature Review 48 3.4 Hand Rank Computation A Poker hand is a set of five cards that expresses the player’s score. Let’s consider the same notation described on Section 2.5.4. Being D the set of all cards in the deck, Pi the set of pocket cards of a particular player i and S the set of community cards so that P1  P2 … P𝑁  S ⊆D, and P𝑖  S for any i is equal to . Thus, the score function is defined as 𝑠𝑐:[D]5→ℕ. For a particular player, the hand ℎ𝑖 is the union of the pocket cards and the community cards (P𝑖∪S). Thus, the player’s score is given by the rank function, as follows (EQ9): 𝑅𝑎𝑛𝑘(ℎ𝑖)=max({𝑠𝑐(𝑥): 𝑥∈[P𝑖∪S]5}) EQ9 The possible hand ranks are from stronger to weaker (see with more detail in Section 2.5.4.1): Straight Flush (sequence of same suit), Four of a Kind (4 cards with same rank), Full House (Three of a Kind + Pair), Flush (5 cards with same suit), Straight (sequence), Three of a Kind (3 cards with same rank), Two Pair, One Pair (2 cards with same rank) and Highest Card (not qualifying to other ranks). Examples of each rank are demonstrated in Table 3. These ranks are not equally valued. Each rank has sub-ranks essentially based on the score of the top cards (e.g.: a pair of aces scores higher than a pair of queens). In total, there are 7,462 possible sub-ranks in Texas Hold’em Poker. A poker hand rank evaluator is a software program that computes the value of the rank function, partially computed by the score function 𝑠:[D]5→ℕ. In Texas Hold’em Poker this evaluator receives as parameter the set of cards Pi + S, where |P𝑖|=2∧|S|∈{5,6,7}. The evaluator returns a natural number representing the relative value of that hand (typically from 0 to 7,461, where 7,461 corresponds to one of the top scored Straight Flushes). The charts in Figure 10 show the relative available data makes this approach very hard to be feasible for online play. 2015 Lucifer Hold’em Iterative CFR / Teams of CFR This is an agent that used, for the first reported time, a non-recursive version of the CFR algorithm. Despite the lack of training time (1 hour against the average of 2 weeks) and computational resources it still could get the 9th place out of 16 at the Head’s on Texas Hold’em Limit Competition. Some of the used techniques are described in Chapter 6. Chapter 3 – Literature Review 49 frequencies of each score for Flop, Turn and River, respectively |S|=5, |S|=6 and |S|=7. The horizontal axis represents the hand ranks (ordered) and the vertical axis is the relative frequency of that hand. Figure 10 – Hand rank distributions in Flop (top), Turn (middle) and River (bottom) It is possible to observe a stair step layout in the first chart (|S|=5). Each stair represents a hand name in Table 3. It is also possible to observe large peeks near the 0,00% 0,01% 0,01% 0,02% 0,02% 0,03% 0,03% 0,04% 0,04% 0,05% Scores |S| = 5 0,00% 0,05% 0,10% 0,15% 0,20% 0,25% Scores |S| = 6 0,00% 0,10% 0,20% 0,30% 0,40% 0,50% 0,60% Scores |S|= 7 Chapter 3 – Literature Review 50 end of each chart. They represent the straight hands, because there are plenty of ways of combining 5 cards to score a straight, but only 10 possible types of straights (Five high, Six High …). To compute the probability of success of a given hand – odds – it is usually necessary to compute several hand ranks before. For instance, the odds calculation methodologies presented in the next section require the computation of hand ranks. Programming an algorithm to determine the hand’s rank is a relatively trivial task. This can be done using a naïve approach, i.e. using an algorithm that intuitively makes sense and that is humanly readable. Naïve hand rank evaluators usually consist of the following steps:  Sort the hand by card value (deuce has the lowest value and ace has the highest);  Iterate through the hand, collecting information about ranks and suits of the cards;  Make specific tests to check, iteratively, if the hand is of a certain rank, starting at the higher ranks. One example to illustrate this idea can be found in Figure 11. This example does not consider the whole set of Texas Hold’em rules. Function HandRank(Hand) { Sort(Hand); If IsStraightFlush(Hand) Return 9; If IsIsFourOfAKind(Hand) Return 8; If IsFullHouse(Hand) Return 7; If IsFlush(Hand) Return 6; If IsStraight(Hand) Return 5; If IsThreeOfAKind(Hand) Return 4; If IsTwoPairs(Hand) Return 3; If IsOnePair(Hand) Return 2; Return 1; } Figure 11 – Hypothetical Naïve Hand Rank Evaluator The problem with naive evaluators resides in their efficiency, which is important because the rank evaluator is used by a hand odds evaluator several times per Chapter 3 – Literature Review 51 computation. The solution to this problem resides in top-down dynamic programming algorithms in order to speed up the rank function. The next subsections will present some developed approaches to solve this issue. 3.4.1 Pokersource Poker-Eval Poker-Eval is a C implementation of a Poker Hand rank evaluator [57]. As described at the beginning of this section, given a hand, this evaluator returns a natural number that represents the hand score. This evaluator uses a naïve approach and, to the best of our knowledge, the fastest one. The main advantages of this evaluator are its architecture which supports multi Poker variants, multi-platform usage, since there are wrappers for other programming languages and its low memory usage when compared to look-up table based approaches. The main issue of this evaluator is its low level API which makes it hard to use by programmers. 3.4.2 Cactus Kev The Cactus Kev's 5-Card Evaluator [58] is a system to compute 5 card hand rank. The idea behind its algorithm is the construction of a pre-computed look-up table with every possible rank. However, since the number of possible 5 card sequences is 𝑃5 52 , the size of the table would be about 2.5 GB of memory (considering 8 bytes to store the hand and its rank). To solve this problem one can group similar hands (same cards, different order), resulting in (52 5) hands, making this approach feasible (the size of the new look-up table would be about 20 MB). However, this solution requires sorting the hand cards before accessing the look-up table, wasting additional CPU time. To solve this, Cactus uses a 32 bit integer representation of the cards (Figure 12). Figure 12 – Cactus Kev’s card representation P (6 bits) represents the value of a card in a form of a prime number, with the following values Two – 2; Three – 3; Four – 5; Five – 7; Six – 11; Seven – 13; Eight – 17; Nine – 19; Ten – 23; Jack – 29; Queen – 31; King – 37; Ace – 41. The reason behind this Chapter 3 – Literature Review 58 of this method is the consideration of Texas Hold’em upcoming rounds. In Figure 15, the average distribution of the PPOT and the NPOT components is shown, through heat maps. It is possible to perceive that there are higher concentrations of high PPOT values for closer cards (which are more likely to score a straight). As for the NPOT values, the hands with cards with lower ranks have a higher negative potential. This presents the same result as Hand Strength in the River round (because the hand cannot evolve any further). Moreover, this method cannot be used in Pre Flop rounds, because it is not possible to calculate the hand strength for a two cards hand. This might be solved by combining this algorithm with Chen Formula (see at the end of this section). Similarly to the hand strength, if the Hand Potential is modified to only iterate over cards that the opponents might have [63], it is possible to obtain a better estimate of the winning ratio. Figure 15 – Heats maps for PPOT and NPOT against 1 opponent. 3.5.3 Effective Hand Strength The probability of winning can be calculated by combining the Hand Strength with the PPOT and NPOT components. P𝑛(win)=HS𝑛×(1−NPot𝑛)+(1−HS𝑛)×PPot𝑛 EQ13 Chapter 3 – Literature Review 59 By setting the NPOT to 0, it is possible to determine the effective hand strength, which is the probability of the hand either being the best or improving to it. EHS𝑛=HS𝑛+(1−HS𝑛)×PPot𝑛 EQ14 Through the observation of the Effective Hand Strength heat map (Figure 16), one can find that it has a similar structure to the simple Hand Strength map. Figure 16 – Effective hand strength heat map against with 1 opponent. Figure 17 – Difference between effective hand strength and the hand strength. 2c 3c 4c 5c 6c 7c 8c 9c Tc Jc Qc Kc Ac 2c 3c 4c 5c 6c 7c 8c 9c Tc Jc Qc Kc Ac 0-0,15 0,15-0,3 0,3-0,45 0,45-0,6 0,6-0,75 0,75-0,9 0,9-1 2c 2s 3h 4d 5c 5s 6h 7d 8c 8s 9h Td Jc Js Q… Kd Ac As 2c 2s 3h 4d 5c 5s 6h 7d 8c 8s 9h Td Jc Js Qh Kd Ac As 0-0,05 0,05-0,1 0,1-0,15 0,15-0,2 0,2-0,25 Chapter 3 – Literature Review 60 For this reason, the additional computation time needed to calculate the effective hand strength might not be worth. To confirm this suspects, we computed the 𝐸𝐻𝑆1−HS1 heat map (Figure 17). In this map, it is possible to observe that the EHS method increases the value of all hands with special focus on hands with less hand strength. This happens because low scored hands have more potential to grow than “already made hands”. 3.5.4 Incomplete Hands In this section the Pre-Flop round of the game is addressed by showing how to compute odds when all community cards are still hidden. One example is the Chen method. Chen is a fast naïve method developed by the professional poker player William Chen [64]. This can determine the relative value of the pocket hand. The main advantage of this over hand strength is that it does not need to generate permutations of card sets. For this reason, this algorithm is much faster than previously presented approaches. function Chen(card1, card2){ score = Max(Score(card1), Score(card2)) if(card1.suit == card2.suit) score = score + 2 switch(abs(card1.rank-card2.rank)) case 0: score = score * 2 case 1: score = score + 1 case 2: score = score – 1 case 3: score = score – 2 case 4: score = score – 4 default: score = score – 5 return score } Figure 18 – Chen code implementation example The algorithm is composed of two functions. The Score function returns a real number that scores a card (10 for Ace, 8 for King, 7 for Queen, 6 for Jack and rank / 2 for remaining). For instance, any ace card has the highest score possible (10). The Chen Formula function returns an integer which represents the value of the hand. Thus, the maximum returned value is 20 for a double Ace hand. Chapter 3 – Literature Review 61 3.6 Opponent Modeling in Poker Opponent modelling consists in classifying the opponents in order to make accurate predictions of their future actions in the game. In this section we present some techniques based on expert knowledge that are still the baseline approaches for abstracting used in very recent agents. One of the most used player classification is the Sklansky classification, explained in [16]. The classification is based on statistical measures about the opponents and they do not usually consider the game results. The measures that can be used to classify players are:  Voluntary Put In Pot (VPIP) – The percentage of how often a player puts money in the pot in Pre-Flop round by calling or raising. It does not count blind-bets.  Pre-Flop Raise (PFR) - A percentage measure of how often a player raises pre-flop compared to calling or folding.  Aggression Factor (AF) - The ratio between raises and call actions (Number of Raises / Number of Calls). Checks do not count.  Flop Continuation Bet (FCB) – The percentage of times where a player makes more than one raise on the same Flop.  Fold Versus Flop Continuation Bet (FvFCB) – The percentage of times that a player folds after doing two or more raises on the same Flop. On the following tables (adapted from 22 ) we present several player classifications based on these measures and ways to explore the opponents that classify on them. 22 The explanation of Poker Statistics: http://pokerai.org/wiki/index.php/Player_statistics Chapter 3 – Literature Review 62 Table 6 - Tight Aggressive Players. Classification Tight Aggressive Conditions VPIP: 12-16, PFR: 9-14, AF: >2.0 Description This type of player will play a few times, but when he does he probably has a premium hand. When in game, this type of player plays very aggressively (high stakes). Exploit This type of players is difficult to exploit because they only play premium hands, despite being predictable. However, a good loose player cannot take advantage over tight aggressive players. Table 7 – Nit/Rock players. Classification Nit/Rock Conditions VPIP: 7-11, PFR: 5-7 Description This type is even stricter than the tight aggressive player. A rock player only plays a very small set of hands, usually above QQ in Pre-Flop and Pair after the Flop. Exploit Blind stealing. Since this type of players play fewer hands, any flat Call on the Pre-flop round should be answered with a Raise. Table 8 – Loose Aggressive Players. Classification Loose Aggressive Conditions VPIP: 17-24, PFR: 15-22, AF: 2.0-5.0 Description They play aggressively a wide range of hands. They usually use position and present good opponent modelling capabilities, being able to make great profit from getting their opponents to fold their better hands, using the concept of fold equity. Exploit Good Loose Aggressive players present few weaknesses. Strategies that could work against this type of opponents are Hammer or Rope- a-dope. Chapter 3 – Literature Review 63 Table 9 – Manic/Aggro Donk players. Classification Maniac/Aggro Donk Conditions VPIP: 30-100, PFR: 30-60, AF >4.0 Description This type of players bet and raises almost any hand and they rarely fold. In the long run, these players lose a lot of money. Exploit A good tight strategy works against these players. Table 10 – Calling station player Classification Calling Station Conditions VPIP: 18-100, PFR: 0-15, AF: <2.0 Description These players call almost every hand and they only raise (little) when they have a very strong hand. Exploit Tight strategy. Table 11 – Short stacker player. Classification Short Stacker Conditions VPIP: 5-9, PFR: 4-9 Description This type of player only applies in cash games. These players only enter the table with a 20 Big Blind stack and they either fold the hand or go All-In (with premium hands) at the Pre-Flop. They often play in position and only with hands above TT. Exploit These players are predictable. Blind stealing works well against this type of players. Table 12 – Loose passive player. Classification Loose Passive Conditions VPIP: >30, PFR <15, AF <2.0 Description Plays a wide range of hands passively. They are similar to calling stations but they fold more often. Exploit Tight and aggressive strategy. Chapter 3 – Literature Review 64 3.7 Poker Books There are many books that give advices on how to proficiently play Poker, written by known professional players or mathematicians. A Poker book normally gives a set of tips about game strategies and how these can be explored, showing common errors of each type of player and real examples of plays in important tournaments. Obviously, many of these tips are subjective and depend heavily on the game situation, so each player should always make his or her own strategy depending on its opponent’s behaviour. The next sub-sections briefly describe some of these well-known books. Many of the concepts present in these books have been constantly used in the development of the current state of the art approaches on computer Poker, especially for wisely abstracting the game information. The concepts in Section 3.6 were based mainly on the work of these authors. 3.7.1 The Theory of Poker The Theory of Poker [16] is one of the most important books about Poker playing ever printed. It was written by the professional gambler David Sklansky and the first edition came out in 1987 (almost three decades ago!). Although being old, much of the content is still a reference for professional poker players and computer Poker researchers. This book presents a complete overview of Poker theory in all main variants with some examples about each concept. Sklansky starts the book by explaining what he calls “The Fundamental Theorem of Poker”: Every time you play a hand differently from the way you would have played it if you could see all your opponents’ cards, they gain; and every time you play your hand the same way you would have played it if you could see all their cards, they lose. Conversely, every time opponents play their hands differently from the way they would have if they could see all your cards, you gain; and every time they play Chapter 3 – Literature Review 65 their hands the same way they would have played if they could see all your cards you lose. David Sklansky [16] In this theorem, Sklansky is clearly talking about Nash-equilibrium theory. When a player does not play its optimal strategy and deviates, he or she makes a mistake, therefore losing. For this reason, to win in Poker a player should take advantage of situations where the opponents do not use their equilibrium strategy. The book also presents concepts about pot odds, the value of deception, getting and giving a free card, semi-bluff, raising correctly, check-raising, using position, bluffing and techniques for reading hands. 3.7.2 Hold’em Poker for Advanced Players This [65] is another book written by David Sklansky (and Mason Malmuth) with the first edition coming out in 1988. This book is considered the continuation of The Theory of Poker but focused on the Texas Hold’em variant of Poker. This book introduces the Sklansky groups of cards in Texas Hold’em. There are 169 distinct sets of two card starting hands in Texas Hold’em. In this book, the authors divided those sets into eight different groups (see Table 13), according to strength and playability. Each group has a description of how to play with those cards. Table 13 – Sklansky and Malmuth groups Group Hands 1 AA, AKs, KK, QQ, JJ 2 AK, AQs, AJs, KQs, TT 3 AQ, ATs, KJs, QJs, JTs, 99 4 AJ, KQ, KTs, QTs, J9s, T9s, 98s, 88 5 A9s...A2s, KJ, QJ, JT, Q9s, T8s, 97s, 87s, 77, 76s, 66 6 AT, KT, QT, J8s, 86s, 75s, 65s, 55, 54s 7 K9s...K2s, Q8s, J9, T9, T7s, 98, 64s, 53s, 44, 43s, 33, 22 8 A9, K9, Q9, J8, J7s, T8, 96s, 87, 85s, 76, 74s, 65, 54, 42s, 32s Chapter 3 – Literature Review 66 It is possible to easily compute this table using the professional player Bill Chen’s formula (see 3.5.4). This formula is presented in his book “The Mathematics of Poker” [64] and it calculates the relative value of the pocket cards. 3.7.3 Super/System: A Course in Power Poker This book [66] written by Doyle Brunson and other known professional Poker players was first published in 1978. This was the book that presented some of the most important concepts about strategy in Poker for the first time, even before Sklansky’s publications. One important characteristic of this book is that the author defends his own aggressive playing style over passive playing styles. Solid theoretical proof now proves that aggressive play is usually superior to a more conservative style, but until the date of publication of this book, there were no previous studies about it [25]. 3.7.4 Gambling Theory and Other Topics This book [67] gives a understanding of how gambling works generally, by explaining the fluctuation that create illusions among the players about how strong they are in the game. It focuses particularly on the mathematics of poker, and how a player can take advantage of them to win. 3.7.5 Every Hand Revealed Every Hand Revealed [68] is a more recent book written by Gus Hansen (known by Poker players as “the madman”). This book presents a very practical approach for learning Poker, where the author shows all the hands that he played during Aussie Millions Poker Tournament in 2007 – one of the most important Poker tournaments that he won against 746 competitors. For each hand, Hansen explains the logic behind his decision usually with mathematical support. Since he is a Loose-Aggressive player, he plays differently than most of the best professional Poker players. For this reason, this book presents an interesting approach for a different winning strategy. Chapter 3 – Literature Review 67 3.8 Poker Simulators A Poker Simulator is a software tool that allows for Computer Poker researchers to test their agents against other agents or human players, allowing them to predict the agents’ success at long term, before putting them in a real life environment. In the case of Poker this is especially important, because assessing agents in real-life environments can cost a lot of money. 3.8.1 LIACC’s Texas Hold’em Simulator LIACC Texas Hold’em Simulator (Figure 19) is a software capable of simulating Limit or No-Limit Texas Hold’em games. It has a client-server architecture where the server communicates with clients (agents) through sockets with a predefined TCP communication protocol. The software was developed in C/C++ [63]. This simulation software supports up to 10 players which could be either human or automated agents (it provides a client for games with human players). The communication protocol between clients and server is based on the ACPC competition protocol (see Section 3.8.3), so the developed agents are ready to compete there. Before starting the simulation, some game options can be defined, such as chip stacks, blind value, log file name, etc. The created log file stores information about bets and how much money each player wins/loses in each game. Figure 19 – LIACC’s Texas Hold’em Simulator. Chapter 3 – Literature Review 74 the strategy of a human player because they might stimulate overconfidence, which can result in careless play [71]. 3.11 Summary In this chapter the current most relevant methodologies for the creation of Poker agents were presented and discussed. Some tools to support agent’s development were also presented as well as some expert knowledge notions and information sources. This chapter serves as support for the rest of the document and is referenced throughout the document when necessary. 75 Chapter 4 Simulation and Tools This chapter describes the general architecture of the simulation systems and tools developed to support Computer Poker research. Three different systems were developed: one simulation system that is used to test Poker agents before entering competitions or playing online, which provides several features that facilitate their assessment; a Poker description language which allows for describing sets of rules to define customized Poker games – allowing future contributions in the domain of general game playing and finally a Poker Bot system which allows for software agents to play online without human players knowing that they are actually playing against an agent, which reduces the psychological impact on humans that participated on some of the tests described in Chapter 7. 4.1 LIACC Poker Simulator New Computer Poker developments are usually made through the implementation of software agents. A Poker agent is software that replaces a human in the task of playing Poker, by taking decisions without any human intervention. Since playing Poker can be considered a repetitive task for a human player, the development of software agents not only allows progresses in computer science (as explained in Chapter 2) but also has potential commercial value to professional Poker players. If they were able to create agents in their image, they could be rewarded for their effective know-how of the Chapter 4 – Simulation and Tools 76 game and not by their physical endurance or patience. This is true, because most lucrative players are usually the ones that play more carefully and more games. The challenge in developing agents for incomplete information games resides in the fact that the decision that gives maximum utility for a given information set is not always ascertainable. In light of this, simulation systems are indispensable for accurate assessment of agents’ capabilities. Nevertheless, and as reviewed in Section 3.8, current systems do not accommodate the needs of computer poker research since they were strictly designed as training tools for human players to improve their skills (with the exception of the ACPC simulator). In order to contribute towards the improvement of computer poker research, a new version of the LIACC Poker Simulator was developed from scratch (it was not based on the one described in Section 3.8.1). This simulator considers scientifically unexplored game modes with the purpose of providing a more realistic simulation environment, where the agent must play carefully to manage its initial resources – the environment follows more closely what actually happens in online rooms at popular casinos. Several other features were introduced in the simulated environment to speed-up the simulator, namely the inclusion of table seat permutation [28], which reduces the variance of the results, requiring therefore much less iterations to properly validate an agent. An evolutionary simulation feature was also included so as to provide support for the improvement of adaptive strategies. The simulator has built-in odds calculation, an agent development API, other platform agents and several variants support and an agent classifier with realistic game indicators including exploitability estimation. Another important aspect of the new system is the consideration of bankroll 29 management – a key concept considered essential by professionals for proper game play. The importance of bankroll management can be explained by the gamblers ruin theorem [72]. This theorem states that even if players use a strategy that has positive expected value 30 , they will still be very likely to be bankrupt if they raise the stakes 31 when they win but do not lower them when they lose. 29 Bankroll – amount of money that a given player reserved for playing Poker. 30 Expected value – average amount of money won per play. Chapter 4 – Simulation and Tools 77 4.1.1 Goals In order to overcome the limitations found in previously developed Poker simulators, a new simulator has been created which aims to integrate the most important features present in other simulators with new features that will certainly lead Computer Poker research into new directions. The requirements of the new simulation system are:  An expandable architecture to support the creation of agents or the introduction of game variants. This includes an agent development API.  New game modes such as ring, which allow researchers to explore the paradigm of bankroll management.  Evolutionary simulation of Poker games, which encourages studies about strategy evolution through the principle of natural selection. This feature is not known to be natively supported by any Poker simulator.  A set of validation tools that allow for a quick and precise assessment of the agent capabilities to predict their performance in different real-life like environments. 4.1.2 Agent Modelling The simulation system described in this thesis uses a multi-agent architecture where an agent represents a Poker player. Many types of agents were created for this simulation platform, each one of them represented in the code by a class. The way each class relates to others is depicted in the UML class diagram of Figure 25. Poker Agent – it is an abstract class based on the Meerkat API [73] that represents any agent in the system. The class contains a set of abstract methods that represent the events that each agent has to answer to during the simulation. Thus, to create an agent that works in this system it is necessary to extend this class. Agents must implement a set of methods corresponding to events of the game:  pocketCards(Card[], Seat) – occurs when the agent receives its pocket cards. 31 Stake – amount of betted money per game. Chapter 4 – Simulation and Tools 78  observeAction(GameInfo) – the main routine of the agent. It is called when the agent is requested to perform an action.  actionEvent(Seat, Action) – A player in a given seat has performed an action.  winEvent(Seat, Amount, Card[]) – A player in a given seat has won an amount of chips with a given hand.  showdownEvent(Seat, Card[]) – player in a given seat has shown his cards.  gameOverEvent() – the current game is now over. Figure 25 – Poker Agents class model. HumanAgent – this agent extends the class PokerAgent and redirects the game events to a graphical user interface (GUI). This GUI is controlled by a human player. Thus, this class represents a form of interaction between human and artificial players. PGDLAgent – this agent extends the class PokerAgent and allows for integrating agents developed with the PGDL System. This agent requires the PGDL Translator which is a parser for PGDL documents. The specifications of the PGDL System are described in Section 4.2. class Class Mo... PokerAgent HumanAgent SocketAgent Translator MeerkatTranslator AAAITranslator «interface» IEvolutionary GUI PGDLTranslator PGDLAgent *1 1 1 Chapter 4 – Simulation and Tools 79 SocketAgent – the socket agent is responsible for communicating with external agents developed for other simulation platforms. This way, any external agent from Poker Academy [73] or AAAI Server [28] can be used in this simulator without need of recoding, using the new PokerAgent class. The communication process is demonstrated in Figure 26. When a SocketAgent receives a request, it chooses the correct translator and then sends a translated request via sockets to an external application that is linked to the external agent. The external agent then sends the response all the way back to the SocketAgent and then the SocketAgent plays accordingly. Game SocketAgent Choose Translator Translate Request External Agent External Socket Application Request Response Response Figure 26 – Communication between the Socket Agent and the External agent. IEvolutionary – this optional interface adds three methods to any class that extends from PokerAgent. These methods allow the agent to participate in evolutionary simulations. The methods of this interface are the following:  ReproduceAsexually – this method should return a new child agent created by the current one, with upgraded parent features;  ReproduceSexually – this method should return a new agent created by crossing characteristics from both this agent and another one;  Fitness – this method returns a number that measures the level of adaptation of the agent to the current environment. The fitness could be for instance the average expected value against all opponents. 4.1.3 Simulation System Architecture The architecture of the simulator is depicted in Figure 27. The simulator was implemented in JAVA to maximize the compatibility with several systems. The simulator is composed of the following components: Chapter 4 – Simulation and Tools 80  Hand Rank Server – a server that is used to calculate the rank of the Poker hands based on the algorithms described in Chapter 5;  Simulation Server/Poker Simulation Library – the application that is responsible for simulating Poker games;  Logging database – all agent moves are registered in a database for future profiling and result analysis;  Poker Agent – this entity represents an abstract Poker agent;  Poker Library – definition of general Poker data structures;  Poker Statistics Library – calculates statistical indicators and thus validates agents;  Poker GUI – user-friendly GUI to allow humans to play against the agents. Figure 27 – Poker Simulation System Architecture. 4.1.3.1 Hand Rank Server The hand rank server is a process that runs concurrently with the simulation server and that evaluates Poker hands for all agents. This was created to save memory since the fastest hand evaluating algorithm – TwoPlusTwo Evaluator [74] – must load a 130 MB Chapter 4 – Simulation and Tools 81 table. If each agent were to load the table individually it would be problematic in terms of memory usage, especially in the evolutionary simulation module where thousands of agents might be needed. The hand ranking server uses a simple TCP communication protocol to provide different measures that evaluate the chance of winning: hand rank; hand strength; hand potential; effective hand strength and Chen formula. Table 14 presents the commands that can be sent to the server (<Hand> is a string composed of 5 to 7 cards like ‘AsAd7s4d2c’). Already computed results can be optionally saved by the hand ranking server in a private database in order to speed up future requests. Precomputed results consider hand isomorphisms, since that for instance, asking the Hand Strength for A♣A♥ is the same as asking for A♦A♠. Table 14 – Hand Ranking Server Commands. Command Description RANK <Hand> Retrieves the rank of the hand. HS <Hand> <NO> Retrieves the hand’s strength. <NO> = remaining adversaries. HP <Hand> <NO> Retrieves the hand’s potential. EHS <Hand> <NO> Retrieves the effective hand strength. CHEN <Card> <Card> Retrieves the relative value of a hand with 2 cards. ARS <Hand> <NO> Retrieves the effective hand strength approximated using the Average Rank Strength tables (see Chapter 5) 4.1.3.2 Logging Database The simulator has a database that contains records of all moves made by registered players, if the logging option is set. Figure 28 presents the class model of the database that was subsequently converted to a relational database model. The database uses a data warehouse model which will help researchers to process the raw data. This produces some intentional redundancy in the data, namely the link between the Player and the Game classes that can be used to facilitate game analysis, reporting and data mining. The model is composed by the following classes: Chapter 4 – Simulation and Tools 82  Action – represents an action in a given game performed by a player. This class represents the star table and thereby a key aspect of the simulator database. An action presents the full state of the game table when it took place, instead of only containing the action type and the value;  Game – represents a game which is a set of actions;  Player – represents a registered player in the game;  Simulation – represents a simulation run on a date and time. It is a set of consecutive games;  Room – some simulation modes require the concept of room/table i.e. the occurrence of games in parallel in the same simulation. Figure 28 – Game moves database class model. The used format is also helpful for case based reasoning agents, because of the presence of redundancy in the action table that aids the computation of approximate information sets [75]. 4.1.3.3 Poker Simulation Module (Poker Simulation Library) This module is responsible for performing the simulation itself. When the simulation starts the user will be asked which players will be part of the game, which simulation Chapter 4 – Simulation and Tools 83 mode to use and which Poker rules. The class diagram in Figure 29 shows the entity structure of the simulation module. The existence of simulation modes is one of the innovative aspects of the system and five different modes were considered.  Simple Tournament – a simple tournament is a set of games that only ends when only one player remains. This kind of simulation allows testing the capabilities of the agent to manage its cash and the blind increase in order to win the tournament and avoid the gamblers ruin theorem [72].  Full Tournament – this mode is similar to a simple tournament but with several gaming tables.  Cash Games – the common type of simulation that is used to validate Poker Agents. It consists of a finite set of games with static blinds and player money reset at the beginning of each game. To reduce the variance of the results, table seat permutations is used – for each game positions are switch and the same cards are dealt, so everyone has equal chances. This type of simulation allows players to be tested on the long run, always on equal footing.  Ring Games – this mode is similar to what happens in online casinos. The agent starts with a given amount of chips and must manage it in order to survive. In addition, the agent should choose the table that contains opponents that are more susceptible to its strategy and tables with blinds that do not present a risk of quickly losing all cash.  Evolutionary Cash Games – this mode is similar to cash games simulation. However, in this mode, from time to time, natural selection is applied. This means that the agents with less fitness will be discarded and the other agents will reproduce, creating child agents that contain characteristics of both parents. Chapter 4 – Simulation and Tools 90 their betting structure, the number of cards in the deck, the way the winner is determined, among other rules. These features represent by themselves unique challenges in Poker agent development. However, to the best of the author’s knowledge there is not a single unified description model that allows for game playing agents to be tested across different Poker variants inexpensively. This is rather important when developing new Poker playing agents for two main reasons:  Each poker variant has unique characteristics in its rules that assess different components of the agents’ strategies. If one develops an agent under a representative formal model of Poker rules, one can more easily adapt and test the agent in new environments thus improving the overall agent’s capacity and robustness in game playing, allowing it to have a much more complete strategy. The goal of this approach is to answer to even more research questions when developing Poker game playing agents.  Interoperability between game playing agents. In fact, nowadays, most Computer Poker researchers use different technologies to develop their game playing agents, which makes it difficult to test new approaches against previously developed ones. Some simulation systems try to solve this, like [22], [77] but they only provide the API and not the communication protocol. Agents can also be assessed in the ACPC competition by AAAI [28] but its benchmark server is only available for people that participated in the last year competition. A unique rule and communication representation model would certainly allow for more proper agent assessment, while maintaining the developers’ preferences regarding technology. For these reasons we propose a new Game Description Language (GDL) for Poker games –Poker Game Description Language (PGDL) – was developed based on XML. The goal of a GDL is to describe the state of a game as a series of facts and the game mechanics as series of logical rules. GDL’s are typically used by General Game-Playing Chapter 4 – Simulation and Tools 91 Systems (GGPS) as input. GGPS are systems that are capable of recognizing a formal description of a game and play the game effectively without human intervention, such as Zillions of Games 32 . PGDL, unlike other incomplete information GDLs, is uniquely focused on Poker agent development and testing. Therefore, PGDL was developed to only identify the key concepts of Poker games rules in order to facilitate the definition of known or nonexistent Poker variants by users with Poker domain knowledge. The reason behind the creation of a Poker specific GDL is to balance the definition and implementation time of a generic Poker playing agent. The usage of a more generic GDL would hinder the development because of its lower level nature, which would make simple strategies really hard to understand and implement. With a Poker specific GDL one sacrifices the agent’s capacity to play other games but agents’ strategies will surely benefit of the extra domain knowledge available. To support the creation and assessment of PGDL entities, a general game playing system was also developed. This system allows users to not only play the PGDL described game against basic agents but also provides a proof of concept API that allows for game playing agent development. The development of the PGDL simulation/game playing system was divided in the following stages:  Identification of Poker base rules with emphasis on the differences between its variants.  Conception of a XML based language capable of specifying the identified rule differences and the creation of PGDL instances.  Creation of a XML-Schema that validates PGDL instances.  Construction of a system that recognizes the XML language (in Prolog) and that is capable of generating the specified game.  Construction of an application (PGDL Builder) that supports the creation of PGDL documents. 32 http://www.zillions-of-games.com/ Chapter 4 – Simulation and Tools 92  Development of a generic game playing agent that can play competently any variant described by PGDL. 4.2.1 Poker Variants Poker is a group of similar games with the same base rule set. The denomination for a specific set of rules is called variant. The variants of Poker can be divided in 3 groups:  Draw Poker – each player receives a set of private cards that only he/she can see and can improve the hand by card replacement. This group of games is usually played by casual players. Examples of Poker games that are part of this group are Five-Card Draw, Badugi and Kansas City Lowball;  Stud Poker – each player receives a set of exposed cards (cards that belong to the player but everybody at the table can see) and a set of pocket cards that only the player can see, in multiple betting rounds. Six- Card Stud, Razz, Eight-or-better and high-low stud are variations of Stud Poker;  Community Card Poker – games in which each player receives a variable number of private cards to form an incomplete hand, which is completed by combining private cards with public shared cards (exposed to every player). The most popular poker variant nowadays, Texas Hold'em, belongs to this group as well as Omaha Hold'em and Manila. Poker variants rules differ on the following features:  Number of betting rounds – for instance, Texas Hold'em has 4 betting rounds and Five-card draw has 3 betting rounds.  Number of private and public cards (and the way they are dealt) – in Texas Hold'em 5 public cards are dealt and each player receives 2 private cards, while in Cincinnati 4 community cards are dealt, one before each round of betting, and each player has 4 private cards.  Forced antes – some variants force all players to bet a certain quantity of money before the cards are dealt. This amount is called ante. Chapter 4 – Simulation and Tools 93  The betting order – there are variants such as Seven-card stud in which the first player to act is the one with the lowest exposed card and variants such as Omaha Hold'em where the first player is the one to the left of the big blind.  The maximum number of players.  Scoring – there are high-games in which the highest hand wins and lowgames where the lowest hand wins. There are also high-low split games, where the best and the worst hands split the pot.  Deck composition – there are variants that are played with only a few cards from the deck, such as Manilla (only cards above 7 with a total of 32 cards).  Existence of wild cards – special cards that can score as any card (usually Jokers).  Replacing cards – some variants, like Anaconda, allow players to pass cards between them in various ways. In other variants, like Badugi, players have the opportunity to improve their hand by discarding some cards and obtaining replacements from the dealer. There are also variants that force players to discard a fixed number of cards, without replacement.  Betting structure – Another major difference between the variants of poker is the betting structure. The structure can be limited, pot-limited and no-limit. The limit games are the ones in which there is a fixed value for each bet made by a player. In a pot-limited game no player can raise more than the size of the total pot. In these last two structures, until winning the game there can be a limited number of raises during a round. In no-limit games there are no limits on bets. Table 18 summarizes the main differences of the most popular and played Poker variants. Chapter 4 – Simulation and Tools 94 Table 18 – Differences between Poker Variants Variant #Rounds Cards #Players Number Shared Exposed Closed Wild Texas Hold’em 4 52 Yes (5) No 2 No 2 to 9 Omaha Hold’em 4 52 Yes (5) No 4 No 2 to 10 Baseball 4 52 No Yes (4) 3 3/9 2 to 8 Cincinnati 5 52 Yes (5) No 5 No 2 to 9 Five-card draw 2 52 No No 5 No 2 to 6 Anaconda 4 52 No No 7 No 2 to 7 Manilla 5 32 Yes (5) No 2 No 2 to 9 Sevencard stud 6 52 No Yes (4) 3 No 2 to 8 Kuhn 1 4 No No 1 No 2 to 3 Leduc 1 8 Yes (1) No 1 No 2 to 3 4.2.2 PGDL Language Specification In this section the structure of PGDL files is described. The PDGL format is based on XML. The format is enclosed in a hierarchical description of game rounds. The description of each game round compromises the flow of the game. There are also other elements to describe generic rules of the variant (such as the number of players) or meta-information (such as the name of the variant). Figure 33 summarizes the key components of the language by presenting the tree structure of a PGDL file. Examples of PGDL documents representing popular Poker games can be found in PGDL Documents. 4.2.2.1 Initial setup The PokerGame is the root component of PGDL which includes the name, the winning determination (High, Low or Mixed), the ante value if the game is played with or without wild cards. Chapter 4 – Simulation and Tools 95 <PokerGame name=”Leduc” wildCards=”No” winningType=”High” ante=”1” /> __________________ Language: XML Every PokerGame node must have a Players child node where the maximum and minimum number of players is defined. <Players minimum=”2” maximum=”4” /> __________________ Language: XML -name -wildCards -winningType -ante PokerGame -minimum -maximum Players Rounds -number -name -communityCardsNumber -faceUpCardsDealt -faceDownCardsDealt -blinds -forceBet Round -type BettingStructure BlindStructure -min -max DrawCards -value -direction PassCards -value DiscardCards -order -firstPlayerBetting BettingOrder -id -name -position -value Blind -value -maxNumRaises Bet -standardDeck -jokers Deck -id -name -value -suit -wild Card Figure 33 – PGDL Specification Chapter 4 – Simulation and Tools 96 4.2.2.2 Deck Poker games can be played with a standard deck (52 cards without Jokers) or with a partial deck with a given number of Jokers. <Deck standardDeck=”Yes” jokers=”0” /> __________________ Language: XML If the game is played with wild cards, any card can be used as wild (usually Jokers are used as the default wild card). The deck definition allows not only using directly a standard deck but also personalize which cards belong to the deck, with custom names. This way one can even define Poker variants with two decks for instance. For each card one has to indicate the id and name of the card, the suit, its value (any value of a standard card) and if that card is wild. This representation does not cover variants with dynamic wild cards. The example of deck for Kuhn Poker (one of the simplest versions of Poker, used mainly for research purposes). <Deck standard=”No” jokers=”0”> <Card id=”k” name=”King” value=”K” suit=”h” wild=”No” /> <Card id=”q” name=”Queen” value=”Q” suit=”h” wild=”No” /> <Card id=”j” name=”Jack” value=”J” suit=”h” wild=”No” /> </Deck> __________________ Language: XML 4.2.2.3 Rounds The Round element is the most important component of the PGDL file structure because it is associated with the game flow. It describes how the rounds will take place during the game. Each round has a round number (to control the order of rounds), a name, the number of dealt shared cards, the number of faced up and faced down cards that each player is dealt, one Boolean to control if the round must start with a bet and another one to check if the round has blinds. Chapter 4 – Simulation and Tools 97 <Round number=”1” name=”Round One” communityCardsNumber=”1” faceUpCardsDealt=”0” faceDownCardsDealt=”1” blinds=”yes” forceBet=”no”> … </Round> __________________ Language: XML Furthermore, each round has sub-components: the Betting and Blind Structure of that round, the Cards Rules and the orders of the bets. Each round must have an individual betting structure defined. The Betting Structure must be one of the three available types: Limit, No Limit and Pot Limit. Depending on the picked type, one has to indicate the maximum number of raises allowed per player and the bets’ default value. <BettingStructure type=”noLimit”> <Bet value=”1” maxNumRaises=”3” /> </BettingStructure> __________________ Language: XML Blind Structure only exists if the attribute blinds is activated (equals to ‘yes’). This element contains a non-empty set of Blind elements. A Blind is described by a name, a unique id, the value of the blind and the position of the player that will post the blind. <BlindStructure type=”noLimit”> <Blind id=”smallBlind” value=”1” name=”Small Blind” position=”nextDealer” /> </BlindStructure> __________________ Language: XML Card Rules are specified by three different elements: Draw Cards, Discard Cards and Pass Cards. Draw Cards indicates the minimum and maximum number of cards that each player can draw in a round. Discard Cards specifies the number of cards that Chapter 4 – Simulation and Tools 98 each player must discard in that round. Pass Cards defines the number of cards that each player must pass and in which direction (clockwise or counter clockwise). <DrawCards min=”0” max=”0” /> <PassCards value=”1” direction=”clockwise” /> <DiscardCards value=”1” /> __________________ Language: XML Betting Order it’s a sub-component of the Round. To specify it, it is necessary to indicate in what order that round will occur (Clockwise or Counter clockwise). The first player to act is also defined in this element. <BettingOrder order=”clockwise” firstPlayerBetting=”nextDealer” /> __________________ Language: XML 4.2.2.4 Scoring With PGDL it is also possible to customize the Poker scoring system. To customize the score we need to add the element Scoring as child of PokerGame root node. After adding it, two options are available:  Use the standard scoring (explained in Sections 2.5.2.2 and 2.5.4.1): there we just need to select the size of the hands used throughout the game (the standard value is 5) and put the element standard attribute as being true. If the Scoring element is not present in the document, the standard scoring will be used.  Use nonstandard scoring: the attribute standard must be false and the handSize must still be specified. In this case we need to have several Score child elements with the formulas (as text under the Subrank child element) to assign that particular score type. The formulas have access to the card values by using $ci where i is the index of the card (between 1 and handSize). Chapter 4 – Simulation and Tools 99 <Scoring standard="false" handSize="5"> <Score name="high card" rank="0" default="true" sort="true" > <Subrank> $c5.rank * 28561 + $c4.rank * 2197 + $c3.rank * 169 + $c2.rank * 13 + $c1.rank </Subrank> </Score> <Score name="pair" rank="1" default="false" sort="true"> <Conditions> </Conditions> <Subrank> $c5.rank == $c4.rank? $c5.rank * 100000 + $c3.rank * 169 + $c2.rank * 13 + $c1.rank: $c4.rank == $c3.rank? $c4.rank * 100000 + $c5.rank * 169 + $c2.rank * 13 + $c1.rank: $c3.rank == $c2.rank? $c3.rank * 100000 + $c5.rank * 169 + $c4.rank * 13 + $c1.rank $c2.rank * 100000 + $c5.rank * 169 + $c4.rank * 13 + $c3.rank </Subrank> </Score> <Score name="two pairs" rank="2" default="false" sort="true" > ... </Score> ... </Scoring> __________________ Language: XML 4.2.3 PGDL System The PGDL system is a set of sofware applications that contemplate the following features:  Support the creation of PGDL files through an intuitive GUI;  Generate the user-defined Poker variants from a PGDL file or through the GUI;  Allow the user to play and create a PGDL-specified Poker variant through a simple 2D game visualizer. Chapter 4 – Simulation and Tools 106 abstract_history(History,AbstractedHistory), play(AbstractedHand, AbstractedHistory, AbstractedAction), translate(AbstractedAction,Action). __________________ Language: PROLOG 4.2.3.8 Built-in agents Two pre-built agents are included in the PGDL system: a random agent and a E[HS] (expected hand strength) based agent. The random agent picks a random action for any information set, avoiding folding (forfeit) when a check action (free pass) is possible. The E[HS] agent is based on adapted E[HS] equation (just like the Poki and Loki agents, see section 3.3). The Expected Hand Strength is the probability of the current hand of a given player being the best if the game reaches a showdown with all remaining players. For a player i against a giver number of opponents n, the E[HS] is given by: 𝐸[𝐻𝑆]𝑛(𝑖)=( 𝐴ℎ𝑒𝑎𝑑(𝑖)+𝑇𝑖𝑒𝑑(𝑖) 2 𝐴ℎ𝑒𝑎𝑑(𝑖)+𝑇𝑖𝑒𝑑(𝑖)+𝐵𝑒ℎ𝑖𝑛𝑑(𝑖))𝑛 EQ15 The implemented agent uses the E[HS] value to choose the action according to Table 19. For each betting structure, the agent has a fixed probability of following each action. This agent just served for testing purposes and these values were adjusted by the author’s own experience of the game. They were adjusted several times empirically after enough manual observations were made. Table 19 – PGDL in-built agent's strategy E[HS] Value Betting Structure Limit No-Limit Fold Call Raise Fold Call Raise 10% Raise 20% Raise 50% All- In < 30% 100% 0% 0% 100% 0% 0% 0% 0% 0% 30-50% 50% 30% 20% 50% 30% 10% 3% 2% 0% 50-80% 5% 50% 45% 5% 50% 25% 10% 5% 5% 80-100% 1% 19% 80% 1% 19% 20% 15% 15% 30% Chapter 4 – Simulation and Tools 107 4.2.3.9 Graphical User Interface In order to make it easier and more intuitive for a user to specify the rules of a poker game, a GUI was developed using Microsoft C# 4.0 Windows Forms. The interface was divided in three parts: Game, Rounds and Deck. Three screenshots of each part are respectively presented in Figure 35, Figure 36 and Figure 37. The first screenshot presents the interface used to specify the Game’s general rules. In this window the user has to indicate the minimum and maximum number of players that can play the game, the way the winner is determined, the name of the game and if the game has dealer or not. In the second screenshot the interface used to define the rounds is shown. The user has the possibility to choose the name of the round, the betting structure, the betting order, the rules that involve cards, and the blind structure where he or she can add the blinds that will occur in the game and the cards dealt. Each round is defined in different tabs. In each tab it is possible to edit that round. The order of the rounds is defined by the order of the tabs in the interface. The rounds can be re-ordered through drag & drop. To specify the composition of the deck (third screenshot), the user has the possibility of choosing to use the standard deck in a checkbox. If not, the user has to select each card one by one from the list on the right. The user must also indicate if the game has wild cards or not. If it has, he or she has to indicate how many jokers will be used or indicate if a particular card is wild or not. To create the game the user has to click in the “Create Game” button. If the specification has errors the user will be notified. If not, the XML and Prolog file with the specification of the rules of the game will be created and the button to play the game in the simulator 2D visualizer (see Figure 31) will be available. Chapter 4 – Simulation and Tools 108 Figure 35 – PGDL GUI Games Module Figure 36 – PGDL GUI Rounds Module Figure 37 – PGDL GUI Deck Module 4.2.4 System validation To validate the PGDL system, several tests were performed. First several popular Poker variants were implemented to confirm that the PGDL specification was sufficient to describe them all (see examples in Appendix C). Next, we tested the E[HS] agent against the random agent to assess if it is competent enough against the most basic agent – the random agent. Finally, we tested the GUI with several users to assess if the system is user-friendly to implement Poker variants. Chapter 4 – Simulation and Tools 109 The following Poker variants were implemented successfully with the PGDL specification: No-limit / Limit Texas Hold’em, Kuhn, Leduc, Cincinnati, Five-card draw, Anaconda, Manilla and Seven-card stud. To check if the GUI is user-friendly and intuitive, usability tests were performed (Table 20). The test consisted of users (16 subjects in our tests, with at least some previous knowledge about Poker) implementing two simple variants of poker: Kuhn Poker (2 times, one with standard deck and one with 3 card deck) and Leduc Hold’em Poker. All subjects were able to complete the task with an average time of 3:42 minutes (with our without help). By analysing the results, the time spent by the users doing the tests was very similar (standard deviation of 76 seconds). Table 20 – PGDL usability tests Needed time (secs) Main issues Kuhn Leduc Kuhn Leduc 150 120 Miss game name Miss game name 420 270 - Community Cards vs Face Down Cards 150 150 - - 145 180 Betting structure Add rounds 210 240 Bet values Community Cards vs Face Down Cards 200 150 Betting structure - 160 210 Max raises Community Cards vs Face Down Cards 174 240 - Deck 350 412 Deck Deck 253 300 Nomenclature Betting Structure 184 266 Number of cards - 243 230 Missed blinds Rounds 240 296 - Rounds 122 116 - Rounds 230 245 Miss game name - Avg: ~3:35 min Avg: ~3:48 min Total Avg: 3:42 min The biggest problems faced in the GUI usage were related to the understanding of the Poker specific nomenclature, even for users that said that they played Poker regularly. This is due to the fact of most Poker variants being unknown even for regular Chapter 4 – Simulation and Tools 110 Poker players (the most played are Limit and No Limit versions of Texas Hold’em and Omaha Hold’em). 4.2.5 Summary PGDL is a generic system for creating poker variants. A XML dialect was defined to represent the specification of most known Poker variant rules. From that specification, the developed system can generate a playable implementation of the game in Prolog. All of the most popular Poker variants are implementable within our system, proving its usefulness. The results of tests showed that the interface is user-friendly, well designed and is easy to use, as shown by the similar time to specify the same poker variants. This approach can enhance not only the easy implementation of any poker variant but also the creation of new variants. For future work, the system could benefit from a general implementation of the Counterfactual Regret Minimization algorithm in order to generate Nash Equilibrium strategies for any specified variant thus providing very competitive agents with the system. The biggest difficulty of that implementation would be the creation of a generic abstraction system for any Poker variant (see Chapter 5 for some pointers on this). 4.3 Poker Bot 4.3.1 Goals A Poker Bot is a software application to serve as an interface between a Poker Software Agent and a Poker Online Casino. This kind of software enables developers to have their agents playing in real time online environments, without their adversaries knowing that an agent is playing – this is especially interesting because previous assessments of having Poker agents playing against humans, were with the human players’ knowledge that they were playing against a bot. This is very important because this way the human players will be playing with their regular strategies without modifying or adapting them to play against a bot. The development of the LIACC Bot was divided in several steps. Due to difficulty of generalization and development of this kind of applications, the recognition only works on No-Limit Texas Hold’em Games. To support its development, OpenCV was Chapter 4 – Simulation and Tools 111 used as well alongside a library to wrap it for C#. As explained in Section 3.9, currently Online Casinos do not support officially the use of bots, and they do not provide APIs to do it. Moreover, most of them also actually try to stop bots from playing in their software. For this reason, to build a bot several steps are needed to overcome this reality:  Since there is no API, the bot must interact with the regular user interface. Therefore it needs to apply image processing to the interface window in order to extract the information about the current state of the game.  The bot must control the mouse and the keyboard to be able to click on the interface controls.  Some Casinos actually record the interaction between the user and the client by taking screenshots or recording small videos. For this reason, the mouse movement must be similar to the way humans use it.  Casino software usually scans for the user’s pc to try to find suspect applications that maybe bots. Therefore, the bot must run in stealth mode in order to avoid detection i.e. it must disguise itself as being another application (in this case a calculator). The development of the bot was divided in the following steps:  Card recognition  Chips and bet amounts detection  Human like interaction with realistic mouse movements  Avoid detection: pressing randomly the interface buttons in random positions, random waiting time between plays...  Deal with Casino client software updates that change the position of interface buttons, colours…  Integrate the bot with the agent API described in Section 4.1 Chapter 4 – Simulation and Tools 112 4.3.2 Card Recognition The first problem to solve to address in card recognition is to identify the regions of the application interface where the cards of the player and the community cards were placed. The first approach was to use an edge detection algorithm, using the cards white background and their contours. However, due to random card occlusions on the application interface (sometimes due to animations) and different displaying style, this method did not have good results – Figure 38 shows an example of this problem where one of the community cards had the chips overlapping it which made the edge detection algorithm to fail. The algorithm that detects the card regions is illustrated on Figure 39. Figure 38 – Card position recognition – the chips occluded the third card Figure 39 – Detecting cards regions algorithm Chapter 4 – Simulation and Tools 113 Due to the method’s poor success rate (it failed about 25% of the times), it was decided to just use configurable regions with fixed positions, that is, the user of the bot has to configure it to select the desirable positions (select the square regions of the positions of the 20 player’s cards and the positions of the 2 player’s cards). This last method is error free (100% accuracy) but has the disadvantage of requiring the user to update the card’s positions when the casino software is updated. After getting the cards position, the following step is to guess which card it is. For this, the approach was template matching, i.e. having a classifier trained with all card templates in order to match the new ones that appear. Only the top left part of the card region was considered, as demonstrated in Figure 40. The reason behind this is that the selected region contains enough information for the card recognition (rank and suit). Using the whole card would not only take much more time (since the image has more pixels) but would also cause more errors. The detection of the top-left region is also by its relative width (27.35%), relative height (43.26%), relative starting position (6.89%, 8.28%) so only that part of the image had to be selected. Figure 40 – Cutting the card for recognition. After cutting the interest region we only have to compare it with all stored templates as demonstrated in Figure 41. One important thing to add is that the templates are grouped by colour density (red and black). This helps in the suit detection because, for instance, the spades and the hearts symbol is somewhat similar. If no template is matched, another screenshot is taken and the process starts all over. If that fails again, two options can occur:  a random card is considered  the card that leads to the worst score possible is considered Chapter 4 – Simulation and Tools 114 Figure 41 – Detecting the card template 4.3.2.1 Tests To test this approach 200 screenshots were taken with two different resolutions and the algorithm was run on every screenshot. The detection rates presented in Table 21 were very good. The suit recognition is not presented on the table because when the card rank was correctly identified, the suit was also. All algorithm responses were manually verified and double-checked. The detection rates on the lower resolution were 100% correct. However, the detection on the higher resolution failed sometimes. One possible reason behind this is that the templates were made from screenshots at the lower resolution which means that the OpenCV template matching algorithm has to resize the sliced images provided. Since that the sliced cards resolution is very low (about 12 x 32 pixels), that could be the reason why this happens. Nevertheless the creation of new templates solved the problem. Chapter 4 – Simulation and Tools 115 Table 21 – Card detection rates Card Image Resolution 1016×728 1158×826 Ace 100% 93,9% 2 100% 86,7% 3 100% 97,5% 4 100% 97,7% 5 100% 86,2% 6 100% 95,0% 7 100% 100,0% 8 100% 92,6% 9 100% 97,6% Ten 100% 90,9% Jack 100% 100,0% Queen 100% 96,6% King 100% 95,9% Average 100% 95,1% 4.3.3 Game State Recognition (dealer button position) Another important part of the interface recognition is the game state recognition. Without it, the agent would be playing blind. First, the current round of the game is identified. This step is rather easy to do because the positions of the community cards are pre-established, like it was referred in the last section. By that, we just have to detect if a card is there or not, by detecting the density of the white color. If we have no cards then we are at the Pre-Flop round, if we have 3 we are at Flop, 4 at Turn and 5 at River. This information is double checked with the bot knowledge. The bot itself reads and registers every play, so it knows the current state of the game just by the actions. This method is also used to detect the end of game, by detecting a new Pre-Flop round. Besides the round, one very important asset is to detect the position of the dealer button (see Figure 42). The approach to detect the dealer button is similar to Chapter 4 – Simulation and Tools 122 Figure 49 – Poker Bot user interface 4.4 Summary This chapter described the tools (and their evaluation) that were developed within this thesis work. They were built to support not only this thesis’s work but also enhance future developments in the Computer Poker and stochastic incomplete information games domain. 123 Chapter 5 Abstraction Techniques This chapter describes the improvement of Poker related abstraction techniques that lead to the creation of two new methodologies – Average Rank Strength (ARS) – which is an improvement of the Effective Hand Strength formula and Reduced Game Utility Abstraction (RGU) – which is a more generic method that can be applied to other games (in Poker particularly, it does not require the Hand Strength). 5.1 Definition Abstraction is the process of reducing the game search space by combining and grouping knowledge. In more practical terms it means having a group of decision points or conditions where we decide to act the same way when different, although similar game conditions are in place. One good example of this is to imagine defining a full rule based strategy for Texas Hold’em Poker (see Section 3.2.1). If no abstraction was done, it would be impossible to do so. But by saying something like “go all-in when you have two pairs or more”, we are already defining an action for a lot of possible hands – which is something that humans do naturally by instinct. In terms of the game of Poker (depending on the game’s rules) three types of abstraction are usually considered:  Card abstraction: for software agents, the cards are usually grouped into very small groups – this is commonly known as bucketing. For instance, Chapter 5 – Abstraction 124 the first approaches of Nash-Equilibrium based agents grouped all card strength combinations into 20 different buckets (different bucket sets were used for each game round), which is very different than the numerous amount of possible scores that exist (however, even with 20 buckets, the length of the search trees were still enormous). Most common abstraction approaches in the last years are based on the Hand Strength Formula (see Section 3.5.1) which has a big problem – it is a simulation method that considers that the probability of playing any hand is equal.  History abstraction: this consists on abstracting betting sequences. A betting sequence is an ordered list of actions that can lead to a stage in the game. E.g. ‘ccr’ means that the first player called, then the player next to it called as well and the next one raised. Betting sequences always lead to the same state, round and acting player – only the current conditions (private and community cards) may change the action that should be selected. One possible way of combining betting sequences would be to replace previous rounds plays by the pot value (like any abstraction, this introduces an error – the way a certain amount of the pot is reached might reveal details about the opponents holdings).  Betting amounts abstraction: abstracting the bet amounts is only applicable to No-Limit versions of Poker, where the value of a raise action is continuous. If we try, for instance, to build all game sequences for a No- Limit game, that would be unfeasible. So, raise action values must be grouped. In Chapter 7 the amount of raises extracted from some game logs could give a hint for betting amounts abstraction, by considering clustering the relative betting amounts into same sized groups. In this thesis we only address card abstraction, by developing two new techniques. Chapter 5 – Abstraction 125 5.2 Improving Current Algorithms In order to improve abstraction techniques for Poker, the first step was to try to improve already existing methodologies. Most methodologies are based on hand rank and odds comparators (see Sections 3.4 and 3.5). First the hand rank evaluators were compared in order to check which one should be used. Hand rank evaluators are very important because they transform the hand rank into a number, being therefore much easier to deal with it. One characteristic of hand rank evaluators is that the higher the number is the higher is the rank. Hand rank evaluators also distinguish between subranks within a rank group (e.g. all possible pairs and their combinations with the several card kickers). 5.2.1 Hand Rank Benchmark In order to determine the fastest hand rank evaluator, a benchmark test was performed. To provide a fair assessment, the test consisted of ranking a pre-computed sequence of all possible combinations of 5 card hands (2,598,960 hands). The tests were performed 1000 times each on an Intel I7-3940XM CPU (8 cores) with or without parallelization. The set of hands was tested with each described hand rank evaluator(s) and the results are presented in Table 24. Table 24 – Hand rank function benchmark Hand rank program Average elapsed time for 1.000 trials in milliseconds Non parallel Parallel Cactus Kev 807.13 591.22 Paul Senzee 403.04 195.44 Pokersource 2,520.44 980.14 TwoPlusTwo 91.09 37.98 From the tests, it is possible to verify that the TwoPlusTwo Evaluator is by far the fastest hand rank evaluator, performing the same calculations in at least roughly a quarter of the time needed by the other evaluators. After testing and using each evaluator, we also identified the main advantages and disadvantages. Below follows a table (Table 25) summing up the qualitative features of each evaluator, which demonstrate as well that the TwoPlusTwo evaluator is not only the fastest evaluator Chapter 5 – Abstraction 126 there is, but also the one with the best features (except from memory, but in today’s computers 80Mb of ram is not a very serious limitation). Table 25 – Hand rank comparison Memory Speed Usage Hand’s size 5 6 7 Cactus < 1Mb ++ Normal × Paul 266Mb ++ Normal × × Pokersource n/a + Hard × × × TwoPlusTwo 80Mb +++ Easy × × × 5.2.2 Hand Odds improvement and benchmark While hand ranks are important, they are not directly used by abstraction techniques since there is not necessarily a clear inter-association between the produced integers by the hand rank functions (they are more used by simulators to assess the game’s winning agent). However hand rankers are essential to produce the hand odds algorithms like Hand Strength or the most currently used: Expected Hand Strength E[HS] (see EQ17 or EQ15 for the simple form). 𝐸[𝐻𝑆]𝑛(𝑃𝑖,𝑆)={𝐻𝑆𝑛(𝑃𝑖,𝑆+𝑥):𝑥∈[D]5−|𝑆|∧𝑥⊄(𝑃𝑖∪𝑆)} EQ17 The expected hand strength (E[HS]n) [79], also known as equity, is the probability of the current hand being the best if the game reaches a showdown, with all remaining players. It consists of enumerating all possible hands that an opponent can have and all possible unveiled shared cards. This methodology is very similar to the Hand Strength (HS), but it is far more accurate because it considers the score value that can be effectively used at the end of the game. However, the number of iterations needed by E[HS]n is much higher than for HS, making it a much slower option. This method can be improved by using Monte Carlo. To do that, EQ17 was changed to sample possible board and opponent cards instead of enumerating them all, so instead of x belonging to all combinations of size 5 of the deck (with exception to the player’s private cards), x belongs to a subset of that superset with quadratic random sampling (with higher probably for higher cards). The obtained results are on Table 26. Chapter 5 – Abstraction 127 Table 26 – Sampling board cards in E[HS] algorithm Number of Samples Number of iterations Error All samples ≈3.17×1011 0 10000 105×𝑃45,4 ~0.0005 1000 104×𝑃45,4 ~0.001 100 103×𝑃45,4 ~0.012 10 102×𝑃45,4 ~0.151 As it can be seen, the best number of samples to use in a Monte Carlo sampled version of E[HS] is 1000, because it already produces a very small error for the small number of iterations. The decrease of the error rate per number of iterations follows approximately a Chi-Square distribution (with 1 degree of freedom: k = 1, also see EQ18). Around the 1,000 iterations point the error decrease rate is so small, that it is not worth to increase the number of iterations. 𝑓(𝑥)=𝑥𝑘2−1×𝑒−𝑥2 2𝑘2Γ(𝑘2) EQ18 5.2.3 Average Rank Strength In order to solve the efficiency problems of the previously presented methods, we introduce a new method called Average Rank Strength (ARS). This method consists of using the hand rank to estimate the future outcome of the match, without having to generate all card combinations. This is simply done by storing the average value of the Odds function in a look-up table, indexed by rank. Since there are only 7462 possible ranks, it is completely feasible to store pre-computed average future ranks in memory. Storing the Odds values for each rank is not enough, since it is necessary to identify the player’s private cards. To better illustrate this, let us analyse the following hand: A♣ A♦ A♥ K♥ K♠. This hand always scores a Full House regardless of which two cards belong to the player. However, depending on which two cards belong to the player, the odds can be different: if the player has the two Kings, an opponent could have the remaining Ace, thus being ahead of the player; if the player has two Aces, then victory is assured. Chapter 5 – Abstraction 128 This problem was addressed by introducing a second dimension in the look-up table – the pocket hands id. The pocket hands id is a unique number for a pair of cards, which takes into consideration game isomorphisms. The total number of possible starting pair ids is 169 (this is the maximum number of possible combinations of two private cards with different meaning, considering the suit rotation: e.g. A♣ A♦ is the same as A♦ A♥). To quickly obtain the pair id, the ids are stored in a 52 × 52 precomputed table named pairs. Thus, the id of a pair P = {Card1, Card2} is given by pairs[Card1][Card2]. Giving the described look-up table structure, its total size is 7462 × 169 × 8 bytes ≈ 9.62 MB, where 7462 is the number of possible card ranks, 169 the number of unique pairs and 8 the size of a double (in most machines). This approach was tested against the approximate computation of the E[HS]n, since it is the most common used technique. Moreover the TwoPlusTwo rank table was also needed to compute the index to search in the Average Rank Strength lookup table (since it is the fastest rank evaluator). Since TwoPlusTwo returns an index between 0 and 36874 with sparse values (only about 20% of the table values are used), an auxiliary table was created (similar to the pairs table) to convert the TwoPlusTwo rank to an index between 0 and 7461. This way we reduced each table’s size from 50 MB to the 9.62 MB. The ARS value for a given position is given by EQ19, where n is the number of opponents, I is the index of the pair of cards, R is the integer value of the rank. The ARS lookup process and architecture is summarized in Figure 50. Both x and y are card hand iterators in this equation: they iterate respectively over all combinations of 2 and 5 cards. x1, and x2 are respectively the first and the second card of the hand x. 𝐴𝑅𝑆𝑛(𝐼,𝑅)={ 𝐸[𝐻𝑆]𝑛(𝑥,𝑦):𝑥𝜖[𝐷]2∧𝑦𝜖[𝐷]5∧ 𝑥⊄𝑦∧𝑅𝑎𝑛𝑘(𝑥,𝑦)=𝑅∧𝑝𝑎𝑖𝑟𝑠[𝑥1][𝑥2]=𝐼}                                                           EQ19 Since this method introduces an error, we included in our architecture the possibility of using a stochastic response. The look-up error δn for ARS is given by: Chapter 5 – Abstraction 129 𝛿𝑛(𝑃𝑖,𝑆)=|𝐸[𝐻𝑆]𝑛(𝑃𝑖,𝑆)−𝐴𝑅𝑆𝑛(𝑝𝑎𝑖𝑟𝑠[𝑃𝑖1][𝑃𝑖2],𝑟𝑎𝑛𝑘(𝑃𝑖,𝑆))| EQ20 The maximum δn,max and minimum δn,min look-up errors for each ARS position can then be stored in two additional look-up tables of the same size. This way, when consulting the ARS table we sum-up a random variable in the interval [δn,min , δn,max] to the value stored in the table. Pairs Table (52 X 52 entries) 11KB TwoPlusTwo Table 80MB Rank Hand Φi ⋃ Ω TPT Index Conversion Table TPT Index (from 0 to 36874) Average Rank Strength Table 9,62 MB Pairs Index (from 0 to 169) Hand Value Round Error Intervals Table 9,62 MB × Number of Intervals Converted Index (from 0 to 7461) Φi ⋃ Ω Φi Figure 50 – ARS tables lookup process and architecture. Chapter 5 – Abstraction 130 It is also possible to increase the precision of this methodology by having more than 2 additional look-up tables. These look-up tables can be used to store the discretized intervals of the error’s distribution by setting them with percentile medians. 5.2.3.1 Results In order to determine the speed-up factor of the new method against the E[HS] method, a benchmark test was performed. The test consisted of ranking a precomputed sequence of 1,000,000 hands with 7 cards each. The tests were performed 1000 times each on an Intel I7-3940XM CPU (8 cores) and are presented on Table 27. The obtained standard deviation from the mean of the presented values is negligible in all cases. The results described in Table 27 did not take into account the δn correction tables. Table 27 – Benchmarking Average Rank Strength Hand rank program Round Average elapsed time for 1000 trials in seconds Non parallel Parallel (8 cores) Expected Hand Strength (E[HS]) Flop 387.71 108.90 Turn 309.18 90.19 River 263.79 75.98 Average Rank Strength (ARS) Flop 0.32 0.06 Turn 0.41 0.09 River 0.43 0.10 Speedup factor Flop 1211.59 1815.00 Turn 754.10 1002.11 River 613.47 759.8 Our benchmark test demonstrates very promising results, with an average speed-up of 1,044.24 (about 1,000 times faster). Poker agent strategies that use abstraction based E[HS] can benefit from this speed improvement. Methods such as CFR [23] need to perform these calculations billions of times. 5.2.3.2 Error analysis We also analyzed the difference between this method and the hand strength method. The heat maps for E[HS] and ARS at the River round and against 1 opponent are in Figure 51. Chapter 5 – Abstraction 131 This approach not only provides a much faster response to queries – about three orders of magnitude faster – but also it does so with negligible error, as can be seen from the heat maps in Figure 51. At the River, the average absolute difference between the two methods is 0.011, the maximum difference found was 0.062 and the summed squared error is 0.039. The use of a stochastic response with the δn correction tables also improved these results. The average maximum error found was 0.02 and the average is less than 0.001, with a speed-up reduction of only about 8%. Figure 51 – Average rank strength VS E[HS] heat maps at River 2c 2h 3c 3h 4c 4h 5c 5h 6c 6h 7c 7h 8c 8h 9c 9h Tc Th Jc Jh Qc Qh Kc Kh Ac Ah 2c 2s 3h 4d 5c 5s 6h 7d 8c 8s 9h Td Jc Js Qh Kd Ac As Average Rank Strength 2c 2s 3h 4d 5c 5s 6h 7d 8c 8s 9h Td Jc Js Qh Kd Ac As 2c 2s 3h 4d 5c 5s 6h 7d 8c 8s 9h Td Jc Js Qh Kd Ac As E[HS] 0-0,2 0,2-0,4 0,4-0,6 0,6-0,8 0,8-1