Question

You will create a PYTHON program for Tic-Tac-Toe game. Tic-Tac-Toe is normally played with two people....

You will create a PYTHON program for Tic-Tac-Toe game. Tic-Tac-Toe is normally played with two people. One player is X and the other player is O. Players take turns placing their X or O. If a player gets three of his/her marks on the board in a row, column, or diagonal, he/she wins. When the board fills up with neither player winning, the game ends in a draw

1) Player 1 VS Player 2: Two players are playing the game (Player 1 and Player 2). You should have a flag for the turn of each player. The program must distinguish the players. You must create your program using functions in order to have a clean and structured code. The Player 1 must have the option to choose his/her symbol (X or O).

2) There is only one player that he is playing against an artificial intelligence (AI). The AI algorithm should choose the next move with the following priority to win, to block the player and randomly. The Player 1 must have the option to choose his/her symbol (X or O).

Save the current state game into a file. You should save the choice that has been made (Player 1 VS Player 2 or Player 1 VS Computer), the board and and the turn of the player. If the player puts as input the number ’0’ this will indicate that he needs to save the game and exit.

3) Load the saved state of the game and continue to play. You will need to create something similar with the memory of the advance calculator.

STARTED:

import random

# tic tac toe board

def drawBoard(board):
print(' | |')
print(' ' + board[7] + ' | ' + board[8] + ' | ' + board[9])
print(' | |')
print('-----------')
print(' | |')
print(' ' + board[4] + ' | ' + board[5] + ' | ' + board[6])
print(' | |')
print('-----------')
print(' | |')
print(' ' + board[1] + ' | ' + board[2] + ' | ' + board[3])
print(' | |')

def menu():
print('Welcome to Tic Tac Toe!')
  

#player vs computer
#player chooses if they want to be x or o
def inputPlayerLetter():
letter = ''
while not (letter == 'X' or letter == 'O'):
print('Player1: Do you want to be X or O?')
letter = input().upper()

if letter == 'X':
return ['X', 'O']
else:
return ['O', 'X']

# who goes first: computer or player
def whoGoesFirst():
if random.randint(0, 1) == 0:
return 'computer'
else:
return 'player'

#play again function

def playAgain():
print('Do you want to play again? (yes or no)')
return input().lower().startswith('y')

def makeMove(board, letter, move):
board[move] = letter

def isWinner(bo, le):

return ((bo[7] == le and bo[8] == le and bo[9] == le) or # across the top
(bo[4] == le and bo[5] == le and bo[6] == le) or # across the middle
(bo[1] == le and bo[2] == le and bo[3] == le) or # across the bottom
(bo[7] == le and bo[4] == le and bo[1] == le) or # down the left side
(bo[8] == le and bo[5] == le and bo[2] == le) or # down the middle
(bo[9] == le and bo[6] == le and bo[3] == le) or # down the right side
(bo[7] == le and bo[5] == le and bo[3] == le) or # diagonal
(bo[9] == le and bo[5] == le and bo[1] == le)) # diagonal

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 isSpaceFree(board, move):
# Return true if the passed move is free on the passed board.
return board[move] == ' '

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? (1-9)')
move = input()
return int(move)

def chooseRandomMoveFromList(board, movesList):
# Returns a valid move from the passed list on the passed board.
# Returns None if there is no valid move.
possibleMoves = []
for i in movesList:
if isSpaceFree(board, i):
possibleMoves.append(i)

if len(possibleMoves) != 0:
return random.choice(possibleMoves)
else:
return None

def getComputerMove(board, computerLetter):
# Given a board and the computer's letter, determine where to move and return that move.
if computerLetter == 'X':
playerLetter = 'O'
else:
playerLetter = 'X'

# Here is our algorithm for our Tic Tac Toe AI:
# First, check if we can win in the next move
for i in range(1, 10):
copy = getBoardCopy(board)
if isSpaceFree(copy, i):
makeMove(copy, computerLetter, i)
if isWinner(copy, computerLetter):
return i

# Check if the player could win on his next move, and block them.
for i in range(1, 10):
copy = getBoardCopy(board)
if isSpaceFree(copy, i):
makeMove(copy, playerLetter, i)
if isWinner(copy, playerLetter):
return i

# Try to take one of the corners, if they are free.
move = chooseRandomMoveFromList(board, [1, 3, 7, 9])
if move != None:
return move

# 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


print('Welcome to Tic Tac Toe!')

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('Hooray! You have won the game!')
gameIsPlaying = False
else:
if isBoardFull(theBoard):
drawBoard(theBoard)
print('The game 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 has beaten you! You lose.')
gameIsPlaying = False
else:
if isBoardFull(theBoard):
drawBoard(theBoard)
print('The game is a tie!')
break
else:
turn = 'player'

