# V2

Post date: Mar 17, 2017 2:52:46 PM

import random

def drawBoard(board):

print(" | | ")

print(" ",board,"|",board,"|",board)

print(" | | ")

print("-------------")

print(" | | ")

print(" ",board,"|",board,"|",board)

print(" | | ")

print("-------------")

print(" | | ")

print(" ",board,"|",board,"|",board)

print(" | | ")

def win(board, player):

if board == player and board == player and board == player:

return True

if board == player and board == player and board == player:

return True

if board == player and board == player and board == player:

return True

if board == player and board == player and board == player:

return True

if board == player and board == player and board == player:

return True

if board == player and board == player and board == player:

return True

if board == player and board == player and board == player:

return True

if board == player and board == player and board == player:

return True

return False

def opponent(sUser):

if sUser == "O":

return "X"

return "O"

############## Strategy to move random ############

def randommove(board, sUser):

emptystep = []

for x in range(0,9):

if board[x] == " ":

emptystep.append(x)

move = random.randint(0,len(emptystep)-1)

move = emptystep[move]

return move

############## Strategy to block win ############

def blockuser(board, sUser):

for x in range(0,9):

if board[x] == " ":

board[x] = sUser

isWin = win(board, sUser)

board[x] = " "

if isWin:

return x

return -1

############## Check for tie ##################

def checktie(board):

isTie = True

for x in range(0,9):

if board[x] == " ":

isTie = False

return isTie

flip = random.randint(0,1)

if flip == 0:

else:

coin = "Tail"

if bet == coin:

return True

return False

############## User move ##################

def usermove(board, user):

move = input("Make your move (1~9):")

if board[int(move) - 1] != " ":

else:

board[int(move) - 1] = user

drawBoard(board)

if win(board, user):

print("The user ", user, "won!!!")

return True

if checktie(board):

print("It is a tie")

return True

return False

############## Computer move ##################

def computermove(board, user):

move = blockuser(board, user)

if move == -1:

move = randommove(board,opponent(user))

board[move] = opponent(user)

print("Computer moves", move + 1)

drawBoard(board)

if win(board, opponent(user)):

print("The computer", opponent(user), "won!!!")

return True

if checktie(board):

print("It is a tie")

return True

return False

################## Main Program ##################

tttBoard = [" "] * 9

drawBoard(tttBoard)

print("You won, you will be X")

user = "X"

else:

print("You lost, you will be O")

user = "O"

print("The computer is", opponent(user))

while(True):

if usermove(tttBoard, user):

break

if computermove(tttBoard, user):

break