我试图在python中实现Connect4游戏。
对于游戏逻辑,如果一行中有四个点,我会从所有可能方向的每个点开始检查。 但我的逻辑只检查到连续三个点。有人可以解释一下我做错了吗?
我认为我在递归时做错了。
我到目前为止开发的代码如下:
#function to ckeck if the game is over
def checkWin(row,col):
r = row
c = col
#print r,c
return checkWinFromCell(r,c)
#function to ckeck if the game is over from current cell
def checkWinFromCell(row, col):
directions = [[0,1], [1,0], [1,1], [1,-1], [0,-1], [-1,0], [-1,-1], [-1,1]]
for d in directions:
canvas.data.temp = [(row,col)]
n=1
finalCheck(row,col,d,n)
#print canvas.data.temp
if (len(canvas.data.temp) == 4):
return True
#function to ckeck if the game is over from current cell in
#all possible directions
def finalCheck(row, col, direction,n):
drow, dcol = direction[0], direction[1]
ddrow = row+drow #next row to check
ddcol = col+dcol #next col to check
#boundary checks
if row < 0 or row>=canvas.data.rows or col < 0 or col >=canvas.data.cols:
return False
#boundary checks
if ddrow < 0 or ddrow>=canvas.data.rows or ddcol < 0 or ddcol >=canvas.data.cols:
return False
#if same color add to list
#print canvas.data.board[row][col]
#print canvas.data.board[ddrow][ddcol]
if(canvas.data.board[row][col] == canvas.data.board[ddrow][ddcol]):
canvas.data.temp.append((ddrow,ddcol))
else:
return False
#call 3 more times recursively to check if 4 are connected
while(n<3):
n += 1
#print str(n)+" "+str(ddrow)+" "+str(ddcol)
#print direction
finalCheck(ddrow,ddcol,direction,n)
PS:我会删除checkWin函数,因为它什么都不做。
PPS:我已经尝试过问同样的问题了,但我想我的问题并不清楚。我想我这次曾以更好的方式尝试过它。答案 0 :(得分:1)
如果您正在使用递归,请不要使用while循环。如果您要展开代码
,则可能需要执行9次操作n = 1
while n < 3
n += 1 # n is now 2
final check
n = 2
while n < 3
n += 1 # n is now 3
final check
n = 3
while n < 3 #fails
while < 3 #fails
while n < 3
n += 1 # n is now 3
final check
n = 3
while n < 3 #fails
while n < 3 #fails
基本上改变,如果
使其
答案 1 :(得分:0)
while(n<3):
n += 1
#print str(n)+" "+str(ddrow)+" "+str(ddcol)
#print direction
finalCheck(ddrow,ddcol,direction,n)
您希望n&lt; = 3或n&lt; 4