if not playAgain():
break

0 0
Add a comment Improve this question Transcribed image text
Answer #1

tic_tac_toe.py:

import random

# tic tac toe board

def drawBoard(board):
print(' | |')
print(' ' + board[7] + ' | ' + board[8] + ' | ' + board[9])
print(' | |')
print('-----------')
print(' | |')
print(' ' + board[4] + ' | ' + board[5] + ' | ' + board[6])
print(' | |')
print('-----------')
print(' | |')
print(' ' + board[1] + ' | ' + board[2] + ' | ' + board[3])
print(' | |')

def menu():
print('Welcome to Tic Tac Toe!')
  

#player vs computer
#player chooses if they want to be x or o
def inputPlayerLetter():
letter = ''
while not (letter == 'X' or letter == 'O'):
print('Player1: Do you want to be X or O?')
letter = input().upper()

if letter == 'X':
return ['X', 'O']
else:
return ['O', 'X']

# who goes first: computer or player
def whoGoesFirst():
return random.choice(('computer', 'player'))


#play again function

def playAgain():
# This function returns True if the player wants to play again, otherwise it returns False.
print('Do you want to play again? (yes or no)')
return input().lower().startswith('y')

def makeMove(board, letter, move):
if isSpaceFree(board,move):
board[move] = letter
else:
raise Exception("makemove: the field is not empty!")
def isWinner(bo, le):
# Given a board and a player's letter, this function returns True if that player has won.
# We use bo instead of board and le instead of letter so we don't have to type as much.
return ((bo[7] == le and bo[8] == le and bo[9] == le) or # across the top
(bo[4] == le and bo[5] == le and bo[6] == le) or # across the middle
(bo[1] == le and bo[2] == le and bo[3] == le) or # across the bottom
(bo[7] == le and bo[4] == le and bo[1] == le) or # down the left side
(bo[8] == le and bo[5] == le and bo[2] == le) or # down the middle
(bo[9] == le and bo[6] == le and bo[3] == le) or # down the right side
(bo[7] == le and bo[5] == le and bo[3] == le) or # diagonal
(bo[9] == le and bo[5] == le and bo[1] == le)) # diagonal

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 isSpaceFree(board, move):
# Return true if the passed move is free on the passed board.
return board[move].isdigit()

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? (1-9)')
move = input()
return int(move)

def chooseRandomMoveFromList(board, movesList):
# Returns a valid move from the passed list on the passed board.
# Returns None if there is no valid move.
possibleMoves = [i for i in movesList if isSpaceFree(board, i)]
return random.choice(possibleMoves) if possibleMoves else None

def getComputerMove(board, computerLetter):
# Given a board and the computer's letter, determine where to move and return that move.
playerLetter = 'O' if computerLetter == 'X' else 'X'

# Here is our algorithm for our Tic Tac Toe AI:
# First, check if we can win in the next move
for i in range(1, 10):
copy = getBoardCopy(board)
if isSpaceFree(copy, i):
makeMove(copy, computerLetter, i)
if isWinner(copy, computerLetter):
return i

# Check if the player could win on his next move, and block them.
for i in range(1, 10):
copy = getBoardCopy(board)
if isSpaceFree(copy, i):
makeMove(copy, playerLetter, i)
if isWinner(copy, playerLetter):
return i

# Try to take one of the corners, if they are free.
move = chooseRandomMoveFromList(board, [1, 3, 7, 9])
if move != None:
return move

# 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

def main():
print('Welcome to Tic Tac Toe!')
while True:
# Reset the board
theBoard = [' '] * 10
for i in range(9,0,-1):
theBoard[i] = str(i)
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('Hooray! You have won the game!')
gameIsPlaying = False
else:
if isBoardFull(theBoard):
drawBoard(theBoard)
print('The game 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 has beaten you! You lose.')
gameIsPlaying = False
else:
if isBoardFull(theBoard):
drawBoard(theBoard)
print('The game is a tie!')
break
else:
turn = 'player'
else:
#compute's turn.
move = getComputerMove(theBoard, computerLetter)
makeMove(theBoard, computerLetter, move)

if isWinner(theBoard, computerLetter):
drawBoard(theBoard)
print('The computer has beaten you! You Lose.')
gameIsPlaying = False
else:
if isBoardFull(theBoard):
drawBoard(theBoard)
print('The game is a tie!.')
break
else:
turn = 'player'
  

if not playAgain():
break
  
if __name__ == "__main__":
main()

Output:

Add a comment
Answer #1

tic_tac_toe.py:

import random

# tic tac toe board

def drawBoard(board):
print(' | |')
print(' ' + board[7] + ' | ' + board[8] + ' | ' + board[9])
print(' | |')
print('-----------')
print(' | |')
print(' ' + board[4] + ' | ' + board[5] + ' | ' + board[6])
print(' | |')
print('-----------')
print(' | |')
print(' ' + board[1] + ' | ' + board[2] + ' | ' + board[3])
print(' | |')

def menu():
print('Welcome to Tic Tac Toe!')
  

#player vs computer
#player chooses if they want to be x or o
def inputPlayerLetter():
letter = ''
while not (letter == 'X' or letter == 'O'):
print('Player1: Do you want to be X or O?')
letter = input().upper()

if letter == 'X':
return ['X', 'O']
else:
return ['O', 'X']

# who goes first: computer or player
def whoGoesFirst():
return random.choice(('computer', 'player'))


#play again function

def playAgain():
# This function returns True if the player wants to play again, otherwise it returns False.
print('Do you want to play again? (yes or no)')
return input().lower().startswith('y')

def makeMove(board, letter, move):
if isSpaceFree(board,move):
board[move] = letter
else:
raise Exception("makemove: the field is not empty!")
def isWinner(bo, le):
# Given a board and a player's letter, this function returns True if that player has won.
# We use bo instead of board and le instead of letter so we don't have to type as much.
return ((bo[7] == le and bo[8] == le and bo[9] == le) or # across the top
(bo[4] == le and bo[5] == le and bo[6] == le) or # across the middle
(bo[1] == le and bo[2] == le and bo[3] == le) or # across the bottom
(bo[7] == le and bo[4] == le and bo[1] == le) or # down the left side
(bo[8] == le and bo[5] == le and bo[2] == le) or # down the middle
(bo[9] == le and bo[6] == le and bo[3] == le) or # down the right side
(bo[7] == le and bo[5] == le and bo[3] == le) or # diagonal
(bo[9] == le and bo[5] == le and bo[1] == le)) # diagonal

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 isSpaceFree(board, move):
# Return true if the passed move is free on the passed board.
return board[move].isdigit()

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? (1-9)')
move = input()
return int(move)

def chooseRandomMoveFromList(board, movesList):
# Returns a valid move from the passed list on the passed board.
# Returns None if there is no valid move.
possibleMoves = [i for i in movesList if isSpaceFree(board, i)]
return random.choice(possibleMoves) if possibleMoves else None

def getComputerMove(board, computerLetter):
# Given a board and the computer's letter, determine where to move and return that move.
playerLetter = 'O' if computerLetter == 'X' else 'X'

# Here is our algorithm for our Tic Tac Toe AI:
# First, check if we can win in the next move
for i in range(1, 10):
copy = getBoardCopy(board)
if isSpaceFree(copy, i):
makeMove(copy, computerLetter, i)
if isWinner(copy, computerLetter):
return i

# Check if the player could win on his next move, and block them.
for i in range(1, 10):
copy = getBoardCopy(board)
if isSpaceFree(copy, i):
makeMove(copy, playerLetter, i)
if isWinner(copy, playerLetter):
return i

# Try to take one of the corners, if they are free.
move = chooseRandomMoveFromList(board, [1, 3, 7, 9])
if move != None:
return move

# 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

def main():
print('Welcome to Tic Tac Toe!')
while True:
# Reset the board
theBoard = [' '] * 10
for i in range(9,0,-1):
theBoard[i] = str(i)
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('Hooray! You have won the game!')
gameIsPlaying = False
else:
if isBoardFull(theBoard):
drawBoard(theBoard)
print('The game 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 has beaten you! You lose.')
gameIsPlaying = False
else:
if isBoardFull(theBoard):
drawBoard(theBoard)
print('The game is a tie!')
break
else:
turn = 'player'
else:
#compute's turn.
move = getComputerMove(theBoard, computerLetter)
makeMove(theBoard, computerLetter, move)

if isWinner(theBoard, computerLetter):
drawBoard(theBoard)
print('The computer has beaten you! You Lose.')
gameIsPlaying = False
else:
if isBoardFull(theBoard):
drawBoard(theBoard)
print('The game is a tie!.')
break
else:
turn = 'player'
  

if not playAgain():
break
  
if __name__ == "__main__":
main()

Output:

Add a comment
Know the answer?
Add Answer to:
You will create a PYTHON program for Tic-Tac-Toe game. Tic-Tac-Toe is normally played with two people....
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • (Tic-Tac-Toe) Create a class Tic-Tac-Toe that will enable you to write a program to play Tic-Tac-Toe....

    (Tic-Tac-Toe) Create a class Tic-Tac-Toe that will enable you to write a program to play Tic-Tac-Toe. The class contains a private 3-by-3 two-dimensional array. Use an enumeration to represent the value in each cell of the array. The enumeration’s constants should be named X, O and EMPTY (for a position that does not contain an X or an O). The constructor should initialize the board elements to EMPTY. Allow two human players. Wherever the first player moves, place an X...

  • Python Complete the player_turn() function that completes a single turn of the game Tic-Tac-Toe (also called...

    Python Complete the player_turn() function that completes a single turn of the game Tic-Tac-Toe (also called Noughts and Crosses). The function takes 3 parameters: 1. The first parameter is called board. It is a list of length 3, where each entry is a string with 3 characters representing a row on a Tic-Tac-Toe board. Each character in a row represents a slot on the Tic-Tac-Toe board with the "#" character indicating an empty slot. An empty board looks like this:...

  • PYTHON Exercise 2. Tic-Tac-Toe In this exercise we are going to create a Tic-Tac-Toe game. 1....

    PYTHON Exercise 2. Tic-Tac-Toe In this exercise we are going to create a Tic-Tac-Toe game. 1. Create the data structure – Nine slots that can each contain an X, an O, or a blank. – To represent the board with a dictionary, you can assign each slot a string-value key. – String values in the key-value pair to represent what’s in each slot on the board: ■ 'X' ■ 'O' ■ ‘ ‘ 2. Create a function to print the...

  • In traditional Tic Tac Toe game, two players take turns to mark grids with noughts and...

    In traditional Tic Tac Toe game, two players take turns to mark grids with noughts and crosses on the 3 x 3 game board. The player who succeeds in placing three of their marks in a horizontal, vertical, or diagonal row in the game board wins the game. Super Tic Tac Toe game also has a 3 x 3 game board with super grid. Each super grid itself is a traditional Tic Tac Toe board. Winning a game of Tic...

  • In a game of Tic Tac Toe, two players take turns making an available cell in...

    In a game of Tic Tac Toe, two players take turns making an available cell in a 3 x 3 grid with their respective tokens (either X or O). When one player has placed three tokens in a horizontal, vertical, or diagonal row on the grid, the game is over and that player has won. A stalemate occurs when all the cells on the grid have been filled with tokens and neither player has achieved a win. Write a program...

  • In a game of Tic Tac Toe, two players take turns making an available cell in...

    In a game of Tic Tac Toe, two players take turns making an available cell in a 3 x 3 grid with their respective tokens (either X or O). When one player has placed three tokens in a horizontal, vertical, or diagonal row on the grid, the game is over and that player has won. A stalemate occurs when all the cells on the grid have been filled with tokens and neither player has achieved a win. Write a program...

  • Implement a tic-tac-toe game. At the bottom of these specifications you will see a template you...

    Implement a tic-tac-toe game. At the bottom of these specifications you will see a template you must copy and paste to cloud9. Do not change the provided complete functions, or the function stub headers / return values. Currently, if the variables provided in main are commented out, the program will compile. Complete the specifications for each function. As you develop the program, implement one function at a time, and test that function. The provided comments provide hints as to what...

  • (Game: play a tic-tac-toe game) In a game of tic-tac-toe, two players take turns marking an...

    (Game: play a tic-tac-toe game) In a game of tic-tac-toe, two players take turns marking an available cell in a grid with their respective tokens (either X or O). When one player has placed three tokens in a horizontal, vertical, or diagonal row on the grid, the game is over and that player has won. A draw (no winner) occurs when all the cells in the grid have been filled with tokens and neither player has achieved a win. Create...

  • Write a program to Simulate a game of tic tac toe in c#

    Write a program to Simulate a game of tic tac toe. A game of tic tac toe has two players. A Player class is required to store /represent information about each player. The UML diagram is given below.Player-name: string-symbol :charPlayer (name:string,symbol:char)getName():stringgetSymbol():chargetInfo():string The tic tac toe board will be represented by a two dimensional array of size 3 by 3 characters. At the start of the game each cell is empty (must be set to the underscore character ‘_’). Program flow:1)    ...

  • 1. Use Turtle Graphics to create a tic tac toe game in Python. Write a Python program that allows for one player vs computer to play tic tac toe game, without using turtle.turtle

    1. Use Turtle Graphics to create a tic tac toe game in Python. Write a Python program that allows for one player vs computer to play tic tac toe game, without using turtle.turtle

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT