stoneskin

learning coding with Scratch , Python and Java

11 Build a TicTacToe Game

Tic‐Tac‐Toe is a very simple two players game. So only two players can play at a time. Or you could build one player play with computer.

This game is also known as Noughts and Crosses or Xs and Os game. One player plays with X and the other player plays with O. In this game we have a board consisting of a 3X3 grid.

11.1 Design the Game

1. Figure out the rules of Tic Tac Toe Game

  1. Two plays control the keyboard in ture
  2. The game board is 3X3 grid
  3. The player who first get 3 dot in one row will win

tic-tac-toe

2. Design the Game UI

  1. Game Start, Game Over
  2. Board, back ground
  3. Chess: Nothing, X, O
  4. User input position: n or (x,y) ex. position of 2nd column and 3rd row
    • Option 1: 8 (position #8 of total positions)
    • Option 2: (x,y)

3. Design the Game Data Structure

  1. Option 1: Use List of object with value 0/1 for each position

      [0,0,0,0,0,0,0,0,0]
    
  2. Option 2: User Double Array

       [
         [0,0,0]
         [0,0,0]
         [0,0,0]
       ]
    

4. Design the Logic to decide who won the game

  1. for Option 1, need check all below possibility

     Row[1]=Row[2]=Row[3] or Row[4]=Row[5]=Row[6] or Row[7]=Row[8]=Row[9]
     Row[1]=Row[4]=Row[6] or Row[2]=Row[5]=Row[8] or Row[3]=Row[6]=Row[9]
     Row[1]=Row[5]=Row[9] or Row[3]=Row[5]=Row[6]
    
  2. for Option 2, check below

    Row[1][1]==Row[1][2]==Row[1][3] or Row[2][1]==Row[2][2]==Row[2][3] or Row[3][1]==Row[3][2]==Row[3][3]
    Row[1][1]==Row[2][1]==Row[3][1] or Row[1][2]==Row[2][2]==Row[3][2] or Row[1][3]==Row[2][3]==Row[3][3]
    Row[1][1]==Row[2][2]==Row[3][3]  or Row[1][3]==Row[2][2]==Row[3][1]

11.2 Implementation Plan

  1. Load the UI object/Image
  2. Add the code for UI interactive
  3. Add the code for Data Structure
  4. Add the code for winning Judgment Logic

Challenge

  1. Change the one of the player to AI
  2. Coding the Logic of the AI player to find the best place to put.

Ref

  1. scratch example https://scratch.mit.edu/projects/199155900/
  2. My OOP TicTacToe example https://github.com/stoneskin/TicTacToe/
  3. python tic-tac-toe example https://www.askpython.com/python/examples/tic-tac-toe-using-python
  4. pygame tic-tac-toe example https://www.geeksforgeeks.org/tic-tac-toe-gui-in-python-using-pygame/