Python Tic Tac Toe
Python Tic Tac Toe
import random
def drawBoard(board):
# This function prints out the board that it was passed.
def inputPlayerLetter():
# Let's 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'):
print('Saad, do you want to be X or O?')
letter = input().upper()
# 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 whoGoesFirst():
# Randomly choose the player who goes first.
if random.randint(0, 1) == 0:
return 'computer'
else:
return 'player'
def playAgain():
# This function returns True if the player wants to play again,
otherwise it returns False.
print('Saad, do you want to play again? (yes or no)')
return input().lower().startswith('y')
def getBoardCopy(board):
# Make a duplicate of the board list and return it the duplicate.
dupeBoard = []
for i in board:
dupeBoard.append(i)
return dupeBoard
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)):
print('What is your next move, Saad? (1-9)')
move = input()
return int(move)
if len(possibleMoves) != 0:
return random.choice(possibleMoves)
else:
return None
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
while True:
# Reset the board
theBoard = [' '] * 10
playerLetter, computerLetter = inputPlayerLetter()
turn = whoGoesFirst()
print('The ' + turn + ' will go first.')
gameIsPlaying = True
while gameIsPlaying:
if turn == 'player':
# Player's turn.
drawBoard(theBoard)
move = getPlayerMove(theBoard)
makeMove(theBoard, playerLetter, move)
if isWinner(theBoard, playerLetter):
drawBoard(theBoard)
print('Less gooooo! You won the game! You are a pro. The
computer is trash. It is a bot. Less gooo!')
gameIsPlaying = False
else:
if isBoardFull(theBoard):
drawBoard(theBoard)
print('Man, you are trash. You are so bad. You lost a
bot. You are such a dissapointment. It is a tie!')
break
else:
turn = 'computer'
else:
# Computer's turn.
move = getComputerMove(theBoard, computerLetter)
makeMove(theBoard, computerLetter, move)
if isWinner(theBoard, computerLetter):
drawBoard(theBoard)
print('The computer won, you are so bad. You are the
trashiest kind of trash. You deserve to die. You are so free, free-er than
a turd in the wind!')
gameIsPlaying = False
else:
if isBoardFull(theBoard):
drawBoard(theBoard)
print('The game is a tie! You are bad. You are adopted
and your family does not love you.')
break
else:
turn = 'player'
if not playAgain():
break