Fork me on GitHub
#beginners
<
2016-07-23
>
magoeke17:07:37

Hi guys ðŸ™‚ I'm pretty new to clojure or functional programming in general. At the moment I'm programming a "connect four". I thought a small game would be a nice start to dive in the clojure world. Until now it went well, but now I have a problem. The problem is that I have no idea how to write a win check. Normally(in any other non functional language) I would solve this problem by using for-loops but I don't think that this is the clojure way of solving this problem. So can you give me some hints to find a neat solution? Btw.: Yes I googled before writing here but I'm not happy with the solutions I found. One reason is because I want the max. flexibility. The algorithm should work on game boards in different sizes.

akiva17:07:55

When I wrote a simple Go program that checked to see if a group of stones was captured, I had a fn thatâ€™d sweep the grid and if it found a stone, it would check the neighbors (only four in the case of Go, eight in the case of Connect 4) and look to see what was around, then itâ€™d check that stoneâ€™s neighbors, and so forth. In the case of Connect 4, Iâ€™d do the same, breaking out if you find an unoccupied neighbor or no neighbors that are the same as the playerâ€™s color. Just follow the â€˜snakeâ€™ of connected pieces until you reach four.

akiva17:07:33

Actually, donâ€™t sweep the grid. Start at where the last piece was played, check the neighbors, and so forth. Since you have the grid in memory, you could actually keep track of potential winning situations and see if the newly played piece is a neighbor of one of the winning situation and check for four along that line.

donaldball18:07:54

One technique for these kinds of problems is for each cell to maintain some state about its situation vis a vis the winning condition, and when adding a piece to a cell, construct that state for it as well as updating the states of all relevant cells. That might be overkill for connect four, but it might be a fun exercise.