Question

In: Computer Science

It is time to play X-O. You should complete the program for this game. Part of...

It is time to play X-O. You should complete the program for this game. Part of this program is provided to you in two files: d4q2.py (it is complete, no need to be modified) and d4q2Lib.py (you have to complete). The annex has examples of messages displayed during the game.

1) The main program controls the game.

a. It asks the user to start a game : if the response is not o or O, the program ends; If the response is o or O, it leads the game by using the following operations :

i. erase the table (with function eraseTable(tab)).

ii. display the table (with function displayble(tab)).

iii. play a step (with function play(tab, player) – including the request made to the player for the new position).

iv. verify if the player has won or if it is a draw (with function verifyWin(tab)). v. if the game is not completed, play again a step with the other player (from iii). Note: the array of the game table is created in the main part of the program in a4q2.py and is passes as reference to other functions.

b. after each game, you are asked to start another game (restart from a.).

2) the function verifyWin call the following functions:

a. testRows(tab) – to check if a row has won.

b. testCols(tab) – to check if a column has won.

c. testDiags(tab) – to check if a diagonal has won.

d. testDraw(tab) – to check for a draw.

Your have to complete the following functions in the file a4q2Lib.py: ·

eraseTable (tab) · verifyWin(tab) · testRows(tab) · testCols(tab) · testDiags(tab) · testDraw(tab)

Notes:

1) The function verifyWin display the message “Draw” instead of “Player X has won!” or “Player O has won!” when there is a draw.

2) The new row and new column are given with input() and are stored in a list with two elements (the first is the row and the second the column).

3) The functions testRows, testCols, and testDiags, return one of the characters ‘-‘, ‘X’ or ‘O’. if ‘-‘ is returned, no one has won, otherwise the character for the winning player is returned.

4) The documentation of each function is available in the file a4q2Lib.py.

Annex – example of games Start a game (O or N): O

0 1 2

0 - - -

1 - - -

2 - - -

Player X, Please provide the row and column from 0 to 2:

Row: 1

Colomn: 1

0 1 2

0 - - -

1 - X -

2 - - -

Player O, Please provide the row and column from 0 to 2:

Row: 0

Column: 0

0 1 2

0 O - -

1 - X -

2 - - -

Player X, Please provide the row and column from 0 to 2:,

Row: 1

Column: 5

Player X, Please provide the row and column from 0 to 2:

Row: 1

Column: 3

Player X, Please provide the row and column from 0 to 2:

Row: 2

Column: 2

0 1 2

0 O - -

1 - X -

2 - - X

Player O, Please provide the row and column from 0 to 2:

Row: 0

Column: 0

The position 0 0 is occupied Player O, Please provide the row and column from 0 to 2:

Row: 0

Column: 2

0 1 2

0 O - O

1 - X -

2 - - X

Player X, Please provide the row and column from 0 to 2:

Row: 1

Column: 0

0 1 2

0 O - O

1 X X -

2 - - X

Player O, Please provide the row and column from 0 to 2:

Row: 0

Column: 1

Player O has won!

0 1 2

0 O O O

1 X X -

2 - - X

Start a game (O or N): N

--------------------------------- a4q2 does not need to be modified, only a4q2lib.py needs to be  --------------------------------

a4q2.py (FIRST FILE - DO NOT MODIFY)

from a4q2Lib import *
    
def displayTable (tab):
    '''
    (list) -> None
    Display the game table
    Preconditions: tab is a reference to an n x n array that contains '-', 'X' or 'O'
    The format is: 
        0 1 2
      0 - - O
      1 - X -
      2 - - X
    '''
    print("   ", end="")
    col = 0
    while col < len(tab): 
      print(col, end="  ")
      col += 1
    print()  
    row = 0  
    while row < len(tab):  
      print(row, end="")
      col = 0
      while col < len(tab[row]): 
        print(" ",tab[row][col], end="")
        col += 1
      print()
      row += 1

