summaryrefslogtreecommitdiff
path: root/chaos_game/sierpinski_carpet.py
blob: 22deee1c5e660eeab8a31fec56bc17afd4798082 (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
95
96
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_square():
    attractor_point = random.choice(vertices)
    _ = Vector2(
        (points[-1].x + 2 * attractor_point.x) / 3,
        (points[-1].y + 2 * attractor_point.y) / 3
    )
    points.append(_)
    return _


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

    for _ in range(iterations):
        new_point = new_point_square()
        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(500, 200), Vector2(800, 200),
    Vector2(200, 500), Vector2(800, 500),
    Vector2(200, 800), Vector2(500, 800), Vector2(800, 800)
]

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_square()

        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()