SlideShare a Scribd company logo
1 of 17
Download to read offline
#In this project you will write a program play TicTacToe
#using two players (labels 0,1) or one play (label 0) playing with the machine (label 1).
#The TicTacToe board has 9 integers board = [1,2,3,4,5,6,7,8,9]. The following
# are the modules for the program
#
#def reset() resets the board to the original values
# board = [1,2,3,4,5,6,7,8,9]
#
#def printBoard() print the current state of the board using the format
#
#The current TicTacToe Board
# | 1 | 2 | 3 |
# | 4 | 5 | 6 |
# | 7 | O | 9 |
#
#The current TicTacToe Board
# | X | 2 | 3 |
# | 4 | 5 | 6 |
# | 7 | O | 9 |
#Note from the above that player 0 and 1 have played numbers 8 and 1
#respectively and the board display O for player 0 and X from player 1
#
#def changeBoard(num1, player) using the chosen box number to change
#the value of the box to 0 or -1 depending on whether the player is 0 or 1,
#respectively.
#
#def play(player) prints the player number (0 or 1) and prompts the player
# to enter a box value that have not changed to 'O' or 'X'
#
#def checkRows(value) checks to see which of the rows of the board
# has the same value and returns True, otherwise, returns False
#
#def checkCols(value) checks to see which of the cols of the board
# has the same value and returns True, otherwise, returns False
#
#def checkDiagonal(value) checks to see which of the diagonals of the board
# has the same value and returns True, otherwise, returns False
#
#def win(player) checks if a player wins the game, returns True of the player wins
# and False otherwise
#
#def machinePlay(player) plays the role of the player using random number.
# this function generates numbers in the interval [1,9] and uses the first
# generated random number that has not been used to play the game. The
#
#def ticTacToe(numPlayers) accepts the number of players and simulates the
#ticTapToe, asking players to enter unused box numbers.
#
#def main() is the driver module that accepts the number of players from the user
# and calls the ticTacToe module
#Assignment: Complete the follwoing modules:
#checkCols
#checkRows
#checkDiagonal
#win
#Sample of the output is
#
#Project
#This game can be played by one or two players
#Enter the number of players, 1/2 for one/two players: 1
#
#The current TicTapToe Board
#| 1 | 2 | 3 |
#| 4 | 5 | 6 |
#| 7 | 8 | 9 |
#Player 0 Enter a box value: 9
#
#The current TicTapToe Board
#| 1 | 2 | 3 |
#| 4 | 5 | 6 |
#| 7 | 8 | O |
#Player 1 ***Computer*** playing
#The current TicTapToe Board
#| 1 | 2 | 3 |
#| 4 | 5 | 6 |
#| 7 | X | O |
#Player 0 Enter a box value: 1
#
#The current TicTapToe Board
#| O | 2 | 3 |
#| 4 | 5 | 6 |
#| 7 | X | O |
#Player 1 ***Computer*** playing
#
#The current TicTapToe Board
#| O | X | 3 |
#| 4 | 5 | 6 |
#| 7 | X | O |
#Player 0 Enter a box value: 5
#
#The current TicTapToe Board
#| O | X | 3 |
#| 4 | O | 6 |
#| 7 | X | O |
#Player 0 Wins
#Do you want to quit?
#Begin Program
#import random number generator
#from random library
#from random import randint, seed
#Global variable board representing the ticTacToe board
board = [1,2,3,4,5,6,7,8,9]
#This module resets the ticTacToe board to the original values
def reset():
for k in range(1,10): #loop through a sequence [1,2,3,..,9]
board[k-1] = k
#This module prints the ticTacToe board in a 3 by 3 matrix
#using the format
# | 1 | 2 | 3 |
# | 4 | 5 | 6 |
# | 7 | 8 | 9 |
#
def printBoard ():
print(' The current TicTapToe Board')
for m in range(3):
string = '| '
for n in range(3):
if board[n+3*m] == 0:
string = string + ' O |'
elif board[n+3*m] == -1:
string = string + ' X |'
else:
string = string + ' ' + str(board[n+3*m]) + ' |'
print(string)
#This module changes the value (num1) of a box in the ticTacTop board chosen
# by player 0 to 0 and player 1 to -1
#
def changeBoard(num1,player):
for k in range(len(board)):
if board[k] == num1 and player == 0:
board[k] = 0
elif board[k] == num1 and player == 1:
board[k] = -1
#This module prompts the player to enter a box value. The format is
# 'Player Enter a box value'
#
def printBoard ():
print(' The current TicTapToe Board')
for m in range(3):
string = '| '
for n in range(3):
if board[n+3*m] == 0:
string = string + ' O |'
elif board[n+3*m] == -1:
string = string + ' X |'
else:
string = string + ' ' + str(board[n+3*m]) + ' |'
print(string)
#This module checks if boxes in anyone of the rows have the same value
#The module returns True if that is the case and False otherwise
#
def checkRows(value):
#Complete
# horizontally , first row of the board contains same mark, it is win
if(board[1] == board[2] and board[2] == board[3]):
return True;
# horizontally , second row of the board contains same mark, it is win
elif(board[4] == board[5] and board[5] == board[6]):
return True;
# horizontally , third row of the board contains same mark, it is win
elif(board[7] == board[8] and board[8] == board[9]):
return True;
# if all the above cases fails, then it is lose
else:
return False;
#
#This module checks if boxes in anyone of the cols have the same value
#The module returns True if that is the case and False otherwise
#
def checkCols(value):
#Complete
# vertically , first column of the board contains same mark, it is win
if (board[1] == board[4] and board[4] == board[7]):
return True;
# vertically , second column of the board contains same mark, it is win
elif (board[2] and board[5] and board[5] == board[8]):
return True;
# vertically , third column of the board contains same mark, it is win
elif (board[3] and board[6] and board[6] == board[9]):
return True;
else:
return False;
#
#This module checks if boxes in anyone of the diagonals have the same value
#The module returns True if that is the case and False otherwise
#
def checkDiagonal(value):
#Complete
#diagonal check for same mark. if yes , then it is win
if (board[1] and board[5] and board[5] == board[9]):
return True;
#diagonal check for same mark. if yes , then it is win
elif (board[3] and board[5] and board[5] == board[7]):
return True;
else:
return False;
#This module determines whether or not a player wins after playing the
# a turn. This module uses checkDiagonal, checkRows and checkCols to
# ascertain if the player wins. As least one of the options (checkDiagonal,
# checkCols and checkRows must return a True.
# This module returns True if the player wins and False, otherwise
# This module also print
# 'Player 0 Wins' if player 0 wins
# 'Player 1 Wins' if player 1 wins
def win(player):
#Complete
if(checkRows(player)==True or checkCols(player)==True or checkDiagonal(player)==True):
if(player==0):
print('Player 0 wins');
else:
print('Player 1 wins');
return True;
else:
return False;
#This module is only for 1 player only. In this case, this player
#plays with the machine. The machine uses random numbers. Random numbers are
#generated and tested to determine whether or not the generated random number has been
#played. The first generated random number that has not been played is chosen.
#If after 100 trials, no unplayed is found, nothing is done and a warning is
#sent to the player. IT IS ASSUMED THAT THIS SCENARIO WILL NOT OCCUR. NOTE
THAT
#THERE IS NOT INTELLIGENCE BUILT IN TO PROGRAM THAT WILL ALLOW
COMPUTER TO
#CHOOSE THE BEST NUMBER TO PLAY. YOU WILL RECEIVE BONUS POINT IF YOU
COULD
#MODIFY THE MODULE TO ALLOW COMPUTER SELECT THE BEST NUMBER.
#
def machinePlay(player):
print('Player ', player, '***Computer*** playing')
seed()
r = randint(1,9)
index = 0
while index<100 and (board[r-1] ==0 or board[r-1] ==-1):
r = randint(1,9)
index = index + 1
if index < 100:
changeBoard(r,player)
printBoard()
else:
print('Computer could not play after 100 trials')
#The module plays the tictactoe game, using modules defined above.
#The module allows players to play any number of games until the
# payer(s) decides to quit. This represent the first while loop.
#The second while loop allows players to take turns making rounds. Note that
#since there are 9 box numbers total, the maximum number of rounds is 9. If
# after 9 rounds and there is no winner, the board is reset and player(s) will
# prompted to determine whether or not to start a new game.
#
def ticTacToe(numPlayers):
quitPlay = 'n'
while (quitPlay == 'n'):
reset()
printBoard()
if numPlayers == 2:
playover = False
rounds = 0
while not(playover) and rounds<9:
player = 0
play(player)
playover = win(player)
rounds = rounds + 1
if not(playover) and rounds <9 :
player = 1
play(player)
playover = win(player)
rounds = rounds + 1
if rounds >= 9:
print("It is a draw")
elif numPlayers == 1:
playover = False
rounds = 1
while not(playover) and rounds<=9:
player = 0
play(player)
playover = win(player)
rounds = rounds + 1
if not(playover) and rounds <9 :
player = 1
machinePlay(player)
playover = win(player)
rounds = rounds + 1
if rounds > 9:
print("It is a draw")
else:
print('Oohs! Number of players is not 1 or 2')
quitPlay = 'y'
if quitPlay != 'y':
quitPlay = input('Do you want to quit?')
def main():
print('Welcome to TicTacToe Game')
print('Project')
print('This game can be played by one or two players')
numPlayers = int(input('Enter the number of players, 1/2 for one/two players: '))
ticTacToe(numPlayers)
print('Thanks for playing TicTapToe!')
main()
#end program
Solution
#In this project you will write a program play TicTacToe
#using two players (labels 0,1) or one play (label 0) playing with the machine (label 1).
#The TicTacToe board has 9 integers board = [1,2,3,4,5,6,7,8,9]. The following
# are the modules for the program
#
#def reset() resets the board to the original values
# board = [1,2,3,4,5,6,7,8,9]
#
#def printBoard() print the current state of the board using the format
#
#The current TicTacToe Board
# | 1 | 2 | 3 |
# | 4 | 5 | 6 |
# | 7 | O | 9 |
#
#The current TicTacToe Board
# | X | 2 | 3 |
# | 4 | 5 | 6 |
# | 7 | O | 9 |
#Note from the above that player 0 and 1 have played numbers 8 and 1
#respectively and the board display O for player 0 and X from player 1
#
#def changeBoard(num1, player) using the chosen box number to change
#the value of the box to 0 or -1 depending on whether the player is 0 or 1,
#respectively.
#
#def play(player) prints the player number (0 or 1) and prompts the player
# to enter a box value that have not changed to 'O' or 'X'
#
#def checkRows(value) checks to see which of the rows of the board
# has the same value and returns True, otherwise, returns False
#
#def checkCols(value) checks to see which of the cols of the board
# has the same value and returns True, otherwise, returns False
#
#def checkDiagonal(value) checks to see which of the diagonals of the board
# has the same value and returns True, otherwise, returns False
#
#def win(player) checks if a player wins the game, returns True of the player wins
# and False otherwise
#
#def machinePlay(player) plays the role of the player using random number.
# this function generates numbers in the interval [1,9] and uses the first
# generated random number that has not been used to play the game. The
#
#def ticTacToe(numPlayers) accepts the number of players and simulates the
#ticTapToe, asking players to enter unused box numbers.
#
#def main() is the driver module that accepts the number of players from the user
# and calls the ticTacToe module
#Assignment: Complete the follwoing modules:
#checkCols
#checkRows
#checkDiagonal
#win
#Sample of the output is
#
#Project
#This game can be played by one or two players
#Enter the number of players, 1/2 for one/two players: 1
#
#The current TicTapToe Board
#| 1 | 2 | 3 |
#| 4 | 5 | 6 |
#| 7 | 8 | 9 |
#Player 0 Enter a box value: 9
#
#The current TicTapToe Board
#| 1 | 2 | 3 |
#| 4 | 5 | 6 |
#| 7 | 8 | O |
#Player 1 ***Computer*** playing
#The current TicTapToe Board
#| 1 | 2 | 3 |
#| 4 | 5 | 6 |
#| 7 | X | O |
#Player 0 Enter a box value: 1
#
#The current TicTapToe Board
#| O | 2 | 3 |
#| 4 | 5 | 6 |
#| 7 | X | O |
#Player 1 ***Computer*** playing
#
#The current TicTapToe Board
#| O | X | 3 |
#| 4 | 5 | 6 |
#| 7 | X | O |
#Player 0 Enter a box value: 5
#
#The current TicTapToe Board
#| O | X | 3 |
#| 4 | O | 6 |
#| 7 | X | O |
#Player 0 Wins
#Do you want to quit?
#Begin Program
#import random number generator
#from random library
#from random import randint, seed
#Global variable board representing the ticTacToe board
board = [1,2,3,4,5,6,7,8,9]
#This module resets the ticTacToe board to the original values
def reset():
for k in range(1,10): #loop through a sequence [1,2,3,..,9]
board[k-1] = k
#This module prints the ticTacToe board in a 3 by 3 matrix
#using the format
# | 1 | 2 | 3 |
# | 4 | 5 | 6 |
# | 7 | 8 | 9 |
#
def printBoard ():
print(' The current TicTapToe Board')
for m in range(3):
string = '| '
for n in range(3):
if board[n+3*m] == 0:
string = string + ' O |'
elif board[n+3*m] == -1:
string = string + ' X |'
else:
string = string + ' ' + str(board[n+3*m]) + ' |'
print(string)
#This module changes the value (num1) of a box in the ticTacTop board chosen
# by player 0 to 0 and player 1 to -1
#
def changeBoard(num1,player):
for k in range(len(board)):
if board[k] == num1 and player == 0:
board[k] = 0
elif board[k] == num1 and player == 1:
board[k] = -1
#This module prompts the player to enter a box value. The format is
# 'Player Enter a box value'
#
def printBoard ():
print(' The current TicTapToe Board')
for m in range(3):
string = '| '
for n in range(3):
if board[n+3*m] == 0:
string = string + ' O |'
elif board[n+3*m] == -1:
string = string + ' X |'
else:
string = string + ' ' + str(board[n+3*m]) + ' |'
print(string)
#This module checks if boxes in anyone of the rows have the same value
#The module returns True if that is the case and False otherwise
#
def checkRows(value):
#Complete
# horizontally , first row of the board contains same mark, it is win
if(board[1] == board[2] and board[2] == board[3]):
return True;
# horizontally , second row of the board contains same mark, it is win
elif(board[4] == board[5] and board[5] == board[6]):
return True;
# horizontally , third row of the board contains same mark, it is win
elif(board[7] == board[8] and board[8] == board[9]):
return True;
# if all the above cases fails, then it is lose
else:
return False;
#
#This module checks if boxes in anyone of the cols have the same value
#The module returns True if that is the case and False otherwise
#
def checkCols(value):
#Complete
# vertically , first column of the board contains same mark, it is win
if (board[1] == board[4] and board[4] == board[7]):
return True;
# vertically , second column of the board contains same mark, it is win
elif (board[2] and board[5] and board[5] == board[8]):
return True;
# vertically , third column of the board contains same mark, it is win
elif (board[3] and board[6] and board[6] == board[9]):
return True;
else:
return False;
#
#This module checks if boxes in anyone of the diagonals have the same value
#The module returns True if that is the case and False otherwise
#
def checkDiagonal(value):
#Complete
#diagonal check for same mark. if yes , then it is win
if (board[1] and board[5] and board[5] == board[9]):
return True;
#diagonal check for same mark. if yes , then it is win
elif (board[3] and board[5] and board[5] == board[7]):
return True;
else:
return False;
#This module determines whether or not a player wins after playing the
# a turn. This module uses checkDiagonal, checkRows and checkCols to
# ascertain if the player wins. As least one of the options (checkDiagonal,
# checkCols and checkRows must return a True.
# This module returns True if the player wins and False, otherwise
# This module also print
# 'Player 0 Wins' if player 0 wins
# 'Player 1 Wins' if player 1 wins
def win(player):
#Complete
if(checkRows(player)==True or checkCols(player)==True or checkDiagonal(player)==True):
if(player==0):
print('Player 0 wins');
else:
print('Player 1 wins');
return True;
else:
return False;
#This module is only for 1 player only. In this case, this player
#plays with the machine. The machine uses random numbers. Random numbers are
#generated and tested to determine whether or not the generated random number has been
#played. The first generated random number that has not been played is chosen.
#If after 100 trials, no unplayed is found, nothing is done and a warning is
#sent to the player. IT IS ASSUMED THAT THIS SCENARIO WILL NOT OCCUR. NOTE
THAT
#THERE IS NOT INTELLIGENCE BUILT IN TO PROGRAM THAT WILL ALLOW
COMPUTER TO
#CHOOSE THE BEST NUMBER TO PLAY. YOU WILL RECEIVE BONUS POINT IF YOU
COULD
#MODIFY THE MODULE TO ALLOW COMPUTER SELECT THE BEST NUMBER.
#
def machinePlay(player):
print('Player ', player, '***Computer*** playing')
seed()
r = randint(1,9)
index = 0
while index<100 and (board[r-1] ==0 or board[r-1] ==-1):
r = randint(1,9)
index = index + 1
if index < 100:
changeBoard(r,player)
printBoard()
else:
print('Computer could not play after 100 trials')
#The module plays the tictactoe game, using modules defined above.
#The module allows players to play any number of games until the
# payer(s) decides to quit. This represent the first while loop.
#The second while loop allows players to take turns making rounds. Note that
#since there are 9 box numbers total, the maximum number of rounds is 9. If
# after 9 rounds and there is no winner, the board is reset and player(s) will
# prompted to determine whether or not to start a new game.
#
def ticTacToe(numPlayers):
quitPlay = 'n'
while (quitPlay == 'n'):
reset()
printBoard()
if numPlayers == 2:
playover = False
rounds = 0
while not(playover) and rounds<9:
player = 0
play(player)
playover = win(player)
rounds = rounds + 1
if not(playover) and rounds <9 :
player = 1
play(player)
playover = win(player)
rounds = rounds + 1
if rounds >= 9:
print("It is a draw")
elif numPlayers == 1:
playover = False
rounds = 1
while not(playover) and rounds<=9:
player = 0
play(player)
playover = win(player)
rounds = rounds + 1
if not(playover) and rounds <9 :
player = 1
machinePlay(player)
playover = win(player)
rounds = rounds + 1
if rounds > 9:
print("It is a draw")
else:
print('Oohs! Number of players is not 1 or 2')
quitPlay = 'y'
if quitPlay != 'y':
quitPlay = input('Do you want to quit?')
def main():
print('Welcome to TicTacToe Game')
print('Project')
print('This game can be played by one or two players')
numPlayers = int(input('Enter the number of players, 1/2 for one/two players: '))
ticTacToe(numPlayers)
print('Thanks for playing TicTapToe!')
main()
#end program

