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 aquacareser

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.pdfaquacareser
 
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.pdfaquacareser
 
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).pdfaquacareser
 
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#.pdfaquacareser
 
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.pdfaquacareser
 
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.pdfaquacareser
 
Web sever environmentA Web server is a program that uses HTTP (Hy.pdf
Web sever environmentA Web server is a program that uses HTTP (Hy.pdfWeb sever environmentA Web server is a program that uses HTTP (Hy.pdf
Web sever environmentA Web server is a program that uses HTTP (Hy.pdfaquacareser
 
We ca use HashSet data structure to remove duplicats from an array i.pdf
We ca use HashSet data structure to remove duplicats from an array i.pdfWe ca use HashSet data structure to remove duplicats from an array i.pdf
We ca use HashSet data structure to remove duplicats from an array i.pdfaquacareser
 
this eample is of t-test for comparing two meanshere mean1 = m.pdf
this eample is of t-test for comparing two meanshere mean1 = m.pdfthis eample is of t-test for comparing two meanshere mean1 = m.pdf
this eample is of t-test for comparing two meanshere mean1 = m.pdfaquacareser
 
The middle ear bones in mammals are derived from bones in the dentar.pdf
The middle ear bones in mammals are derived from bones in the dentar.pdfThe middle ear bones in mammals are derived from bones in the dentar.pdf
The middle ear bones in mammals are derived from bones in the dentar.pdfaquacareser
 
There is an old saying “Do not put all eggs in one basket”WhyBe.pdf
There is an old saying “Do not put all eggs in one basket”WhyBe.pdfThere is an old saying “Do not put all eggs in one basket”WhyBe.pdf
There is an old saying “Do not put all eggs in one basket”WhyBe.pdfaquacareser
 
The ER Model is focussed to be a description of real-world entities..pdf
The ER Model is focussed to be a description of real-world entities..pdfThe ER Model is focussed to be a description of real-world entities..pdf
The ER Model is focussed to be a description of real-world entities..pdfaquacareser
 
Please find the answers belowAnswer 16 Option A (IEP). (IEP or i.pdf
Please find the answers belowAnswer 16 Option A (IEP). (IEP or i.pdfPlease find the answers belowAnswer 16 Option A (IEP). (IEP or i.pdf
Please find the answers belowAnswer 16 Option A (IEP). (IEP or i.pdfaquacareser
 
Question 1 answer is A Global trade allows wealthy countries to use .pdf
Question 1 answer is A Global trade allows wealthy countries to use .pdfQuestion 1 answer is A Global trade allows wealthy countries to use .pdf
Question 1 answer is A Global trade allows wealthy countries to use .pdfaquacareser
 
Precipitation hardening, or age hardening, provides one of the most .pdf
Precipitation hardening, or age hardening, provides one of the most .pdfPrecipitation hardening, or age hardening, provides one of the most .pdf
Precipitation hardening, or age hardening, provides one of the most .pdfaquacareser
 
Protists are beneficial to the ecosystem in generating oxygen as the.pdf
Protists are beneficial to the ecosystem in generating oxygen as the.pdfProtists are beneficial to the ecosystem in generating oxygen as the.pdf
Protists are beneficial to the ecosystem in generating oxygen as the.pdfaquacareser
 
Now a normal O2 molecule has 12 electrons in the valence shell so, O.pdf
Now a normal O2 molecule has 12 electrons in the valence shell so, O.pdfNow a normal O2 molecule has 12 electrons in the valence shell so, O.pdf
Now a normal O2 molecule has 12 electrons in the valence shell so, O.pdfaquacareser
 
P1.javaimport java.util.Scanner;keyboard inputting package pub.pdf
P1.javaimport java.util.Scanner;keyboard inputting package pub.pdfP1.javaimport java.util.Scanner;keyboard inputting package pub.pdf
P1.javaimport java.util.Scanner;keyboard inputting package pub.pdfaquacareser
 
operating system linux,ubuntu,Mac#include iostream #include .pdf
operating system linux,ubuntu,Mac#include iostream #include .pdfoperating system linux,ubuntu,Mac#include iostream #include .pdf
operating system linux,ubuntu,Mac#include iostream #include .pdfaquacareser
 
Network Protocol1) A Protocol is used for the communication betwe.pdf
Network Protocol1) A Protocol is used for the communication betwe.pdfNetwork Protocol1) A Protocol is used for the communication betwe.pdf
Network Protocol1) A Protocol is used for the communication betwe.pdfaquacareser
 

More from aquacareser (20)

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
 
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.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
 
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
 
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
 
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
 
Web sever environmentA Web server is a program that uses HTTP (Hy.pdf
Web sever environmentA Web server is a program that uses HTTP (Hy.pdfWeb sever environmentA Web server is a program that uses HTTP (Hy.pdf
Web sever environmentA Web server is a program that uses HTTP (Hy.pdf
 
We ca use HashSet data structure to remove duplicats from an array i.pdf
We ca use HashSet data structure to remove duplicats from an array i.pdfWe ca use HashSet data structure to remove duplicats from an array i.pdf
We ca use HashSet data structure to remove duplicats from an array i.pdf
 
this eample is of t-test for comparing two meanshere mean1 = m.pdf
this eample is of t-test for comparing two meanshere mean1 = m.pdfthis eample is of t-test for comparing two meanshere mean1 = m.pdf
this eample is of t-test for comparing two meanshere mean1 = m.pdf
 
The middle ear bones in mammals are derived from bones in the dentar.pdf
The middle ear bones in mammals are derived from bones in the dentar.pdfThe middle ear bones in mammals are derived from bones in the dentar.pdf
The middle ear bones in mammals are derived from bones in the dentar.pdf
 
There is an old saying “Do not put all eggs in one basket”WhyBe.pdf
There is an old saying “Do not put all eggs in one basket”WhyBe.pdfThere is an old saying “Do not put all eggs in one basket”WhyBe.pdf
There is an old saying “Do not put all eggs in one basket”WhyBe.pdf
 
The ER Model is focussed to be a description of real-world entities..pdf
The ER Model is focussed to be a description of real-world entities..pdfThe ER Model is focussed to be a description of real-world entities..pdf
The ER Model is focussed to be a description of real-world entities..pdf
 
Please find the answers belowAnswer 16 Option A (IEP). (IEP or i.pdf
Please find the answers belowAnswer 16 Option A (IEP). (IEP or i.pdfPlease find the answers belowAnswer 16 Option A (IEP). (IEP or i.pdf
Please find the answers belowAnswer 16 Option A (IEP). (IEP or i.pdf
 
Question 1 answer is A Global trade allows wealthy countries to use .pdf
Question 1 answer is A Global trade allows wealthy countries to use .pdfQuestion 1 answer is A Global trade allows wealthy countries to use .pdf
Question 1 answer is A Global trade allows wealthy countries to use .pdf
 
Precipitation hardening, or age hardening, provides one of the most .pdf
Precipitation hardening, or age hardening, provides one of the most .pdfPrecipitation hardening, or age hardening, provides one of the most .pdf
Precipitation hardening, or age hardening, provides one of the most .pdf
 
Protists are beneficial to the ecosystem in generating oxygen as the.pdf
Protists are beneficial to the ecosystem in generating oxygen as the.pdfProtists are beneficial to the ecosystem in generating oxygen as the.pdf
Protists are beneficial to the ecosystem in generating oxygen as the.pdf
 
Now a normal O2 molecule has 12 electrons in the valence shell so, O.pdf
Now a normal O2 molecule has 12 electrons in the valence shell so, O.pdfNow a normal O2 molecule has 12 electrons in the valence shell so, O.pdf
Now a normal O2 molecule has 12 electrons in the valence shell so, O.pdf
 
P1.javaimport java.util.Scanner;keyboard inputting package pub.pdf
P1.javaimport java.util.Scanner;keyboard inputting package pub.pdfP1.javaimport java.util.Scanner;keyboard inputting package pub.pdf
P1.javaimport java.util.Scanner;keyboard inputting package pub.pdf
 
operating system linux,ubuntu,Mac#include iostream #include .pdf
operating system linux,ubuntu,Mac#include iostream #include .pdfoperating system linux,ubuntu,Mac#include iostream #include .pdf
operating system linux,ubuntu,Mac#include iostream #include .pdf
 
Network Protocol1) A Protocol is used for the communication betwe.pdf
Network Protocol1) A Protocol is used for the communication betwe.pdfNetwork Protocol1) A Protocol is used for the communication betwe.pdf
Network Protocol1) A Protocol is used for the communication betwe.pdf
 

Recently uploaded

Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17Celine George
 
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdfssuser54595a
 
CELL CYCLE Division Science 8 quarter IV.pptx
CELL CYCLE Division Science 8 quarter IV.pptxCELL CYCLE Division Science 8 quarter IV.pptx
CELL CYCLE Division Science 8 quarter IV.pptxJiesonDelaCerna
 
Painted Grey Ware.pptx, PGW Culture of India
Painted Grey Ware.pptx, PGW Culture of IndiaPainted Grey Ware.pptx, PGW Culture of India
Painted Grey Ware.pptx, PGW Culture of IndiaVirag Sontakke
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)eniolaolutunde
 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxNirmalaLoungPoorunde1
 
Biting mechanism of poisonous snakes.pdf
Biting mechanism of poisonous snakes.pdfBiting mechanism of poisonous snakes.pdf
Biting mechanism of poisonous snakes.pdfadityarao40181
 
Types of Journalistic Writing Grade 8.pptx
Types of Journalistic Writing Grade 8.pptxTypes of Journalistic Writing Grade 8.pptx
Types of Journalistic Writing Grade 8.pptxEyham Joco
 
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptxVS Mahajan Coaching Centre
 
Framing an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdf
Framing an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdfFraming an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdf
Framing an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdfUjwalaBharambe
 
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
 
How to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxHow to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxmanuelaromero2013
 
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️9953056974 Low Rate Call Girls In Saket, Delhi NCR
 
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxPOINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxSayali Powar
 
Interactive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationInteractive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationnomboosow
 
History Class XII Ch. 3 Kinship, Caste and Class (1).pptx
History Class XII Ch. 3 Kinship, Caste and Class (1).pptxHistory Class XII Ch. 3 Kinship, Caste and Class (1).pptx
History Class XII Ch. 3 Kinship, Caste and Class (1).pptxsocialsciencegdgrohi
 
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
 

Recently uploaded (20)

9953330565 Low Rate Call Girls In Rohini Delhi NCR
9953330565 Low Rate Call Girls In Rohini  Delhi NCR9953330565 Low Rate Call Girls In Rohini  Delhi NCR
9953330565 Low Rate Call Girls In Rohini Delhi NCR
 
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
 
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
 
CELL CYCLE Division Science 8 quarter IV.pptx
CELL CYCLE Division Science 8 quarter IV.pptxCELL CYCLE Division Science 8 quarter IV.pptx
CELL CYCLE Division Science 8 quarter IV.pptx
 
Painted Grey Ware.pptx, PGW Culture of India
Painted Grey Ware.pptx, PGW Culture of IndiaPainted Grey Ware.pptx, PGW Culture of India
Painted Grey Ware.pptx, PGW Culture of India
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)
 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptx
 
Biting mechanism of poisonous snakes.pdf
Biting mechanism of poisonous snakes.pdfBiting mechanism of poisonous snakes.pdf
Biting mechanism of poisonous snakes.pdf
 
Types of Journalistic Writing Grade 8.pptx
Types of Journalistic Writing Grade 8.pptxTypes of Journalistic Writing Grade 8.pptx
Types of Journalistic Writing Grade 8.pptx
 
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
 
Framing an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdf
Framing an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdfFraming an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdf
Framing an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdf
 
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
 
OS-operating systems- ch04 (Threads) ...
OS-operating systems- ch04 (Threads) ...OS-operating systems- ch04 (Threads) ...
OS-operating systems- ch04 (Threads) ...
 
How to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxHow to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptx
 
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdfTataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
 
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
 
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxPOINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
 
Interactive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationInteractive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communication
 
History Class XII Ch. 3 Kinship, Caste and Class (1).pptx
History Class XII Ch. 3 Kinship, Caste and Class (1).pptxHistory Class XII Ch. 3 Kinship, Caste and Class (1).pptx
History Class XII Ch. 3 Kinship, Caste and Class (1).pptx
 
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
 

#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