Search code examples
pythoncanvastkintergraphic

Detect whether a tkinter pattern is repeating itself


I have a program (more specifically a spirograph) that draws a pattern. After a certain amount of time, it will, inevitably begin to repeat itself. I need a way to detect when that happens.

There are several approaches to this.

  1. Detect whether where the line is plotting is on top of a black pixel. Stop after this repeats a few times
  2. Somehow pre-calculate the number of iterations it will take to complete a pattern
  3. Test for new lines intersecting old ones
  4. Store all the points plotted, then stop when the new points generated are the same as older points.

Which method is the best?


Solution

  • Approach one is out, as research will turn up, tkinter canvases have no direct way to determine the color of a given pixel on them. Approach 2 would be incredibly complicated, and beyond my ability. Approach 3 is impractical as normal patterns regularly self-intersect. But approach 4 worked for me. Here's how I did it:

    #Detection of whether pattern is repeating itself
            if point2 not in previousPositions:
                previousPositions.append(point2)
                inarow = 0
            else:
                inarow += 1
    
            if inarow > 5:
                print "Pattern is detected to be repeating itself"
                run = 0
    

    This was in a loop where setting run to zero stops the loop. This successfully stops graphing the pattern as soon as 5 new points match previously drawn points

    Possible flaws

    Some patterns, might, eventually have points that match other points before the graph is over. It is improbable that this will happen more than 5 times. For this to happen, the grapher would have to be moving in a different direction across the same points in a different order. This could be solved by accounting the order of the points occurring. However, it is extremely improbable that this would occur repeatedly, and I was unable to find a pattern that would cause this issue.