user1871052
user1871052

Reputation: 11

How do I count turtle above, below, and diagonal using netlogo?

I am working on creating a connect four game using netlogo for an assignment. I am having trouble keeping track of how many reds or blues are in a row. (determining the winner)

This is pretty much what I want it to do:

if this circle is red then add one to successive circles else set successive reds back down to 0 if successive reds is 4 (or greater) show you win buddy/gal else set successive-reds 0

This is what I have tried and does not work.

ifelse any? patches with [ (pcolor = red) and (pxcor 1)]
    [set successive-reds = successive-reds + 1]
    [set successive-reds 0]
    if successive-reds = 4
       [show "you won"]

I have searched stackoverflow for help and found ways to do this but not using the netlogo program. I have also tried using neighbors and turtles-on and can not find a way to ask turtles to ask their neighboring turtle if their color is the same as the turtle asking.

any help would be greatly appreciated. Thanks

Upvotes: 1

Views: 573

Answers (1)

Nicolas Payette
Nicolas Payette

Reputation: 14972

Argh... I know that, since this is for an assignment, I should just gently guide you into figuring out for yourself how to do that, but this is such a cool little problem, for which NetLogo is so well suited, that I can't resist posting a solution:

to-report wins? ; patch procedure
  report member? true map wins-in-direction? n-values 8 [ ? * 45 ]
end

to-report wins-in-direction? [ h ] ; patch procedure
  report not member? false map [
    ([ pcolor ] of patch-at-heading-and-distance h ?) = red
  ] (n-values 4 [ ? ])
end

Given the above code, a statement like:

any? patches with [wins?]

...will tell you if any patch is the extremity of a winning sequence.

Now you should not use that code unless you understand it. The use of map and n-values probably makes it a little challenging if you are not used to that style, but feel free to ask questions in the comments, and I'll update my answer to address them.

Bonus points: This only checks for a red win. Generalize this so it can check for another color, without naively duplicating the code.

Upvotes: 1

Related Questions