summaryrefslogtreecommitdiff
path: root/chaos_game/sierpinski_triangle.py
blob: 4509fac1af414b781e5cc6a6301ee8a2b271a8ed (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
from pygame.locals import *
from pygame import Vector2, Surface
import pygame

import random
from sys import argv


def convert2int(t):
    return list(map(int, t))


def new_point_triangle():
    attractor_point = random.choice(vertices)
    path = attractor_point - points[-1]
    _ = points[-1] + path.normalize() * path.length() / 2
    points.append(_)
    return _


def generate_surface(iterations):
    surf = Surface((WIDTH, HEIGHT))

    for _ in range(iterations):
        new_point = new_point_triangle()
        surf.set_at(convert2int(new_point), WHITE)

    return surf


pygame.init()

WIDTH, HEIGHT = SIZE = 1000, 1000

screen = pygame.display.set_mode(SIZE)

BLACK = Color('black')
WHITE = Color('white')
GREEN = Color('green')

font = pygame.font.SysFont('courier', 30)

vertices = [
    Vector2(200, 200),
    Vector2(505, 505),
    Vector2(30, 400)
]


points = [Vector2(201, 200)]

iterations = 0
static = False
surface = None

try:
    iterations = int(argv[1])
    static = True
    surface = generate_surface(iterations)

except (ValueError, IndexError):
    pass


while True:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            quit()

    if static:
        screen.fill(BLACK)

        screen.blit(surface, (0, 0))

        for point in vertices:
            pygame.draw.circle(screen, GREEN, convert2int(point), 3)

    else:
        for point in points:
            screen.set_at(convert2int(point), WHITE)

        for point in vertices:
            pygame.draw.circle(screen, GREEN, convert2int(point), 3)

        new_point_triangle()

        iterations += 1

    text = font.render('interation: {}'.format(iterations), 4, WHITE)
    screen.fill(BLACK, text.get_rect(x=10, y=10))
    screen.blit(text, text.get_rect(x=10, y=10))

    pygame.display.flip()