More Related Content

Similar to #In this project you will write a program play TicTacToe #using tw.pdf

Please help with this. program must be written in C# .. All of the g.pdf
Please help with this. program must be written in C# .. All of the g.pdfPlease help with this. program must be written in C# .. All of the g.pdf
Please help with this. program must be written in C# .. All of the g.pdfmanjan6
 
The following is my code for a connectn program. When I run my code .pdf
The following is my code for a connectn program. When I run my code .pdfThe following is my code for a connectn program. When I run my code .pdf
The following is my code for a connectn program. When I run my code .pdfeyelineoptics
 
project 6cards.pyimport randomclass Card( object ).docx
project 6cards.pyimport randomclass Card( object ).docxproject 6cards.pyimport randomclass Card( object ).docx
project 6cards.pyimport randomclass Card( object ).docxbriancrawford30935
 
Game programming-help
Game programming-helpGame programming-help
Game programming-helpSteve Nash
 
You will write a multi-interface version of the well-known concentra.pdf
You will write a multi-interface version of the well-known concentra.pdfYou will write a multi-interface version of the well-known concentra.pdf
You will write a multi-interface version of the well-known concentra.pdfFashionColZone
 
NO PAPER ANSWERS. ALL ANSWER SUBMISSIONS SHOULD BE ABLE TO RUN WIT.pdf
NO PAPER ANSWERS. ALL ANSWER SUBMISSIONS SHOULD BE ABLE TO RUN WIT.pdfNO PAPER ANSWERS. ALL ANSWER SUBMISSIONS SHOULD BE ABLE TO RUN WIT.pdf
NO PAPER ANSWERS. ALL ANSWER SUBMISSIONS SHOULD BE ABLE TO RUN WIT.pdffms12345
 
