Question
PYTHON- This is a Tic Tac Toe game. All I have to do is implement the try..except clause for all the input. I haven't used
PYTHON- This is a Tic Tac Toe game. All I have to do is implement the try..except clause for all the input. I haven't used this clause before, so if anyone could do the modifications needed in the code and implement the try..except clause wherever required.
import random
class TicTacToe:
def __init__(self):
# "board" is a list of 10 strings representing the board (ignore index 0)
self.board = [" "]*10
self.board[0]="#"
def drawBoard(self):
# This method prints out the board with current plays adjacent to a board with index.
print(' ' + self.board[7] + ' | ' + self.board[8] + ' | ' + self.board[9],' 7 | 8 | 9 ', sep='\t')
print('-----------','-----------', sep='\t')
print(' ' + self.board[4] + ' | ' + self.board[5] + ' | ' + self.board[6],' 4 | 5 | 6 ', sep='\t')
print('-----------','-----------', sep='\t')
print(' ' + self.board[1] + ' | ' + self.board[2] + ' | ' + self.board[3],' 1 | 2 | 3 ', sep='\t')
def boardFull(self):
# This method checks if the board is already full and returns True. Returns false otherwise
if " " in self.board:
return False
else:
return True
def cellIsEmpty(self, cell):
if cell==0 or cell>9:
return False
else:
return self.board[cell]==" "
def assignMove(self, cell,ch):
# assigns the cell of the board to the character ch
if cell<10 and cell>0:
self.board[cell]=turn
def whoWon(self):
# returns the symbol of the player who won if there is a winner, otherwise it returns an empty string.
if self.isWinner("x"):
return "x"
elif self.isWinner("o"):
return "o"
else:
return ""
def isWinner(self, ch):
# Given a player's letter, this method returns True if that player has won.
return ((self.board[7] == ch and self.board[8] == ch and self.board[9] == ch) or # across the top
(self.board[4] == ch and self.board[5] == ch and self.board[6] == ch) or # across the middle
(self.board[1] == ch and self.board[2] == ch and self.board[3] == ch) or # across the bottom
(self.board[7] == ch and self.board[4] == ch and self.board[1] == ch) or # down the left side
(self.board[8] == ch and self.board[5] == ch and self.board[2] == ch) or # down the middle
(self.board[9] == ch and self.board[6] == ch and self.board[3] == ch) or # down the right side
(self.board[7] == ch and self.board[5] == ch and self.board[3] == ch) or # diagonal
(self.board[9] == ch and self.board[5] == ch and self.board[1] == ch)) # diagonal
def isWinnerIfPlay(self,ch,cell):
# Given a player's letter (ch) and a cell position (cell), this method returns True if that player would win had he played that position.
if cell<0 or cell> 9: # incorrect range
return False
if self.board[cell]!=" ": #the position can't be played
return False
cboard=[" "]*10 #copy the board into another one to be able to simulate the plyer at the new position
for i in range(0,10):
cboard[i]=self.board[i]
cboard[cell]=ch #palying the player ch at position cell
return ((cboard[7] == ch and cboard[8] == ch and cboard[9] == ch) or # across the top
(cboard[4] == ch and cboard[5] == ch and cboard[6] == ch) or # across the middle
(cboard[1] == ch and cboard[2] == ch and cboard[3] == ch) or # across the bottom
(cboard[7] == ch and cboard[4] == ch and cboard[1] == ch) or # down the left side
(cboard[8] == ch and cboard[5] == ch and cboard[2] == ch) or # down the middle
(cboard[9] == ch and cboard[6] == ch and cboard[3] == ch) or # down the right side
(cboard[7] == ch and cboard[5] == ch and cboard[3] == ch) or # diagonal
(cboard[9] == ch and cboard[5] == ch and cboard[1] == ch)) # diagonal
def ComputerPlaysDum(board):
for i in range(1,10):
if board.cellIsEmpty(i):
return str(i)
def ComputerPlaysRandom(board):
r=random.randint(1,9)
while not board.cellIsEmpty(r):
r=random.randint(1,9)
return str(r)
def ComputerPlaysSmart(board,turn):
# First, check if we can win in the next move
for i in range(1, 10):
if board.isWinnerIfPlay(turn,i):
return str(i)
if turn=='x': #check the letter of the player (turn is computer)
player='o'
else:
player="x"
# Check if the player could win on his next move, and block them.
for i in range(1, 10):
if board.isWinnerIfPlay(player,i):
return str(i)
# Try to take the center, if it is free.
if board.cellIsEmpty(5):
return "5"
# Try to take one of the corners, if they are free.
corners=""
if board.cellIsEmpty(1):
corners+="1"
if board.cellIsEmpty(3):
corners+="3"
if board.cellIsEmpty(7):
corners+="7"
if board.cellIsEmpty(9):
corners+="9"
if corners!="":
return random.choice(corners)
# Move on one of the sides.
corners=""
if board.cellIsEmpty(2):
corners+="2"
if board.cellIsEmpty(4):
corners+="4"
if board.cellIsEmpty(6):
corners+="6"
if board.cellIsEmpty(8):
corners+="8"
if corners!="":
return random.choice(corners)
print ("Welcome to Tic Tac Toe Series")
myLoop=True
while myLoop:
print ("User against user ...............1")
print ("User against dumb computer ......2")
print ("User against random computer ....3")
print ("User against smart computer......4")
print ("Quit ............................5")
game=""
while game not in "1 2 3 4 5".split():
game=input("Enter your choice ")
if game=="5":
myLoop=False
elif game=="1":
myBoard=TicTacToe()
gameIsOn=True
turn="x"
while gameIsOn:
myBoard.drawBoard()
print ("It is the turn for", turn,". ",end="")
move="0"
while not myBoard.cellIsEmpty(int(move)):
move="0"
while move not in "1 2 3 4 5 6 7 8 9".split():
move=input("what is your move?")
if not myBoard.cellIsEmpty(int(move)):
print (move,"is not available. ",end='')
move="0"
myBoard.assignMove(int(move),turn)
winner=myBoard.whoWon()
if winner!='':
myBoard.drawBoard()
print (turn,"wins. Congrats!")
input("Press Enter to continue")
gameIsOn=False
elif myBoard.boardFull():
myBoard.drawBoard()
print ("It's a tie.")
input("Press Enter to continue")
gameIsOn=False
elif turn=="x":
turn="o"
else:
turn="x"
elif game=="2":
myBoard=TicTacToe()
gameIsOn=True
myTurn="."
while myTurn not in "o x".split():
myTurn=input("Do you want to play x or o?")
myTurn=myTurn.lower()
turn="x"
while gameIsOn:
myBoard.drawBoard()
if turn==myTurn:
print ("It is the turn for", turn,". ",end="")
move="0"
while not myBoard.cellIsEmpty(int(move)):
move="0"
while move not in "1 2 3 4 5 6 7 8 9".split():
move=input("What is your move?")
if not myBoard.cellIsEmpty(int(move)):
print (move,"is not available. ",end='')
move="0"
else:
print ("Computer's turn.",end="")
move=ComputerPlaysDum(myBoard)
print (" Played",move)
myBoard.assignMove(int(move),turn)
winner=myBoard.whoWon()
if winner!='':
drawBoard(myBoard)
if turn==myTurn:
print (turn,"wins. Congrats!")
else:
print ("Computer wins.")
input("Press Enter to continue")
gameIsOn=False
elif myBoard.boardFull():
drawBoard(myBoard)
print ("It's a tie.")
input("Press Enter to continue")
gameIsOn=False
elif turn=="x":
turn="o"
else:
turn="x"
elif game=="3":
myBoard=TicTacToe()
gameIsOn=True
myTurn="."
while myTurn not in "o x".split():
myTurn=input("Do you want to play x or o?")
myTurn=myTurn.lower()
turn="x"
while gameIsOn:
myBoard.drawBoard()
if turn==myTurn:
print ("It is the turn for", turn,". ",end="")
move="0"
while not myBoard.cellIsEmpty(int(move)):
move="0"
while move not in "1 2 3 4 5 6 7 8 9".split():
move=input("What is your move?")
if not myBoard.cellIsEmpty(int(move)):
print (move,"is not available. ",end='')
move="0"
else:
print ("Computer's turn.",end="")
move=ComputerPlaysRandom(myBoard)
print (" Played",move)
myBoard.assignMove(int(move),turn)
winner=myBoard.whoWon()
if winner!='':
myBoard.drawBoard()
if turn==myTurn:
print (turn,"wins. Congrats!")
else:
print ("Computer wins.")
input("Press Enter to continue")
gameIsOn=False
elif myBoard.boardFull():
myBoard.drawBoard()
print ("It's a tie.")
input("Press Enter to continue")
gameIsOn=False
elif turn=="x":
turn="o"
else:
turn="x"
elif game=="4":
myBoard=TicTacToe()
gameIsOn=True
myTurn="."
while myTurn not in "o x".split():
myTurn=input("Do you want to play x or o?")
myTurn=myTurn.lower()
turn="x"
while gameIsOn:
myBoard.drawBoard()
if turn==myTurn:
print ("It is the turn for", turn,". ",end="")
move="0"
while not myBoard.cellIsEmpty(int(move)):
move="0"
while move not in "1 2 3 4 5 6 7 8 9".split():
move=input("What is your move?")
if not myBoard.cellIsEmpty(int(move)):
print (move,"is not available. ",end='')
move="0"
else:
print ("Computer's turn.",end="")
move=ComputerPlaysSmart(myBoard,turn)
print (" Played",move)
myBoard.assignMove(int(move),turn)
winner=myBoard.whoWon()
if winner!='':
myBoard.drawBoard()
if turn==myTurn:
print (turn,"wins. Congrats!")
else:
print ("Computer wins.")
input("Press Enter to continue")
gameIsOn=False
elif myBoard.boardFull():
myBoard.drawBoard()
print ("It's a tie.")
input("Press Enter to continue")
gameIsOn=False
elif turn=="x":
turn="o"
else:
turn="x"
Step by Step Solution
There are 3 Steps involved in it
Step: 1
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started