Answer to Question #274813 in Python for Venkat

Question #274813

Tic-tac-toe game code in python

1
Expert's answer
2021-12-03T00:37:12-0500
import random


class TicTacToe:

   def __init__(self):
      self.board = []
      for i in range(3):
         row = []
         for j in range(3):
            row.append('-')
         self.board.append(row)

   def show_board(self):
      for row in self.board:
         for item in row:
            print(item, end=' ')
         print()

   def is_player_win(self, player):
      n = len(self.board)
      for i in range(n):
         win = True
         for j in range(n):
            if self.board[i][j] != player:
               win = False
               break
         if win:
            return win

      for i in range(n):
         win = True
         for j in range(n):
            if self.board[j][i] != player:
               win = False
               break
         if win:
            return win

      win = True
      for i in range(n):
         if self.board[i][i] != player:
            win = False
            break
      if win:
         return win

      win = True
      for i in range(n):
         if self.board[i][n - 1 - i] != player:
            win = False
            break
      if win:
         return win
      return False

   def is_board_filled(self):
      for row in self.board:
         for item in row:
            if item == '-':
               return False
      return True

   def swap(self, player):
      return 'X' if player == 'O' else 'O'

   def start(self):
      player = 'X' if random.randint(0, 1) else 'O'
      while True:
         print(f'Player {player} turn')
         self.show_board()
         row, col = list(
            map(int, input('Enter row and column numbers to fix spot: ').split()))
         self.board[row][col] = player
         if self.is_player_win(player):
            print(f'Player {player} wins the game')
            break
         if self.is_board_filled():
            print("Match Draw!")
            break
         player = self.swap(player)
      print()
      self.show_board()


ttt = TicTacToe()
ttt.start()

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS