Advertisement
xgeovanni

Tic-Tac-Toe

Dec 2nd, 2011
100
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 5.42 KB | None | 0 0
  1. #Tic-Tac-Toe
  2. #Plays the game of tic-tac-toe, human vs computer
  3.  
  4. #global constants
  5. X = "X"
  6. O = "O"
  7. EMPTY = " "
  8. TIE = "TIE"
  9. NUM_SQUARES = 9
  10.  
  11. def instructions():
  12.     """Display game instructions"""
  13.     print(
  14.     """
  15. Welcome to the greatest intellectual challenge of all time: Iic-Tac-Toe.
  16. This will be a showdown between your human brain and my silicon processor.
  17.  
  18. You will make your move by entering a number, 1-9. The number
  19. will correspond to the board position as illustrated:
  20.  
  21.                   0 | 1 | 2
  22.                   ---------
  23.                   3 | 4 | 5
  24.                   ---------
  25.                   6 | 7 | 8
  26.  
  27. Prepare yourself, human. The ultimate battle is about to begin. \n
  28. """
  29.     )
  30.  
  31. def ask_yes_no(question):
  32.     """ask a yes or no question"""
  33.     response = None
  34.     while response not in ("y", "n"):
  35.         response = input(question).lower()
  36.     return response
  37.  
  38. def ask_number(question, low, high):
  39.     """Ask for a number within a range"""
  40.     response = None
  41.     while response not in range(low, high):
  42.         response = int(input(question))
  43.     return response
  44.  
  45. def pieces():
  46.     """Detirmine if the player or the computer goes first"""
  47.     go_first = ask_yes_no("Do you require the first move? (y/n) ")
  48.     if go_first == "y":
  49.         print("\nThen take the first move, you'll need it.")
  50.         human = X
  51.         computer = O
  52.     else:
  53.         print("\nYour bravery will be your undoing, I will go first")
  54.         computer = X
  55.         human = O
  56.     return computer, human
  57.  
  58. def new_board():
  59.     """Create new game board"""
  60.     board = []
  61.     for square in range(NUM_SQUARES):
  62.         board.append(EMPTY)
  63.     return board
  64.  
  65. def display_board(board):
  66.     """Display game board on-screen"""
  67.     print("\n\t", board[0], "|", board[1], "|", board[2])
  68.     print("\t", "---------")
  69.     print("\t", board[3], "|", board[4], "|", board[5])
  70.     print("\t", "---------")
  71.     print("\t", board[6], "|", board[7], "|", board[8])
  72.  
  73. def legal_moves(board):
  74.     """Create a list of legal moves"""
  75.     moves = []
  76.     for square in range(NUM_SQUARES):
  77.         if board[square] == EMPTY:
  78.             moves.append(square)
  79.     return moves
  80.  
  81. def winner(board):
  82.     """Determine the game winner"""
  83.     WAYS_TO_WIN = ((0, 1, 2),
  84.                    (3, 4, 5),
  85.                    (6, 7, 8),
  86.                    (0, 3, 6),
  87.                    (1, 4, 7),
  88.                    (2, 5, 8),
  89.                    (0, 4, 8),
  90.                    (2, 4, 6))
  91.  
  92.     for row in WAYS_TO_WIN:
  93.         if board[row[0]] == board[row[1]] == board[row[2]] != EMPTY:
  94.             winner = board[row[0]]
  95.             return winner
  96.  
  97.     if EMPTY not in board:
  98.         return TIE
  99.  
  100.     return None
  101.  
  102. def human_move(board, human):
  103.     """Get human move"""
  104.     legal = legal_moves(board)
  105.     move = None
  106.     while move not in legal:
  107.         move = ask_number("Where will you move? (0 - 8) ", 0, NUM_SQUARES)
  108.         if move not in legal:
  109.             print("\nThat square is already occupied, foolish human. Choose another.\n")
  110.     print("Fine...")
  111.     return move
  112.  
  113. def computer_move(board, human, computer):
  114.     """make computer move"""
  115.     #make a copy to work with
  116.     board = board[:]
  117.  
  118.     #The best positions to have, in order
  119.     BEST_MOVES = (4, 0, 2, 6, 8, 1, 3, 5, 7)
  120.  
  121.     print("I shall take square number", end = " ")
  122.  
  123.     #if computer can win, take that move
  124.     for move in legal_moves(board):
  125.         board[move] = computer
  126.         if winner(board) == computer:
  127.             print(move)
  128.             return move
  129.         #done checking this move, undo it
  130.         board[move] = EMPTY
  131.  
  132.     #if human can win, block that move
  133.     for move in legal_moves(board):
  134.         board[move] = human
  135.         if winner(board) == human:
  136.             print(move)
  137.             return move
  138.         #done checking this move, undo it
  139.         board[move] = EMPTY
  140.  
  141.     #pick the best open square
  142.     for move in BEST_MOVES:
  143.         if move in legal_moves(board):
  144.             print(move)
  145.             return move
  146.  
  147. def next_turn(turn):
  148.     """Switch turns"""
  149.     if turn == X:
  150.         return O
  151.     else:
  152.         return X
  153.  
  154. def congrat_winner(the_winner, computer, human):
  155.     """congratulate the winner"""
  156.     if the_winner != TIE:
  157.         print(the_winner, "won!\n")
  158.     else:
  159.         print("It's a tie!\n")
  160.  
  161.     if the_winner == computer:
  162.         print("As I predicted, human, I am triumphant once more. \n"
  163.               "Proof that computers are superior in all regards.")
  164.  
  165.     elif the_winner == human:
  166.         print("No, no! It cannot be! Somehow you tricked me, human. \n"
  167.               "But never again! I, the computer, so swear it!")
  168.  
  169.     elif the_winner == TIE:
  170.         print("You were most lucky, human, and somehow managed to tie with me. \n"
  171.               "Celebrate today... for this is the best you will ever achieve.")
  172. def main():
  173.     instructions()
  174.     computer, human = pieces()
  175.     turn = X
  176.     board = new_board()
  177.     display_board(board)
  178.  
  179.     while not winner(board):
  180.         if turn == human:
  181.             move = human_move(board, human)
  182.             board[move] = human
  183.         else:
  184.             move = computer_move(board, computer, human)
  185.             board[move] = computer
  186.         display_board(board)
  187.         turn = next_turn(turn)
  188.  
  189.     the_winner = winner(board)
  190.     congrat_winner(the_winner, computer, human)
  191.  
  192. #start the program
  193. main()
  194. input("\n\nPress enter to exit")
  195.  
  196.  
  197.  
  198.  
  199.  
  200.  
  201.  
  202.  
  203.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement