Python上的井字游戏

时间:2019-09-12 01:47:05

标签: python python-3.x

因此,此代码制作了一个井字游戏,并允许用户继续玩直到有赢家为止。但是,我的代码正在创建数组,并自动确定第二个玩家是赢家。我通过调试器运行它,它将为棋盘创建阵列,并将自动选择玩家2的获胜者。我知道数组制作后的事实,但是我不知道为什么。非常感谢您的任何帮助。

"""tictactoe game for 2 players"""
choices = []
for x in range(1, 9):
    choices.append(x)
    breakpoint()



playerOneTurn = True
winner = False

def printBoard():
    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] + '|')
    print(' -----\n')



while winner:
    printBoard()
    if playerOneTurn:
        print("Player 1:")
    else:
        print("Player 2:")

    try:
        choice = int(input(">> "))
    except:
        print("please enter a valid field")
        continue

    if choices[choice - 1] == 'X' or choices[choice] == 'O':
        print("illegal move, please try again")
        continue

    if playerOneTurn:
        choices[choice - 1] = "X"
    else:
        choices[choice - 1] = "O"

    playerOneTurn = not playerOneTurn

    for x in range(0, 3):
            y = x * 3
            if choices[y] == choices[(y + 1)] and choices[y] == choices[(y + 2)]:
                winner = True
                printBoard()
            if choices[x] == choices[(x + 3)] and choices[x] == choices[(x + 6)]:
                winner = True
                printBoard()

    if((choices[0] == choices[4] and choices[0] == choices[8]) or
       (choices[2] == choices[4] and choices[4] == choices[6])):
        winner = True
        printBoard()

print("Player " + str(int(playerOneTurn + 1)) + " wins!\n")

0 个答案:

没有答案