Question

In: Computer Science

If you were to write a game of tic-tac-toe, you may store the representation of the...

If you were to write a game of tic-tac-toe, you may store the representation of the game board as a two dimensional list such as   [['X', '', 'X'], ['O', 'X', ''], ['', 'O', 'X']] where each sublist is a row in the board.   Empty strings ('') denote a space that does not yet have a value. Assuming this representation, write functions (contained in the same file) that do the following:

a) Create a new empty tic-tac-toe board. This function should take no parameters and it should return the board representation with all empty spaces. Assume the board is 3 rows and 3 columns as shown above.

b) Updates the board with a new value. This function takes three parameters -- the board representation, a tuple with two values (row, column) and a character, either "X" or "O". The (row, column) tuple indicates where the value should be placed. In the example above, we might put a new value ("X") in position (1, 2) which would change our board representation to [['X', '', 'X'], ['O', 'X', 'X'], ['', 'O', 'X']].   Your function should issue a warning ("This move cannot be made") if there is not an empty string in position(row, column). This function takes parameters, but does not return anything.

c) Check to see if there is a win -- you can restrict this to either 3 X's or O's in any row or column (minimum requirement) or you can add the diagonal check if you wish (optional). This function takes one parameter -- the board representation -- and should return True (there is a win) or False (there is no win). This function should NOT print anything.

