[text] q

Viewer

  1. board = [" " for x in range(9)]
  2.  
  3. def print_board():
  4.     row1 = "| {} | {} | {} |".format(board[0], board[1], board[2])
  5.     row2 = "| {} | {} | {} |".format(board[3], board[4], board[5])
  6.     row3 = "| {} | {} | {} |".format(board[6], board[7], board[8])
  7.  
  8.     print()
  9.     print(row1)
  10.     print(row2)
  11.     print(row3)
  12.     print()
  13.  
  14. def player_move(icon):
  15.     if icon == "X":
  16.         number = 1
  17.     elif icon == "O":
  18.         number = 2
  19.         
  20.     print("Your turn player {}".format(number))
  21.     
  22.     choice = int(input("Enter your move (1-9): ").strip())
  23.     if board[choice - 1] == " ":
  24.         board[choice - 1] = icon
  25.     else:
  26.         print()
  27.         print("That space is taken!")
  28.  
  29. def is_victory(icon):
  30.     if (board[0] == icon and board[1] == icon and board[2] == icon) or \
  31.        (board[3] == icon and board[4] == icon and board[5] == icon) or \
  32.        (board[6] == icon and board[7] == icon and board[8] == icon) or \
  33.        (board[0] == icon and board[3] == icon and board[6] == icon) or \
  34.        (board[1] == icon and board[4] == icon and board[7] == icon) or \
  35.        (board[2] == icon and board[5] == icon and board[8] == icon) or \
  36.        (board[0] == icon and board[4] == icon and board[8] == icon) or \
  37.        (board[2] == icon and board[4] == icon and board[6] == icon):
  38.         return True
  39.     else:
  40.         return False
  41.  
  42. def is_draw():
  43.     if " " not in board:
  44.         return True
  45.     else:
  46.         return False
  47.  
  48. while True:
  49.     print_board()
  50.     player_move("X")
  51.     print_board()
  52.     if is_victory("X"):
  53.         print("X wins! Congratulations!")
  54.         break
  55.     elif is_draw():
  56.         print("It's a draw!")
  57.         break
  58.     player_move("O")
  59.     if is_victory("O"):
  60.         print_board()
  61.         print("O wins! Congratulations!")
  62.         break
  63.     elif is_draw():
  64.         print("It's a draw!")
  65.         break
  66.  

Editor

You can edit this paste and save as new:


File Description
  • q
  • Paste Code
  • 27 Jan-2023
  • 1.85 Kb
You can Share it: