Tic-tac-toe game code in python
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()
Comments
Leave a comment