我试图在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 :我已经试过问同样的问题了,但我想我的问题不清楚。我想这次我已经尝试了更好的方法。
发布于 2014-06-27 17:50:54
while(n<3):
n += 1
#print str(n)+" "+str(ddrow)+" "+str(ddcol)
#print direction
finalCheck(ddrow,ddcol,direction,n)您想要n <= 3或n<4
发布于 2014-06-27 18:15:44
如果使用递归,请不要使用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基本上更改为if
使之成为n <=3或n<4
https://stackoverflow.com/questions/24457891
复制相似问题