def play (tab, player):
    '''
    (list, str) -> None
    Plays a step of the game
    Preconditions: tab is a reference to the n x n tab containing '-', 'X' and 'O'
    The player is X or O
    tab is modified (an elementis changed)
    '''               
    
    valid = False
                 
    while not valid:   
        place = [-1,-1] # create a table with two elements
        while not((0 <= place[0] < len(tab)) and (0 <= place[1] < len(tab))):
          print ("Player ",player, end="")
          print(", Please provide the row and the columm from 0 to", (len(tab)-1), ": ")
          place[0] = int(input("Row: ")) # 
          place[1] = int(input("Column: "))
        #find a position that is not busy that contains '-‘             
        if tab[place[0]][place[1]] != '-':
          print("The position", place[0], place[1], "is occupied");
          valid = False
        else:
          valid = True             
          # put the player in the array 
          tab[place[0]][place[1]] = player 
    # no result
  

# Create the game table 
table = [['-','-','-'],['-','-','-'],['-','-','-']] # The only array used in the program.
    
response = input("Start a game (O or N): ");    
while response == 'o' or response == 'O': 
      eraseTable(table)  # prepares the game table
      winner = False  # initializes the variable winner 
      while not winner: 
        displayTable(table) # display the game table
        play(table,'X')  # ask player X to play
        winner = verifyWin(table)  # Did he win?
        if not winner: 
          # no winner, the other player can play
          displayTable(table) # display the game table
          play(table,'O')  # ask player O to play
          winner = verifyWin(table)  # Did he win?
          
      displayTable(table) # display the game table
      response = input("Start a game (O or N): ") # new game?

----------------- COMPLETE THIS TEMPLATE WHERE NECESSARY

a4q2lib.py

def eraseTable (tab):
   '''
   (list) -> None
   This function prepares the game table (array) 
   by putting '-' in all the elements.
   It does not create a new array
   Preconditions: tab is a reference to an nxn array matrice n x n that contains '-', 'X' or 'O'
   '''
   
    # to complete
    
    # returns nothing

      
def verifyWin(tab):  
    '''(list) ->  bool
    * Preconditions: tab is a reference to an nxn array that contains '-', 'X' or 'O'
    * Verify if there is a winner.
    * Look for 3 X's and O's in a row, column, and diagonal.
    * If we find one, we display the winner (the message "Player X has won" 
    * or "Player O has won!") and returns True.
    * If there is a draw (verify it with the function testdraw),
    * display "It is a draw" and returns True.
    * If the game is not over, returns False.
    * The function call the functions testrows, testCols, testDiags
    * pour verifier s'il y a un gagnant.
    * Those functions returns the winner 'X' or 'O', or '-' if there is no winner.
    '''

    # to complete
   
    return False  # to change

 
def testRows(tab):
   ''' (list) ->  str
   * verify if there is a winning row.
   * Look for three 'X' or three 'O' in a row.  
   * If they are found, the character 'X' or 'O' is returned, otherwise '-' is returned.
   * Preconditions: tab is a reference to an nxn array that contains '-', 'X' or 'O'
   '''

   # to complete
  
   return '-' # to be modified so that it returns the winner, or '-' if there is no winner 

  
  
def testCols(tab):
   ''' (list) ->  str
   * verify a winning column.
   * look for three 'X' or three 'O' in a column.  
   * If it is the case the character 'X' or 'O' is returned, otherwise '-' is returned.
   * Preconditions: tab is a reference to an nxn array that contains '-', 'X' or 'O'
   '''
    
   # to complete
  
   return '-'   #to be modified so that it returns the winner, or '-' if there is no winner

   
def testDiags(tab):
   ''' (list) ->  str
   * Look for three 'X' or three 'O' in a diagonal.  
   * If it is the case, the character 'X' or 'O' is returned
   * otherwise '-' is returned.
   * Preconditions: tab is a reference to an nxn array that contains '-', 'X' or 'O'
   '''

   # to complete
    
   return '-'   # #to be modified so that it returns the winner, or '-' if there is no winner

  
  
