【发布时间】:2021-01-04 18:29:51
【问题描述】:
所以我有一个有 9 个位置和 6 个棋子的棋盘,3 个 [X] 和 3 个 [ ](你也可以考虑一个棋子“[ ]”,但它代表一个空位置)。玩家可以选择将棋子移动到任何他想要的位置到他附近的位置。在下面的棋盘中,“X”(这就是我们表示棋子的方式,就像棋盘上的棋子一样,但没有 [])必须移动,但他无处可去。我想要一个函数来查看玩家是否没有合法动作,如果是,则返回 True。这些是helping functions:
#pc stands for piece, brd for board and pos for position
board = ["[X]","[X]","[X]",
"[O]","[O]","[O]",
"[ ]","[ ]","[ ]"]
def near_pos(pos): #positions are represented 1-9 and this functions gives the near positions of a position
if pos== 1:
return (2,4,5)
elif pos== 2:
return (1,3,4,5,6)
elif pos== 3:
return (2,5,6)
elif pos== 4:
return (1,2,5,7,8)
elif pos== 5:
return (1,2,3,4,6,7,8,9)
elif pos== 6:
return (2,3,5,8,9)
elif pos== 7:
return (4,5,8)
elif pos== 8:
return (4,5,6,7,9)
elif pos== 9:
return (5,6,8)
def free_pos(brd,pos): #you give it a board and a position and it returns True if it is free
pos -= 1
if brd[pos] == "[ ]":
return True
else:
return False
def player_pos(brd,pc): #It works now
l = []
for i in range(0,9):
if pc == "X":
if brd[i] == "[X]":
l.append(i + 1)
elif pc == "O":
if brd[i] == "[O]":
l.append(i + 1)
return (* l,)
#The last function (the one that I'll write next, sorry if I caused any misunderstanding) was supposed to see if from the positions I got from player_pos, if any had a close position available. The way I thought I could do that was by seeing for each position the positions near that one, using near_pos function, and determine if there was any clear one, using free_pos.
我写的是这个,但它是错误的,我不知道如何解决它
def No_Free_Positions(brd,pc):
if pc == "X":
a = "O"
if pc =="O":
a = "X"
for player_pos(brd,pc) in near_pos(pc):
if Free_Pos(brd,near_pos(pc)) is False:
return "No"
else:
return "Yes"
有什么问题?
【问题讨论】:
-
brd[pos] == " "永远不会是真的。如果要匹配一个空方块,应该是brd[pos] == "[ ]" -
也许你不应该将
[和]放在board中,只需将X、O或空格。然后在显示板时添加括号。
标签: python python-3.x