# Week 16 - Tic tac toe random move

Post date: Feb 10, 2017 3:50:14 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"

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

tttBoard = [" "] * 9

drawBoard(tttBoard)

user = input("X or O?:")

if user != "O" and user != "X":

print("You will be X")

user = "X"

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

while(True):

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

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

else:

tttBoard[int(move) - 1] = user

drawBoard(tttBoard)

if win(tttBoard, user):

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

break

move = randommove(tttBoard,opponent(user))

tttBoard[move] = opponent(user)

print("The Attila moves", move + 1)

drawBoard(tttBoard)

if win(tttBoard, opponent(user)):

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

break