-
Notifications
You must be signed in to change notification settings - Fork 0
/
ui.py
81 lines (65 loc) · 2.44 KB
/
ui.py
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
from itertools import imap, islice
from operator import itemgetter
from numpy import fromiter
import pygame
from random import choice, random
from mutate import Deleter, Inserter, Repeater, Reverser
from player import Sequencer
generations = [
't t 8 >> t 9 >> | * 46 & t 8 >> & t t 13 >> & t 6 >> | ^',
# '2435687942743854 t 10 >> !! t & 127 & t 9 >> t & 100 % 127 & - 2 -',
]
# Try to strike a balance between interactivity and not clicking on
# chunk boundaries.
CHUNKSIZE = 4000
# play through the population getting ratings for the user - rating
# corresponds to how many mutated descendants to generate.
pygame.mixer.pre_init(frequency=8000, size=8, channels=1)
pygame.init()
screen = pygame.display.set_mode((640, 480))
current = 0
seq = Sequencer(generations[current], 0)
def make_sound_chunk(seq, length):
samples = fromiter(imap(itemgetter(1), islice(seq, length)), dtype='int8')
return pygame.sndarray.make_sound(samples)
def play_and_queue(channel, seq):
channel.play(make_sound_chunk(seq, CHUNKSIZE))
channel.queue(make_sound_chunk(seq, CHUNKSIZE))
channel = pygame.mixer.find_channel()
channel.set_endevent(pygame.USEREVENT)
play_and_queue(channel, seq)
def change_current(direction):
global current
current += direction
current = current % len(generations)
print 'playing:', generations[current]
seq.program = generations[current]
play_and_queue(channel, seq)
MUTATORS = [Inserter, Deleter, Repeater, Reverser]
def mutate(individual):
mutator = choice(MUTATORS)(iter(random, None))
individual = individual.split()
mutated = mutator.mutate(individual)
return mutator, ' '.join(mutated)
def mutate_current():
mutator, new_individual = mutate(generations[current])
print 'applied', mutator
print 'got:', new_individual
generations[current + 1:] = [new_individual]
change_current(1)
finished = False
while not finished:
for event in pygame.event.get():
if (event.type == pygame.QUIT
or event.type == pygame.KEYUP and event.key == pygame.K_ESCAPE):
finished = True
break
elif event.type == pygame.USEREVENT:
channel.queue(make_sound_chunk(seq, CHUNKSIZE))
elif event.type == pygame.KEYUP:
if event.key == pygame.K_f:
change_current(1)
elif event.key == pygame.K_b:
change_current(-1)
elif event.key == pygame.K_m:
mutate_current()