Guest User

Untitled

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