Question

In: Computer Science

Program Description, Interfaces, and Functionality To create a Python tic-tac-toe game, use Python's randint function from...

Program Description, Interfaces, and Functionality
To create a Python tic-tac-toe game, use Python's randint function from the random module to control
the computer's moves. To determine if the game has been won or is a tie/draw, write at least the func-
tions: def move(), def check_cols(), def check_diag1(), def check_diag2(), def check_rows(),
and def print_board(). Four of the functions will check if a winning state exist. To win tic-tac-toe, a user
needs to have three of the same game pieces, either an X or an O, in a row, column, or diagonal. When either
the player or computer wins, the game will announce a winner. Use the provided functions def check_ifwin()
to determine if the board is in a winning state. Refer to the example game play in this handout.

2. The def move() function will make a computer move using the random Python module. Refer to the
skeleton code for how to move the computer.
3. The functions: def check_cols(), def check_diag1(), def check_diag2(), def check_rows(),
will traverse the board to check for winning states. Refer to the skeleton code for more details.
4. The def print\_board() function will print out the current state of the board. Refer to the example
game play for the look-and-feel of the game.
5. The game of tic-tac-toe will continuously play until either the computer or player wins or the game is a
draw. A player can then decide to play another round or exit the game.

example:

>python.py
---
O--
---
Enter in cell for your move as a coordinate pair (e.g. 00, 10, etc): 11
---
OX-
O--
Enter in cell for your move as a coordinate pair (e.g. 00, 10, etc): 00
X--
OX-
OO-
Enter in cell for your move as a coordinate pair (e.g. 00, 10, etc): 12
We have a winner!
X--
OXX #example computer wins
OOO
Do you want to try again? enter yes or no: yes
---
---
--O
Enter in cell for your move as a coordinate pair (e.g. 00, 10, etc): 11
---
OX-
--O
Enter in cell for your move as a coordinate pair (e.g. 00, 10, etc): 20
---
OX-
XOO
Enter in cell for your move as a coordinate pair (e.g. 00, 10, etc): 02
We have a winner!
--X
OX- #example player wins
XOO
Do you want to try again? enter yes or no: yes
O--
---
---
Enter in cell for your move as a coordinate pair (e.g. 00, 10, etc): 11
O--
-X-
O--
Enter in cell for your move as a coordinate pair (e.g. 00, 10, etc): 22
O--
-XO
O-X
Enter in cell for your move as a coordinate pair (e.g. 00, 10, etc): 02
OOX
-XO
O-X
Enter in cell for your move as a coordinate pair (e.g. 00, 10, etc): 10
Better luck to both of you next round
OOX
XXO #example tie/draw
OOX

Please follow the instructions in bold fill the code:

from random import randint
# void function to print the board state
def print_board ( board ):
# prints the current board
print ("the board as rows and columns ")
# Boolean function to check rows for a win
def check_rows ( board ):
# X X X O O O <-check each row for a win
#
# if a win , return true
# else return false
#

return True # or False
# Boolean function to check cols for a win
def check_cols ( board ):
# X O <-check each column for a win
# X or O
# X O
# if a win , return true
# else return false

return True # or False
# Boolean function to check diagonal 1 for a win
def check_diag1 ( board ):
# X O <-check diagonal 1 for a win
# X or O
# X O
# if a win , return true
# else return false

return True # or False
# Boolean function to check diagonal 2 for a win
def check_diag2 ( board ):
# X O <-check diagonal 2 for a win
# X or O
# X O
# if a win , return true
# else return false

return True # or False

# Void function to control the computer 's moves uses randint for next move
def move ( board ):
# Tip: a 2D coordinate can be computed from
# a number n using integer division and
# modulo arithmetic
#
# For example , the coordinate pairs
# (xy) 00 ,01 ,10 ,11 for a 2x2 grid with
# four cell numbers (c) 0 ,1 ,2 ,3 can be
# computed from the cell number c as:
#
# c = randint (0 ,3)
# x = c // 2; y = c % 2

print (" move ")
# Function to check if there is a winning state on the board
def check_ifwin ( board ):
if ( check_rows ( board )):
return True
if ( check_cols ( board )):
return True
if ( check_diag1 ( board )):
return True
if ( check_diag2 ( board )):
return True
return False

# Game function of tic -tac -toe
def tic_tac_toe ():
while True :
# Create the game -board , list of lists
b= [[0 ,0 ,0] ,[0 ,0 ,0] ,[0 ,0 ,0]]
# Todo A3:
# initialize the board to an empty game piece . For example , '-'
# - - -
# - - -
# - - -
# keep track of moves made , computer can move max 5 times

total_moves = 0
# Play the game
while (not ( check_ifwin (b ))):
# Computer moves first / last
move (b)
print_board (b)
# Todo A3: check if computer won or reached max moves
# if ( TODO A3 )
# break
#
# Human move
# A3 optional todo : check if cell occupied by computer
# before making the move , not implemented in skeleton code
#

