Sunday, 18 August 2019

A Framework for Board Games - Part I

This post provides a framework which can implement various turn based (human Vs computer) board games such as Tic-Tac-Tao and Connect 4. In this Part I, a structure of the overall logic for a game is given. The program can ask for move from human, and will get its moves by random, it also knows whether the game is ended or not by checking a set of ending rules. In Part II, a tree searching algorithm for determining the moves of the computer is presented. With that intelligence, the computer will act like an expert player and can beat all human in theory.
  1. The game Tic-Tac-Tao is choosen for demonstration.
  2. The game is run in console mode, only a minimal graphics composed by text is included.
  3. Two Python classes are used to represent the players' states and the game itself.
  4. The set operations provided by Python are employed to determine whether the game is ended.

Source Code




Test Run



Computer chooses 8

     |   |  
  ---|---|---
     |   |  
  ---|---|---
     | X |  


Your turn [1, 2, 3, 4, 5, 6, 7, 9] ? 2

     | O |  
  ---|---|---
     |   |  
  ---|---|---
     | X |  


Computer chooses 5

     | O |  
  ---|---|---
     | X |  
  ---|---|---
     | X |  


Your turn [1, 3, 4, 6, 7, 9] ? 1

   O | O |  
  ---|---|---
     | X |  
  ---|---|---
     | X |  


Computer chooses 3

   O | O | X
  ---|---|---
     | X |  
  ---|---|---
     | X |  


Your turn [4, 6, 7, 9] ? 7

   O | O | X
  ---|---|---
     | X |  
  ---|---|---
   O | X |  


Computer chooses 9

   O | O | X
  ---|---|---
     | X |  
  ---|---|---
   O | X | X


Your turn [4, 6] ? 4

   O | O | X
  ---|---|---
   O | X |  
  ---|---|---
   O | X | X




   O | O | X
  ---|---|---
   O | X |  
  ---|---|---
   O | X | X

Human wins!

No comments:

Post a Comment