Answer:
Code:
# importing all necessary libraries
import numpy as np
import random
# Select a random place for the player
def play(board, player):
selection = availableSpots(board)
if player==1:
row=(int)(input("Enter the row :"))
column=(int)(input("Enter the column :"))
current_loc=(row-1,column-1)
while current_loc not in selection:
print("Invalid Input. Please give again")
row=(int)(input("Enter the row :"))
column=(int)(input("Enter the column :"))
current_loc=(row-1,column-1)
else:
current_loc = random.choice(selection)
board[current_loc] = player
return board
# Check for empty places on board
def availableSpots(board):
l = []
for i in range(len(board)):
for j in range(len(board)):
if board[i][j] == 0:
l.append((i, j))
return(l)
# Creates an empty board
def create_board():
return(np.array([[0, 0, 0],
[0, 0, 0],
[0, 0, 0]]))
# Checks whether the player has three
# of their marks in a horizontal row
def row_win(board, player):
for x in range(len(board)):
win = True
for y in range(len(board)):
if board[x, y] != player:
win = False
continue
if win == True:
return(win)
return(win)
# Checks whether the player has three
# of their marks in a vertical row
def col_win(board, player):
for x in range(len(board)):
win = True
for y in range(len(board)):
if board[y][x] != player:
win = False
continue
if win == True:
return(win)
return(win)
# Checks whether the player has three
# of their marks in a diagonal row
def diag_win(board, player):
win = True
for x in range(len(board)):
if board[x, x] != player:
win = False
return(win)
# Evaluates whether there is
# a winner or a tie
def evaluate(board):
winner = 0
for player in [1, 2]:
if (row_win(board, player) or
col_win(board,player) or
diag_win(board,player)):
winner = player
if np.all(board != 0) and winner == 0:
winner = -1
return winner
def printWinner(winner):
print("Game Over !!!")
if winner==1:
print("Player Wins")
elif winner==2:
print("Computer Wins")
else:
print("Nobody Wins")
# Main function to start the game
def play_game():
board, winner = create_board(), 0
print(board)
while winner == 0:
for player in [1, 2]:
board = play(board, player)
print("Board")
print(board)
winner = evaluate(board)
if winner != 0:
break
printWinner(winner)
play_game()
Explanation:
See screen shot of code and see final output