shh_algo_PY

Basic Piano

Mar 25th, 2022 (edited)
46
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.23 KB | None | 0 0
  1. # import pygame library - which allows sounds
  2.  
  3. import pygame
  4. import play
  5.  
  6. # Backdrop colour
  7. play.set_backdrop('light blue')
  8.  
  9. introduce1 = play.new_text(words='Piano for fun!', x=0, y=200)
  10.  
  11. introduce2 = play.new_text(words='Create your melody by pressing the keys', x=0, y=150)
  12.  
  13. # BUTTONS
  14. key_play_melody = play.new_box(color='light green', border_color='black', border_width=1, x=-100, y=-170, width=160, height=50)
  15.  
  16. kpm = play.new_text(words='play melody', x=-100, y=-170, font_size=20)
  17.  
  18. key_clear_melody = play.new_box(color='light yellow', border_color='black', border_width=1, x=100, y=-170, width=160, height=50)
  19.  
  20. kcm = play.new_text(words='clear melody', x=100, y=-170, font_size=20)
  21. sound_clear_melody = pygame.mixer.Sound('clear_melody.wav') # DELETE THIS IF YOU DON'T HAVE THE FILE
  22.  
  23. # Activate the for loop + lists
  24.  
  25. keys = []
  26. sounds = []
  27.  
  28. for i in range(8):
  29.     key_x = -180 + i * 50
  30.     key = play.new_box(color='white', border_color='black', border_width=3, x=key_x, y=0, width=40, height=100)
  31.     sound = pygame.mixer.Sound(str(i+1)+'.ogg') # Adds the sound file: 1.ogg, 2.ogg, ...
  32.     keys.append(key)     # Adds keys to the keys list
  33.     sounds.append(sound) # Adds sounds to the sound list
  34.  
  35. melody = []
  36.  
  37. # This is the intro jingle that plays at the start of the program ✨
  38.  
  39. @play.when_program_starts
  40. def start():
  41.     pygame.mixer_music.load('hello-1.mp3')
  42.     pygame.mixer_music.play()
  43.  
  44. # This is clearing the melody - delete all
  45.        
  46. @key_clear_melody.when_clicked
  47. def clear():
  48.     melody.clear()
  49.     sound_clear_melody.play() # DELETE IF YOU DON'T HAVE IT
  50.  
  51. # Processing clicks - when button is clicked, what happens?
  52.  
  53. @key_play_melody.when_clicked
  54. async def play_m():
  55.     for i in range(len(melody)):
  56.         await play.timer(seconds=0.5)
  57.         sounds[melody[i]].play()
  58.  
  59. # Recording sounds - remembers the melody by adding it to the list
  60.  
  61. @play.repeat_forever
  62. async def play_piano():
  63.     for i in range(len(keys)):
  64.         if keys[i].is_clicked:
  65.             keys[i].color = 'light grey'    # Changes to this
  66.             sounds[i].play()
  67.             await play.timer(seconds=0.3)
  68.             keys[i].color = 'white'         # Go back to starting colour
  69.             melody.append(i)
  70.  
  71. play.start_program()
Add Comment
Please, Sign In to add comment