【发布时间】:2020-04-27 00:02:39
【问题描述】:
我是一名新程序员,我开始学习 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