Difficulties with my python tic-tac-toe - python

I am following Charles Dierbach's book, Introduction to Computer Science using Python.
I am on chapter 5. I am trying to do this exercise on tic-tac-toe automate play.
I am having difficulties creating a function for the pc to select an empty box ([]).
Here is my code
import re
import random
def template():
mylst = list()
for i in range(0, 3):
my_temp = []
for j in range(0, 3):
my_temp.append([])
mylst.append(my_temp)
return mylst
def template_2(alst):
print()
al = ("A", "B", "C")
for a in al:
if a == "A":
print (format(a, ">6"), end="")
if a == "B":
print (format(a, ">5"), end="")
if a == "C":
print (format(a, ">5"), end="")
print()
for j in range(len(alst)):
print(str(j + 1), format( " ", ">1"), end="")
print(alst[j])
print()
def print_template(alst):
print()
al = ("A", "B", "C")
for a in al:
if a == "A":
print (format(a, ">6"), end="")
if a == "B":
print (format(a, ">4"), end="")
if a == "C":
print (format(a, ">3"), end="")
print()
for j in range(len(alst)):
print(str(j + 1), format( " ", ">1"), end="")
print(alst[j])
print()
def first_player(lst):
print()
print ("Your symbol is 'X'. ")
alpha = ("A", "B", "C")
#check it was entered correctly
check = True
temp_lst1 = []
while check:
correct_entry = False
while not correct_entry:
coord = input("Please enter your coordinates ")
player_regex = re.compile(r'(\w)(\d)')
aSearch = player_regex.search(coord)
if aSearch == None:
correct_entry = False
if aSearch.group(1) != "A" or aSearch.group(1) != "B" or aSearch.group(1) != "C" or aSearch.group(2) != 1 or aSearch.group(2) == 2 or aSearch.group(3) != 3:
correct_entry = False
if aSearch.group(1) == "A" or aSearch.group(1) == "B" or aSearch.group(1) == "C" or aSearch.group(2) == 1 or aSearch.group(2) == 2 or aSearch.group(3) == 3:
correct_entry = True
else:
correct_entry = True
blank = False
while not blank:
if lst[(int(coord[-1])) - 1][alpha.index(coord[0])] == []:
lst[(int(coord[-1])) - 1][alpha.index(coord[0])] = "X"
temp_lst1.append((int(coord[-1])-1))
temp_lst1.append((alpha.index(coord[0])))
blank = True
else:
blank = True
correct_entry = False
if blank == True and correct_entry == True:
check = False
return True
def pc_player(lst):
print()
print ("PC symbol is 'O'. ")
alpha = ("A", "B", "C")
num_list = (0, 1, 2)
for i in range(0, len(lst)):
for j in range(0, len(lst[i])):
if lst[i][j] ==[]:
lst[i][j] = "O"
break
break
return True
def check_1st_player(lst):
if lst[0][0] == "X" and lst[0][1] == "X" and lst[0][2] == "X":
return True
elif lst[1][0] == "X" and lst[1][1] == "X" and lst[1][2] == "X":
return True
elif lst[2][0] == "X" and lst[2][1] == "X" and lst[2][2] == "X":
return True
elif lst[0][0] == "X" and lst[1][0] == "X" and lst[2][0] == "X":
return True
elif lst[0][1] == "X" and lst[1][1] == "X" and lst[2][1] == "X":
return True
elif lst[0][2] == "X" and lst[1][2] == "X" and lst[2][2] == "X":
return True
elif lst[0][0] == "X" and lst[1][1] == "X" and lst[2][2] == "X":
return True
elif lst[2][0] == "X" and lst[1][1] == "X" and lst[0][2] == "X":
return True
else:
return False
def check_pc_player(lst):
if lst[0][0] == "O" and lst[0][1] == "O" and lst[0][2] == "O":
return True
elif lst[1][0] == "O" and lst[1][1] == "O" and lst[1][2] == "O":
return True
elif lst[2][0] == "O" and lst[2][1] == "O" and lst[2][2] == "O":
return True
elif lst[0][0] == "O" and lst[1][0] == "O" and lst[2][0] == "O":
return True
elif lst[0][1] == "O" and lst[1][1] == "O" and lst[2][1] == "O":
return True
elif lst[0][2] == "O" and lst[1][2] == "O" and lst[2][2] == "O":
return True
elif lst[0][0] == "O" and lst[1][1] == "O" and lst[2][2] == "O":
return True
elif lst[2][0] == "O" and lst[1][1] == "O" and lst[0][2] == "O":
return True
else:
return False
def play_game():
ask = input("Do you want to play a two player game of Tic-Tac-Toe game? (y/n) ")
if ask in yes_response:
# contruct the template for tic-tac-toe
print()
print("How many rounds do you want to play? " )
print("Please enter only odd integers" )
print("Please enter your coordinates", end="")
print(" using format A1 or B2")
print("New Round")
return True
def play_again():
tell_me = input("Do you want you play a game ? (y/n)")
if tell_me == "Y" or "y":
return True
else:
return False
def is_full(lst):
count = 0
for i in lst:
for j in i:
if j != []:
count += 1
if count == 9:
return True
#
#-- main
print("Welcome to Awesome 2 Player Tic-Tac-Toe Game? ")
print()
answer = False
yes_response =("Y", "y")
no_response = ("N", "n")
while not answer:
print("Enter an even integer to exit")
ask = int(input("How many matches do you want to play? (odd integers only)? " ))
game = play_game()
structure = template()
print_template(structure)
if ask % 2 == 1:
score_player1 = 0
score_pc = 0
count = 0
while count < ask:
pc_lst = []
if count >= 1:
structure = template()
print_template(structure)
while game:
check_pc = True
while check_pc:
pc_player(structure)
template_2(structure)
check_pc = False
check_pc_winner = True
while check_pc_winner:
game_pc = check_pc_player(structure)
check_pc_winner = False
if game_pc == True:
print("Congratulations PC won")
score_pc += 1
game = False
break
check_player1 = True
while check_player1:
first_player(structure)
template_2(structure)
check_player1 = False
check_first_winner = True
while check_first_winner:
game_first = check_1st_player(structure)
check_first_winner = False
if game_first == True:
print("Congratulations Player 1 won")
score_player1 += 1
game = False
break
board_full = False
while not board_full:
check_board = is_full(structure)
board_full = True
if check_board == True:
print("This round was a tie.")
game = False
print("Player 1 : ", score_player1, " PC : ", score_pc)
count += 1
game = True
if score_player1 > score_pc:
print("Player 1 won")
elif score_player1 < score_pc:
print("PC won")
if play_again() == False:
answer = True
else:
answer = False
The problem I have is at def pc_player():
I would like to know how to loop the list and sublists so that AI can select an empty box as its choice to place an "O"
My current for loop does not work. AI only selects the first box.

