import random, time, pickle, turtle
from pyo import *
c = turtle.Screen()
note = {}
s = Server().boot()
s.start()
##  Begins the sound generator. Detune changes the sound a bit. It must be between
##  0 and 1. Take out detune and change to Sine or Phasor for a different sound.
sine = SuperSaw(0, detune=0.5).out()
test = False
styinp = 'N'
lnotes = []
##  Defines one octave
notes = {'a':110.0,
         'a#':116.54,
         'b':123.47,
         'c':130.81,
         'c#':138.59,
         'd':146.83,
         'd#':155.56,
         'e':164.81,
         'f':174.61,
         'f#':185.00,
         'g': 196.00,
         'g#':207.65}
note5 = {}
for x in notes.keys():
    lnotes.append(x)
lnotes = []
##  Defines other two octaves
for x in notes.keys():
    note[x.capitalize()] = notes[x] * 2
for v in notes:
    x = '-1'+v
    note[x] = notes[v] / 2
##  Generates more variables. Don't touch it.
for x in note.keys():
    notes[x] = note[x]
for x in notes.keys():
    lnotes.append(x)
for x in notes.keys():
    note5[notes[x]] = x
lnotes.sort()
for x in range(0, len(lnotes)):
    try:
        ghtlysdf = lnotes[x][2]
    except:
        lnotes[x] = lnotes[x].swapcase()
ntlst = []
for x in note5:
    ntlst.append(x)
ntlst.sort()
lnkey = ntlst[:]
cdlst = []
timlst = []
minlst = []
##  Background Color
c.bgcolor(0, 0, 0)
##r = 0
##g = 1
##b = 0
##otest = False
##  Defines keys to use
keys2prs = []
keys2prs3 = ['q', 'w', 'e', 'r', 't', 'y', 'u', 'i', 'o', 'p', '[', ']']
keys2prs2 = ['a', 's', 'd', 'f', 'g', 'h', 'j', 'k', 'l', ';', '\'', 'Return']
keys2prs1 = ['z', 'x', 'c', 'v', 'b', 'n', 'm', ',', '.', '/', 'Left', 'Right']
num1 = 0
num2 = 0
num3 = 0
for x in lnkey:
        x2 = note5[x]
        if x2.find('-1') > -1: 
            keys2prs.append(keys2prs1[num1])
            num1 += 1
        elif x2.capitalize() != x2:
            keys2prs.append(keys2prs2[num2])
            num2 += 1
        else:
            keys2prs.append(keys2prs3[num3])
            num3 += 1
##  Generates functions that play notes
for x in range(0, len(lnkey)):
    exec('def chrd'+str(x)+'():\n\tglobal sine, xkcd, s\n\ts.start()\n\tsine.setFreq(0)\n\tsine.setFreq('+str(lnkey[x]))+')\n\txkcd.clear()\n\txkcd.write(str(note5[sine.freq]), align="center", font=(\'Times New Roman\', 500, \'bold\'))'
    print(x)
##  Makes turtle that writes the letter of each note.
xkcd = turtle.Pen()
xkcd.speed(0)
xkcd.up()
xkcd.hideturtle()
xkcd.color(1, 1, 1)
xkcd.setpos(0, -250)
##  Binds notes to key press.
for x in keys2prs:
    c.listen()
    exec('c.onkey(chrd'+str(keys2prs.index(x))+', x)')
##  Makes the space bar turn off music
def non():
    global sine, t
    print ':)'
    sine.setFreq(0)
    s.stop()
c.onkey(non, 'space')
##  Constant loop so music can play.
while True:
    c.update()
    c.listen()
