TicTacToe没有人赢得胜利,并超越了玩家的选择

问题描述 投票:0回答:3

我是一名新程序员,我开始学习python,想学习编写井字游戏的代码。

游戏继续进行,但是获胜条件和计算机场选择不能正常工作:它不知道何时停止比赛,有时计算机会选择一个已经选择的场,因此覆盖了我的选择(如果我尝试执行相同的操作,则出现ValueError)。

对于胜利算法,我不想手工遍历所有选项,因此我使用了集合。我创建了一个包含所有获胜条件的组合。在迭代每个子集(行,列和对角线)时,我检查这是否是玩家/计算机位置的子集。

问题是:它不起作用。如果我尝试执行任何操作,则会得到ValueError:list.remove(x)x not in list。有时在删除playerChoice或从计算机上删除那行的时候出现此错误。如上所述的另一个问题是计算机可以替代我的选择。

我认为问题在于从一组元素中删除元素并将其添加到另一组元素,但是我找不到解决此问题的方法

这里是代码:

import random

board = [" ", " ", " ", " ", " ", " ", " ", " ", " "]
playerSymbol = ""
playerPosition = []
aiSymbol = ""
aiPosition = []
possiblePositions = [0, 1, 2, 3, 4, 5, 6, 7, 8]
turn = 0


def drawBoard():
    print(board[0] + " | " + board[1] + " | " + board[2])
    print("___" + "___" + "___")
    print(board[3] + " | " + board[4] + " | " + board[5])
    print("___" + "___" + "___")
    print(board[6] + " | " + board[7] + " | " + board[8])


def choice():
    global playerSymbol
    global aiSymbol

    answer = input("What do you want to play as? (type x or o) ")

    if answer.upper() == "X":
        playerSymbol = "X"
        aiSymbol = "O"
    else:
        playerSymbol = "O"
        aiSymbol = "X"


def won():
    winningPositions = [{0, 1, 2}, {3, 4, 5}, {6, 7, 8}, {0, 4, 8}, {2, 4, 6}, {0, 3, 6}, {1, 4, 7}, {2, 5, 8}]

    for position in winningPositions:
        if position.issubset(playerPosition):
            print("Player Wins :)")
            return True
        elif position.issubset(aiPosition):
            print("AI wins :(")
            return True
        else:
            return False


def play():
    global turn
    choice()

    while not won():
        if turn % 2 == 0:
            pos = int(input("Where would you like to play? (0-8) "))
            possiblePositions.remove(pos)
            playerPosition.append(pos)
            board[pos] = playerSymbol
            turn += 1
            drawBoard()
        else:
            aiTurn = random.randint(0, len(possiblePositions) - 1)
            possiblePositions.remove(possiblePositions[aiTurn])
            aiPosition.append(aiTurn)
            board[aiTurn] = aiSymbol
            turn += 1
            print("\n")
            print("\n")
            drawBoard()
    else:
        print("Thanks for playing :)")


play()

我愿意接受各种建议和改进我的代码的方法。预先感谢并保持健康,克里斯蒂

python tic-tac-toe
3个回答
0
投票

首先,最好打印整个温度字段和带有输入数字的字段,因为从0-8中选择框会很不舒服。这样,它很容易理解(例如):


0
投票

一些尝试:


0
投票

两件事:

© www.soinside.com 2019 - 2024. All rights reserved.