C++ projct
C++ projctC++ projct
C++ projctJ M
 

Similar to #In this project you will write a program play TicTacToe #using tw.pdf (7)

Please help with this. program must be written in C# .. All of the g.pdf
Please help with this. program must be written in C# .. All of the g.pdfPlease help with this. program must be written in C# .. All of the g.pdf
Please help with this. program must be written in C# .. All of the g.pdf
 
The following is my code for a connectn program. When I run my code .pdf
The following is my code for a connectn program. When I run my code .pdfThe following is my code for a connectn program. When I run my code .pdf
The following is my code for a connectn program. When I run my code .pdf
 
project 6cards.pyimport randomclass Card( object ).docx
project 6cards.pyimport randomclass Card( object ).docxproject 6cards.pyimport randomclass Card( object ).docx
project 6cards.pyimport randomclass Card( object ).docx
 
Game programming-help
Game programming-helpGame programming-help
Game programming-help
 
You will write a multi-interface version of the well-known concentra.pdf
You will write a multi-interface version of the well-known concentra.pdfYou will write a multi-interface version of the well-known concentra.pdf
You will write a multi-interface version of the well-known concentra.pdf
 
NO PAPER ANSWERS. ALL ANSWER SUBMISSIONS SHOULD BE ABLE TO RUN WIT.pdf
NO PAPER ANSWERS. ALL ANSWER SUBMISSIONS SHOULD BE ABLE TO RUN WIT.pdfNO PAPER ANSWERS. ALL ANSWER SUBMISSIONS SHOULD BE ABLE TO RUN WIT.pdf
NO PAPER ANSWERS. ALL ANSWER SUBMISSIONS SHOULD BE ABLE TO RUN WIT.pdf
 
