def getPlayerMove(board): # Let the player type in his move. move = ' ' while move not in '1 2 3 4 5 6 7 8 9'.split() or not isSpaceFree(board, int(move)): prompt('What is your next move? (1-9)') move = getMove() return int(move)
def inputPlayerLetter(): # Lets the player type which letter they want to be. # Returns a list with the player's letter as the first item, and the computer's letter as the second. letter = '' while not (letter == 'X' or letter == 'O'): prompt('Do you want to be X (blinky) or O (steady)?') letter = getLetter() # the first element in the tuple is the player's letter, the second is the computer's letter. if letter == 'X': return ['X', 'O'] else: return ['O', 'X']
def playAgain(): # This function returns True if the player wants to play again, otherwise it returns False. prompt('Do you want to play again? (yes or no)') return getYesOrNo()
# Try to take the center, if it is free. if isSpaceFree(board, 5): return 5 # Move on one of the sides. return chooseRandomMoveFromList(board, [2, 4, 6, 8]) def isBoardFull(board): # Return True if every space on the board has been taken. Otherwise return False. for i in range(1, 10): if isSpaceFree(board, i): return False return True prompt('Welcome to Tic Tac Toe!') while True: # Reset the board theBoard = [' '] * 10 playerLetter, computerLetter = inputPlayerLetter() turn = whoGoesFirst() prompt('The ' + turn + ' will go first.') gameIsPlaying = True while gameIsPlaying: if turn == 'player': # Player's turn. drawBoard(theBoard) move = getPlayerMove(theBoard) makeMove(theBoard, playerLetter, move)