Guest User

Untitled

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