C++ projct
C++ projctC++ projct
C++ projct
 

More from aquapariwar

First, lets find out what we need.The question asks for the empi.pdf
First, lets find out what we need.The question asks for the empi.pdfFirst, lets find out what we need.The question asks for the empi.pdf
First, lets find out what we need.The question asks for the empi.pdfaquapariwar
 
DiversityDiversity scheme refers to a method for improving the re.pdf
DiversityDiversity scheme refers to a method for improving the re.pdfDiversityDiversity scheme refers to a method for improving the re.pdf
DiversityDiversity scheme refers to a method for improving the re.pdfaquapariwar
 
due to repulsions between lone pair and bond pair of electrons on Te.pdf
due to repulsions between lone pair and bond pair of electrons on Te.pdfdue to repulsions between lone pair and bond pair of electrons on Te.pdf
due to repulsions between lone pair and bond pair of electrons on Te.pdfaquapariwar
 
AnswerKidneys are the functional units of renal system of rom uri.pdf
AnswerKidneys are the functional units of renal system of rom uri.pdfAnswerKidneys are the functional units of renal system of rom uri.pdf
AnswerKidneys are the functional units of renal system of rom uri.pdfaquapariwar
 
a. In puple bacteria P870 is present. External electron donors are h.pdf
a. In puple bacteria P870 is present. External electron donors are h.pdfa. In puple bacteria P870 is present. External electron donors are h.pdf
a. In puple bacteria P870 is present. External electron donors are h.pdfaquapariwar
 
A)ANS)In this TCPIP - System Access Layer, you will find out ab.pdf
A)ANS)In this TCPIP - System Access Layer, you will find out ab.pdfA)ANS)In this TCPIP - System Access Layer, you will find out ab.pdf
A)ANS)In this TCPIP - System Access Layer, you will find out ab.pdfaquapariwar
 
The ice allows the refluxed materials to crystall.pdf
                     The ice allows the refluxed materials to crystall.pdf                     The ice allows the refluxed materials to crystall.pdf
The ice allows the refluxed materials to crystall.pdfaquapariwar
 
this is my code to count the frequency of words in a text file#.pdf
 this is my code to count the frequency of words in a text file#.pdf this is my code to count the frequency of words in a text file#.pdf
this is my code to count the frequency of words in a text file#.pdfaquapariwar
 
1.1Yearcash flowpresent value of cash inflow = cash flow(1+r).pdf
1.1Yearcash flowpresent value of cash inflow = cash flow(1+r).pdf1.1Yearcash flowpresent value of cash inflow = cash flow(1+r).pdf
1.1Yearcash flowpresent value of cash inflow = cash flow(1+r).pdfaquapariwar
 
HNO2 is a much weaker acid then HNO3 (strong acid.pdf
                     HNO2 is a much weaker acid then HNO3 (strong acid.pdf                     HNO2 is a much weaker acid then HNO3 (strong acid.pdf
HNO2 is a much weaker acid then HNO3 (strong acid.pdfaquapariwar
 
1. Identify five differences between DNA replication and gene transc.pdf
1. Identify five differences between DNA replication and gene transc.pdf1. Identify five differences between DNA replication and gene transc.pdf
1. Identify five differences between DNA replication and gene transc.pdfaquapariwar
 
1. b2. c (bed bug)3. d (caterpillars)4. c (lyme disease)5. e.pdf
1. b2. c (bed bug)3. d (caterpillars)4. c (lyme disease)5. e.pdf1. b2. c (bed bug)3. d (caterpillars)4. c (lyme disease)5. e.pdf
1. b2. c (bed bug)3. d (caterpillars)4. c (lyme disease)5. e.pdfaquapariwar
 
A. the chemical formula for the base calcium (II) hydroxide is Ca(OH.pdf
A. the chemical formula for the base calcium (II) hydroxide is Ca(OH.pdfA. the chemical formula for the base calcium (II) hydroxide is Ca(OH.pdf
A. the chemical formula for the base calcium (II) hydroxide is Ca(OH.pdfaquapariwar
 
1) MODERN TIMES is a very well prepared movie that describes the mis.pdf
1) MODERN TIMES is a very well prepared movie that describes the mis.pdf1) MODERN TIMES is a very well prepared movie that describes the mis.pdf
1) MODERN TIMES is a very well prepared movie that describes the mis.pdfaquapariwar
 
An ion is an atom that has a charge. These charges can be postive or.pdf
An ion is an atom that has a charge. These charges can be postive or.pdfAn ion is an atom that has a charge. These charges can be postive or.pdf
An ion is an atom that has a charge. These charges can be postive or.pdfaquapariwar
 
Acids are substances that form hydrogen ions, H+(.pdf
                     Acids are substances that form hydrogen ions, H+(.pdf                     Acids are substances that form hydrogen ions, H+(.pdf
Acids are substances that form hydrogen ions, H+(.pdfaquapariwar
 
ANSWER1.Apocalypse Now film overall formIt is the height o.pdf
ANSWER1.Apocalypse Now film overall formIt is the height o.pdfANSWER1.Apocalypse Now film overall formIt is the height o.pdf
ANSWER1.Apocalypse Now film overall formIt is the height o.pdfaquapariwar
 
15.0mL = 0.015L phenylacetic acid 0.50molL 0.01.pdf
                     15.0mL = 0.015L phenylacetic acid 0.50molL 0.01.pdf                     15.0mL = 0.015L phenylacetic acid 0.50molL 0.01.pdf
15.0mL = 0.015L phenylacetic acid 0.50molL 0.01.pdfaquapariwar
 
4 water molecules are like a magnet because beca.pdf
                     4 water molecules are like a magnet because beca.pdf                     4 water molecules are like a magnet because beca.pdf
4 water molecules are like a magnet because beca.pdfaquapariwar
 

More from aquapariwar (19)

First, lets find out what we need.The question asks for the empi.pdf
First, lets find out what we need.The question asks for the empi.pdfFirst, lets find out what we need.The question asks for the empi.pdf
First, lets find out what we need.The question asks for the empi.pdf
 
DiversityDiversity scheme refers to a method for improving the re.pdf
DiversityDiversity scheme refers to a method for improving the re.pdfDiversityDiversity scheme refers to a method for improving the re.pdf
DiversityDiversity scheme refers to a method for improving the re.pdf
 
due to repulsions between lone pair and bond pair of electrons on Te.pdf
due to repulsions between lone pair and bond pair of electrons on Te.pdfdue to repulsions between lone pair and bond pair of electrons on Te.pdf
due to repulsions between lone pair and bond pair of electrons on Te.pdf
 
AnswerKidneys are the functional units of renal system of rom uri.pdf
AnswerKidneys are the functional units of renal system of rom uri.pdfAnswerKidneys are the functional units of renal system of rom uri.pdf
AnswerKidneys are the functional units of renal system of rom uri.pdf
 
a. In puple bacteria P870 is present. External electron donors are h.pdf
a. In puple bacteria P870 is present. External electron donors are h.pdfa. In puple bacteria P870 is present. External electron donors are h.pdf
a. In puple bacteria P870 is present. External electron donors are h.pdf
 
A)ANS)In this TCPIP - System Access Layer, you will find out ab.pdf
A)ANS)In this TCPIP - System Access Layer, you will find out ab.pdfA)ANS)In this TCPIP - System Access Layer, you will find out ab.pdf
A)ANS)In this TCPIP - System Access Layer, you will find out ab.pdf
 