def testDraw(tab):
   ''' (list) ->  bool
   * verify if there is a draw
   * check if all the array elements have X or O, not '-'.  
   * If we do not find find any '-' in the array, return True. 
   * If there is any '-', return false.
   * Preconditions: tab is a reference to an nxn array that contains '-', 'X' or 'O'
   '''
    
   # to complete
  
   return False  # to BE modiffied

Note: PLEASE modify according to the comments

Solutions

Expert Solution

The a4q2.py file is unchanged. The code of file a4q2lib.py is given below.

def eraseTable (tab):
'''
(list) -> None
This function prepares the game table (array)
by putting '-' in all the elements.
It does not create a new array
Preconditions: tab is a reference to an nxn array matrice n x n that contains '-', 'X' or 'O'
'''
for i in range(3):
for j in range(3):
tab[i][j] = '-'
# returns nothing

  
def verifyWin(tab):
'''(list) -> bool
* Preconditions: tab is a reference to an nxn array that contains '-', 'X' or 'O'
* Verify if there is a winner.
* Look for 3 X's and O's in a row, column, and diagonal.
* If we find one, we display the winner (the message "Player X has won"
* or "Player O has won!") and returns True.
* If there is a draw (verify it with the function testdraw),
* display "It is a draw" and returns True.
* If the game is not over, returns False.
* The function call the functions testrows, testCols, testDiags
* pour verifier s'il y a un gagnant.
* Those functions returns the winner 'X' or 'O', or '-' if there is no winner.
'''

row = testRows(tab)
col = testCols(tab)
diag = testDiags(tab)
if(row!='-'):
print("Player "+row+" has won")
return True
elif(col!='-'):
print("Player "+col+" has won")
return True
elif(diag!='-'):
print("Player "+diag+" has won")
return True
elif(testDraw(tab)==True):
print("It is a draw")
return True
return False # to change


def testRows(tab):
''' (list) -> str
* verify if there is a winning row.
* Look for three 'X' or three 'O' in a row.
* If they are found, the character 'X' or 'O' is returned, otherwise '-' is returned.
* Preconditions: tab is a reference to an nxn array that contains '-', 'X' or 'O'
'''
for player in ['X','O']:
for i in range(3):
win = True
for j in range(3):
if tab[i][j] != player:
win = False
break
if win == True:
return player
return '-' # to be modified so that it returns the winner, or '-' if there is no winner

  
  
def testCols(tab):
''' (list) -> str
* verify a winning column.
* look for three 'X' or three 'O' in a column.
* If it is the case the character 'X' or 'O' is returned, otherwise '-' is returned.
* Preconditions: tab is a reference to an nxn array that contains '-', 'X' or 'O'
'''
  
for player in ['X','O']:
for i in range(3):
win = True
for j in range(3):
if tab[j][i] != player:
win = False
break
if win == True:
return player
return '-' #to be modified so that it returns the winner, or '-' if there is no winner


def testDiags(tab):
''' (list) -> str
* Look for three 'X' or three 'O' in a diagonal.
* If it is the case, the character 'X' or 'O' is returned
* otherwise '-' is returned.
* Preconditions: tab is a reference to an nxn array that contains '-', 'X' or 'O'
'''

for player in ['X','O']:
win = True
# left diagonal
for i in range(3):
if(tab[i][i]!=player):
win = False
break
if(win==True):
return player
win = True
# right diagonal
for i in range(3):
if(tab[i][2-i]!=player):
win = False
break
if(win==True):
return player
  
return '-' # #to be modified so that it returns the winner, or '-' if there is no winner

  
  
def testDraw(tab):
''' (list) -> bool
* verify if there is a draw
* check if all the array elements have X or O, not '-'.
* If we do not find find any '-' in the array, return True.
* If there is any '-', return false.
* Preconditions: tab is a reference to an nxn array that contains '-', 'X' or 'O'
'''
  
for i in range(3):
for j in range(3):
if(tab[i][j]=='-'):
return False
return True


