Advertisement
Guest User

Untitled

a guest
Sep 25th, 2017
84
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 6.38 KB | None | 0 0
  1. ### Tic Tac Toe ###
  2.  
  3. # instructions
  4. # determine who goes first
  5. # create board
  6. # display board
  7. # while no one has one and it's not a tie:
  8. ## if its human's turn
  9. ### get human's move
  10. ### update the board with the move
  11. ## otherwise
  12. ### calculate the computer's move
  13. ### update the board with the move
  14. ## display the board
  15. ## switch turns
  16. # congratulate the winner or declare a tie
  17.  
  18. # Global Constants
  19.  
  20. X = "X"
  21. O = "O"
  22. EMPTY = " "
  23. TIE = "TIE"
  24. SQUARES = (1, 2, 3, 4, 5, 6, 7, 8, 9)
  25.  
  26. def displayInstruct():
  27.     """ Display game instructions. """
  28.     print(
  29.         """
  30.    Welcome to the greatest intellectual challenge of all time: Tic-Tac-Toe.
  31.    This will be a showdown between your human brain and my silicon processor.
  32.  
  33.    You will make your move known by entering a number, 1 - 9.  The number
  34.    will correspond to the board position as illustrated:
  35.  
  36.             1 | 2 | 3
  37.             ---------
  38.             4 | 5 | 6
  39.             ---------
  40.             7 | 8 | 9
  41.  
  42.    Prepare yourself, human.  The ultimate battle is about to begin.  \n
  43.    """
  44.         )
  45.  
  46. def askYesNo(question):
  47.     """Ask a yes or no question."""
  48.     response = None
  49.     while response not in ("y", "n"):
  50.         response = input(question).lower()
  51.         response = response.rstrip("\r\n")
  52.     return response
  53.  
  54. def askNumber(question, low, high):
  55.     """ Ask for a number within a range."""
  56.     response = None
  57.     while response not in range(low, high):
  58.         response = input(question)
  59.         response = response.rstrip("\r\n")
  60.         response = int(response)
  61.     return response
  62.  
  63. def pieces():
  64.     """Determine if the player or computer goes first. """
  65.     go_first = askYesNo("Do you require the first move?  (y/n): ")
  66.     if go_first == "y":
  67.         print("\nThen take the first move.  You will need it.")
  68.         human = X
  69.         computer = O
  70.  
  71.     else:
  72.         print("\nYour bravery will be your undoing... I will go first." )
  73.         computer = X
  74.         human = O
  75.        
  76.     return computer, human
  77.  
  78. def newBoard():
  79.     """Create new game board."""
  80.     board = []
  81.     for i in SQUARES:
  82.         board.append(EMPTY)
  83.     return board
  84.  
  85. def displayBoard(board):
  86.     """Display game board on screen."""
  87.     print("\n\t", board[0], "|", board[1], "|", board[2] )
  88.     print("\t", "--------- ")
  89.     print("\t", board[3], "|", board[4], "|", board[5] )
  90.     print("\t", "--------- ")
  91.     print("\t", board[6], "|", board[7], "|", board[8] )
  92.  
  93. def legalMoves(board):
  94.     """Create a list of legal moves."""
  95.     moves = []
  96.     for i in SQUARES:
  97.         if board[i] == EMPTY:
  98.             moves.append(i)
  99.     return moves
  100.  
  101. def winner(board):
  102.     """ Determine the game winner. """
  103.     WAYS_TO_WIN = ((1, 2, 3),
  104.                    (4, 5, 6),
  105.                    (7, 8, 9),
  106.                    (1, 4, 7),
  107.                    (2, 5, 8),
  108.                    (3, 6, 9),
  109.                    (1, 5, 9),
  110.                    (7, 5, 3))
  111.  
  112.     for row in WAYS_TO_WIN:
  113.         if board[row[0]] == board[row[1]] == board[row[2]] != EMPTY:
  114.             winner = board[i[0]]
  115.             return winner
  116.     if EMPTY not in board:
  117.         return TIE
  118.     return None
  119.  
  120. def humanMove(board, human):
  121.     """Get human's move."""
  122.     legal = legalMoves(board)
  123.     move = None
  124.     while move not in legal:
  125.         move = askNumber("Where will you move? (1 - 9): ", 1, 10)        
  126.         if move not in legal:
  127.             print("\nThat square is already occupied, foolish human.  Choose another.\n")
  128.     print("Fine..." )
  129.     return move
  130.    
  131. def computerMove(board, computer, human):
  132.     "make computer move."""
  133.     #making a copy to work with since function will be changing list
  134.    
  135.     lboard = board[:]
  136.  
  137.     BEST_MOVES = (5, 7, 9, 1, 3, 4, 8, 6, 2)
  138.    
  139.     print("I shall take square number", end=" ")
  140.     # if computer can win, take that move:
  141.     for move in legalMoves(board):
  142.         lboard[move] = computer
  143.         if winner(board) == computer:
  144.             print(move)
  145.             return move
  146.         #done checking move, undo it:
  147.         lboard[move] = EMPTY
  148.  
  149.     # if human can win, block the move:
  150.     for move in legalMoves(board):
  151.         lboard[move] = human
  152.         if winner(board) == human:
  153.             print(move)
  154.             return move
  155.     #done checking move, undo it:
  156.         lboard[move] = EMPTY
  157.  
  158.     #since no one can win, pick best open square:
  159.     for move in BEST_MOVES:
  160.         if move in legalMoves(board):
  161.             print(move)
  162.             return move
  163.  
  164. def nextTurn(turn):
  165.     """Switch turns."""
  166.     if turn == X:
  167.         return O
  168.     else:
  169.         return X
  170.  
  171. def congratWinner(the_winner, computer, human):
  172.     if the_winner != TIE:
  173.         print(the_winner, "won!\n")
  174.     else:
  175.         print("It's a tie!\n")
  176.  
  177.     if the_winner == computer:
  178.         print("As I predicted, human, I am triumpant once more.  \n" \
  179.               "Proff that computers are superior to humans in all regards." )
  180.  
  181.     elif the_winner == human:
  182.         print("No, no!  It cannot be!  Somehow you tricked me, human.  \n" \
  183.               "But never again!  I, the computer, so swear it!")
  184.  
  185.     elif the_winner == TIE:
  186.         print("You were most lucky, human, and somehow managed to tie me.  \n" \
  187.               "Celebrate today, for this is the best you will ever achieve.")
  188.  
  189. def playAgain():
  190.     replay = askYesNo("\n\nWould you like to play again?  (y/n): ")
  191.     if replay == "y":
  192.         return True
  193.     else:
  194.         return False
  195.  
  196. def main():
  197.     displayInstruct()
  198.     computer, human = pieces()
  199.     turn = X
  200.     board = newBoard()
  201.     displayBoard(board)
  202.  
  203.     while not winner(board):
  204.         if turn == human:
  205.             move = humanMove(board, human)
  206.             board[move] = human
  207.         else:
  208.             move = computerMove(board, computer, human)
  209.             board[move] = computer
  210.         displayBoard(board)
  211.         turn = nextTurn(turn)
  212.  
  213.     the_winner = winner(board)
  214.     congratWinner(the_winner, computer, human)
  215.  
  216. while True:
  217.     main()
  218.     playAgain()
  219.  
  220. ## The Error:
  221. ##Traceback (most recent call last):
  222. ##  File "C:\Python32\tic-tactoe.py", line 217, in <module>
  223. ##    main()
  224. ##  File "C:\Python32\tic-tactoe.py", line 203, in main
  225. ##    while not winner(board):
  226. ##  File "C:\Python32\tic-tactoe.py", line 113, in winner
  227. ##    if board[row[0]] == board[row[1]] == board[row[2]] != EMPTY:
  228. ##IndexError: list index out of range
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement