【问题标题】:Tic-tac-toe game logic problems井字游戏逻辑问题
【发布时间】:2021-01-17 01:11:27
【问题描述】:

[已编辑] 为简单起见,我将在此处包含整个文件:

choices = ['1', '2', '3', '4', '5', '6', '7', '8', '9']
Is_Current_One = True
won = False
wrongEntryPlayer1 = False
wrongEntryPlayer2 = False
while not won:
    if not wrongEntryPlayer1 and not wrongEntryPlayer2:
        print('\n')
        print('|' + choices[0] + '|' + choices[1] + '|' + choices[2] + '|')
        print('----------')
        print('|' + choices[3] + '|' + choices[4] + '|' + choices[5] + '|')
        print('----------')
        print('|' + choices[6] + '|' + choices[7] + '|' + choices[8] + '|')
    # above code is to print board layouts
    if Is_Current_One:
        print("Player 1's turn.\nChoose a number to put an X there.")
        try:
            choice = int(input("> ").strip())
            wrongEntryPlayer1 = False
        except ValueError:
            print("Please enter only valid fields from board (0-8)")
            wrongEntryPlayer1 = True
            continue
    else:
        print("Player 2's turn.\nChoose a number to put an O there.")
        try:
            choice = int(input("> ").strip())
            wrongEntryPlayer2 = False
        except ValueError:
            print("Please enter only valid fields from board (0-8)")
            wrongEntryPlayer2 = True
            continue

    if Is_Current_One:
        if choices[choice - 1] == int:
            try:
                choices[choice - 1] = 'X'
                wrongEntryPlayer1 = False
            except IndexError:
                print("Please enter only valid fields from board (0-8)")
                wrongEntryPlayer1 = True
        else:
            print("Please choose a number that is empty.")
            wrongEntryPlayer1 = True
    else:
        if choices[choice - 1] == int:
            try:
                choices[choice - 1] = 'O'
                wrongEntryPlayer2 = False
            except IndexError:
                print("Please enter only valid fields from board (0-8)")
                wrongEntryPlayer2 = True
        else:
            print("Please choose a number that is empty.")
            wrongEntryPlayer2 = True
    # code to toggle between True and False
    Is_Current_One = not Is_Current_One

    for pos_x in range(0, 3):
        pos_y = pos_x * 3

        # for row condition:
        if (choices[pos_y] == choices[(pos_y + 1)]) and (
                choices[pos_y] == choices[(pos_y + 2)]):
            won = True

        # column condition:
        if (choices[pos_x] == choices[(pos_x + 3)]) and (
                choices[pos_x] == choices[(pos_x + 6)]):
            won = True
    if ((choices[0] == choices[4] and choices[0] == choices[8])
            or (choices[2] == choices[4] and choices[4] == choices[6])):
        won = True

print("Player " + str(int(Is_Current_One + 1)) + " won, Congratulations!")

如果你真的读过代码,你会发现我在做一个井字游戏。 我已经声明了两个布尔变量:wrongEntryPlayer1wrongEntryPlayer2,最初默认设置为False,因为游戏刚刚开始。 在玩这个游戏时,玩家需要输入一个整数,在游戏板中显示,在其中放置一个XO。 如果玩家没有输入一个整数,程序就会崩溃,我不想这样。相反,我使用try 语句并在他们没有输入整数时打印一条用户友好的消息。 发生这种情况时,我不想让 Python 重新打印游戏板,所以当玩家输入错误的值时,我将相应的 wrongEntryPlayer 变量设置为 True。这样,如果任何一个玩家输入了错误的值,我将完全跳过打印游戏板。

但是,当我尝试运行它并在第一回合输入错误的值,然后输入正确的值时,游戏板仍然不显示。即使轮到玩家 2,游戏板仍然没有打印出来。

当玩家输入正确的值(整数)时,游戏板仍然不显示。

另外,当玩家输入已经被其他玩家占用的值时,程序应该提示玩家再次输入。相反,它只是跳过玩家的回合。

我是python初学者,所以有些代码可能看起来很傻。谁能帮助我并向我解释如何解决这个问题?谢谢! 感谢 Sanetro,我原来的问题得到了解决。现在发生了另一个错误。详细问题发布在 Sanetro 答案的评论部分。我在这里包含我的详细编辑代码。

choices = ['1', '2', '3', '4', '5', '6', '7', '8', '9']
Is_Current_One = True
won = False
wrongEntryPlayer1 = False
wrongEntryPlayer2 = False
while not won:
    if not wrongEntryPlayer1 and not wrongEntryPlayer2:
        print('\n')
        print('|' + choices[0] + '|' + choices[1] + '|' + choices[2] + '|')
        print('----------')
        print('|' + choices[3] + '|' + choices[4] + '|' + choices[5] + '|')
        print('----------')
        print('|' + choices[6] + '|' + choices[7] + '|' + choices[8] + '|')
    # above code is to print board layouts
    if Is_Current_One:
        print("Player 1's turn.\nChoose a number to put an X there.")
        try:
            choice = int(input("> ").strip())
            wrongEntryPlayer1 = False
        except ValueError:
            print("Please enter only valid fields from board (0-8)")
            wrongEntryPlayer1 = True
            continue
        except IndexError:
            print("Please enter only valid fields from board (0-8)")
            wrongEntryPlayer1 = True
            continue
    else:
        print("Player 2's turn.\nChoose a number to put an O there.")
        try:
            choice = int(input("> ").strip())
            wrongEntryPlayer2 = False
        except ValueError:
            print("Please enter only valid fields from board (0-8)")
            wrongEntryPlayer2 = True
            continue
        except IndexError:
            print("Please enter only valid fields from board (0-8)")
            wrongEntryPlayer2 = True
            continue
    if Is_Current_One:
        if choices[choice - 1].isnumeric():
            try:
                choices[choice - 1] = 'X'
                wrongEntryPlayer1 = False
            except ValueError:
                print("Please enter only valid fields from board (0-8)")
                wrongEntryPlayer1 = True
                continue
            except IndexError:
                print("Please enter only valid fields from board (0-8)")
                wrongEntryPlayer1 = True
                continue
        else:
            print("Please choose a number that is empty.")
            wrongEntryPlayer1 = True
    else:
        if choices[choice - 1].isnumeric():
            try:
                choices[choice - 1] = 'O'
                wrongEntryPlayer2 = False
            except ValueError:
                print("Please enter only valid fields from board (0-8)")
                wrongEntryPlayer2 = True
                continue
            except IndexError:
                print("Please enter only valid fields from board (0-8)")
                wrongEntryPlayer2 = True
                continue
        else:
            print("Please choose a number that is empty.")
            wrongEntryPlayer2 = True

    # code to toggle between True and False
    if wrongEntryPlayer1 == False and wrongEntryPlayer2 == False:
        Is_Current_One = not Is_Current_One

    for pos_x in range(0, 3):
        pos_y = pos_x * 3

        # for row condition:
        if (choices[pos_y] == choices[(pos_y + 1)]) and (
                choices[pos_y] == choices[(pos_y + 2)]):
            won = True

        # column condition:
        if (choices[pos_x] == choices[(pos_x + 3)]) and (
                choices[pos_x] == choices[(pos_x + 6)]):
            won = True
    if ((choices[0] == choices[4] and choices[0] == choices[8])
            or (choices[2] == choices[4] and choices[4] == choices[6])):
        won = True

print("Player " + str(int(Is_Current_One + 1)) + " won, Congratulations!")

[编辑 2] 好的,Sanetro,这实际上是不是最终编辑。 我正在制作退​​出命令。当播放器类型>退出时,程序退出。我最初认为这真的很简单。你做一个while循环,当玩家类型退出时打破循环,然后就是这样!嗯,它简单(至少对我来说)。由于 choice = input(.....) 是 in 循环,我不能将它放在循环之外(或在声明选择变量之前),这很糟糕。我在顶部创建了一个新变量:exitTrigger 并将新行放入 while 循环中。它现在不起作用。当玩家类型退出时,它只是说请只输入有效字段。可能是因为except语句仍然有效,我想添加一个条件来触发except语句,并且我想要exitTrigger为True时的except语句。我可以这样做吗?谢谢。