Related Solutions

In this python program , you are to build a trivia game. The game should present...
In this python program , you are to build a trivia game. The game should present each question – either in order or randomly – to the player, and display up to four possible answers. The player is to input what they believe to be the correct answer.   The game will tell the player if they got it right or wrong and will display their score. If they got it right, their score will go up. If they got it...
Write a program in Basic to play the game of Nim with acom­puter.
Write a program in Basic to play the game of Nim with acom­puter.
Part I. The trial balance for Game Time on December 31 is as follows: Game Time...
Part I. The trial balance for Game Time on December 31 is as follows: Game Time Trial Balance December 31, 2019 Account Name Debit Credit Cash 8,721 Prepaid Insurance 1,295 Equipment 17,642 Accumulated Depreciation - Equipment 2,287 Repair Equipment 1,265 Accumulated Depreciation – Repair Equipment 880 Accounts Payable 942 B. Ryan, Capital 23,871 B. Ryan, Drawing 2,000 Game Fees 1,954 Concession Fees 3,752 Wages Expense 1,068 Rent Expense 980 Utilities Expense 246 Repair Expense 180 Supplies Expense 257 Miscellaneous Expense...
You are to implement a program to play “Guess an Animal.”  Your program should construct a tree...
You are to implement a program to play “Guess an Animal.”  Your program should construct a tree with a string at each node.  This tree stores the knowledge that your program currently knows.  At leaf nodes, the strings should contain the names of animals, while interior nodes should contain yes/no questions.  The program should start at the root and ask the question stored at the root.  If the user answers the question no, the program traverses the left branch of the tree, while if the...
Write a program where a user of this program will play a game in which he/she...
Write a program where a user of this program will play a game in which he/she needs to guess a target number, which is a number that the program has randomly picked in the range that the user chooses. The program will repeatedly prompt for the guessed number and provide a clue whether the guessed number is bigger or smaller than the target number, until the guessed number equals the target number.
SECOND PRICE AUCTIONS o Is this a game of complete information or is some information asymmetric?...
SECOND PRICE AUCTIONS o Is this a game of complete information or is some information asymmetric? If information is asymmetric, briefly describe the information asymmetry. o Who are the players in the game? What are the player’s strategies? What are the player’s payoff functions? o Clearly describe the Nash equilibrium of the game.
IN C++ Write a program to play the Card Guessing Game. Your program must give the...
IN C++ Write a program to play the Card Guessing Game. Your program must give the user the following choices: - Guess only the face value of the card. -Guess only the suit of the card. -Guess both the face value and suit of the card. Before the start of the game, create a deck of cards. Before each guess, use the function random_shuffle to randomly shuffle the deck.
Rock, Paper, Scissors Game Write a Python program rps.py that lets the user play the game...
Rock, Paper, Scissors Game Write a Python program rps.py that lets the user play the game of Rock, Paper, Scissors against the computer. The program should work as follows: You can set these constant global variables at the top outside of your main function definition: COMPUTER_WINS = 1 PLAYER_WINS = 2 TIE = 0 INVALID = 3 ROCK = 1 PAPER = 2 SCISSORS = 3 For this program 1 represents rock, 2 represents paper, and 3 represents scissors. In...
Write a program with at least 2 functions that play the game of “guess the number”...
Write a program with at least 2 functions that play the game of “guess the number” as follows: Your program chooses the number to be guessed by selecting an integer at random in the range 1 to 1000. The program then displays the following: I have a number between 1 and 1000. Can you guess my number? Please type in your first guess. The player then types the first guess. The program then responds with one of the following: 1.      ...
Write a program to allow a user to play the game Hangman. DO NOT USE AN...
Write a program to allow a user to play the game Hangman. DO NOT USE AN ARRAY The program will generate a random number (between 1 and 4581) to pick a word from the file - this is the word you then have to guess. Note: if the random number you generate is 42, you need the 42nd word - so loop 41 times picking up the word from the file and not doing anything with it, it is the...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT