736dd0685727939d528cdccef7788f1011fa3804
[minwii.git] / src / app / widgets / playingscreen.py
1 # -*- coding: utf-8 -*-
2 """
3 Écran de jeu MinWii :
4 bandes arc-en-ciel représentant un clavier.
5
6 $Id$
7 $URL$
8 """
9 import pygame
10 from cursors import WarpingCursor
11 from column import Column
12 import events
13 from eventutils import event_handler, EventDispatcher, EventHandlerMixin
14 import types
15 from musicxml import Tone
16
17 from config import FRAMERATE
18 from config import FIRST_HUE
19 from config import MIDI_VELOCITY_RANGE
20 from config import MIDI_PAN_RANGE
21
22 from globals import BACKGROUND_LAYER
23 from globals import CURSOR_LAYER
24 from globals import PLAYING_MODES_DICT
25
26 class _PlayingScreenBase(pygame.sprite.LayeredDirty, EventHandlerMixin) :
27
28 def __init__(self, synth, distinctNotes=[]) :
29 """
30 distinctNotes : notes disctinctes présentes dans la chanson
31 triées du plus grave au plus aigu.
32 """
33 super(_PlayingScreenBase, self).__init__()
34 self.synth = synth
35 self.distinctNotes = distinctNotes
36 self.keyboardLength = 0
37 self.keyboardRects = []
38 self.cursor = None
39 self._initRects()
40 self.columns = {}
41 self._initColumns()
42 self._running = False
43 self.draw(pygame.display.get_surface())
44 self._initCursor()
45
46 def _initRects(self) :
47 """ création des espaces réservés pour
48 afficher les colonnes.
49 """
50 #ambitus = self.distinctNotes[-1].midi - self.distinctNotes[0].midi
51 #if ambitus <= 12 :
52 # self.keyboardLength = 8
53 #else :
54 # self.keyboardLength = 11
55 self.keyboardLength = len(self.distinctNotes)
56
57 screen = pygame.display.get_surface()
58
59 # taille de la zone d'affichage utile (bordure autour)
60 self.dispWidth = dispWidth = screen.get_width()
61 self.dispHeight = dispHeight = screen.get_height()
62
63 columnWidth = int(round(float(dispWidth) / self.keyboardLength))
64
65 rects = []
66 for i in range(self.keyboardLength) :
67 upperLeftCorner = (i*columnWidth, 0)
68 rect = pygame.Rect(upperLeftCorner, (columnWidth, dispHeight))
69 rects.append(rect)
70
71 self.keyboardRects = rects
72
73 def _initColumns(self) :
74
75 hueStep = FIRST_HUE / (self.keyboardLength - 1)
76 for i, rect in enumerate(self.keyboardRects) :
77 hue = FIRST_HUE - hueStep * i
78 tone = self.distinctNotes[i]
79 c = Column(self, i, hue, rect, tone)
80 self.add(c, layer=BACKGROUND_LAYER)
81 self.columns[tone.midi] = c
82
83
84 def _initCursor(self) :
85 self.cursor = WarpingCursor(blinkMode=True)
86 self.add(self.cursor, layer=CURSOR_LAYER)
87
88 def run(self):
89 self._running = True
90 clock = pygame.time.Clock()
91 pygame.display.flip()
92 pygame.mouse.set_visible(False)
93 while self._running :
94 EventDispatcher.dispatchEvents()
95 dirty = self.draw(pygame.display.get_surface())
96 pygame.display.update(dirty)
97 clock.tick(FRAMERATE)
98
99 def stop(self) :
100 self._running = False
101 self.synth.system_reset()
102 pygame.mouse.set_visible(True)
103 self.cursor._stopBlink()
104
105 @event_handler(pygame.KEYDOWN)
106 def handleKeyDown(self, event) :
107 if event.key == pygame.K_q:
108 self.stop()
109
110 @event_handler(pygame.MOUSEBUTTONDOWN)
111 def onMouseDown(self, event) :
112 # TODO à cleaner : on vire le dernier élément
113 # parce qu'il s'agit du curseur
114 for col in reversed(self.sprites()[:-1]) :
115 if col.rect.collidepoint(*event.pos):
116 self.raiseColDown(col, event.pos)
117 break
118
119 @event_handler(pygame.MOUSEBUTTONUP)
120 def onMouseUp(self, event) :
121 for col in reversed(self.sprites()[:-1]) :
122 if col.rect.collidepoint(*event.pos) :
123 self.raiseColUp(col, event.pos)
124 break
125
126 @event_handler(pygame.MOUSEMOTION)
127 def onMouseMove(self, event) :
128 for col in reversed(self.sprites()[:-1]) :
129 if col.rect.collidepoint(*event.pos) :
130 self.raiseColOver(col, event.pos)
131 break
132
133 def raiseColDown(self, col, pos) :
134 evt = pygame.event.Event(events.COLDOWN, column=col, pos=pos)
135 pygame.event.post(evt)
136
137 def raiseColUp(self, col, pos) :
138 evt = pygame.event.Event(events.COLUP, column=col, pos=pos)
139 pygame.event.post(evt)
140
141 def raiseColOver(self, col, pos) :
142 evt = pygame.event.Event(events.COLOVER, column=col, pos=pos)
143 pygame.event.post(evt)
144
145 def getVelocity(self, pos) :
146 vel = (float(self.dispWidth) - pos[1]) / self.dispWidth
147 vel = int(vel * (MIDI_VELOCITY_RANGE[1] - MIDI_VELOCITY_RANGE[0])) + MIDI_VELOCITY_RANGE[0]
148 return vel
149
150 def getPan(self, index) :
151 pan = float(index) / (self.keyboardLength -1)
152 pan = int(pan * (MIDI_PAN_RANGE[1] - MIDI_PAN_RANGE[0])) + MIDI_PAN_RANGE[0]
153 return pan
154
155
156 class PlayingScreen(_PlayingScreenBase) :
157 "fenêtre de jeu pour improvisation"
158
159 scale = [55, 57, 59, 60, 62, 64, 65, 67, 69, 71, 72]
160
161 def __init__(self, synth) :
162 distinctNotes = []
163 for midi in self.scale :
164 tone = Tone(midi)
165 distinctNotes.append(tone)
166
167 super(PlayingScreen, self).__init__(synth, distinctNotes)
168
169 @event_handler(events.NOTEON)
170 def noteon(self, evt) :
171 tone = evt.tone
172 self.synth.noteon(0, tone.midi, 96)
173
174 @event_handler(events.NOTEOFF)
175 def noteoff(self, evt) :
176 tone = evt.tone
177 self.synth.noteoff(0, tone.midi)
178
179
180 class SongPlayingScreen(_PlayingScreenBase) :
181
182 def __init__(self, synth, song, mode=PLAYING_MODES_DICT['EASY']) :
183 super(SongPlayingScreen, self).__init__(synth, song.distinctNotes)
184 self.song = song
185 self.quarterNoteDuration = song.quarterNoteDuration
186 self.currentColumn = None
187 self.noteIterator = self.song.iterNotes()
188 self.displayNext()
189 if mode == PLAYING_MODES_DICT['NORMAL'] :
190 EventDispatcher.addEventListener(events.COLDOWN, self.handleColumnDown)
191 EventDispatcher.addEventListener(events.COLUP, self.handleColumnUp)
192 elif mode == PLAYING_MODES_DICT['EASY'] :
193 EventDispatcher.addEventListener(events.COLOVER, self.handleColumnOver)
194
195
196 def displayNext(self, event=None) :
197 if self.currentColumn:
198 self.currentColumn.update(False)
199 note, verseIndex = self.noteIterator.next()
200 syllabus = note.lyrics[verseIndex].syllabus()
201 column = self.columns[note.midi]
202 column.update(True, syllabus)
203 self.currentColumn = column
204 self.currentNote = note
205 self.currentNotePlayed = False
206
207 def handleColumnDown(self, event) :
208 col = event.column
209 if col.state:
210 pan = self.getPan(col.index)
211 self.synth.cc(0, 10, pan)
212 vel = self.getVelocity(event.pos)
213 self.synth.noteon(0, col.tone.midi, vel)
214 self.currentNotePlayed = True
215
216 def handleColumnUp(self, event) :
217 if self.currentNotePlayed :
218 self.synth.noteoff(0, self.currentColumn.tone.midi)
219 self.displayNext()
220
221 def handleColumnOver(self, event) :
222 col = event.column
223 if col.state and not self.currentNotePlayed :
224 pan = self.getPan(col.index)
225 self.synth.cc(0, 10, pan)
226 vel = self.getVelocity(event.pos)
227 self.synth.noteon(0, col.tone.midi, vel)
228 SongPlayingScreen.setNoteTimeout(
229 int(self.currentNote.duration * \
230 self.quarterNoteDuration)
231 )
232 self.currentNotePlayed = True
233
234 @event_handler(events.NOTEEND)
235 def clearTimeOutAndDisplayNext(self, evt) :
236 pygame.time.set_timer(evt.type, 0)
237 self.synth.noteoff(0, self.currentNote.midi)
238 self.displayNext()
239
240 @staticmethod
241 def setNoteTimeout(delay) :
242 pygame.time.set_timer(events.NOTEEND, delay)
243
244 def stop(self) :
245 pygame.time.set_timer(events.NOTEEND, 0)
246 super(SongPlayingScreen, self).stop()
247