我正在尝试用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:我已经试过问这个问题了,但我想我的问题还不清楚。我想这次我试得更好了。你知道吗
您想要n<;=3还是n<;4
如果使用递归,不要使用while循环。当你打算做3次手术时,你可能要做9次手术。如果展开代码
基本上改变了
并使其n<;=3或n<;4
相关问题 更多 >
编程相关推荐