Advertisement
kernel_memory_dump

TicTacToe

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