Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- ### Tic Tac Toe ###
- # instructions
- # determine who goes first
- # create board
- # display board
- # while no one has one and it's not a tie:
- ## if its human's turn
- ### get human's move
- ### update the board with the move
- ## otherwise
- ### calculate the computer's move
- ### update the board with the move
- ## display the board
- ## switch turns
- # congratulate the winner or declare a tie
- # Global Constants
- X = "X"
- O = "O"
- EMPTY = " "
- TIE = "TIE"
- SQUARES = (1, 2, 3, 4, 5, 6, 7, 8, 9)
- def displayInstruct():
- """ Display game instructions. """
- print(
- """
- Welcome to the greatest intellectual challenge of all time: Tic-Tac-Toe.
- This will be a showdown between your human brain and my silicon processor.
- You will make your move known by entering a number, 1 - 9. The number
- will correspond to the board position as illustrated:
- 1 | 2 | 3
- ---------
- 4 | 5 | 6
- ---------
- 7 | 8 | 9
- Prepare yourself, human. The ultimate battle is about to begin. \n
- """
- )
- def askYesNo(question):
- """Ask a yes or no question."""
- response = None
- while response not in ("y", "n"):
- response = input(question).lower()
- response = response.rstrip("\r\n")
- return response
- def askNumber(question, low, high):
- """ Ask for a number within a range."""
- response = None
- while response not in range(low, high):
- response = input(question)
- response = response.rstrip("\r\n")
- response = int(response)
- return response
- def pieces():
- """Determine if the player or computer goes first. """
- go_first = askYesNo("Do you require the first move? (y/n): ")
- if go_first == "y":
- print("\nThen take the first move. You will need it.")
- human = X
- computer = O
- else:
- print("\nYour bravery will be your undoing... I will go first." )
- computer = X
- human = O
- return computer, human
- def newBoard():
- """Create new game board."""
- board = []
- for i in SQUARES:
- board.append(EMPTY)
- return board
- def displayBoard(board):
- """Display game board on screen."""
- print("\n\t", board[0], "|", board[1], "|", board[2] )
- print("\t", "--------- ")
- print("\t", board[3], "|", board[4], "|", board[5] )
- print("\t", "--------- ")
- print("\t", board[6], "|", board[7], "|", board[8] )
- def legalMoves(board):
- """Create a list of legal moves."""
- moves = []
- for i in SQUARES:
- if board[i] == EMPTY:
- moves.append(i)
- return moves
- def winner(board):
- """ Determine the game winner. """
- WAYS_TO_WIN = ((1, 2, 3),
- (4, 5, 6),
- (7, 8, 9),
- (1, 4, 7),
- (2, 5, 8),
- (3, 6, 9),
- (1, 5, 9),
- (7, 5, 3))
- for row in WAYS_TO_WIN:
- if board[row[0]] == board[row[1]] == board[row[2]] != EMPTY:
- winner = board[i[0]]
- return winner
- if EMPTY not in board:
- return TIE
- return None
- def humanMove(board, human):
- """Get human's move."""
- legal = legalMoves(board)
- move = None
- while move not in legal:
- move = askNumber("Where will you move? (1 - 9): ", 1, 10)
- if move not in legal:
- print("\nThat square is already occupied, foolish human. Choose another.\n")
- print("Fine..." )
- return move
- def computerMove(board, computer, human):
- "make computer move."""
- #making a copy to work with since function will be changing list
- lboard = board[:]
- BEST_MOVES = (5, 7, 9, 1, 3, 4, 8, 6, 2)
- print("I shall take square number", end=" ")
- # if computer can win, take that move:
- for move in legalMoves(board):
- lboard[move] = computer
- if winner(board) == computer:
- print(move)
- return move
- #done checking move, undo it:
- lboard[move] = EMPTY
- # if human can win, block the move:
- for move in legalMoves(board):
- lboard[move] = human
- if winner(board) == human:
- print(move)
- return move
- #done checking move, undo it:
- lboard[move] = EMPTY
- #since no one can win, pick best open square:
- for move in BEST_MOVES:
- if move in legalMoves(board):
- print(move)
- return move
- def nextTurn(turn):
- """Switch turns."""
- if turn == X:
- return O
- else:
- return X
- def congratWinner(the_winner, computer, human):
- if the_winner != TIE:
- print(the_winner, "won!\n")
- else:
- print("It's a tie!\n")
- if the_winner == computer:
- print("As I predicted, human, I am triumpant once more. \n" \
- "Proff that computers are superior to humans in all regards." )
- elif the_winner == human:
- print("No, no! It cannot be! Somehow you tricked me, human. \n" \
- "But never again! I, the computer, so swear it!")
- elif the_winner == TIE:
- print("You were most lucky, human, and somehow managed to tie me. \n" \
- "Celebrate today, for this is the best you will ever achieve.")
- def playAgain():
- replay = askYesNo("\n\nWould you like to play again? (y/n): ")
- if replay == "y":
- return True
- else:
- return False
- def main():
- displayInstruct()
- computer, human = pieces()
- turn = X
- board = newBoard()
- displayBoard(board)
- while not winner(board):
- if turn == human:
- move = humanMove(board, human)
- board[move] = human
- else:
- move = computerMove(board, computer, human)
- board[move] = computer
- displayBoard(board)
- turn = nextTurn(turn)
- the_winner = winner(board)
- congratWinner(the_winner, computer, human)
- while True:
- main()
- playAgain()
- ## The Error:
- ##Traceback (most recent call last):
- ## File "C:\Python32\tic-tactoe.py", line 217, in <module>
- ## main()
- ## File "C:\Python32\tic-tactoe.py", line 203, in main
- ## while not winner(board):
- ## File "C:\Python32\tic-tactoe.py", line 113, in winner
- ## if board[row[0]] == board[row[1]] == board[row[2]] != EMPTY:
- ##IndexError: list index out of range
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement