Solution: Beginner level
The tic-tac-toe game will be created without using functions or object oriented programming. To create this game we will use loops, conditionals, lists and the random library. The random library will be used by the "computer" to randomly select the field where the sign ("X" or "O") will be placed.import randomTo create Game menu we will use while loop. In this game menu two options are available i.e. 1. New Game (type New), 2. Quit (type Quit). In case the value of the OPTION variable is equal to 1 the New game will start. In case the value of the OPTION variable is equal to 2 the game will be terminated and output will be displayed "Exit the game!".In case the user incorrectly typed New or Quit the string "Invalid entry! Please try again." will be shown as output.
while True:The rest of the game code will be placed inside the if conditional i.e. (if OPTION == "New"). The game will start by creating the field that will be used for the game. The field is a 5 nested lists each list with 5 elements. The list is assigned to the variable named test. In each list the first and third element will be filled with vertical lines "|". The 0, 2, and 4 element will be field with empty character " ". The first and third list will be filled with "___________________" string. The code for creating the field for tic-tac-toe game is placed inside the if conditional as the rest of the game and is given below.
print("""\t Welcome to Tic-Tac-Toe game\n \t 1. New Game (type New)\n \t 2. Quit (type Quit)\n""")
OPTION = input("Choose an option:> ")
if OPTION == "New":
# Game code
elif OPTION == "Quit":
print("Exit the game!")
break
elif OPTION != "New" or OPTION != "Quit":
print("Invalid entery! Please try again.")
continue
test = [[] for i in range(0,5,1)]The previous block of code when executed will produce an empty field for tic-tac-toe game that consist of 5 rows and 5 columns. However 3 rows (lists with index 0, 2 and 4) and three columns (columns with indexes 0, 2, and 4) are used for in the game.
print(test)
for i in range(len(test)):
if i%2 == 0:
count = 0
while count < 5:
if count%2 == 0:
test[i].append(" ")
else:
test[i].append("|")
count += 1
else:
test[i].append("_____________________")
for i in range(len(test)):
print(test[i])
Output:
[' ', '|', ' ', '|', ' ']The available "empty" files are shown as output just before selecting the character that we and opponent (computer) are going to use.
['_____________________']
[' ', '|', ' ', '|', ' ']
['_____________________']
[' ', '|', ' ', '|', ' ']
print("""Enter a cell number. Cells are:Now we have to create a piece of code that will ask us which symbol we are going to use "X" or "O". When we type the sign that we are going to use the second sign (character) will be automatically assigned to the opponent (computer). To do this we will use while loop and try and except block.
[0][0], [0][2], [0][4]
[2][0], [2][2], [2][4]
[4][0], [4][2], [4][4]""")
while True:After the user has chosen a character with which he is going to play the game the procedure for filling the empty fields inside the nested list must be created. In this case we will also use the while loop. First the user has to type the row number and then the column number. Then it has to check if the cell already contains character "X" or character "O". If the cell contains one of these character the user has to type another row number and another column number. If the cell does not contain any of two character (X or O) then the cell will be field with user character. In case the user accidentally type the character which cannot be converted to integer than the program will skip to except block to prevent Python from raising the ValueError and show the string "Invalid input. Please try again!" as the output. After the user enters a character the entire tic-tac-toe board will be displayed.
USER_INPUT = input("Type X or O:> ")
if USER_INPUT == "X":
COMPUTER = "O"
break
elif USER_INPUT == "O":
COMPUTER = "X"
break
elif USER_INPUT != "X" or USER_INPUT != "O":
print("Invalid Character! Please enter a valid character again!")
continue
while True:In this next step the opponent (Computer) has to play but to do this first the empty cells must be found. So we have to write for loops to collect the indexes of the cells containing "_" character. After all these are found the random function will be used to choose a random cell in which the opponent (computer) character will be placed. After that the entire tic-tac-toe field will be shown.
while True:
try:
UR_CellRow = int(input("Enter Cell Row:>"))
UR_CellCol = int(input("Enter Cell Column:>"))
#check if the field is empty
if test[UR_CellRow][UR_CellCol] == USER_INPUT or\
test[UR_CellRow][UR_CellCol] == COMPUTER:
print("Cell is already filled. Please choose another cell.")
continue
else:
test[UR_CellRow][UR_CellCol] = USER_INPUT
break
except ValueError:
print("Invalid input. Please try again!")
continue
# Show the map
for i in range(len(test)):
print(test[i])
#########################################################After the opponent (computer) placed its character in one of the empty cells the entire tic-tac-toe field has to be evaluated. So in this step we are searching for three characters in a row or column, or diagonal. If there are three characters in a row the game will be finished and the score would be displayed. This final part starts with defining two variables SCORE_USER, and SCORE_COMPUTER and assigning the values 0 to these variables. To see if three characters (USER_INPUT/COMPUTER) are the same the following code is used.
# Check empty cells
#########################################################
Empty_rows = []
Empty_cols = []
for i in range(len(test)):
for j in range(len(test[i])):
if test[i][j] == " ":
Empty_rows.append(i)
Empty_cols.append(j)
print("Empty_rows = {}".format(Empty_rows))
print("Empty_cols = {}".format(Empty_cols))
index = random.randint(0,len(Empty_rows)-1)
print("index = {}".format(index))
CR_Index = Empty_rows[index]
CC_Index = Empty_cols[index]
print("CR_Index = {}".format(CR_Index))
print("CC_Index = {}".format(CC_Index))
test[CR_Index][CC_Index] = COMPUTER
# Show the map
for i in range(len(test)):
print(test[i])
for i in range(len(test)):As seen from previous code if three characters are the same in a row (USER_INPUT/COMPUTER) then the value of SCORE_USER or SCORE_COMPUTER changes from 0 to 1 and the output is displayed i.e. "You Win!"/"Computer Wins!" and the execution exits the while loop. To check if the three characters are the same in a column the following code is used.
if test[i][0] == USER_INPUT and test[i][2] == USER_INPUT and test[i][4] == USER_INPUT:
SCORE_USER = 1
print("You Win!")
break
elif test[i][0] == COMPUTER and test[i][2] == COMPUTER and test[i][4] == COMPUTER:
SCORE_COMPUTER = 1
print("Computer Wins!")
break
if SCORE_USER == 1 or SCORE_COMPUTER == 1:
break
for j in range(len(test[0])): #Vertical ElementsAs seen from previous code block the procedure is the same as in the case of checking for the same three elements in a row (horizontal elements). If the same three elements are found in column (USER_INPUT or COMPUTER) then the SOCRE_USER/SCORE_COMPUTER changes its value from 0 to 1. The string is shown "You Win!" or "Computer Wins!" and the program will exit the while loop. The procedure for checking if the same three characters are placed diagonally are shown below.
if test[0][j] == USER_INPUT and test[2][j] == USER_INPUT and test[4][j] == USER_INPUT:
SCORE_USER = 1
print("You Win!")
break
if test[0][j] == COMPUTER and test[2][j] == COMPUTER and test[4][j] == COMPUTER:
SCORE_COMP = 1
print("Computer Wins!")
break
if SCORE_USER == 1 or SCORE_COMPUTER == 1:
break
if test[0][0] == USER_INPUT and test[2][2] == USER_INPUT and test[4][4] == USER_INPUT:The entire while loop that is responsible for playing the game is given below.
SCORE_USER = 1
print("You Win!")
break
elif test[4][0] == USER_INPUT and test[2][2] == USER_INPUT and test[0][4] == USER_INPUT:
SCORE_USER = 1
print("You Win!")
break
elif test[0][0] == COMPUTER and test[2][2] == COMPUTER and test[4][4] == COMPUTER:
SCORE_USER = 1
print("You Win!")
break
elif test[4][0] == COMPUTER and test[2][2] == COMPUTER and test[0][4] == COMPUTER:
SCORE_USER = 1
print("You Win!")
break
if SCORE_USER == 1 or SCORE_COMPUTER == 1:
break
while True:The entire program for tic-tac-toe game at beginner level is shown below.
while True:
try:
UR_CellRow = int(input("Enter Cell Row:>"))
UR_CellCol = int(input("Enter Cell Column:>"))
#check if the field is empty
if test[UR_CellRow][UR_CellCol] == USER_INPUT or\
test[UR_CellRow][UR_CellCol] == COMPUTER:
print("Cell is already filled. Please choose another cell.")
continue
else:
test[UR_CellRow][UR_CellCol] = USER_INPUT
break
except ValueError:
print("Invalid input. Please try again!")
continue
# Show the map
for i in range(len(test)):
print(test[i])
#########################################################
# Check empty cells
#########################################################
Empty_rows = []
Empty_cols = []
for i in range(len(test)):
for j in range(len(test[i])):
if test[i][j] == " ":
Empty_rows.append(i)
Empty_cols.append(j)
print("Empty_rows = {}".format(Empty_rows))
print("Empty_cols = {}".format(Empty_cols))
index = random.randint(0,len(Empty_rows)-1)
print("index = {}".format(index))
CR_Index = Empty_rows[index]
CC_Index = Empty_cols[index]
print("CR_Index = {}".format(CR_Index))
print("CC_Index = {}".format(CC_Index))
test[CR_Index][CC_Index] = COMPUTER
# Show the map
for i in range(len(test)):
print(test[i])
###############################################
# Counting SCORE
###############################################
# Check if three symbols are in rows
###############################################
SCORE_USER = 0
SCORE_COMPUTER = 0
for i in range(len(test)):
if test[i][0] == USER_INPUT and test[i][2] == USER_INPUT and test[i][4] == USER_INPUT:
SCORE_USER = 1
print("You Win!")
break
elif test[i][0] == COMPUTER and test[i][2] == COMPUTER and test[i][4] == COMPUTER:
SCORE_COMPUTER = 1
print("Computer Wins!")
break
if SCORE_USER == 1 or SCORE_COMPUTER == 1:
break
for j in range(len(test[0])): #Vertical Elements
if test[0][j] == USER_INPUT and test[2][j] == USER_INPUT and test[4][j] == USER_INPUT:
SCORE_USER = 1
print("You Win!")
break
if test[0][j] == COMPUTER and test[2][j] == COMPUTER and test[4][j] == COMPUTER:
SCORE_COMPUTER = 1
print("Computer Wins!")
break
if SCORE_USER == 1 or SCORE_COMPUTER == 1:
break
if test[0][0] == USER_INPUT and test[2][2] == USER_INPUT and test[4][4] == USER_INPUT:
SCORE_USER = 1
print("You Win!")
break
elif test[4][0] == USER_INPUT and test[2][2] == USER_INPUT and test[0][4] == USER_INPUT:
SCORE_USER = 1
print("You Win!")
break
elif test[0][0] == COMPUTER and test[2][2] == COMPUTER and test[4][4] == COMPUTER:
SCORE_USER = 1
print("You Win!")
break
elif test[4][0] == COMPUTER and test[2][2] == COMPUTER and test[0][4] == COMPUTER:
SCORE_USER = 1
print("You Win!")
break
if SCORE_USER == 1 or SCORE_COMPUTER == 1:
break
while True:Output:
print("""\t Welcome to Tic-Tac-Toe game\n \t 1. New Game (type New)\n \t 2. Quit (type Quit)\n""")
OPTION = input("Choose an option:> ")
if OPTION == "New":
test = [[] for i in range(0,5,1)]
print(test)
for i in range(len(test)):
if i%2 == 0:
count = 0
while count < 5:
if count%2 == 0:
test[i].append(" ")
else:
test[i].append("|")
count += 1
else:
test[i].append("_____________________")
for i in range(len(test)):
print(test[i])
print("""Enter a cell number. Cells are:
[0][0], [0][2], [0][4]
[2][0], [2][2], [2][4]
[4][0], [4][2], [4][4]""")
while True:
USER_INPUT = input("Type X or O:> ")
if USER_INPUT == "X":
COMPUTER = "O"
break
elif USER_INPUT == "O":
COMPUTER = "X"
break
elif USER_INPUT != "X" or USER_INPUT != "O":
print("Invalid Character! Please enter a valid character again!")
continue
while True:
while True:
try:
UR_CellRow = int(input("Enter Cell Row:>"))
UR_CellCol = int(input("Enter Cell Column:>"))
#check if the field is empty
if test[UR_CellRow][UR_CellCol] == USER_INPUT or\
test[UR_CellRow][UR_CellCol] == COMPUTER:
print("Cell is already filled. Please choose another cell.")
continue
else:
test[UR_CellRow][UR_CellCol] = USER_INPUT
break
except ValueError:
print("Invalid input. Please try again!")
continue
# Show the map
for i in range(len(test)):
print(test[i])
#########################################################
# Check empty cells
#########################################################
Empty_rows = []
Empty_cols = []
for i in range(len(test)):
for j in range(len(test[i])):
if test[i][j] == " ":
Empty_rows.append(i)
Empty_cols.append(j)
print("Empty_rows = {}".format(Empty_rows))
print("Empty_cols = {}".format(Empty_cols))
index = random.randint(0,len(Empty_rows)-1)
print("index = {}".format(index))
CR_Index = Empty_rows[index]
CC_Index = Empty_cols[index]
print("CR_Index = {}".format(CR_Index))
print("CC_Index = {}".format(CC_Index))
test[CR_Index][CC_Index] = COMPUTER
# Show the map
for i in range(len(test)):
print(test[i])
###############################################
# Counting SCORE
###############################################
# Check if three symbols are in rows
###############################################
SCORE_USER = 0
SCORE_COMPUTER = 0
for i in range(len(test)):
if test[i][0] == USER_INPUT and test[i][2] == USER_INPUT and test[i][4] == USER_INPUT:
SCORE_USER = 1
print("You Win!")
break
elif test[i][0] == COMPUTER and test[i][2] == COMPUTER and test[i][4] == COMPUTER:
SCORE_COMPUTER = 1
print("Computer Wins!")
break
if SCORE_USER == 1 or SCORE_COMPUTER == 1:
break
for j in range(len(test[0])): #Vertical Elements
if test[0][j] == USER_INPUT and test[2][j] == USER_INPUT and test[4][j] == USER_INPUT:
SCORE_USER = 1
print("You Win!")
break
if test[0][j] == COMPUTER and test[2][j] == COMPUTER and test[4][j] == COMPUTER:
SCORE_COMPUTER = 1
print("Computer Wins!")
break
if SCORE_USER == 1 or SCORE_COMPUTER == 1:
break
if test[0][0] == USER_INPUT and test[2][2] == USER_INPUT and test[4][4] == USER_INPUT:
SCORE_USER = 1
print("You Win!")
break
elif test[4][0] == USER_INPUT and test[2][2] == USER_INPUT and test[0][4] == USER_INPUT:
SCORE_USER = 1
print("You Win!")
break
elif test[0][0] == COMPUTER and test[2][2] == COMPUTER and test[4][4] == COMPUTER:
SCORE_USER = 1
print("You Win!")
break
elif test[4][0] == COMPUTER and test[2][2] == COMPUTER and test[0][4] == COMPUTER:
SCORE_USER = 1
print("You Win!")
break
if SCORE_USER == 1 or SCORE_COMPUTER == 1:
break
elif OPTION == "Quit":
print("Exit the game!")
break
elif OPTION != "New" or OPTION != "Quit":
print("Invalid entery! Please try again.")
continue
Solution: Intermediate Level
At these stage we will re-use the code from the Solution: Beginner Level and introduce functions. In this case four functions were created and these are:- MainMenu function - when this function is called it will display a menu in which user is asking to choose between New game or Quit Game. For New game user has to type "New", and for Quit Game user has to type "Quit". The Function returns the string typed by user ("New"/"Quit")
- GamePrep function - this function will generate a tic-tac-toe board in which the user will play against computer. Besides that this function will ask a user to choose a sign "X" or "O"- If the user chooses "X" the "O" will be assigned to other player (COMPUTER) and vice versa. All these three variables will be generated with this function.
- PlaceCharacter function- will ask user to choose the cell inside the tic-tac-toe filed and then this function will randomly place the opponent sign (COMPUTER) in the tic-tac-toe field.
- ScoreCounting function - will search for three USER or COMPUTER signs ("X" or "O") if they are placed side-by-side horizontally, vertically, and diagonally.
import randomThe program will start with the MainMenu() function that will ask user to choose between New Game or to Quit Game. For a New Game user has to type New and to quit game user has to type Quit.
def MainMenu():After all these functions are created they will be called and executed inside the main while loop. The loop is shown below.
while True:The body of the GamePrep() function is given below:
print("""\t Welcome to Tic-Tac-Toe game\n \t 1. New Game (type New)\n \t 2. Quit (type Quit)\n""")
OPTION = input("Choose an option:> ")
if OPTION == "New":
# Game code
elif OPTION == "Quit":
print("Exit the game!")
break
elif OPTION != "New" or OPTION != "Quit":
print("Invalid entery! Please try again.")
continue
def GamePrep():The function used to place the characters ("X" or "O") inside the tic-tac-toe field is called the PlaceCharacter and the body of this function is shown below.
test = [[] for i in range(0,5,1)]
print(test)
for i in range(len(test)):
if i%2 == 0:
count = 0
while count < 5:
if count%2 == 0:
test[i].append(" ")
else:
test[i].append("|")
count += 1
else:
test[i].append("_____________________")
for i in range(len(test)):
print(test[i])
print("""Enter a cell number. Cells are:
[0][0], [0][2], [0][4]
[2][0], [2][2], [2][4]
[4][0], [4][2], [4][4]""")
while True:
USER_INPUT = input("Type X or O:> ")
if USER_INPUT == "X":
COMPUTER = "O"
break
elif USER_INPUT == "O":
COMPUTER = "X"
break
elif USER_INPUT != "X" or USER_INPUT != "O":
print("Invalid Character! Please enter a valid character again!")
continue
return test, USER_INPUT, COMPUTER
def PlaceCharacter(test, USER_INPUT,COMPUTER):The last function that has to be defined is the function responsible for checking who one after each of the characters ("X" or "O") are placed. This function is named ScoreCounting and the entire function is shown below.
while True:
try:
UR_CellRow = int(input("Enter Cell Row:>"))
UR_CellCol = int(input("Enter Cell Column:>"))
#check if the field is empty
if test[UR_CellRow][UR_CellCol] == USER_INPUT or\
test[UR_CellRow][UR_CellCol] == COMPUTER:
print("Cell is already filled. Please choose another cell.")
continue
else:
test[UR_CellRow][UR_CellCol] = USER_INPUT
break
except ValueError:
print("Invalid input. Please try again!")
continue
# Show the map
for i in range(len(test)):
print(test[i])
#########################################################
# Check empty cells
#########################################################
Empty_rows = []
Empty_cols = []
for i in range(len(test)):
for j in range(len(test[i])):
if test[i][j] == " ":
Empty_rows.append(i)
Empty_cols.append(j)
print("Empty_rows = {}".format(Empty_rows))
print("Empty_cols = {}".format(Empty_cols))
index = random.randint(0,len(Empty_rows)-1)
print("index = {}".format(index))
CR_Index = Empty_rows[index]
CC_Index = Empty_cols[index]
print("CR_Index = {}".format(CR_Index))
print("CC_Index = {}".format(CC_Index))
test[CR_Index][CC_Index] = COMPUTER
# Show the map
for i in range(len(test)):
print(test[i])
return test
def ScoreCounting(test, USER_INPUT, COMPUTER):All these functions are used in the while loop and this loop is shown below.
###############################################
# Counting SCORE
###############################################
# Check if three symbols are in rows
###############################################
SCORE_USER = 0
SCORE_COMPUTER = 0
for i in range(len(test)):
if test[i][0] == USER_INPUT and test[i][2] == USER_INPUT and test[i][4] == USER_INPUT:
SCORE_USER = 1
print("You Win!")
elif test[i][0] == COMPUTER and test[i][2] == COMPUTER and test[i][4] == COMPUTER:
SCORE_COMPUTER = 1
print("Computer Wins!")
for j in range(len(test[0])): #Vertical Elements
if test[0][j] == USER_INPUT and test[2][j] == USER_INPUT and test[4][j] == USER_INPUT:
SCORE_USER = 1
print("You Win!")
if test[0][j] == COMPUTER and test[2][j] == COMPUTER and test[4][j] == COMPUTER:
SCORE_COMP = 1
print("Computer Wins!")
if test[0][0] == USER_INPUT and test[2][2] == USER_INPUT and test[4][4] == USER_INPUT:
SCORE_USER = 1
print("You Win!")
elif test[4][0] == USER_INPUT and test[2][2] == USER_INPUT and test[0][4] == USER_INPUT:
SCORE_USER = 1
print("You Win!")
elif test[0][0] == COMPUTER and test[2][2] == COMPUTER and test[4][4] == COMPUTER:
SCORE_USER = 1
print("You Win!")
elif test[4][0] == COMPUTER and test[2][2] == COMPUTER and test[0][4] == COMPUTER:
SCORE_USER = 1
print("You Win!")
return SCORE_USER, SCORE_COMPUTER
while True:As seen from the previous code block there are two while loops. The first one outer while loop and second inner while loop. The outer while loop will be terminated and the program will be terminated when user types "Quit" instead of "New". On the other hand the inner while loop will be terminated when my score or the computer score is equal to 1.0. The entire code is given below.
Option = MainMenu()
if Option == "New":
XOempty, UserInput, Computer = GamePrep()
while True:
XOempty = PlaceCharacter(XOempty, UserInput,Computer)
ScoreUser, ScoreComputer = ScoreCounting(XOempty, UserInput, Computer)
if ScoreUser == 1 or ScoreComputer == 1:
break
elif Option == "Quit":
print("Exit the game!")
break
def MainMenu(): while True: print("""\t Welcome to Tic-Tac-Toe game\n \t 1. New Game (type New)\n \t 2. Quit (type Quit)\n""") OPTION = input("Choose an option:> ") if OPTION == "New" or OPTION == "Quit": break else: print("Invalid entery! Please try again.") continue return OPTION def GamePrep(): test = [[] for i in range(0,5,1)] print(test) for i in range(len(test)): if i%2 == 0: count = 0 while count < 5: if count%2 == 0: test[i].append(" ") else: test[i].append("|") count += 1 else: test[i].append("_____________________") for i in range(len(test)): print(test[i]) print("""Enter a cell number. Cells are: [0][0], [0][2], [0][4] [2][0], [2][2], [2][4] [4][0], [4][2], [4][4]""") while True: USER_INPUT = input("Type X or O:> ") if USER_INPUT == "X": COMPUTER = "O" break elif USER_INPUT == "O": COMPUTER = "X" break elif USER_INPUT != "X" or USER_INPUT != "O": print("Invalid Character! Please enter a valid character again!") continue return test, USER_INPUT, COMPUTER def PlaceCharacter(test, USER_INPUT,COMPUTER): while True: try: UR_CellRow = int(input("Enter Cell Row:>")) UR_CellCol = int(input("Enter Cell Column:>")) #check if the field is empty if test[UR_CellRow][UR_CellCol] == USER_INPUT or\ test[UR_CellRow][UR_CellCol] == COMPUTER: print("Cell is already filled. Please choose another cell.") continue else: test[UR_CellRow][UR_CellCol] = USER_INPUT break except ValueError: print("Invalid input. Please try again!") continue # Show the map for i in range(len(test)): print(test[i]) ######################################################### # Check empty cells ######################################################### Empty_rows = [] Empty_cols = [] for i in range(len(test)): for j in range(len(test[i])): if test[i][j] == " ": Empty_rows.append(i) Empty_cols.append(j) print("Empty_rows = {}".format(Empty_rows)) print("Empty_cols = {}".format(Empty_cols)) index = random.randint(0,len(Empty_rows)-1) print("index = {}".format(index)) CR_Index = Empty_rows[index] CC_Index = Empty_cols[index] print("CR_Index = {}".format(CR_Index)) print("CC_Index = {}".format(CC_Index)) test[CR_Index][CC_Index] = COMPUTER # Show the map for i in range(len(test)): print(test[i]) return test def ScoreCounting(test, USER_INPUT, COMPUTER): ############################################### # Counting SCORE ############################################### # Check if three symbols are in rows ############################################### SCORE_USER = 0 SCORE_COMPUTER = 0 for i in range(len(test)): if test[i][0] == USER_INPUT and test[i][2] == USER_INPUT and test[i][4] == USER_INPUT: SCORE_USER = 1 print("You Win!") elif test[i][0] == COMPUTER and test[i][2] == COMPUTER and test[i][4] == COMPUTER: SCORE_COMPUTER = 1 print("Computer Wins!") for j in range(len(test[0])): #Vertical Elements if test[0][j] == USER_INPUT and test[2][j] == USER_INPUT and test[4][j] == USER_INPUT: SCORE_USER = 1 print("You Win!") if test[0][j] == COMPUTER and test[2][j] == COMPUTER and test[4][j] == COMPUTER: SCORE_COMP = 1 print("Computer Wins!") if test[0][0] == USER_INPUT and test[2][2] == USER_INPUT and test[4][4] == USER_INPUT: SCORE_USER = 1 print("You Win!") elif test[4][0] == USER_INPUT and test[2][2] == USER_INPUT and test[0][4] == USER_INPUT: SCORE_USER = 1 print("You Win!") elif test[0][0] == COMPUTER and test[2][2] == COMPUTER and test[4][4] == COMPUTER: SCORE_USER = 1 print("You Win!") elif test[4][0] == COMPUTER and test[2][2] == COMPUTER and test[0][4] == COMPUTER: SCORE_USER = 1 print("You Win!") return SCORE_USER, SCORE_COMPUTER while True: Option = MainMenu() if Option == "New": XOempty, UserInput, Computer = GamePrep() while True: XOempty = PlaceCharacter(XOempty, UserInput,Computer) ScoreUser, ScoreComputer = ScoreCounting(XOempty, UserInput, Computer) if ScoreUser == 1 or ScoreComputer == 1: break elif Option == "Quit": print("Exit the game!") break
Solution: Advanced Level
At this level we will built the Tic-Tac-Toe Program using Object-Oriented programming.To do this the code will be used from previous two examples (beginner and intermediate level). First we will need as in previous cases the random library which is used to randomly selects one of the empty fields and place there its character.import randomThe class is named TicTacToeGame() which consist of four different methods and these are MainMenu, GamePrep, PlaceCharacter, and ScoreCounting method.
class TicTacToe():The purpose of the MainMenu function is to ask user to choose between New Game or Quit Game. As before to choose New Game the user has to type New and to quit game the user has to type Quit. After the user types "New" or "Quit" the value will be assigned to the variable named OPTION. In case the user types something other than the "New" or "Quit" the output will be shown "Invalid entry! Please try again." The entire code of the Main Menu method paced inside the TicTacToe class is given below.
class TicTacToe():The next method is a GamePrep method which is used to initialize empty table for tic-tac-toe game, ask the user to choose a character (X or O) in a game, and after user chooses the character the other is automatically assigned to the opponent in this case computer. It should be noted that the table in tic-tac-toe game is 5 times 5 table i.e. the list with 5 nested lists each containing 5 elements. The first and third list (lists with indexes 1 and 3) are filled with horizontal line ("a number of "-" characters). These lists represents horizontal borders in tic-tac-toe table. The same goes for columns i.e. first and third columns (indexes 1 and 3) are filled with "|" (Vertical lines). The TicTacToe class with MainMenu and GamePrep method is shown below.
def MainMenu(self):
while True:
print("""\t Welcome to Tic-Tac-Toe game\n
\t 1. New Game (type New)\n
\t 2. Quit (type Quit)\n""")
OPTION = input("Choose an option:> ")
if OPTION == "New" or OPTION == "Quit":
break
else:
print("Invalid entry! Please try again.")
continue
return OPTION
class TicTacToe():The next method is PlaceCharacter method which will be used to place users character and computer character (X or O). The class with this method is shown below.
def MainMenu(self):
while True:
print("""\t Welcome to Tic-Tac-Toe game\n
\t 1. New Game (type New)\n
\t 2. Quit (type Quit)\n""")
OPTION = input("Choose an option:> ")
if OPTION == "New" or OPTION == "Quit":
break
else:
print("Invalid entry! Please try again.")
continue
return OPTION
def GamePrep(self):
test = [[] for i in range(0,5,1)]
print(test)
for i in range(len(test)):
if i%2 == 0:
count = 0
while count < 5:
if count%2 == 0:
test[i].append(" ")
else:
test[i].append("|")
count += 1
else:
test[i].append("_____________________")
for i in range(len(test)):
print(test[i])
print("""Enter a cell number. Cells are:
[0][0], [0][2], [0][4]
[2][0], [2][2], [2][4]
[4][0], [4][2], [4][4]""")
while True:
USER_INPUT = input("Type X or O:> ")
if USER_INPUT == "X":
COMPUTER = "O"
break
elif USER_INPUT == "O":
COMPUTER = "X"
break
elif USER_INPUT != "X" or USER_INPUT != "O":
print("Invalid Character! Please enter a valid character again!")
continue
return test, USER_INPUT, COMPUTER
class TicTacToe(): def __init__(self): self.OPTION = '' self.test = [[] for i in range(0,5,1)] self.USER_INPUT = '' self.COMPUTER = '' def MainMenu(self, OPTION): while True: print("""\t Welcome to Tic-Tac-Toe game\n \t 1. New Game (type New)\n \t 2. Quit (type Quit)\n""") OPTION = input("Choose an option:> ") if OPTION == "New" or OPTION == "Quit": break else: print("Invalid entery! Please try again.") continue return OPTION def GamePrep(self, test, USER_INPUT, COMPUTER): print(test) for i in range(len(test)): if i%2 == 0: count = 0 while count < 5: if count%2 == 0: test[i].append(" ") else: test[i].append("|") count += 1 else: test[i].append("_____________________") for i in range(len(test)): print(test[i]) print("""Enter a cell number. Cells are: [0][0], [0][2], [0][4] [2][0], [2][2], [2][4] [4][0], [4][2], [4][4]""") while True: USER_INPUT = input("Type X or O:> ") if USER_INPUT == "X": COMPUTER = "O" break elif USER_INPUT == "O": COMPUTER = "X" break elif USER_INPUT != "X" or USER_INPUT != "O": print("Invalid Character! Please enter a valid character again!") continue return test, USER_INPUT, COMPUTER def PlaceCharacter(self, test, USER_INPUT,COMPUTER): while True: try: UR_CellRow = int(input("Enter Cell Row:>")) UR_CellCol = int(input("Enter Cell Column:>")) #check if the field is empty if test[UR_CellRow][UR_CellCol] == USER_INPUT or\ test[UR_CellRow][UR_CellCol] == COMPUTER: print("Cell is already filled. Please choose another cell.") continue else: test[UR_CellRow][UR_CellCol] = USER_INPUT break except ValueError: print("Invalid input. Please try again!") continue # Show the map for i in range(len(test)): print(test[i]) ######################################################### # Check empty cells ######################################################### Empty_rows = [] Empty_cols = [] for i in range(len(test)): for j in range(len(test[i])): if test[i][j] == " ": Empty_rows.append(i) Empty_cols.append(j) print("Empty_rows = {}".format(Empty_rows)) print("Empty_cols = {}".format(Empty_cols)) index = random.randint(0,len(Empty_rows)-1) print("index = {}".format(index)) CR_Index = Empty_rows[index] CC_Index = Empty_cols[index] print("CR_Index = {}".format(CR_Index)) print("CC_Index = {}".format(CC_Index)) test[CR_Index][CC_Index] = COMPUTER # Show the map for i in range(len(test)): print(test[i]) return testThe entire Class function is given below.
class TicTacToe(): def __init__(self): self.OPTION = '' self.test = [[] for i in range(0,5,1)] self.USER_INPUT = '' self.COMPUTER = '' def MainMenu(self, OPTION): while True: print("""\t Welcome to Tic-Tac-Toe game\n \t 1. New Game (type New)\n \t 2. Quit (type Quit)\n""") OPTION = input("Choose an option:> ") if OPTION == "New" or OPTION == "Quit": break else: print("Invalid entery! Please try again.") continue return OPTION def GamePrep(self, test, USER_INPUT, COMPUTER): print(test) for i in range(len(test)): if i%2 == 0: count = 0 while count < 5: if count%2 == 0: test[i].append(" ") else: test[i].append("|") count += 1 else: test[i].append("_____________________") for i in range(len(test)): print(test[i]) print("""Enter a cell number. Cells are: [0][0], [0][2], [0][4] [2][0], [2][2], [2][4] [4][0], [4][2], [4][4]""") while True: USER_INPUT = input("Type X or O:> ") if USER_INPUT == "X": COMPUTER = "O" break elif USER_INPUT == "O": COMPUTER = "X" break elif USER_INPUT != "X" or USER_INPUT != "O": print("Invalid Character! Please enter a valid character again!") continue return test, USER_INPUT, COMPUTER def PlaceCharacter(self, test, USER_INPUT,COMPUTER): while True: try: UR_CellRow = int(input("Enter Cell Row:>")) UR_CellCol = int(input("Enter Cell Column:>")) #check if the field is empty if test[UR_CellRow][UR_CellCol] == USER_INPUT or\ test[UR_CellRow][UR_CellCol] == COMPUTER: print("Cell is already filled. Please choose another cell.") continue else: test[UR_CellRow][UR_CellCol] = USER_INPUT break except ValueError: print("Invalid input. Please try again!") continue # Show the map for i in range(len(test)): print(test[i]) ######################################################### # Check empty cells ######################################################### Empty_rows = [] Empty_cols = [] for i in range(len(test)): for j in range(len(test[i])): if test[i][j] == " ": Empty_rows.append(i) Empty_cols.append(j) print("Empty_rows = {}".format(Empty_rows)) print("Empty_cols = {}".format(Empty_cols)) index = random.randint(0,len(Empty_rows)-1) print("index = {}".format(index)) CR_Index = Empty_rows[index] CC_Index = Empty_cols[index] print("CR_Index = {}".format(CR_Index)) print("CC_Index = {}".format(CC_Index)) test[CR_Index][CC_Index] = COMPUTER # Show the map for i in range(len(test)): print(test[i]) return test def ScoreCounting(self, test, USER_INPUT, COMPUTER): ############################################### # Counting SCORE ############################################### # Check if three symbols are in rows ############################################### SCORE_USER = 0 SCORE_COMPUTER = 0 for i in range(len(test)): if test[i][0] == USER_INPUT and test[i][2] == USER_INPUT and test[i][4] == USER_INPUT: SCORE_USER = 1 print("You Win!") elif test[i][0] == COMPUTER and test[i][2] == COMPUTER and test[i][4] == COMPUTER: SCORE_COMPUTER = 1 print("Computer Wins!") for j in range(len(test[0])): #Vertical Elements if test[0][j] == USER_INPUT and test[2][j] == USER_INPUT and test[4][j] == USER_INPUT: SCORE_USER = 1 print("You Win!") if test[0][j] == COMPUTER and test[2][j] == COMPUTER and test[4][j] == COMPUTER: SCORE_COMP = 1 print("Computer Wins!") if test[0][0] == USER_INPUT and test[2][2] == USER_INPUT and test[4][4] == USER_INPUT: SCORE_USER = 1 print("You Win!") elif test[4][0] == USER_INPUT and test[2][2] == USER_INPUT and test[0][4] == USER_INPUT: SCORE_USER = 1 print("You Win!") elif test[0][0] == COMPUTER and test[2][2] == COMPUTER and test[4][4] == COMPUTER: SCORE_USER = 1 print("You Win!") elif test[4][0] == COMPUTER and test[2][2] == COMPUTER and test[0][4] == COMPUTER: SCORE_USER = 1 print("You Win!") return SCORE_USER, SCORE_COMPUTER while True: start = TicTacToe() Option = start.MainMenu(start.OPTION) if Option == "New": XO_Field, UserInput, Computer = start.GamePrep(start.test, start.USER_INPUT, start.COMPUTER) while True: XO_Field_Modified = start.PlaceCharacter(XO_Field, UserInput, Computer)