Post on 17-Oct-2021
transcript
TicTacToe DocumentationRelease 0.1
deterralba
December 18, 2015
Contents
1 Forewords 1
2 Let’s go to the point! 3
3 Contents: 53.1 The main module, where you should start! . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 53.2 List of all the packages . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 63.3 The trash module, just a random test file . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13
4 Indices and tables 15
Python Module Index 17
i
ii
CHAPTER 1
Forewords
Dear reader,
This is the cherish documentation of my TicTacToe program. I made this program with love and patience to learn howthe use of a bunch of new technologies.
For instance, the doc you are currently reading is compiled with sphinx, a very powerful and noob-unfriendly software.
1
TicTacToe Documentation, Release 0.1
2 Chapter 1. Forewords
CHAPTER 2
Let’s go to the point!
If you are in a hurry, please go the the main module page. Everything is explained there if you just want to run aquick simulation.
3
TicTacToe Documentation, Release 0.1
4 Chapter 2. Let’s go to the point!
CHAPTER 3
Contents:
The project is divided in several packages. They are all called from the main module located at the root of the project.
The core package provides... the core classes of the program, which represent a game, the board, the manager of asimulation, basic players etc.
The players package contains more sophisticated players that have either simple strategies or are able to learn fromthe past game! It is in this package that you should create your own players.
The misc package (aka miscellaneous) contains other useful packages, for instance the one used to plot graphs ofsimulations’ results.
3.1 The main module, where you should start!
This is the entry point of the program, the first module executed.
Here you can parameter all the program, no need to read other source files.
3.1.1 How it works!
There are 6 main steps:
1. importation of the useful packages
2. instantiation if the main objects (Game, BoardAndRules and Simulation)
3. instantiation if the players
4. settings of the simulation parameters (choice of the players, of the numbers of games played etc.)
5. execution of the simulation
6. printing of the results
See the commented source code of to configure the simulation and lunch the program.
main()I’m your link to the main module !
5
TicTacToe Documentation, Release 0.1
3.2 List of all the packages
3.2.1 core package
Submodules
core.BoardAndRules module
class BoardAndRules(game)Represents the rules of the game, saves the present state of the game and checks that the players follow the rules.
Variables
• game (Game) – A reference to the game.
• boardS (BoardState) – Represents the present physical board.
extractLines()Extracts the 8 lines than can be completed:
•3 vertical: left -> right,
•3 horizontal: up -> down,
•2 diagonal: 11->33 & 31->13.
Returns The list of lines
Return type list of list
getBoard()
Returns a copy of the self.board that will not be updated when a new movement is made
Return type BoardState
play(mvt)Verifies that the movement of the player follows the rules and writes it on the board.
Also sets Movement.turn and registers the movement in the list Game.movements Registers boardSin Game.states
Parameters mvt (Movement) – The Movement the player wants to play
Returns True if the movement is possible, else False
Return type bool
reset()Resets the state for a new game
thereIsAWinner()Sets Game.winner if there is one.
Returns True if there is a winner (ie if 3 dots are aligned), else False
Return type bool
6 Chapter 3. Contents:
TicTacToe Documentation, Release 0.1
core.BoardState module
class BoardState(hash=None)Represents the physical board.
Variables state (3-list (line) of 3-list (column)) – The state of the board: initialised with“0”: [[0, 0, 0], [0, 0, 0], [0, 0, 0]] uses player.order to put “1” or “2”where the players play.
Parameters hash (int, optional) – If hash is in **kwargs, it will be used to fill the board, defaultis None.
Examples
emptyB = BoardState() fullB = BoardState(hash=122121121)
__eq__(other)
Returns True if self.state and other.state are equal
Return type bool
__hash__()
Returns An integer created by the concatenation of all the cases
Return type int
Examples
[[0, 1, 2], [3, 4, 5], [6, 7, 8]] returns 12345678
Warning: First 0 is gone!
__len__()
Returns the turn of the board: counts the 0 and deduces the turn T = 9 - nb(0)
Return type int
__repr__()
Returns 3 lines representing the board (plus one line above and one under) with X and O insteadof 1 and 2
Return type string
copy()
Returns A new identical copy of BoardState (useful for storage)
Return type BoardState
reset()Reset self.state for a new game: to [[0, 0, 0], [0, 0, 0], [0, 0, 0]]
unhash(theHash)
3.2. List of all the packages 7
TicTacToe Documentation, Release 0.1
core.Game module
class GameMain object, registers the Board and the Players.
Variables
• boardAR (BoardAndRules) – Reference to the main BoardAndRules instance
• and player2 (player1) – References to the players
• and nextPlayer (lastPlayer) – References to player1 and player2, are exchanged be-tween the turns
• movements (list of Movement) – the chronological list of Movement() played
• states (list of BoardStates) – the chronological list of BoardStates()
• turn (int) – The present turn of the game, initialised at 0, first turn must be 1 (modified instart() )
• movements – the list of all the Movements made
• states – the list of the different BoardState of the game
• winner (Player or None) – Defined by BoardAndRules.thereIsAWinner(), staysNone is there is none
• interactionLevel (InteractionLevel) – used to define the level of printed outputs
Warning: movements and states must be updated by boardAR.play()
reset()Resets the game for a new game
Resets turn, movements, sates, winner, next and last player Calls boardAR.reset()
start()Plays a game until it is over, i.e. there is a winner or the game is even
How it is working:
As long as the game is not over (ie self.turn < 9 and thereIsAWinner == False) there isa loop where:
•turn is incremented,
•nextPlayer.play() is called and then next and last player are inverted,
•if wanted, the board is printed.
When it is over, meth:.Player.endOfGame() of player1 and player2 is called - if wanted, the result isprinted.
core.InteractionLevel module
class InteractionLevelThis object is used to store the parameters of the simulation.
Variables
• showEveryMovement (bool) – Print the state of the game after every movement
8 Chapter 3. Contents:
TicTacToe Documentation, Release 0.1
• showEveryMovementAndWait (bool) – Print the state of the game after every move-ment and wait that the user press enter to continue
• showFinalBoard (bool) – Print the final state of the game
• showElapsedTime (bool) – Print the total time that the simulation took
• showPlayerDebug (bool) – Print the debug messages of each player
core.Movement module
class Movement(player, place)Represents a movement played by a player.
Variables
• place (2-list of int) – The place [line, column].
• turn (int) – Must be set in board.play().
• player (Player) – The player playing.
Parameters
• player (Player) –
• place (2-list of int) –
Warning: self.turn must be set in BoardAndRules.play().
core.Player module
class Player(game, boardAR)” Represents a random player, is subclassed to create human and intelligent players
Variables
• boardAR (BoardAndRules) – A reference to the board (and rules)
• game (Game) – A reference to the game
• order (int) – Tells if the player is the first to play or the second, is used to select the typeof mark used on the board !! initialised with -1, must be set !!
• statistic (PlayerStatistic) – Saves the stats of the player
Warning: player.order must be set by the game
endOfGame()
play()Calls randomPlay()
randomPlay()Play a random movement (stupid: tries until a movement is not refused)
3.2. List of all the packages 9
TicTacToe Documentation, Release 0.1
core.PlayerStatistic module
class PlayerStatistic(player)
newResult(game)
core.Simulation module
class Simulation(game)
start()
Module contents
This is the Core package of the Game, it contains the primary classes of the game that are all needed to start a seriesof games between two random players.
Importation
The clean way to import the core package is:
from core import *
This may seem like a bad idea but the importation process in controlled in the core/__init__.py file. All thefollowing classes will be imported:
• BoardAndRules
• BoardState
• Game
• InteractionLevel
• Movement
• Player
• PlayerStatistic
• Simulation
Use
To use the imported classes, just write:
game = Game()bAndR = BoardAndRules() # etc...
no need to use core.Game.Game().
This is made possible thanks to the use of from core.Game import Game in the core/__init__.py file.
10 Chapter 3. Contents:
TicTacToe Documentation, Release 0.1
3.2.2 players package
Submodules
players.HAL1Player module
class HAL1Player(game, board)Bases: core.Player.Player
Subclass of Player, first try of learning player.
Variables
• memories (Memory) – Advanced dictionary that registers the past games.
• saveGame (bool) – Indicates if the game must be saved or not (True by default, set to Falseif the game is known).
• nbOfIntelligentGame (int) – The number of game where the memory have been used.
• evolutionOfMemories (list of int) – The lengths of the memory, one entry added atthe end hof each game.
endOfGame()Record the game if it is not an already know game
This function is called when a game is over, it relies on self.saveGame to know if the game must be learnor not. If it is the case, memories.addGame(game) is called. Reset self.saveGame to True at the end.Manages self.evolutionOfMemories
openTraining(trainingFileName)Imports a trained memories dictionary
play()Play a first random movement and then tries to play intelligently
Intelligently means it recognises learned the boardStates that leads to direct victory (in one movement) andplays the winning movement — not so intelligent but self learning !
saveTraining(trainingFileName)Saves a trained memories dictionary
players.HumanPlayer module
class HumanPlayer(game, boardAR)Bases: core.Player.Player
Subclass of Player, asks via the command prompt where to play (line and column, between 1 and 3)
play()
players.LinePlayer module
class LinePlayer(game, boardAR)Bases: core.Player.Player
Subclass of Player with an aggressive strategy:
first move is random, then checks if there is an unoccupied line with 2 cases already checked by itself and checkthe last case, (if there is none do the same with a free line where there is already one case checked)
3.2. List of all the packages 11
TicTacToe Documentation, Release 0.1
play()Plays a first random movement and then tries to complete lines
players.Memory module
class Memory
addGame(game)Add a game in the dictionary pastGames :
•key = hash of the state before the wining movement
•value = the Movement.place (couple [x,y]) that linked to the victory
Parameters game (Game) – the ended Game instance to save
Warning: Does not check is the result is an even or a victory
Module contents
This is the Players package: it contains Player’s subclasses that try to develop some kind of intelligence...
Importation
Do as you want, there is nothing special in the players/__init__.py file.
Use
To use the imported classes, just write:
Game()
no need to use core.Game.Game().
This is made possible thanks to the addition of the core/ folder path to the Python path and the use of fromcore.Game import Game in the __init__.py file.
3.2.3 misc package
Submodules
misc.Tools module
class Analyze
static createMovingRatios(resultsList, window)
static createTotalRatios(resultsList)
static extractMovingAverage(list, window)
12 Chapter 3. Contents:
TicTacToe Documentation, Release 0.1
static replaceInList(l, sample, newSample)
class Plot
static plotMovingRatio(player, window=20)
static plotTotalRatio(player)
static writeResultsInConsole(resultsList, precision=10)
Module contents
3.3 The trash module, just a random test file
This is a test file used as a Python interpreter.. Chunks of more or less useful pices of code!
3.3. The trash module, just a random test file 13
TicTacToe Documentation, Release 0.1
14 Chapter 3. Contents:
CHAPTER 4
Indices and tables
• genindex
• modindex
• search
15
TicTacToe Documentation, Release 0.1
16 Chapter 4. Indices and tables
Python Module Index
ccore, 10core.BoardAndRules, 6core.BoardState, 7core.Game, 8core.InteractionLevel, 8core.Movement, 9core.Player, 9core.PlayerStatistic, 10core.Simulation, 10
mmain, 5misc, 13misc.Tools, 12
pplayers, 12players.HAL1Player, 11players.HumanPlayer, 11players.LinePlayer, 11players.Memory, 12
ttrash, 13
17
TicTacToe Documentation, Release 0.1
18 Python Module Index
Index
Symbols__eq__() (BoardState method), 7__hash__() (BoardState method), 7__len__() (BoardState method), 7__repr__() (BoardState method), 7
AaddGame() (Memory method), 12Analyze (class in misc.Tools), 12
BBoardAndRules (class in core.BoardAndRules), 6BoardState (class in core.BoardState), 7
Ccopy() (BoardState method), 7core (module), 10core.BoardAndRules (module), 6core.BoardState (module), 7core.Game (module), 8core.InteractionLevel (module), 8core.Movement (module), 9core.Player (module), 9core.PlayerStatistic (module), 10core.Simulation (module), 10createMovingRatios() (Analyze static method), 12createTotalRatios() (Analyze static method), 12
EendOfGame() (HAL1Player method), 11endOfGame() (Player method), 9extractLines() (BoardAndRules method), 6extractMovingAverage() (Analyze static method), 12
GGame (class in core.Game), 8getBoard() (BoardAndRules method), 6
HHAL1Player (class in players.HAL1Player), 11
HumanPlayer (class in players.HumanPlayer), 11
IInteractionLevel (class in core.InteractionLevel), 8
LLinePlayer (class in players.LinePlayer), 11
Mmain (module), 5main() (in module main), 5Memory (class in players.Memory), 12misc (module), 13misc.Tools (module), 12Movement (class in core.Movement), 9
NnewResult() (PlayerStatistic method), 10
OopenTraining() (HAL1Player method), 11
Pplay() (BoardAndRules method), 6play() (HAL1Player method), 11play() (HumanPlayer method), 11play() (LinePlayer method), 11play() (Player method), 9Player (class in core.Player), 9players (module), 12players.HAL1Player (module), 11players.HumanPlayer (module), 11players.LinePlayer (module), 11players.Memory (module), 12PlayerStatistic (class in core.PlayerStatistic), 10Plot (class in misc.Tools), 13plotMovingRatio() (Plot static method), 13plotTotalRatio() (Plot static method), 13
19
TicTacToe Documentation, Release 0.1
RrandomPlay() (Player method), 9replaceInList() (Analyze static method), 12reset() (BoardAndRules method), 6reset() (BoardState method), 7reset() (Game method), 8
SsaveTraining() (HAL1Player method), 11Simulation (class in core.Simulation), 10start() (Game method), 8start() (Simulation method), 10
TthereIsAWinner() (BoardAndRules method), 6trash (module), 13
Uunhash() (BoardState method), 7
WwriteResultsInConsole() (Plot static method), 13
20 Index