Tic Tac Toe - Finding empty grid tiles [closed]

2019-08-30 05:34发布

问题:

This is a continuation of my previous question regarding the tic tac toe game. I am making a function that will collect all the empty grid tiles of a tic tac toe board, and return them in a list. This function would be recursive, in that it would keep looking for empty grid tiles that are adjacent to a move made. Something like this:

<------->
< X O - >
< - - X >
< O X - >
<------->

So lets say the user (or in this case, the code I wrote for the computer playing against the computer) wants to know what grid tiles are empty by picking a tile. For the above example, the tiles would be numbered

0 1 2
3 4 5 
6 7 8

and so lets say the computer chose tile 1 - it would search the adjacent tiles (so in this case, top, left, right, and bottom) and see if it can make moves there. If it finds that an adjacent tile is empty, it finds the adjacent tiles of that tile as well, until it exhausts all possibilities. So I want to be able to call my function with the current board and a playerMove, and find the adjacent tiles that are empty, and append them to a list. Any tips?

def whatIsEmpty(moveList,move):
     emptyTiles = []
     #something that allows you to find the adjacent tiles of the move
     #something that allows you to find the adjacent tiles of the tiles found above, until all are found

I know I need a couple for loops for this, but I'm not sure how to start. What I know is I want to have move in the middle of an imaginary 3x3 grid, and find its adjacent tiles to see if they are empty, and so on. So in a 2D list, I would use something like this:

moveList[x-1][y]
moveList[x][y+1]
moveList[x+1][y]
moveList[x][y+1]

Where each of those corresponds to top, right, left, and bottom, and this would be used recursively. Any tips are greatly appreciated.

回答1:

A recursive strategy might not be best in this scenario. Consider the example you yourself provided:

<------->
< X O - >
< - - X >
< O X - >
<------->

Suppose the next move was made in the middle tile. If the recursive function checks only the four tiles adjacent to it, then it would miss the tile that was "cut off" from the rest (the bottom right one). And if you were to write a function to check all 8 adjacent tiles (including diagonally adjacent) you might as well write it iteratively.

for i in range(3):
   for j in range(3):
      pass # Replace with code to add empty tile to list