The ice allows the refluxed materials to crystall.pdf
                     The ice allows the refluxed materials to crystall.pdf                     The ice allows the refluxed materials to crystall.pdf
The ice allows the refluxed materials to crystall.pdf
 
this is my code to count the frequency of words in a text file#.pdf
 this is my code to count the frequency of words in a text file#.pdf this is my code to count the frequency of words in a text file#.pdf
this is my code to count the frequency of words in a text file#.pdf
 
1.1Yearcash flowpresent value of cash inflow = cash flow(1+r).pdf
1.1Yearcash flowpresent value of cash inflow = cash flow(1+r).pdf1.1Yearcash flowpresent value of cash inflow = cash flow(1+r).pdf
1.1Yearcash flowpresent value of cash inflow = cash flow(1+r).pdf
 
HNO2 is a much weaker acid then HNO3 (strong acid.pdf
                     HNO2 is a much weaker acid then HNO3 (strong acid.pdf                     HNO2 is a much weaker acid then HNO3 (strong acid.pdf
HNO2 is a much weaker acid then HNO3 (strong acid.pdf
 
1. Identify five differences between DNA replication and gene transc.pdf
1. Identify five differences between DNA replication and gene transc.pdf1. Identify five differences between DNA replication and gene transc.pdf
1. Identify five differences between DNA replication and gene transc.pdf
 
1. b2. c (bed bug)3. d (caterpillars)4. c (lyme disease)5. e.pdf
1. b2. c (bed bug)3. d (caterpillars)4. c (lyme disease)5. e.pdf1. b2. c (bed bug)3. d (caterpillars)4. c (lyme disease)5. e.pdf
1. b2. c (bed bug)3. d (caterpillars)4. c (lyme disease)5. e.pdf
 
A. the chemical formula for the base calcium (II) hydroxide is Ca(OH.pdf
A. the chemical formula for the base calcium (II) hydroxide is Ca(OH.pdfA. the chemical formula for the base calcium (II) hydroxide is Ca(OH.pdf
A. the chemical formula for the base calcium (II) hydroxide is Ca(OH.pdf
 
1) MODERN TIMES is a very well prepared movie that describes the mis.pdf
1) MODERN TIMES is a very well prepared movie that describes the mis.pdf1) MODERN TIMES is a very well prepared movie that describes the mis.pdf
1) MODERN TIMES is a very well prepared movie that describes the mis.pdf
 
An ion is an atom that has a charge. These charges can be postive or.pdf
An ion is an atom that has a charge. These charges can be postive or.pdfAn ion is an atom that has a charge. These charges can be postive or.pdf
An ion is an atom that has a charge. These charges can be postive or.pdf
 
Acids are substances that form hydrogen ions, H+(.pdf
                     Acids are substances that form hydrogen ions, H+(.pdf                     Acids are substances that form hydrogen ions, H+(.pdf
Acids are substances that form hydrogen ions, H+(.pdf
 
ANSWER1.Apocalypse Now film overall formIt is the height o.pdf
ANSWER1.Apocalypse Now film overall formIt is the height o.pdfANSWER1.Apocalypse Now film overall formIt is the height o.pdf
ANSWER1.Apocalypse Now film overall formIt is the height o.pdf
 
15.0mL = 0.015L phenylacetic acid 0.50molL 0.01.pdf
                     15.0mL = 0.015L phenylacetic acid 0.50molL 0.01.pdf                     15.0mL = 0.015L phenylacetic acid 0.50molL 0.01.pdf
15.0mL = 0.015L phenylacetic acid 0.50molL 0.01.pdf
 
4 water molecules are like a magnet because beca.pdf
                     4 water molecules are like a magnet because beca.pdf                     4 water molecules are like a magnet because beca.pdf
4 water molecules are like a magnet because beca.pdf
 

Recently uploaded

CARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxCARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxGaneshChakor2
 
EPANDING THE CONTENT OF AN OUTLINE using notes.pptx
EPANDING THE CONTENT OF AN OUTLINE using notes.pptxEPANDING THE CONTENT OF AN OUTLINE using notes.pptx
EPANDING THE CONTENT OF AN OUTLINE using notes.pptxRaymartEstabillo3
 
Final demo Grade 9 for demo Plan dessert.pptx
Final demo Grade 9 for demo Plan dessert.pptxFinal demo Grade 9 for demo Plan dessert.pptx
Final demo Grade 9 for demo Plan dessert.pptxAvyJaneVismanos
 
MARGINALIZATION (Different learners in Marginalized Group
MARGINALIZATION (Different learners in Marginalized GroupMARGINALIZATION (Different learners in Marginalized Group
MARGINALIZATION (Different learners in Marginalized GroupJonathanParaisoCruz
 
Alper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentAlper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentInMediaRes1
 
Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Educationpboyjonauth
 
Meghan Sutherland In Media Res Media Component
Meghan Sutherland In Media Res Media ComponentMeghan Sutherland In Media Res Media Component
Meghan Sutherland In Media Res Media ComponentInMediaRes1
 
Roles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in PharmacovigilanceRoles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in PharmacovigilanceSamikshaHamane
 
Full Stack Web Development Course for Beginners
Full Stack Web Development Course  for BeginnersFull Stack Web Development Course  for Beginners
Full Stack Web Development Course for BeginnersSabitha Banu
 
How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17Celine George
 
KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...
KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...
KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...M56BOOKSTORE PRODUCT/SERVICE
 
Earth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatEarth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatYousafMalik24
 
Hierarchy of management that covers different levels of management
Hierarchy of management that covers different levels of managementHierarchy of management that covers different levels of management
Hierarchy of management that covers different levels of managementmkooblal
 
Crayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon ACrayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon AUnboundStockton
 
DATA STRUCTURE AND ALGORITHM for beginners
DATA STRUCTURE AND ALGORITHM for beginnersDATA STRUCTURE AND ALGORITHM for beginners
DATA STRUCTURE AND ALGORITHM for beginnersSabitha Banu
 
Capitol Tech U Doctoral Presentation - April 2024.pptx
Capitol Tech U Doctoral Presentation - April 2024.pptxCapitol Tech U Doctoral Presentation - April 2024.pptx
Capitol Tech U Doctoral Presentation - April 2024.pptxCapitolTechU
 
internship ppt on smartinternz platform as salesforce developer
internship ppt on smartinternz platform as salesforce developerinternship ppt on smartinternz platform as salesforce developer
internship ppt on smartinternz platform as salesforce developerunnathinaik
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)eniolaolutunde
 

Recently uploaded (20)

CARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxCARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptx
 
EPANDING THE CONTENT OF AN OUTLINE using notes.pptx
EPANDING THE CONTENT OF AN OUTLINE using notes.pptxEPANDING THE CONTENT OF AN OUTLINE using notes.pptx
EPANDING THE CONTENT OF AN OUTLINE using notes.pptx
 
Final demo Grade 9 for demo Plan dessert.pptx
Final demo Grade 9 for demo Plan dessert.pptxFinal demo Grade 9 for demo Plan dessert.pptx
Final demo Grade 9 for demo Plan dessert.pptx
 
MARGINALIZATION (Different learners in Marginalized Group
MARGINALIZATION (Different learners in Marginalized GroupMARGINALIZATION (Different learners in Marginalized Group
MARGINALIZATION (Different learners in Marginalized Group
 
Alper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentAlper Gobel In Media Res Media Component
Alper Gobel In Media Res Media Component
 
Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Education
 
Meghan Sutherland In Media Res Media Component
Meghan Sutherland In Media Res Media ComponentMeghan Sutherland In Media Res Media Component
Meghan Sutherland In Media Res Media Component
 
Roles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in PharmacovigilanceRoles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in Pharmacovigilance
 
Full Stack Web Development Course for Beginners
Full Stack Web Development Course  for BeginnersFull Stack Web Development Course  for Beginners
Full Stack Web Development Course for Beginners
 
How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17
 
KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...
KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...
KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...
 
Earth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatEarth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice great
 
Hierarchy of management that covers different levels of management
Hierarchy of management that covers different levels of managementHierarchy of management that covers different levels of management
Hierarchy of management that covers different levels of management
 
Crayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon ACrayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon A
 
DATA STRUCTURE AND ALGORITHM for beginners
DATA STRUCTURE AND ALGORITHM for beginnersDATA STRUCTURE AND ALGORITHM for beginners
DATA STRUCTURE AND ALGORITHM for beginners
 
Capitol Tech U Doctoral Presentation - April 2024.pptx
Capitol Tech U Doctoral Presentation - April 2024.pptxCapitol Tech U Doctoral Presentation - April 2024.pptx
Capitol Tech U Doctoral Presentation - April 2024.pptx
 
internship ppt on smartinternz platform as salesforce developer
internship ppt on smartinternz platform as salesforce developerinternship ppt on smartinternz platform as salesforce developer
internship ppt on smartinternz platform as salesforce developer
 
ESSENTIAL of (CS/IT/IS) class 06 (database)
ESSENTIAL of (CS/IT/IS) class 06 (database)ESSENTIAL of (CS/IT/IS) class 06 (database)
ESSENTIAL of (CS/IT/IS) class 06 (database)
 
OS-operating systems- ch04 (Threads) ...
OS-operating systems- ch04 (Threads) ...OS-operating systems- ch04 (Threads) ...
OS-operating systems- ch04 (Threads) ...
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)
 

#In this project you will write a program play TicTacToe #using tw.pdf

  • 1. #In this project you will write a program play TicTacToe #using two players (labels 0,1) or one play (label 0) playing with the machine (label 1). #The TicTacToe board has 9 integers board = [1,2,3,4,5,6,7,8,9]. The following # are the modules for the program # #def reset() resets the board to the original values # board = [1,2,3,4,5,6,7,8,9] # #def printBoard() print the current state of the board using the format # #The current TicTacToe Board # | 1 | 2 | 3 | # | 4 | 5 | 6 | # | 7 | O | 9 | # #The current TicTacToe Board # | X | 2 | 3 | # | 4 | 5 | 6 | # | 7 | O | 9 | #Note from the above that player 0 and 1 have played numbers 8 and 1 #respectively and the board display O for player 0 and X from player 1 # #def changeBoard(num1, player) using the chosen box number to change #the value of the box to 0 or -1 depending on whether the player is 0 or 1, #respectively. # #def play(player) prints the player number (0 or 1) and prompts the player # to enter a box value that have not changed to 'O' or 'X' # #def checkRows(value) checks to see which of the rows of the board # has the same value and returns True, otherwise, returns False # #def checkCols(value) checks to see which of the cols of the board # has the same value and returns True, otherwise, returns False #
  • 2. #def checkDiagonal(value) checks to see which of the diagonals of the board # has the same value and returns True, otherwise, returns False # #def win(player) checks if a player wins the game, returns True of the player wins # and False otherwise # #def machinePlay(player) plays the role of the player using random number. # this function generates numbers in the interval [1,9] and uses the first # generated random number that has not been used to play the game. The # #def ticTacToe(numPlayers) accepts the number of players and simulates the #ticTapToe, asking players to enter unused box numbers. # #def main() is the driver module that accepts the number of players from the user # and calls the ticTacToe module #Assignment: Complete the follwoing modules: #checkCols #checkRows #checkDiagonal #win #Sample of the output is # #Project #This game can be played by one or two players #Enter the number of players, 1/2 for one/two players: 1 # #The current TicTapToe Board #| 1 | 2 | 3 | #| 4 | 5 | 6 | #| 7 | 8 | 9 | #Player 0 Enter a box value: 9 # #The current TicTapToe Board #| 1 | 2 | 3 | #| 4 | 5 | 6 | #| 7 | 8 | O |
  • 3. #Player 1 ***Computer*** playing #The current TicTapToe Board #| 1 | 2 | 3 | #| 4 | 5 | 6 | #| 7 | X | O | #Player 0 Enter a box value: 1 # #The current TicTapToe Board #| O | 2 | 3 | #| 4 | 5 | 6 | #| 7 | X | O | #Player 1 ***Computer*** playing # #The current TicTapToe Board #| O | X | 3 | #| 4 | 5 | 6 | #| 7 | X | O | #Player 0 Enter a box value: 5 # #The current TicTapToe Board #| O | X | 3 | #| 4 | O | 6 | #| 7 | X | O | #Player 0 Wins #Do you want to quit? #Begin Program #import random number generator #from random library #from random import randint, seed #Global variable board representing the ticTacToe board board = [1,2,3,4,5,6,7,8,9] #This module resets the ticTacToe board to the original values def reset(): for k in range(1,10): #loop through a sequence [1,2,3,..,9]
  • 4. board[k-1] = k #This module prints the ticTacToe board in a 3 by 3 matrix #using the format # | 1 | 2 | 3 | # | 4 | 5 | 6 | # | 7 | 8 | 9 | # def printBoard (): print(' The current TicTapToe Board') for m in range(3): string = '| ' for n in range(3): if board[n+3*m] == 0: string = string + ' O |' elif board[n+3*m] == -1: string = string + ' X |' else: string = string + ' ' + str(board[n+3*m]) + ' |' print(string) #This module changes the value (num1) of a box in the ticTacTop board chosen # by player 0 to 0 and player 1 to -1 # def changeBoard(num1,player): for k in range(len(board)): if board[k] == num1 and player == 0: board[k] = 0 elif board[k] == num1 and player == 1: board[k] = -1 #This module prompts the player to enter a box value. The format is # 'Player Enter a box value' # def printBoard (): print(' The current TicTapToe Board') for m in range(3): string = '| ' for n in range(3):
  • 5. if board[n+3*m] == 0: string = string + ' O |' elif board[n+3*m] == -1: string = string + ' X |' else: string = string + ' ' + str(board[n+3*m]) + ' |' print(string) #This module checks if boxes in anyone of the rows have the same value #The module returns True if that is the case and False otherwise # def checkRows(value): #Complete # horizontally , first row of the board contains same mark, it is win if(board[1] == board[2] and board[2] == board[3]): return True; # horizontally , second row of the board contains same mark, it is win elif(board[4] == board[5] and board[5] == board[6]): return True; # horizontally , third row of the board contains same mark, it is win elif(board[7] == board[8] and board[8] == board[9]): return True; # if all the above cases fails, then it is lose else: return False; # #This module checks if boxes in anyone of the cols have the same value #The module returns True if that is the case and False otherwise # def checkCols(value): #Complete # vertically , first column of the board contains same mark, it is win if (board[1] == board[4] and board[4] == board[7]): return True; # vertically , second column of the board contains same mark, it is win elif (board[2] and board[5] and board[5] == board[8]): return True;
  • 6. # vertically , third column of the board contains same mark, it is win elif (board[3] and board[6] and board[6] == board[9]): return True; else: return False; # #This module checks if boxes in anyone of the diagonals have the same value #The module returns True if that is the case and False otherwise # def checkDiagonal(value): #Complete #diagonal check for same mark. if yes , then it is win if (board[1] and board[5] and board[5] == board[9]): return True; #diagonal check for same mark. if yes , then it is win elif (board[3] and board[5] and board[5] == board[7]): return True; else: return False; #This module determines whether or not a player wins after playing the # a turn. This module uses checkDiagonal, checkRows and checkCols to # ascertain if the player wins. As least one of the options (checkDiagonal, # checkCols and checkRows must return a True. # This module returns True if the player wins and False, otherwise # This module also print # 'Player 0 Wins' if player 0 wins # 'Player 1 Wins' if player 1 wins def win(player): #Complete if(checkRows(player)==True or checkCols(player)==True or checkDiagonal(player)==True): if(player==0): print('Player 0 wins'); else: print('Player 1 wins'); return True; else:
  • 7. return False; #This module is only for 1 player only. In this case, this player #plays with the machine. The machine uses random numbers. Random numbers are #generated and tested to determine whether or not the generated random number has been #played. The first generated random number that has not been played is chosen. #If after 100 trials, no unplayed is found, nothing is done and a warning is #sent to the player. IT IS ASSUMED THAT THIS SCENARIO WILL NOT OCCUR. NOTE THAT #THERE IS NOT INTELLIGENCE BUILT IN TO PROGRAM THAT WILL ALLOW COMPUTER TO #CHOOSE THE BEST NUMBER TO PLAY. YOU WILL RECEIVE BONUS POINT IF YOU COULD #MODIFY THE MODULE TO ALLOW COMPUTER SELECT THE BEST NUMBER. # def machinePlay(player): print('Player ', player, '***Computer*** playing') seed() r = randint(1,9) index = 0 while index<100 and (board[r-1] ==0 or board[r-1] ==-1): r = randint(1,9) index = index + 1 if index < 100: changeBoard(r,player) printBoard() else: print('Computer could not play after 100 trials') #The module plays the tictactoe game, using modules defined above. #The module allows players to play any number of games until the # payer(s) decides to quit. This represent the first while loop. #The second while loop allows players to take turns making rounds. Note that #since there are 9 box numbers total, the maximum number of rounds is 9. If # after 9 rounds and there is no winner, the board is reset and player(s) will # prompted to determine whether or not to start a new game. # def ticTacToe(numPlayers):
  • 8. quitPlay = 'n' while (quitPlay == 'n'): reset() printBoard() if numPlayers == 2: playover = False rounds = 0 while not(playover) and rounds<9: player = 0 play(player) playover = win(player) rounds = rounds + 1 if not(playover) and rounds <9 : player = 1 play(player) playover = win(player) rounds = rounds + 1 if rounds >= 9: print("It is a draw") elif numPlayers == 1: playover = False rounds = 1 while not(playover) and rounds<=9: player = 0 play(player) playover = win(player) rounds = rounds + 1 if not(playover) and rounds <9 : player = 1 machinePlay(player) playover = win(player) rounds = rounds + 1 if rounds > 9: print("It is a draw") else: print('Oohs! Number of players is not 1 or 2')
  • 9. quitPlay = 'y' if quitPlay != 'y': quitPlay = input('Do you want to quit?') def main(): print('Welcome to TicTacToe Game') print('Project') print('This game can be played by one or two players') numPlayers = int(input('Enter the number of players, 1/2 for one/two players: ')) ticTacToe(numPlayers) print('Thanks for playing TicTapToe!') main() #end program Solution #In this project you will write a program play TicTacToe #using two players (labels 0,1) or one play (label 0) playing with the machine (label 1). #The TicTacToe board has 9 integers board = [1,2,3,4,5,6,7,8,9]. The following # are the modules for the program # #def reset() resets the board to the original values # board = [1,2,3,4,5,6,7,8,9] # #def printBoard() print the current state of the board using the format # #The current TicTacToe Board # | 1 | 2 | 3 | # | 4 | 5 | 6 | # | 7 | O | 9 | # #The current TicTacToe Board # | X | 2 | 3 | # | 4 | 5 | 6 | # | 7 | O | 9 | #Note from the above that player 0 and 1 have played numbers 8 and 1 #respectively and the board display O for player 0 and X from player 1
  • 10. # #def changeBoard(num1, player) using the chosen box number to change #the value of the box to 0 or -1 depending on whether the player is 0 or 1, #respectively. # #def play(player) prints the player number (0 or 1) and prompts the player # to enter a box value that have not changed to 'O' or 'X' # #def checkRows(value) checks to see which of the rows of the board # has the same value and returns True, otherwise, returns False # #def checkCols(value) checks to see which of the cols of the board # has the same value and returns True, otherwise, returns False # #def checkDiagonal(value) checks to see which of the diagonals of the board # has the same value and returns True, otherwise, returns False # #def win(player) checks if a player wins the game, returns True of the player wins # and False otherwise # #def machinePlay(player) plays the role of the player using random number. # this function generates numbers in the interval [1,9] and uses the first # generated random number that has not been used to play the game. The # #def ticTacToe(numPlayers) accepts the number of players and simulates the #ticTapToe, asking players to enter unused box numbers. # #def main() is the driver module that accepts the number of players from the user # and calls the ticTacToe module #Assignment: Complete the follwoing modules: #checkCols #checkRows #checkDiagonal #win #Sample of the output is #
  • 11. #Project #This game can be played by one or two players #Enter the number of players, 1/2 for one/two players: 1 # #The current TicTapToe Board #| 1 | 2 | 3 | #| 4 | 5 | 6 | #| 7 | 8 | 9 | #Player 0 Enter a box value: 9 # #The current TicTapToe Board #| 1 | 2 | 3 | #| 4 | 5 | 6 | #| 7 | 8 | O | #Player 1 ***Computer*** playing #The current TicTapToe Board #| 1 | 2 | 3 | #| 4 | 5 | 6 | #| 7 | X | O | #Player 0 Enter a box value: 1 # #The current TicTapToe Board #| O | 2 | 3 | #| 4 | 5 | 6 | #| 7 | X | O | #Player 1 ***Computer*** playing # #The current TicTapToe Board #| O | X | 3 | #| 4 | 5 | 6 | #| 7 | X | O | #Player 0 Enter a box value: 5 # #The current TicTapToe Board #| O | X | 3 | #| 4 | O | 6 |
  • 12. #| 7 | X | O | #Player 0 Wins #Do you want to quit? #Begin Program #import random number generator #from random library #from random import randint, seed #Global variable board representing the ticTacToe board board = [1,2,3,4,5,6,7,8,9] #This module resets the ticTacToe board to the original values def reset(): for k in range(1,10): #loop through a sequence [1,2,3,..,9] board[k-1] = k #This module prints the ticTacToe board in a 3 by 3 matrix #using the format # | 1 | 2 | 3 | # | 4 | 5 | 6 | # | 7 | 8 | 9 | # def printBoard (): print(' The current TicTapToe Board') for m in range(3): string = '| ' for n in range(3): if board[n+3*m] == 0: string = string + ' O |' elif board[n+3*m] == -1: string = string + ' X |' else: string = string + ' ' + str(board[n+3*m]) + ' |' print(string) #This module changes the value (num1) of a box in the ticTacTop board chosen # by player 0 to 0 and player 1 to -1 #
  • 13. def changeBoard(num1,player): for k in range(len(board)): if board[k] == num1 and player == 0: board[k] = 0 elif board[k] == num1 and player == 1: board[k] = -1 #This module prompts the player to enter a box value. The format is # 'Player Enter a box value' # def printBoard (): print(' The current TicTapToe Board') for m in range(3): string = '| ' for n in range(3): if board[n+3*m] == 0: string = string + ' O |' elif board[n+3*m] == -1: string = string + ' X |' else: string = string + ' ' + str(board[n+3*m]) + ' |' print(string) #This module checks if boxes in anyone of the rows have the same value #The module returns True if that is the case and False otherwise # def checkRows(value): #Complete # horizontally , first row of the board contains same mark, it is win if(board[1] == board[2] and board[2] == board[3]): return True; # horizontally , second row of the board contains same mark, it is win elif(board[4] == board[5] and board[5] == board[6]): return True; # horizontally , third row of the board contains same mark, it is win elif(board[7] == board[8] and board[8] == board[9]): return True; # if all the above cases fails, then it is lose
  • 14. else: return False; # #This module checks if boxes in anyone of the cols have the same value #The module returns True if that is the case and False otherwise # def checkCols(value): #Complete # vertically , first column of the board contains same mark, it is win if (board[1] == board[4] and board[4] == board[7]): return True; # vertically , second column of the board contains same mark, it is win elif (board[2] and board[5] and board[5] == board[8]): return True; # vertically , third column of the board contains same mark, it is win elif (board[3] and board[6] and board[6] == board[9]): return True; else: return False; # #This module checks if boxes in anyone of the diagonals have the same value #The module returns True if that is the case and False otherwise # def checkDiagonal(value): #Complete #diagonal check for same mark. if yes , then it is win if (board[1] and board[5] and board[5] == board[9]): return True; #diagonal check for same mark. if yes , then it is win elif (board[3] and board[5] and board[5] == board[7]): return True; else: return False; #This module determines whether or not a player wins after playing the # a turn. This module uses checkDiagonal, checkRows and checkCols to # ascertain if the player wins. As least one of the options (checkDiagonal,
  • 15. # checkCols and checkRows must return a True. # This module returns True if the player wins and False, otherwise # This module also print # 'Player 0 Wins' if player 0 wins # 'Player 1 Wins' if player 1 wins def win(player): #Complete if(checkRows(player)==True or checkCols(player)==True or checkDiagonal(player)==True): if(player==0): print('Player 0 wins'); else: print('Player 1 wins'); return True; else: return False; #This module is only for 1 player only. In this case, this player #plays with the machine. The machine uses random numbers. Random numbers are #generated and tested to determine whether or not the generated random number has been #played. The first generated random number that has not been played is chosen. #If after 100 trials, no unplayed is found, nothing is done and a warning is #sent to the player. IT IS ASSUMED THAT THIS SCENARIO WILL NOT OCCUR. NOTE THAT #THERE IS NOT INTELLIGENCE BUILT IN TO PROGRAM THAT WILL ALLOW COMPUTER TO #CHOOSE THE BEST NUMBER TO PLAY. YOU WILL RECEIVE BONUS POINT IF YOU COULD #MODIFY THE MODULE TO ALLOW COMPUTER SELECT THE BEST NUMBER. # def machinePlay(player): print('Player ', player, '***Computer*** playing') seed() r = randint(1,9) index = 0 while index<100 and (board[r-1] ==0 or board[r-1] ==-1): r = randint(1,9) index = index + 1
  • 16. if index < 100: changeBoard(r,player) printBoard() else: print('Computer could not play after 100 trials') #The module plays the tictactoe game, using modules defined above. #The module allows players to play any number of games until the # payer(s) decides to quit. This represent the first while loop. #The second while loop allows players to take turns making rounds. Note that #since there are 9 box numbers total, the maximum number of rounds is 9. If # after 9 rounds and there is no winner, the board is reset and player(s) will # prompted to determine whether or not to start a new game. # def ticTacToe(numPlayers): quitPlay = 'n' while (quitPlay == 'n'): reset() printBoard() if numPlayers == 2: playover = False rounds = 0 while not(playover) and rounds<9: player = 0 play(player) playover = win(player) rounds = rounds + 1 if not(playover) and rounds <9 : player = 1 play(player) playover = win(player) rounds = rounds + 1 if rounds >= 9: print("It is a draw") elif numPlayers == 1: playover = False rounds = 1
  • 17. while not(playover) and rounds<=9: player = 0 play(player) playover = win(player) rounds = rounds + 1 if not(playover) and rounds <9 : player = 1 machinePlay(player) playover = win(player) rounds = rounds + 1 if rounds > 9: print("It is a draw") else: print('Oohs! Number of players is not 1 or 2') quitPlay = 'y' if quitPlay != 'y': quitPlay = input('Do you want to quit?') def main(): print('Welcome to TicTacToe Game') print('Project') print('This game can be played by one or two players') numPlayers = int(input('Enter the number of players, 1/2 for one/two players: ')) ticTacToe(numPlayers) print('Thanks for playing TicTapToe!') main() #end program