Abhinav and Anjali are playing the Tic-Tac-Toe game. Tic-Tac-Toe is a game played on a grid that's three squares by three squares. Abhinav is O, and Anjali is X. Players take turns putting their marks in empty squares. The first player to get 3 of her marks in a diagonal or horizontal, or vertical row is the winner. When all nine squares are complete, the game is over. If no player has three marks in a row, the game ends in a tie. Write a program to decide the winner in the Tic-Tac-Toe game.
class TicTacToeGame:
def __init__(self):
self.board = []
def initBoard(self):
for i in range(3):
row = []
for j in range(3):
row.append('-')
self.board.append(row)
def setSymbol(self, row, col, player):
self.board[row][col] = player
def checkWinner(self, player):
isWinner = None
n = len(self.board)
for i in range(n):
isWinner = True
for j in range(n):
if self.board[i][j] != player:
isWinner = False
break
if isWinner:
return isWinner
for i in range(n):
isWinner = True
for j in range(n):
if self.board[j][i] != player:
isWinner = False
break
if isWinner:
return isWinner
isWinner = True
for i in range(n):
if self.board[i][i] != player:
isWinner = False
break
if isWinner:
return isWinner
isWinner = True
for i in range(n):
if self.board[i][n - 1 - i] != player:
isWinner = False
break
if isWinner:
return isWinner
return False
for row in self.board:
for symbol in row:
if symbol == '-':
return False
return True
def isDraw(self):
for row in self.board:
for symbol in row:
if symbol == '-':
return False
return True
def swapPlayer(self, player):
return 'X' if player == 'O' else 'O'
def displayBoard(self):
for row in self.board:
for symbol in row:
print(symbol, end=" ")
print()
def play(self):
self.initBoard()
player = 'X'
while True:
print(f"Player {player} turn")
self.displayBoard()
row= int(input("Enter row: "))
col= int(input("Enter column: "))
print()
self.setSymbol(row - 1, col - 1, player)
if self.checkWinner(player):
print(f"Player {player} wins the game!")
break
if self.isDraw():
print("Draw!")
break
player = self.swapPlayer(player)
print()
self.displayBoard()
ticTacToeGame = TicTacToeGame()
ticTacToeGame.play()
Comments
Leave a comment