grower.py 2.18 KB
Newer Older
1
from math import floor
Michael Keller's avatar
zoom    
Michael Keller committed
2
3
4
5
6
7
8
import random

def print_field(field):
    for row in field:
        for p in row:
            print(p, end="\t")
        print("")
9

Michael Keller's avatar
Michael Keller committed
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
# Grow method A 
def growA(field):
    newField = []
    x = len(field)
    y = len(field[0])
    for i in range(x):
        newRow = []
        for j in range(int(y/2)):
            newRow.append(field[i][2 * j])
            newRow.append(field[i][2 * j + 1])
            newRow.append(field[i][2 * j])
            newRow.append(field[i][2 * j + 1])
        newField.append(newRow)
    return newField

Michael Keller's avatar
Michael Keller committed
25
26
27
28
29
30
31
32
33
34
35
36
37
# Grow method A (alt def)
def growA_alt(field, f):
    x = len(field)
    y = len(field[0])
    newField = [[-1 for _ in range(f * (y-1)+1)] for _ in range(f * (x-1)+1)]
    for i in range(f * (x-1)+1):
        for j in range(f * (y-1)+1):
            a = int( floor(i / f) + ((i + floor(i / f)) % 2))
            b = int( floor(j / f) + ((j + floor(j / f)) % 2))

            newField[i][j] = field[a][b]
    return newField

38
def growB(field, fx, fy):
Michael Keller's avatar
Michael Keller committed
39
    newField = []
40
41
42
    y = len(field)
    x = len(field[0])
    for j in range((y-1) * fy + 1):
Michael Keller's avatar
Michael Keller committed
43
        newRow = []
44
45
46
47
        a = floor(j / fy) + (j + floor(j / fy)) % 2
        for i in range((x-1) * fx + 1):
            b = floor(i / fx) + (i + floor(i / fx)) % 2
            newRow.append(field[a][b])
Michael Keller's avatar
Michael Keller committed
48
        newField.append(newRow)
Michael Keller's avatar
zoom    
Michael Keller committed
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
    return newField

# makes a solution fit exact problem constraints
# Assumes field is smaller than wanted
def fix(field, dist, xGoal, yGoal):
    x = len(field)
    y = len(field[0])
    dx = xGoal - x
    dy = yGoal - y

    # increase the field size
    for i in range(dx):
        field.append([-1] * y)
    for i in range(yGoal):
        field[i] += [-1] * dy

    # see what has already been planted
    for i in range(x):
        for j in range(y):
            dist[field[i][j]] -= 1

    # assign fields randomly
    coordinates = [(j, i) for i in range(xGoal) for j in range(yGoal)]
    choices = list(filter(lambda c: field[c[0]][c[1]] == -1, coordinates))

    # plant randomly
    random.shuffle(choices)
    for index, d in enumerate(dist):
        for _ in range(d):
            pixel = choices.pop()
            field[pixel[0]][pixel[1]] = index
    
    return field