My current for loop does not work. AI only selects the first box.
I suppose you refer to this part:
def pc_player(lst):
print()
print ("PC symbol is 'O'. ")
alpha = ("A", "B", "C")
num_list = (0, 1, 2)
for i in range(0, len(lst)):
for j in range(0, len(lst[i])):
if lst[i][j] ==[]:
lst[i][j] = "O"
break
break
return True
The break instructions together with the way you initialize the for loops will only attempt to set lst[0][0]. Other cells are not considered.
To make an evenly distributed random choice, it is essential to gather the possibilities first. For this, it is convenient to have all cells in a plain list first:
from itertools import chain
all_cells = list(chain.from_iterable(lst))
Then, you can filter out non-empty cells:
empty_cells = filter(lambda l: len(l) == 0, all_cells)
# empty_cells = filter(lambda l: not l, all_cells)
# empty_cells = [cell for cell in all_cells if not cell]
Based on this you can now trigger your random selection and symbol placement:
import random
cell_to_place = random.choice(empty_cells)
cell_to_place.append('O')
If you need the index of the cell being modified, you can do the following:
import itertools
indices = list(itertools.product(range(3), range(3)))
indexed_cells = zip(indices, map(lambda (i, j): lst[i][j], indices))
indexed_cells = filter(lambda (_, l): not l, indexed_cells) # filter non-empty
(i,j), cell_to_place = random.choice(indexed_cells)
# ...
These code samples do not take into account that there could be no empty cell left. Also, your code has some general design issues. For example:
Why do you use lists as cell items in the first place? You could simply use None, 'X' and 'O' as the elements of the 2-dimensional list.
check_pc_player and check_1st_player can be easily generalized by making the symbol to check for a parameter of the function.
Why is this a while-loop?
while check_first_winner:
game_first = check_1st_player(structure)
check_first_winner = False

Start by finding all empty boxes:
empty= [(i,j) for i in range(len(lst)) for j in range(len(lst[i])) if lst[i][j]==[]]
Then choose a random one:
import random
chosen_i, chosen_j= random.choice(empty)
And finally put an O there:
lst[chosen_i][chosen_j]= 'O'

Related

If loop with multiple conditions still executing when one condition is not met

I'm making a roman numeral to integer converter. In the code below, you will see the function math_logic. When I give the input CCC, the program should skip the if statements and elif statements (because of the keyword and) and go right to the else statement since only one of the two conditions are met. The else statement should return a dictionary value using parameter char_0 as the key. However, the program will run the code inside the second elif statement and return TypeError: unsupported operand type(s) for +: 'int' and 'NoneType' as the error.
I'm not sure why this is happening. You can put a debug point at line 38 and step into 4 times to get to the issue I'm having.
Please see code below
romanToIntDictionary = {
"I": 1,
"V": 5,
"X": 10,
"L": 50,
"C": 100,
"D": 500,
"M": 1000
}
subtraction_happened = [
4,
9,
40,
90,
400,
900
]
def convert_roman_to_int(string, checker_state):
characters_left = len(string)
character_list = []
total = 0
if checker_state:
print("What you entered is a valid roman numeral.")
for character in string:
character_list.append(character)
while characters_left > 1:
did_i_sub = False
for item in subtraction_happened:
if (not did_i_sub) and (item == math_logic(character_list[0], character_list[1], romanToIntDictionary)): #the order of multiple conditions matters
total = total + math_logic(character_list[0], character_list[1], romanToIntDictionary)
characters_left -= 2
character_list.pop(0)
character_list.pop(0)
did_i_sub = True
if not did_i_sub:
total = total + math_logic(character_list[0], character_list[1], romanToIntDictionary)
characters_left -= 1
character_list.pop(0)
while characters_left == 1:
total = total + romanToIntDictionary[character_list[0]]
characters_left -= 1
character_list.pop(0)
print(total)
if not checker_state:
print("What you entered is not a roman numeral.")
def math_logic(char_0, char_1, r_to_i_dict):
if (char_0 == "I") and (char_1 == "V" or "X"):
if char_1 == "V":
return 4
elif char_1 == "X":
return 9
elif (char_1 == "L" or "C") and (char_0 == "X"):
if char_1 == "L":
return 40
elif char_1 == "C":
return 90
elif (char_1 == "D" or "M") and (char_0 == "C"):
if char_1 == "D":
return 400
elif char_1 == "M":
return 900
else:
return r_to_i_dict[char_0]
def roman_numeral_checker(string):
is_roman_numeral = True
characters_left = len(string)
while is_roman_numeral and characters_left > 0:
for character in string:
if character not in romanToIntDictionary.keys():
is_roman_numeral = False
characters_left -= 1
if not is_roman_numeral:
return False
if is_roman_numeral:
return True
string_from_user = (input("Enter a roman numeral to convert: ")).upper()
convert_roman_to_int(string_from_user, roman_numeral_checker(string_from_user))
The trouble is in your boolean logic:
value = 'c'
print(value == 'X' or 'V')
'V'
This is because 'V' is a "truthy" value:
bool('V')
True
So you are saying if value == 'X' or True: which will always be True. Because of this, there's an else that isn't evaluating:
if value == 'X' or 'V':
if value == 'X':
print('X!')
elif value == 'V':
print('V!')
else:
print('unexpected')
unexpected
The correct syntax is:
if value == 'X' or value == 'V':
Or even more succinctly:
if value in ('X', 'V'):
if value == 'X':
do something
else:
do something
The else ensures that all cases are covered, and they are, because value could only be 'X' or 'V'.
So your whole math logic function would be:
def math_logic(char_0, char_1, r_to_i_dict):
if char_0 == "I" and char_1 in ('V', 'X'):
if char_1 == "V":
return 4
else:
return 9
elif char_1 in ('L', 'C') and char_0 == "X":
if char_1 == "L":
return 40
else:
return 90
elif char_1 in ('D', 'M') and char_0 == "C":
if char_1 == "D":
return 400
else:
return 900
else:
return r_to_i_dict[char_0]

Python, unexpected looping continuously when run the codes

I am currently learning python and trying to build a tic tac toe game. I wrote a program to prevent the user repeating the same input but when I repeat the same number two times, the program starts looping continuously without stopping. Could someone give me advice on how to rectify this issue? see below the code:
from tabulate import tabulate
# define the board
board = ["_", "_", "_",
"_", "_", "_",
"_", "_", "_"]
# Current player
current_player = "X"
winner = None
game_still_on = True
def play_game():
while game_still_on:
position()
board_display()
handle_player()
winner_check()
winner_check2()
def handle_player():
global current_player
if current_player == "X":
current_player = "O"
elif current_player == "O":
current_player = "X"
def board_display():
board_row1 = [board[0], board[1], board[2]]
board_row2 = [board[3], board[4], board[5]]
board_row3 = [board[6], board[7], board[8]]
com_board = [board_row1,
board_row2,
board_row3]
print(tabulate(com_board, tablefmt="grid"))
# position input
def position():
global board
print(current_player+"'s turn")
positions = input("enter 1-9")
valid = False
while not valid:
while int(positions) >= 10 or 0 >= int(positions):
positions = input("Choose a position from 1 -9")
positions = int(positions)
if board[positions-1] == "_":
valid = True
else:
print("Choose another")
board[positions - 1] = current_player
def winner_check():
if board[0] == board[1] == board[2] != "_":
return board[0]
elif board[3] == board[4] == board[5] != "_":
return board[3]
elif board[6] == board[7] == board[8] != "_":
return board[6]
elif board[0] == board[3] == board[6] != "_":
return board[0]
elif board[1] == board[4] == board[7] != "_":
return board[1]
elif board[2] == board[5] == board[8] != "_":
return board[2]
elif board[0] == board[4] == board[8] != "_":
return board[0]
elif board[2] == board[4] == board[6] != "_":
return board[1]
else:
return None
def winner_check2():
row_winner = winner_check()
if row_winner:
global game_still_on
global winner
winner = row_winner
print((winner+ " won"))
game_still_on = False
play_game()
Let's look at this function:
# position input
def position():
global board
print(current_player+"'s turn")
positions = input("enter 1-9")
valid = False
while not valid:
while int(positions) >= 10 or 0 >= int(positions):
positions = input("Choose a position from 1 -9")
positions = int(positions)
if board[positions-1] == "_":
valid = True
else:
print("Choose another")
board[positions - 1] = current_player
This has nested validation loops. The inner one checks the range of the input integer (if it is an integer -- otherwise it throws an exception) and requests input until it's in range. That's fine.
Then in the outer validation loop, it checks if the requested space is unoccupied. If so, fine. If not, it prompts the user to choose another. But the input call is before the outer loop, so it just tries again to validate the same input that already failed.
Try moving the input into the outer loop:
# position input
def position():
global board
print(current_player+"'s turn")
valid = False
while not valid:
positions = input("enter 1-9")
while int(positions) >= 10 or 0 >= int(positions):
positions = input("Choose a position from 1 -9")
positions = int(positions)
if board[positions-1] == "_":
valid = True
else:
print("Choose another")
board[positions - 1] = current_player
I'd probably also change the inner loop to be just an if with a continue and make the handling of non-integer input more robust.

Tic Tac Toe Game, I want to offer the user the option to save game during gameplay(after first move). Here's a portion of my current code

I am attempting to prompt the user the option to save the game, after the first move, during gameplay?
After the game is completed I want to prompt the user to reset the game(Y or N) then call the play game function(with a loop)?
However, I am unsure how to organize the code to accomplish these tasks. I am a beginner to python.
def play_game():
game = True
while game == True:
game_choice = menu()
if game_choice == 1:
choice_one()
elif game_choice ==2:
player1VSai()
elif game_choice ==3:
save_and_exit()
elif game_choice==4:
load_game()
#After the game is completed I want to reset the game and call the play game function(with a loop).
# reset_game()
# play_game()
def choice_one():
# Display initial board
display_board()
while game_still_playing:
# handle a single turn of a arbitrary player
handle_turn(current_player)
# check if win or tie
check_if_game_over()
# flip to other player
alternate_player()
# The game has ended
if winner == 'X' or winner == 'O':
print(winner + " won.")
elif winner == None:
print("Tie.")
# handle a single turn of a random player
def handle_turn(player):
print(player + "'s turn.")
position = input("Choose a position from 1 to 9: ")
# I can index into position with int instead of string
valid = False
while not valid:
while position not in ["1", "2", "3", "4", "5", "6", "7", "8", "9"] or position ==0:
position = input("Choose a position from 1-9: ")
if position == 0:
save_and_exit()
pass
# convert from string to int
position = int(position) - 1
if board[position] == '':
valid = True
else:
print("Space filled. Go again.")
# Board at position equals X
board[position] = player
display_board()
print("Press 0 to save & exit game.")
#then if? or loop? prompt user to save game?
For saving code, your Game has things that you should save:
The state of the board, variable player
Whose turn it is, variable
board
This means you would have to write a function that takes these 2 variables as input argument and writes the content to a file.
#Remy this is what I have for the save function,
which I believe works properly as I've saved the data I need.
def save_and_exit():
global current_player
#save and end loop
turn=current_player
option = menu()
file=open("HW3game.txt", "w")
for x in board:
file.write(x)
file.write(turn)
file.write(str(option))
file.close()
print("You have saved the game and exited")
return
import random
# functions
# board
# display board
# ask if you want to be x or O
# menu
# play game
# take input & alternate turns
# check win
# check rows
# check columns
# check diagonals
# check tie
# is board full
# ---- Global Variables -----
# Game Board
board = [''] * 9
# If game is still going
game_still_playing = True
# Who won? Or Tie?
winner = None
# Prompt user to choose X's or O's
letter = input("Choose a letter X or O: ").upper()
current_player = letter
# Input validation
while current_player not in ('x', 'o', 'X', 'O'):
letter = input("Try again. Choose a letter X or O:").upper()
current_player = letter
if letter.upper() not in ('X', 'O'):
print("Not an appropriate choice.")
else:
break
print("Player 1 will be ", current_player + "'s.\n")
def display_board():
print(board[6], "\t|", board[7] + " | " + board[8])
print("--------------")
print(board[3], "\t|", board[4] + " | " + board[5])
print("--------------")
print(board[0], "\t|", board[1] + " | " + board[2])
# ("1) Player 1 vs Player 2\n2) Player 1 vs AI\n3) Load Game\n0) Save & Exit")
# play tic tac toe
def play_game():
begin = "Y"
while begin == "Y":
game_choice = menu()
if game_choice == 1:
choice_one()
elif game_choice ==2:
player1VSai()
elif game_choice ==3:
save_and_exit()
elif game_choice==4:
load_game()
def choice_one():
# Display initial board
display_board()
while game_still_playing:
# handle a single turn of a arbitrary player
handle_turn(current_player)
# check if win or tie
check_if_game_over()
# flip to other player
alternate_player()
# The game has ended
if winner == 'X' or winner == 'O':
print(winner + " won.")
clear_board = reset_game()
play_game()
elif winner == None:
print("Tie.")
reset_game()
play_game()
# handle a single turn of a random player
def handle_turn(player):
print(player + "'s turn.")
position = input("Choose a position from 1 to 9: ")
# I can index into position with int instead of string
valid = False
while not valid:
while position not in ["1", "2", "3", "4", "5", "6", "7", "8", "9"] or position ==0:
position = input("Choose a position from 1-9: ")
if position == 0:
save_and_exit()
pass
# convert from string to int
position = int(position) - 1
if board[position] == '':
valid = True
else:
print("Space filled. Go again.")
# Board at position equals X
board[position] = player
display_board()
print("Press 0 to save & exit game.")
#then if? or loop? prompt user to save game?
def check_if_game_over():
# 3 in a row
check_for_winner()
# full board
check_if_tie()
def check_for_winner():
# Set up global variables
global winner
# check rows
row_winner = check_rows()
# check columns
column_winner = check_columns()
# check diagonals
diagonal_winner = check_diagonals()
if row_winner:
winner = row_winner
print("There was a ROW win!")
elif column_winner:
winner = column_winner
print("There was a COLUMN win!")
elif diagonal_winner:
winner = diagonal_winner
print("There was a DIAGONAL win!")
else:
winner = None
def check_rows():
# Set up global variables
global game_still_playing
# check rows for all the same values & is not an empty ''
row_1 = board[6] == board[7] == board[8] != ''
row_2 = board[3] == board[4] == board[5] != ''
row_3 = board[0] == board[1] == board[2] != ''
# if any row does have a match, flag that there is a win
if row_1 or row_2 or row_3:
game_still_playing = False
# Return the winner (X or O)
if row_1:
return board[6]
elif row_2:
return board[3]
elif row_3:
return board[0]
# return X or O if winner
# then flag game still playing to false to end loop
def check_columns():
# Set up global variables
global game_still_playing
# check columns for all the same values & is not an empty ''
column_1 = board[6] == board[3] == board[0] != ''
column_2 = board[7] == board[4] == board[1] != ''
column_3 = board[8] == board[5] == board[2] != ''
# if any column does have a match, flag that there is a win
if column_1 or column_2 or column_3:
game_still_playing = False
# Return the winner (X or O)
if column_1:
return board[6]
elif column_2:
return board[7]
elif column_3:
return board[8]
# return X or O if winner
# then flag game still playing to false to end loop
def check_diagonals():
# Set up global variables
global game_still_playing
# check columns for all the same values & is not an empty ''
diagonal_1 = board[0] == board[4] == board[8] != ''
diagonal_2 = board[6] == board[4] == board[2] != ''
# if any row does have a match, flag that there is a win
if diagonal_1 or diagonal_2:
game_still_playing = False
# Return the winner (X or O)
if diagonal_1:
return board[0]
elif diagonal_2:
return board[6]
# return X or O if winner
# then flag game still playing to false to end loop
def check_if_tie():
# declare global variable
global game_still_playing
# check if board full
if '' not in board:
game_still_playing = False
return
def alternate_player():
global current_player
# if current player is == to X then change it to O
if current_player == "X":
current_player = 'O'
# if current player is == to O then change it to X
elif current_player == "O":
current_player = 'X'
def player1VSai():
#random number
return
def save_and_exit():
global current_player
#save and end loop
turn=current_player
option = menu()
file=open("HW3game.txt", "w")
for x in board:
file.write(x)
file.write(turn)
file.write(str(option))
file.close()
print("You have saved the game and exited")
return
def menu():
print("Welcome to Tic Tac Toe")
print("1) Player 1 vs Player 2\n2) Player 1 vs AI\n3) Save & Exit\n4) Load Game")
game_choice = int(input("Choose an option, 0-4: "))
#
return game_choice
def load_game():
#setup global
global current_player
file = open("HW3game.txt", "r")
for i in range(0,8):
board[i]=file.read(1)
current_player=file.read(1)
#current choice of game.
game_choice=int(file.read(1))
file.close()
print("You have called the load function.")
return
def reset_game():
global board
#erase contents in current board
#replay game
clear_board = board.clear()
return clear_board
play_game()

How can I check for matching rows and columns with Python?

I am building a ticTacToe game and I have everything figured out but how to check for three in a row or three down a column. I think there is something simple missing, but I could have it wrong entirely. Here is the code:
def isWin(gameBoard):
#check for row matches
for row in range(0, 3):
if gameBoard[row][0] == gameBoard[row][1] and gameBoard[row][0] == gameBoard[row][2]:
return True
Maybe you can consider to use set? Something like:
def isWin(gameBoard):
for row in gameBoard:
if len(set(row)) == 1:
return true
I think I figured it out!
def isWin(gameBoard):
#check for row and column matches
for row in range(0, 3):
if gameBoard[row][0] == "X" and gameBoard[row][1] == "X" and gameBoard[row][2] == "X":
return True
if gameBoard[row][0] == "O" and gameBoard[row][1] == "O" and gameBoard[row][2] == "O":
return True
if gameBoard[0][row] == "X" and gameBoard[1][row] == "X" and gameBoard[2][row] == "X":
return True
if gameBoard[0][row] == "O" and gameBoard[1][row] == "O" and gameBoard[2][row] == "O":
return True
So I figured it out and am super excited! I am new to coding so thank you all for the support! Please let me know if you think it could be more efficient. :)
Here is the full code:
import sys
def main():
gameBoard = [[" ", " ", " "],
[" ", " ", " "],
[" ", " ", " "]]
printBoard(gameBoard)
while True:
#
playerXturn(gameBoard)
printBoard(gameBoard)
if isWin(gameBoard):
print("Player X wins!")
sys.exit()
elif boardFull(gameBoard):
print("Draw. No more plays left.")
sys.exit()
playerOturn(gameBoard)
printBoard(gameBoard)
if isWin(gameBoard):
print("Player O wins!")
sys.exit()
elif boardFull(gameBoard):
print("Draw. No more plays left.")
sys.exit()
def printBoard(gameBoard):
print("---------")
print(gameBoard[0][0], "|", gameBoard[0][1], "|", gameBoard[0][2])
print("---------")
print(gameBoard[1][0], "|", gameBoard[1][1], "|", gameBoard[1][2])
print("---------")
print(gameBoard[2][0], "|", gameBoard[2][1], "|", gameBoard[2][2])
print("---------")
def playerXturn(gameBoard):
playerXrow = int(input("Enter a row (0, 1, or 2) for player X: "))
playerXcolumn = int(input("Enter a column (0, 1, or 2) for player X: "))
while gameBoard[playerXrow][playerXcolumn] == "X" or gameBoard[playerXrow][playerXcolumn] == "O":
print("This spot is already taken. Try again:")
playerXrow = int(input("Enter a row (0, 1, or 2) for player X: "))
playerXcolumn = int(input("Enter a column (0, 1, or 2) for player X: "))
gameBoard[playerXrow][playerXcolumn] = "X"
return gameBoard
def playerOturn(gameBoard):
playerOrow = int(input("Enter a row (0, 1, or 2) for player O: "))
playerOcolumn = int(input("Enter a column (0, 1, or 2) for player O: "))
while gameBoard[playerOrow][playerOcolumn] == "X" or gameBoard[playerOrow][playerOcolumn] == "O":
print("This spot is already taken. Try again:")
playerOrow = int(input("Enter a row (0, 1, or 2) for player O: "))
playerOcolumn = int(input("Enter a column (0, 1, or 2) for player O: "))
gameBoard[playerOrow][playerOcolumn] = "O"
return gameBoard
#check for empty spaces on the board
def boardFull(gameBoard):
for i in range(3):
for j in range(3):
if gameBoard[i][j] == " ":
return False
return True
#check for 3 in a row
def isWin(gameBoard):
#check for row matches
for row in range(0, 3):
if gameBoard[row][0] == "X" and gameBoard[row][1] == "X" and gameBoard[row][2] == "X":
return True
if gameBoard[row][0] == "O" and gameBoard[row][1] == "O" and gameBoard[row][2] == "O":
return True
if gameBoard[0][row] == "X" and gameBoard[1][row] == "X" and gameBoard[2][row] == "X":
return True
if gameBoard[0][row] == "O" and gameBoard[1][row] == "O" and gameBoard[2][row] == "O":
return True
#check for diagonal matches
if gameBoard[1][1] != " " and gameBoard[0][0] == gameBoard [1][1] and gameBoard[0][0] == gameBoard [2][2]:
return True
if gameBoard[1][1] != " " and gameBoard[0][2] == gameBoard [1][1] and gameBoard[0][2] == gameBoard [2][0]:
return True
return False
main()

Python 3 IndentationError

In spite of seeing a lot of posts about the python indentation error and trying out a lot of solutions, I still get this error:
import random
import copy
import sys
the_board = [" "]*10
def printboard(board):
print(board[7] + " " + "|" + board[8] + " " + "|" + board[9])
print("--------")
print(board[4] + " " + "|" + board[5] + " " + "|" + board[6])
print("--------")
print(board[1] + " " + "|" + board[2] + " " + "|" + board[3])
def choose_player():
while True:
player = input("What do you want to be; X or O?")
if player == "X":
print("You chose X")
comp = "O"
break
elif player == "O":
print("You chose O")
comp = "X"
break
else:
print("Invalid Selection")
continue
return [player, comp]
def virtual_toss():
print("Tossing to see who goes first.....")
x = random.randint(0,1)
if x== 0:
print("AI goes first")
move = "comp"
if x == 1:
print("Human goes first")
move = "hum"
return move
def win(board,le):
if (board[7] == le and board[8] == le and board[9]==le) or (board[4] == le and board[5]==le and board[6] == le)or (board[1] == le and board[2]==le and board[3] == le)or (board[7] == le and board[5]==le and board[3] == le)or (board[9] == le and board[5]==le and board[1] == le)or (board[7] == le and board[4]==le and board[1] == le)or (board[8] == le and board[5]==le and board[2] == le)or (board[9] == le and board[6]==le and board[3] == le):
return True
else:
return False
def make_move(board,number,symbol):
board[number] = symbol
def board_full(board):
count = 0
for item in board:
if item in ["X","O"]:
count+= 1
if count ==9 :
return True
else:
return False
def valid_move(board,num):
if board[num] == " ":
return True
else:
return False
def player_move(board):
number = int(input("Enter the number"))
return number
def copy_board(board):
copied_board = copy.copy(board)
return copied_board
def check_corner(board):
if (board[7] == " ") or (board[9] == " ") or (board[1] == " ") or (board[3] == " "):
return True
else:
return False
def check_center(board):
if (board[5] == " "):
return True
else:
return False
while True:
count = 0
loop_break = 0
print("welcome to TIC TAC TOE")
pla,comp = choose_player()
turn = virtual_toss()
while True:
printboard(the_board)
if turn == "hum":
if board_full() == True:
again = input ("Game is a tie. Want to try again? Y for yes and N for No")
if again == "Y":
loop_break = 6
break
else:
system.exit()
if loop_break == 6:
continue
while True:
number = player_move(the_board)
if (valid_move(the_board,number) == True) and not(board_full == False):
make_move(the_board,number,pla)
break
else:
print("Invalid Move, try again!")
continue
if (win(the_board,pla) == True):
print ("Yay, you won!!!")
printboard(the_board)
count = 1
break
else:
turn = "comp"
printboard(the_board)
continue
else:
if board_full() == True:
again = input ("Game is a tie. Want to try again? Y for yes and N for No")
if again == "Y":
loop_break = 6
break
else:
system.exit()
if loop_break = 6:
continue
copy_board(the_board)
for i in range(0,9):
make_move(copied_board,i,pla)
if(win(copied_board,pla) == True):
make_move(the_board,comp)
turn = "hum"
loop_break = 1
break
else:
continue
if loop_break = 1:
continue
if (check_corner(the_board) == True) or (check_center(the_board)==True):
for i in [7,9,1,3,5]:
if(valid_move(copied_board,i)==True):
make_move(copied_board,i,comp)
if(win(copied_board,comp)==True):
make_move(the_board,i,comp)
print("The AI beat you")
loop_break = 2
count = 1
break
else:
make_move(the_board,i,comp)
turn = "hum"
loop_break = 3
break
if loop_break == 2:
break
elif loop_break == 3:
continue
else:
for i in [8,4,6,2]:
if(valid_move(copied_board,i)==True):
make_move(copied_board,i,comp)
if(win(copied_board,comp)):
make_move(the_board,i,comp)
print("The AI beat you")
count = 1
loop_break = 4
break
else:
make_move(the_board,i,comp)
turn = "hum"
loop_break = 5
break
if loop_break == 4:
break
elif loop_break == 5:
continue
if count == 1:
again = input("Would you like to play again? y/n")
if again == "y":
continue
else:
system.exit()
I know that this is quite a long code, but I will point out the particular area where the error lies. You see, I am getting the following error message:
Traceback (most recent call last):
File "python", line 106
if (win(the_board,pla) == True):
^
IndentationError: unindent does not match any outer indentation level
More specifically, this part of the code:
while True:
number = player_move(the_board)
if (valid_move(the_board,number) == True) and not(board_full == False):
make_move(the_board,number,pla)
break
else:
print("Invalid Move, try again!")
continue
if (win(the_board,pla) == True):
print ("Yay, you won!!!")
printboard(the_board)
count = 1
break
Any help? I cannot get the code to work by any means!!
Try unindenting the previous seven lines of code by one level (the code in that while loop). This should make the indents work correctly. Also, it seems that there is an extra space before the if statement that is causing you errors. Remove this space as well. This would make that part of the code like this:
while True:
number = player_move(the_board)
if (valid_move(the_board,number) == True) and not(board_full == False):
make_move(the_board,number,pla)
break
else:
print("Invalid Move, try again!")
continue
if (win(the_board,pla) == True):
print ("Yay, you won!!!")
printboard(the_board)
count = 1
break
You need to indent the block under while (True): consistently. E.g.:
while True:
number = player_move(the_board)
if (valid_move(the_board,number) == True) and not(board_full == False):
make_move(the_board,number,pla)
break
else:
print("Invalid Move, try again!")
continue
if (win(the_board,pla) == True):
print ("Yay, you won!!!")
printboard(the_board)
count = 1
break
else:
turn = "comp"
printboard(the_board)
continue
The problem is, the if statement is one indentation back from the rest of the code. You want to align all the code and the error should go away.
while True:
number = player_move(the_board)
if (valid_move(the_board,number) == True) and not(board_full == False):
make_move(the_board,number,pla)
break
else:
print("Invalid Move, try again!")
continue
if (win(the_board,pla) == True):
print ("Yay, you won!!!")
printboard(the_board)
count = 1
break

Categories

Resources