In: Computer Science
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 ()
# 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!!!