### Week 16 - Tic Tac Toe Block User Win

posted Feb 17, 2017, 7:51 AM by Attila Lengyel   [ updated Feb 17, 2017, 8:03 AM ]
 import randomdef drawBoard(board):  print("    |   |   ")  print(" ",board[0],"|",board[1],"|",board[2])  print("    |   |   ")    print("-------------")  print("    |   |   ")  print(" ",board[3],"|",board[4],"|",board[5])  print("    |   |   ")    print("-------------")  print("    |   |   ")  print(" ",board[6],"|",board[7],"|",board[8])  print("    |   |   ")  def win(board, player):  if board[0] == player and board[1] == player and board[2] == player:    return True  if board[3] == player and board[4] == player and board[5] == player:    return True  if board[6] == player and board[7] == player and board[8] == player:    return True  if board[0] == player and board[3] == player and board[6] == player:    return True  if board[1] == player and board[4] == player and board[7] == player:    return True  if board[2] == player and board[5] == player and board[8] == player:    return True  if board[0] == player and board[4] == player and board[8] == player:    return True  if board[2] == player and board[4] == player and board[6] == player:    return True    return Falsedef 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################## Main Program ##################tttBoard = [" "] * 9drawBoard(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):  ############## User move ##################  move = input("Make your move (1~9):")  if tttBoard[int(move) - 1] != " ":    print("You lost your move!!!")  else:    tttBoard[int(move) - 1] = user    drawBoard(tttBoard)  if win(tttBoard, user):    print("The user ", user, "won!!!")    break    if checktie(tttBoard):    print("It is a tie")    break  ############## Computer move ##################  move = blockuser(tttBoard, user)  if move == -1:    move = randommove(tttBoard,opponent(user))    tttBoard[move] = opponent(user)  print("Computer moves", move + 1)    drawBoard(tttBoard)    if win(tttBoard, opponent(user)):    print("The computer", opponent(user), "won!!!")    break    if checktie(tttBoard):    print("It is a tie")    break