d) Write a function that first creates an empty tic-tac-toe board then repeatedly asks the user for a letter (X or O) and where they want to play (a row/column position) and calls the function to update the value on the board. After each "play", check to see if there is a win. (Note that a user could enter all "X"s or all "O's" -- that's ok, you don't need to ensure that they are playing "fairly". Users should, of course, be given the option to quit entering values.

I need to program this in python 3. Will be appreciated if you can help me.

Solutions

Expert Solution

Python Program:

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 that contains '-', 'X' or 'O'
   '''
   # Iterating over rows
   for i in range(0, 3):
       for j in range(0, 3):
           tab[i][j] = ' '
  
def verifyWinner(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.
   '''
   # Checking for draw
   if testDraw(tab):
       print("It is a draw")
       return True
   elif testRows(tab)=='X' or testCols(tab)=='X' or testDiags(tab)=='X':
       print("Player X has won!")
       return True
   elif testRows(tab)=='O' or testCols(tab)=='O' or testDiags(tab)=='O':
       print("Player O has won!")
       return True
      
   # 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'
   '''
   # Iterating over rows
   for lst in tab:
       c = 0
       # Iterating over columns
       for ch in lst:
           if ch == 'X':
               c = c+1
       # Checking for 3 X
       if c==3:
           return 'X'
          
   # Iterating over rows
   for lst in tab:
       c = 0
       # Iterating over columns
       for ch in lst:
           if ch == 'O':
               c = c+1
       # Checking for 3 O
       if c==3:
           return 'O'
          
   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'
   '''
   # Iterating over columns
   for i in range(0, 3):
       c = 0
       # Iterating over rows
       for j in range(0, 3):
           if tab[j][i] == 'X':
               c = c+1
       # Checking for 3 X
       if c==3:
           return 'X'
          
   # Iterating over columns
   for i in range(0, 3):
       c = 0
       # Iterating over rows
       for j in range(0, 3):
           if tab[j][i] == 'O':
               c = c+1
       # Checking for 3 O
       if c==3:
           return 'O'
  
   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'
   '''
   if (tab[0][0]=='X' and tab[1][1]=='X' and tab[2][2]=='X') or (tab[0][2]=='X' and tab[1][1]=='X' and tab[2][0]=='X'):
       return 'X'
   elif (tab[0][0]=='O' and tab[1][1]=='O' and tab[2][2]=='O') or (tab[0][2]=='O' and tab[1][1]=='O' and tab[2][0]=='O'):
       return 'O'
  
   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'
   '''
   # Iterating over rows
   for lst in tab:
       # Iterating over columns
       for ch in lst:
           # Checking for -
           if ch == ' ':
               return False
   return True
  


def displayTable (tab):
   '''
       (list) -> None
       display the table of the game
       Preconditions: tab is a reference to an nxn array that contains ' ', 'X' or 'O'
   '''
   print("\n |---|---|---| ")
   # Outer loop for rows
   for i in range(3):
       # Inner loop for columns
       for j in range(3):
           # Printing character
           print(" | %c"%(tab[i][j]), end="");
       print(" |",end="");
       # Printing footer
       print("\n |---|---|---| ");
   print("\n")

def play (tab, player):
   '''
   (list, str) -> None
   Play a step of the game
   Preconditions: tab is a reference to the n x n tab containing '-', 'X' and 'O'
   The player is either X or O
   tab is modified (an element has 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(", Provide the row and column from 0 to", (len(tab)-1), ": ")
           place[0] = int(input("Row: ")) #
           place[1] = int(input("Column: "))
           #find a position that is not busy and contains '-‘
           if tab[place[0]][place[1]] != ' ':
               print("the position", place[0], place[1], "is busy")
               valid = False
           else:
               valid = True
               # put the player in the array
               tab[place[0]][place[1]] = player
      
      
# Create the game table
table = [[' ',' ',' '],[' ',' ',' '],[' ',' ',' ']] # the only array used in the program.
  
response = input("Start a game (Y or N): ");
while response == 'y' or response == 'Y':
   eraseTable(table) # prepare the game table
   winner = False # initialize winner variable
   while not winner:
       displayTable(table) # display the game table
       play(table,'X') # ask the player X to play
       winner = verifyWinner(table) # did he win?
       if not winner:
           # no winner, the other player can play
           displayTable(table) # dplay the game table
           play(table,'O') # ask the player O to play
           winner = verifyWinner(table) # did he win?
      
   displayTable(table) # display the game table
   response = input("Start a game (O or N): ") # new game?

_________________________________________________________________________________________

Code Screenshot:

_________________________________________________________________________________________

Sample Run:


Related Solutions

Write a program that plays tic-tac-toe. The tic-tac-toe game is played on a 3 × 3...
Write a program that plays tic-tac-toe. The tic-tac-toe game is played on a 3 × 3 grid as shown below: The game is played by two players, who take turns. The first player marks moves with a circle, the second with a cross. The player who has formed a horizontal, vertical, or diagonal sequence of three marks wins. Your program should draw the game board, ask the user for the coordinates of the next mark (their move), change the players...
How to make tic tac toe game in javascript with vue.js
How to make tic tac toe game in javascript with vue.js
If anyone can please write a code for a 5x5 tic tac toe game in matlab...
If anyone can please write a code for a 5x5 tic tac toe game in matlab I would greatly appreciate it. Its extra credit. PLEASE HELP ME :(
In a game of tic tac toe. How do you check if all the positions in...
In a game of tic tac toe. How do you check if all the positions in a double array are taken, the double arrays are used to store the x's and o's?
Implement the Tic-tac-toe game for variable board sizes, you may assume: 2 < s < 11,...
Implement the Tic-tac-toe game for variable board sizes, you may assume: 2 < s < 11, where s is the board size. Before the game starts the program will prompt for the board size. Note: the winning conditions are the same as the original Tic-tac-toe game in that you need to fill the entire row/column/diagonal to win. Here are a few sample runs. The output is a bit different so that we can handle two-digit coordinates consistently. We expect (but...
The objective of this assignment is to implement the tic-tac-toe game with a C program. The...
The objective of this assignment is to implement the tic-tac-toe game with a C program. The game is played by two players on a board defined as a 5x5 grid (array). Each board position can contain one of two possible markers, either ‘X’ or ‘O’. The first player plays with ‘X’ while the second player plays with ‘O’. Players place their markers in an empty position of the board in turns. The objective is to place 5 consecutive markers of...
Write a program that allows two players to play a game of tic-tac-toe. Use a two-dimensional...
Write a program that allows two players to play a game of tic-tac-toe. Use a two-dimensional char array with three rows and three columns as the game board. Each element of the array should be initialized with an asterisk (*). The program should run a loop that does the following: Displays the contents of the board array. Allows player 1 to select a location on the board for an X. The program should ask the user to enter the row...
For this assignment, you will write a tic-tac-toe application in HTML and JavaScript, using an HTML...
For this assignment, you will write a tic-tac-toe application in HTML and JavaScript, using an HTML <canvas> tag. The game will be played "hot seat" where players take turns using the same device. Requirements: The canvas should be 600px tall and wide, with the gameplay area occupying most of the canvas. The X's and O's may be drawn using polygons or large-font text The grid should be drawn using polygons, specifically long, thin rectangles Before & between games, the canvas...
Game of Tic Tac Toe with the following conditions A point system where a  move that leads...
Game of Tic Tac Toe with the following conditions A point system where a  move that leads to a winning game is given 1 point, a move that leads to a tie is given 0 point, and a  lead to a losing game will get -1 point. Grid size of 5x5 A timer that can be set for how long a game can be played 5 symbols in a row to get a point Connected lines cannot be crossed (No diagonal lines)...
please create a tic tac toe game with python using only graphics.py library
please create a tic tac toe game with python using only graphics.py library
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT