Search code examples
pythonfunctionfor-loopartificial-intelligencetic-tac-toe

Difficulties with my python tic-tac-toe


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.


Solution

  • 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'