Search code examples
pythonarraysdrawtrigonometrytriangulation

How can I draw a circle in a data array/map in python


I have an array that will be 100 * 100, I can access any point like

map[x][y]

It kinda will look like this:

for i in map:
    for ii in i:
        print ii,
    print '\n',

output:

. . . . . . . . . . .
. . . . . . . . . . .
. . . . . . . . . . .
. . . . . . . . . . .
. . . . . . . . . . .
. . . . . . . . . . .
. . . . . . . . . . .
. . . . . . . . . . .
. . . . . . . . . . .
. . . . . . . . . . .
. . . . . . . . . . .

I want to make a circle in it like:

. . . . . # . . . . .
. . . # # . # # . . .
. . # . . . . . # . .
. # . . . . . . . # .
. # . . . . . . . # .
# . . . . . . . . . #
. # . . . . . . . # .
. # . . . . . . . # .
. . # . . . . . # . .
. . . # # . # # . . .
. . . . . # . . . . .

How can i do this?

I want to try and make a triangulation system where i will find the point that 3 circles will overlap. Is there any other way I can achieve this.

I just want to get the distance (dots from center) and the direction.


Solution

  • The basic formula for a circle is

    (x - a)**2 + (y - b)**2 = r**2
    

    Where (x, y) is a point, (a, b) is the center of the circle and r is the radius.

    width, height = 11, 11
    a, b = 5, 5
    r = 5
    EPSILON = 2.2
    
    map_ = [['.' for x in range(width)] for y in range(height)]
    
    # draw the circle
    for y in range(height):
        for x in range(width):
            # see if we're close to (x-a)**2 + (y-b)**2 == r**2
            if abs((x-a)**2 + (y-b)**2 - r**2) < EPSILON**2:
                map_[y][x] = '#'
    
    # print the map
    for line in map_:
        print ' '.join(line)
    

    This results in

    . . . # # # # # . . .
    . . # . . . . . # . .
    . # . . . . . . . # .
    # . . . . . . . . . #
    # . . . . . . . . . #
    # . . . . . . . . . #
    # . . . . . . . . . #
    # . . . . . . . . . #
    . # . . . . . . . # .
    . . # . . . . . # . .
    . . . # # # # # . . .
    

    You'll have to fiddle with the value for EPSILON with this method.

    Alternatively, iterate by angle and calculate the (x,y) coordinate as you go

    import math
    # draw the circle
    for angle in range(0, 360, 5):
        x = r * math.sin(math.radians(angle)) + a
        y = r * math.cos(math.radians(angle)) + b
        map_[int(round(y))][int(round(x))] = '#'
    

    Gives:

    . . . # # # # # . . .
    . # # . . . . . # # .
    . # . . . . . . . # .
    # . . . . . . . . # #
    # . . . . . . . . . #
    # . . . . . . . . . #
    # . . . . . . . . . #
    # . . . . . . . . . #
    . # . . . . . . . # .
    . # # . . . . . # # .
    . . . # # # # # . . .