基于Python的Tic-tac-toe游戏

2024-06-28 11:50:20 发布

您现在位置:Python中文网/ 问答频道 /正文

所以这段代码正在制作一个tic-tac-toe游戏,让用户一直玩到有赢家为止。但是,我的代码正在创建数组,并自动决定玩家2是赢家。我通过调试器运行它,它将为棋盘创建数组,并将自动选择玩家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")

Tags: and代码trueforif玩家数组choices