Fork me on GitHub

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.


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.


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.


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.