所以我正在编码井字游戏
我将环境创建为9个元素的列表,如下所示-
board=[' ']*9
然后我将X或O放在板上
board[move-1] = 'X'
效果很好
我遇到的问题是放置X或O后,我无法检查获胜条件。输出始终返回为假check the output here
if (board[0] and board[1] and board[2] == 'X') or (board[0] and board[1] and board[2] == 'O') :
return winner==1
即使在索引0,1和2为X的情况下,上述代码中的也会将获胜者返回为false。
我认为这是一个简单的字符串处理问题,但我不确定。任何帮助将不胜感激。
答案 0 :(得分:0)
尝试对if语句使用以下内容:如果all
的所有3个元素均为True
,则board
将为X
。 O
if all(board[i]=='X' for i in range(3)) or all(board[i]=='O' for i in range(3)):
return winner==1
答案 1 :(得分:0)
要涵盖垂直,水平和对角线,您可以建立每个方向的轴位置列表,并检查是否有任何一个映射到XXX或OOO:
axes = [(0,1,2),(3,4,5),(6,7,8),(0,3,6),(1,4,7),(2,5,8),(0,4,8),(2,4,6)]
win = any(board[a]+board[b]+board[c] in ["XXX","OOO"] for a,b,c in axes)
如果要让计算机玩游戏,可以创建一个移动评级功能,该功能可以分析每个可玩位置并返回与该位置的好坏相对应的数字。
这是一个例子:
from random import sample
axes = [(0,1,2),(3,4,5),(6,7,8),(0,3,6),(1,4,7),(2,5,8),(0,4,8),(2,4,6)]
def isWin(board):
return any(board[a]+board[b]+board[c] in ["XXX","OOO"] for a,b,c in axes)
def rating(position,play,board,level=3**6):
if board[position] != " " or level < 3: return 0
newBoard = board[:position]+[play]+board[position+1:]
if isWin(newBoard): return level*2
nextRatings = [rating(p,"XO"[play=="X"],newBoard,level/3) for p in range(9)]
return level-max(nextRatings,key=abs)
while True:
board = [" "]*9
player,computer = sample("XOXO",2)
while True:
for r in range(0,9,3):
print("("+") (".join(board[r:r+3])+")",list(range(r+1,r+4)))
available = [str(p+1) for p in range(9) if board[p] == " "]
if isWin(board) or not available : break
player = "XO"[player=="X"]
if player == computer:
position = max(sample(range(9),9),key=lambda p:rating(p,computer,board))
print(f"Computer plays {player} at {position+1}")
else:
while True:
position = input(f"Position to play for {player}: ")
if position not in available: print("Invalid position")
else : position = int(position)-1; break
board[position] = player
print( f"{player}'s WIN !!!\n" if isWin(board) else "DRAW.\n")
rating()
函数通过可能的移动来递归地返回一个值,该值基于达到游戏结束所需的移动数量而越来越小。每个级别的值根据轮到哪个玩家而增加或减少