choices = ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12', '13', '14', '15', '16']
Is_Current_One = True
won = False
wrongEntryPlayer1 = False
wrongEntryPlayer2 = False
exitTrigger = False
while not won and not exitTrigger:
    if not wrongEntryPlayer1 and not wrongEntryPlayer2:
        print("Type exit to quit game")
        print('\n')
        print('|' + choices[0] + ' |' + choices[1] + ' |' + choices[2] + ' |' + choices[3] + ' |')
        print('-------------')
        print('|' + choices[4] + ' |' + choices[5] + ' |' + choices[6] + ' |' + choices[7] + ' |')
        print('-------------')
        print('|' + choices[8] + ' |' + choices[9] + '|' + choices[10] + '|' + choices[11] + '|')
        print('-------------')
        print('|' + choices[12] + '|' + choices[13] + '|' + choices[14] + '|' + choices[15] + '|')
    # above code is to print board layouts
    if Is_Current_One:
        print("Player 1's turn.\nChoose a number to put an X there.")
        try:
            choice = int(input("> ").strip())
            if choice == "exit":
                exitTrigger = True
            else:
                wrongEntryPlayer1 = False
        except ValueError:
            if not exitTrigger:
                print("Please enter only valid fields from board (1-16)")
                wrongEntryPlayer1 = True
                continue
        except IndexError:
            if not exitTrigger:
                print("Please enter only valid fields from board (1-16)")
                wrongEntryPlayer1 = True
                continue
    else:
        print("Player 2's turn.\nChoose a number to put an O there.")
        try:
            choice = int(input("> ").strip())
            if choice == "exit":
                exitTrigger = True
            else:
                wrongEntryPlayer2 = False
        except ValueError:
            print("Please enter only valid fields from board (1-16)")
            wrongEntryPlayer2 = True
            continue
        except IndexError:
            if not exitTrigger:
                print("Please enter only valid fields from board (1-16)")
                wrongEntryPlayer2 = True
                continue

    if not exitTrigger:
        if Is_Current_One:
            try:  # <============ HERE
                if choices[choice - 1].isnumeric():
                    try:
                        choices[choice - 1] = 'X'
                        wrongEntryPlayer1 = False
                    except ValueError:
                        print("Please enter only valid fields from board (1-16)")
                        wrongEntryPlayer1 = True
                        continue
                    except IndexError:
                        print("Please enter only valid fields from board (1-16)")
                        wrongEntryPlayer1 = True
                        continue
                else:
                    print("Please choose a number that is empty.")
                    wrongEntryPlayer1 = True
            except:  # <============ HERE
                print("Please enter only valid fields from board (1-16)")
                wrongEntryPlayer1 = True
                continue
        else:
            try:  # <============ HERE
                if choices[choice - 1].isnumeric():
                    try:
                        choices[choice - 1] = 'O'
                        wrongEntryPlayer2 = False
                    except ValueError:
                        print("Please enter only valid fields from board (1-16)")
                        wrongEntryPlayer2 = True
                        continue
                    except IndexError:
                        print("Please enter only valid fields from board (1-16)")
                        wrongEntryPlayer2 = True
                        continue
                else:
                    print("Please choose a number that is empty.")
                    wrongEntryPlayer2 = True
            except:  # <============ HERE
                print("Please enter only valid fields from board (1-16)")
                wrongEntryPlayer2 = True
                continue

    # code to toggle between True and False
    if not exitTrigger:
        if wrongEntryPlayer1 == False and wrongEntryPlayer2 == False:
            Is_Current_One = not Is_Current_One

        for pos_x in range(0, 4):
            pos_y = pos_x * 4

            # for row condition:
            if (choices[pos_y] == choices[(pos_y + 1)]) and (
                    choices[pos_y] == choices[(pos_y + 2)]) and (
                    choices[pos_y] == choices[(pos_y + 3)]):
                won = True

            # column condition:
            if (choices[pos_x] == choices[(pos_x + 4)]) and (
                    choices[pos_x] == choices[(pos_x + 8)]) and (
                    choices[pos_x] == choices[(pos_x + 12)]):
                won = True
        if ((choices[0] == choices[5] and choices[0] == choices[10] and choices[0] == choices[15])
                or (choices[3] == choices[6] and choices[3] == choices[9] and choices[3] == choices[12])):
            won = True