r = input (" Enter in cell for your move as a coordinate pair (e.g.00 ,10 , etc ): x = int(r [0]); y = int(r [1]) b[x][y] = 'X';
# total number of moves made
total_moves +=1
# Check for winning state
if (not check_ifwin (b)):
print (" Better luck to both of you next round ")
else :
print ("We have a winner !")
# Print the game - board
print_board (b);
r = input ("Do you want to try again ? enter yes or no\n")
if(r == "no"):
break
input (" Enter any key to exit ")
# play the game
tic_tac_toe ()

Solutions

Expert Solution

# TIC-TAC-TOE Game in Python 3
from random import randint

def print_board(board):
    for i in range(3): print(board[i][0], board[i][1], board[i][2])
    
def check_rows(board):
    for i in range(3):
        if (board[i][0]=='O') and (board[i][1]=='O') and (board[i][2]=='O'):
            break
        if (board[i][0]=='X') and (board[i][1]=='X') and (board[i][2]=='X'):
            break
    else:
        return False
    
    return True

def check_cols(board):
    for i in range(3):
        if (board[0][i]=='O') and (board[1][i]=='O') and (board[2][i]=='O'):
            break
        if (board[0][i]=='X') and (board[1][i]=='X') and (board[2][i]=='X'):
            break
    else:
        return False
    
    return True

def check_diag1(board):
    if (board[0][0]=='O') and (board[1][1]=='O') and (board[2][2]=='O'):
        return True
    if (board[0][0]=='X') and (board[1][1]=='X') and (board[2][2]=='X'):
        return True
    return False

def check_diag2(board):
    if (board[2][0]=='O') and (board[1][1]=='O') and (board[0][2]=='O'):
        return True
    if (board[2][0]=='X') and (board[1][1]) and (board[0][2]=='X'):
        return True
    return False

# Function to control the computer's next move
def move(board):
    while True:
        c = randint(0, 8)
        x = c//3
        y = c%3
        if(board[x][y] == '-'):
            board[x][y] = 'O'
            break
    
    return board

def check_ifwin(board):
    if (check_rows (board)):
        return True
    if (check_cols (board)):
        return True
    if (check_diag1 (board)):
        return True
    if (check_diag2 (board)):
        return True
    
    return False


# Game function of tic -tac -toe
def tic_tac_toe ():
    while True:
        b = [['-', '-', '-'], ['-', '-', '-'], ['-', '-', '-']]
        total_moves = 0
        
        # Play the game
        while (not (check_ifwin (b)) ):
            # Computer moves
            move(b)
            total_moves += 1
            print_board(b)
            
            # Check if computer won or reached max moves
            if ((check_ifwin(b) or (total_moves==9))):
                break
            
            # Player Moves
            while True:
                r = input ("\nEnter in cell for your move as a coordinate pair (e.g.00, 10, etc): ")
                x = int(r[0])
                y = int(r[1])
                if (b[x][y] == '-'):
                    b[x][y] = 'X'
                    break
                else:
                    print("Error: Cell Occupied")
            
            total_moves += 1
        
        # Check for winning state
        if (not check_ifwin (b)):
            print ("Better luck to both of you next round")
        else:
            print ("\nWe have a winner!")
        
        # Print the game - board
        print_board (b);
        r = input ("\nDo you want to try again ? enter yes or no\n")
        if(r == "no"):
            break
        
    input (" Enter any key to exit ")


# play the game
tic_tac_toe()

Just save this code with ".py" extension and execute/run it.

I have also attached a sample output below.

Please give a LIKE, if you find this answer helpful.

Thank You!!!


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...
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
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...
How to make tic tac toe game in javascript with vue.js
How to make tic tac toe game in javascript with vue.js
Use JavaScript/HTML to create a Tic Tac Toe game displaying X's O's. Score the result. Each...
Use JavaScript/HTML to create a Tic Tac Toe game displaying X's O's. Score the result. Each player takes a turn putting their mark until done or tied.
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?
Python Code Needed Two-Player, Two-Dimensional Tic-Tac-Toe Write a script to play two-dimensional Tic-Tac-Toe between two human...
Python Code Needed Two-Player, Two-Dimensional Tic-Tac-Toe Write a script to play two-dimensional Tic-Tac-Toe between two human players who alternate entering their moves on the same computer. Create a 3-by-3 two-dimensional array. Each player indicates their moves by entering a pair of numbers representing the row and column indices of the square in which they want to place their mark, either an 'X' or an 'O'. When the first player moves, place an 'X' in the specified square. When the second...
In C# A Tic Tac Toe program that uses functions and arrays. The program should start...
In C# A Tic Tac Toe program that uses functions and arrays. The program should start by asking the player one for their name and then player two for their name. Then should print the board and ask the user what column and then what row they would like to put their x (or o, depending on the player) . Use the clear function to make it look as though the board is never repeating.. Thanks!
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)...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT