我的 python 井字游戏有困难

Difficulties with my python tic-tac-toe

我正在关注 Charles Dierbach 的书《计算机科学导论》Python。

我正在学习第 5 章。我正在尝试在井字游戏自动播放中进行此练习。

我在为 pc 创建一个函数到 select 一个空框 ([]) 时遇到困难。

这是我的代码

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

我遇到的问题是 def pc_player():

我想知道如何循环列表和子列表,以便 AI 可以 select 选择一个空框来放置 "O"

我当前的 for 循环不起作用。 AI 仅 select 第一个框。

My current for loop does not work. AI only selects the first box.

我想你是指这部分:

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

break 指令连同初始化 for 循环的方式只会尝试设置 lst[0][0]。不考虑其他单元格。

要做出均匀分布的随机选择,必须先收集可能性。为此,首先将所有单元格放在一个普通列表中会很方便:

from itertools import chain
all_cells = list(chain.from_iterable(lst))

然后,您可以过滤掉非空单元格:

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]

基于此,您现在可以触发随机选择和符号放置:

import random
cell_to_place = random.choice(empty_cells)
cell_to_place.append('O')

如果需要被修改的单元格的索引,可以这样做:

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)
# ...

这些代码示例没有考虑到可能没有剩余的空单元格。此外,您的代码存在一些一般设计问题。例如:

  • 为什么首先使用列表作为单元格项目?您可以简单地使用 None'X''O' 作为二维列表的元素。
  • check_pc_playercheck_1st_player 可以很容易地通过使符号检查函数的参数来概括。
  • 为什么这是一个 while 循环?

        while check_first_winner:
            game_first = check_1st_player(structure)
            check_first_winner = False
    

首先找到所有空框:

empty= [(i,j) for i in range(len(lst)) for j in range(len(lst[i])) if lst[i][j]==[]]

然后随机选择一个:

import random
chosen_i, chosen_j= random.choice(empty)

最后放一个 O 在那里:

lst[chosen_i][chosen_j]= 'O'