TrickJarrett.com

Simple Tic-Tac-Toe in Python

2/13/2021 3:00 pm | : 2 mins. | Share to:

My learning of Python continued today with me coding a simple Tic-Tac-Toe client. It is very dumb, the computer always plays randomly and currently has no intelligence to it. But I wrote it from scratch with no outside resource or code segments. Doing things like this is always a great feeling for me, learning something is one of my favorite things to do.

Here is my Python code:

from random import randint

board = [1,2,3,4,5,6,7,8,9]
legalplays = [1,2,3,4,5,6,7,8,9]

def drawboard(board):
   print(board[0],"|",board[1],"|",board[2])
   print("---------")
   print(board[3],"|",board[4],"|",board[5])
   print("---------")
   print(board[6],"|",board[7],"|",board[8])


def checkboard(board):
   patterns = [[0,1,2],
               [3,4,5],
               [6,7,8],
               [0,3,6],
               [1,4,7],
               [2,5,8],
               [0,4,8],
               [2,4,6]]
   for pattern in patterns:
       if board[pattern[0]] == board[pattern[1]] and board[pattern[0]] == board[pattern[2]]:
           return board[pattern[0]]
   return 0


def computerPlay(board):
   availableplays = []
   for i in board:
       if i in legalplays:
           availableplays.append(i-1);
   moves = len(availableplays)
   move = randint(0,moves-1)
   return availableplays[move]


playfirst = randint(1,2)

if playfirst == 1:
   #Computer Plays First
   play = randint(0,8)
   board[play] = "O";

noresult = True

while noresult:
   drawboard(board)
   player = input("Choose where to put your X: ")

   if player.isnumeric():
       player = int(player) - 1
       if player