if won:
    print('\n')
    print('|' + choices[0] + ' |' + choices[1] + ' |' + choices[2] + ' |' + choices[3] + ' |')
    print('-------------')
    print('|' + choices[4] + ' |' + choices[5] + ' |' + choices[6] + ' |' + choices[7] + ' |')
    print('-------------')
    print('|' + choices[8] + ' |' + choices[9] + '|' + choices[10] + '|' + choices[11] + '|')
    print('-------------')
    print('|' + choices[12] + '|' + choices[13] + '|' + choices[14] + '|' + choices[15] + '|')
    # above code is to print board layouts
    print("Player " + str(int(Is_Current_One + 1)) + " won, Congratulations!")
if exitTrigger:
    print("Game quited")

顺便说一句,游戏板现在是 4*4 :D

【问题讨论】:

    标签: python python-3.x


    【解决方案1】:

    您的代码实际上存在两个问题 - 首先,您请求帮助的问题是由切换标志 Is_Current_One 引起的,即使玩家输入“错误”输入也是如此。换句话说,当玩家一输入“asdf”时,我们希望他们有机会再次输入“好”输入,而不是立即切换到玩家二。将if 块放在读取if not wrongEntryPlayer1 and not wrongEntryPlayer2: 的那一行上。

    第二个更大的问题是,您对玩家输入是否为int 的类型检查不起作用。首先,choices[choice - 1] == int 将数组中的值与类型进行比较,该类型始终为False。其次,即使函数isinstance(choices[choice-1], int) 也不起作用,因为选项的每个成员都是字符串类型。因此,您应该使用字符串方法choices[choice-1].isnumeric(),它将确定数组中的字符串是否为数字。 (或者,您可以只测试它不是 x 或 o,但这更符合 Pythonic。)

    我测试了这些更改,它们似乎有效。 pastebin

    【讨论】:

    • 谢谢!我忘记了我实际上是在将值与类型进行比较。现在它完美运行了!
    【解决方案2】:

    [编辑] 我做了一些修复,一切正常。

    choices = ['1', '2', '3', '4', '5', '6', '7', '8', '9']
    Is_Current_One = True
    won = False
    wrongEntryPlayer1 = False
    wrongEntryPlayer2 = False
    while not won:
        if not wrongEntryPlayer1 and not wrongEntryPlayer2:
            print('\n')
            print('|' + choices[0] + '|' + choices[1] + '|' + choices[2] + '|')
            print('----------')
            print('|' + choices[3] + '|' + choices[4] + '|' + choices[5] + '|')
            print('----------')
            print('|' + choices[6] + '|' + choices[7] + '|' + choices[8] + '|')
        # above code is to print board layouts
        if Is_Current_One:
            print("Player 1's turn.\nChoose a number to put an X there.")
            try:
                choice = int(input("> ").strip())
                wrongEntryPlayer1 = False
            except ValueError:
                print("Please enter only valid fields from board (0-8)")
                wrongEntryPlayer1 = True
                continue
        else:
            print("Player 2's turn.\nChoose a number to put an O there.")
            try:
                choice = int(input("> ").strip())
                wrongEntryPlayer2 = False
            except ValueError:
                print("Please enter only valid fields from board (0-8)")
                wrongEntryPlayer2 = True
                continue
    
        if Is_Current_One:
            if choices[choice - 1].isnumeric():
                try:
                    choices[choice - 1] = 'X'
                    wrongEntryPlayer1 = False
                except IndexError:
                    print("Please enter only valid fields from board (0-8)")
                    wrongEntryPlayer1 = True
            else:
                print("Please choose a number that is empty.")
                wrongEntryPlayer1 = True
        else:
            if choices[choice - 1].isnumeric():
                try:
                    choices[choice - 1] = 'O'
                    wrongEntryPlayer2 = False
                except IndexError:
                    print("Please enter only valid fields from board (0-8)")
                    wrongEntryPlayer2 = True
            else:
                print("Please choose a number that is empty.")
                wrongEntryPlayer2 = True
    
        # code to toggle between True and False
        if wrongEntryPlayer1 == False and wrongEntryPlayer2 == False:
            Is_Current_One = not Is_Current_One
    
        for pos_x in range(0, 3):
            pos_y = pos_x * 3
    
            # for row condition:
            if (choices[pos_y] == choices[(pos_y + 1)]) and (
                    choices[pos_y] == choices[(pos_y + 2)]):
                won = True
    
            # column condition:
            if (choices[pos_x] == choices[(pos_x + 3)]) and (
                    choices[pos_x] == choices[(pos_x + 6)]):
                won = True
        if ((choices[0] == choices[4] and choices[0] == choices[8])
                or (choices[2] == choices[4] and choices[4] == choices[6])):
            won = True
    
    print("Player " + str(int(Is_Current_One + 1)) + " won, Congratulations!")
    

    所以,我想为一些错误道歉。 我在互联网上找到了解决方案。在第 35if choices[choice - 1] == int: 你必须像这样更改 if choices[choice - 1].isnumeric():,大多数变量都被视为对象。如果您想尝试使用type(),您将收到错误消息。 接下来我删除了我的choices_closed这些东西'='。这是完全没有必要的。你的想法比我做的好。我说的是条件if it's different then intiger it's fill'。我没有看到这几行代码:

        # code to toggle between True and False
        Is_Current_One = not Is_Current_One
    

    我马上写了:

        # code to toggle between True and False
        if wrongEntryPlayer1 == False and wrongEntryPlayer2 == False:
            Is_Current_One = not Is_Current_One
    

    我以为你和我一样困,而你没有注意到这一点。 我必须说这是我的错误

    [编辑] 我在这里添加了一些例外:

        if Is_Current_One:
            try: # <============ HERE
                if choices[choice - 1].isnumeric():
                    try:
                        choices[choice - 1] = 'X'
                        wrongEntryPlayer1 = False
                    except ValueError:
                        print("Please enter only valid fields from board (0-8)")
                        wrongEntryPlayer1 = True
                        continue
                    except IndexError:
                        print("Please enter only valid fields from board (0-8)")
                        wrongEntryPlayer1 = True
                        continue
                else:
                    print("Please choose a number that is empty.")
                    wrongEntryPlayer1 = True
            except: # <============ HERE
                print("Please enter only valid fields from board (0-8)")
                wrongEntryPlayer1 = True
                continue
        else:
            try: # <============ HERE
                if choices[choice - 1].isnumeric():
                    try:
                        choices[choice - 1] = 'O'
                        wrongEntryPlayer2 = False
                    except ValueError:
                        print("Please enter only valid fields from board (0-8)")
                        wrongEntryPlayer2 = True
                        continue
                    except IndexError:
                        print("Please enter only valid fields from board (0-8)")
                        wrongEntryPlayer2 = True
                        continue
                else:
                    print("Please choose a number that is empty.")
                    wrongEntryPlayer2 = True
            except: # <============ HERE
                print("Please enter only valid fields from board (0-8)")
                wrongEntryPlayer2 = True
                continue
    

    也许这是最后的编辑:P 当您发现更多内容时,我会尽力提供帮助。

    【讨论】:

    • 我搞错了。我醒来时会做这个
    • 我注意到当玩家选择一个被占用的空间时,他们仍然会跳过他们的回合。这就是你说的问题吗?
    • 是的,但现在我确定现在可以了。很难阅读,因为凌晨 4 点我的眼睛几乎闭上了。我重写了所有文本,所以请检查一下。
    • 您好,很抱歉再次打扰。我尝试了各种不好的答案,最后发现了另一个错误。如果输入大于 9 的值,则会引发索引错误。您可以看到有两个if Is_Current_One 语句。 try 和 except 仅包含 ValueError,第二个 if Is_Current_One 语句仅包含 IndexError。所以我分别在第一个和第二个语句中添加了 IndexError 和 ValueError。尽管如此,这仍然行不通。 > 11 Traceback(最近一次调用最后一次):第 42 行,在 如果选择 [choice - 1].isnumeric(): IndexError: list index out of range
    • 我已经编辑了我的问题并包含了我编辑的代码。
    【解决方案3】:

    我认为不是使用

     if not wrongEntryPlayer1 and not wrongEntryPlayer2:
    

    你应该使用:

    if wrongEntryPlayer1 or wrongEntryPlayer2:
    

    这将修复打印板的部分。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多