3e1a6d78d278d0c0bdf60b892bffad0d1646c167
[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 BORDER
19 from config import FIRST_HUE
20 from config import DEFAULT_MIDI_VELOCITY
21
22 from globals import BACKGROUND_LAYER
23 from globals import CURSOR_LAYER
24 from globals import PLAYING_MODES
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 dispWidth = screen.get_width() - 2 * BORDER
61 dispHeight = screen.get_height() - 2 * BORDER
62
63 columnWidth = int(round(float(dispWidth) / self.keyboardLength))
64
65 rects = []
66 for i in range(self.keyboardLength) :
67 upperLeftCorner = (i*columnWidth + BORDER, BORDER)
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, 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 pygame.mouse.set_visible(True)
100 self.cursor._stopBlink()
101
102 @event_handler(pygame.KEYDOWN)
103 def handleKeyDown(self, event) :
104 if event.key == pygame.K_q:
105 self._running = False
106
107 @event_handler(pygame.MOUSEBUTTONDOWN)
108 def onMouseDown(self, event) :
109 # TODO à cleaner : on vire le dernier élément
110 # parce qu'il s'agit du curseur
111 for col in reversed(self.sprites()[:-1]) :
112 if col.rect.collidepoint(*event.pos):
113 self.raiseColDown(col)
114 break
115
116 @event_handler(pygame.MOUSEBUTTONUP)
117 def onMouseUp(self, event) :
118 for col in reversed(self.sprites()[:-1]) :
119 if col.rect.collidepoint(*event.pos) :
120 self.raiseColUp(col)
121 break
122
123 @event_handler(pygame.MOUSEMOTION)
124 def onMouseMove(self, event) :
125 for col in reversed(self.sprites()[:-1]) :
126 if col.rect.collidepoint(*event.pos) :
127 self.raiseColOver(col)
128 break
129
130 def raiseColDown(self, col) :
131 evt = pygame.event.Event(events.COLDOWN, column=col)
132 pygame.event.post(evt)
133
134 def raiseColUp(self, col) :
135 evt = pygame.event.Event(events.COLUP, column=col)
136 pygame.event.post(evt)
137
138 def raiseColOver(self, col) :
139 evt = pygame.event.Event(events.COLOVER, column=col)
140 pygame.event.post(evt)
141
142
143 class PlayingScreen(_PlayingScreenBase) :
144 "fenêtre de jeu pour improvisation"
145
146 scale = [55, 57, 59, 60, 62, 64, 65, 67, 69, 71, 72]
147
148 def __init__(self, synth) :
149 distinctNotes = []
150 for midi in self.scale :
151 tone = Tone(midi)
152 distinctNotes.append(tone)
153
154 super(PlayingScreen, self).__init__(synth, distinctNotes)
155
156 @event_handler(events.NOTEON)
157 def noteon(self, evt) :
158 tone = evt.tone
159 self.synth.noteon(0, tone.midi, DEFAULT_MIDI_VELOCITY)
160
161 @event_handler(events.NOTEOFF)
162 def noteoff(self, evt) :
163 tone = evt.tone
164 self.synth.noteoff(0, tone.midi)
165
166
167 class SongPlayingScreen(_PlayingScreenBase) :
168
169 def __init__(self, synth, song, mode=PLAYING_MODES['EASY']) :
170 super(SongPlayingScreen, self).__init__(synth, song.distinctNotes)
171 self.song = song
172 self.currentColumn = None
173 self.noteIterator = self.song.iterNotes()
174 self.displayNext()
175 if mode == PLAYING_MODES['NORMAL'] :
176 EventDispatcher.addEventListener(events.COLDOWN, self.handleColumnDown)
177 EventDispatcher.addEventListener(events.COLUP, self.handleColumnUp)
178 elif mode == PLAYING_MODES['EASY'] :
179 EventDispatcher.addEventListener(events.COLOVER, self.handleColumnOver)
180
181
182 def displayNext(self, event=None) :
183 if self.currentColumn:
184 self.currentColumn.update(False)
185 note, verseIndex = self.noteIterator.next()
186 syllabus = note.lyrics[verseIndex].syllabus(encoding="iso-8859-1")
187 column = self.columns[note.midi]
188 column.update(True, syllabus)
189 self.currentColumn = column
190 self.currentNote = note
191 self.currentNotePlayed = False
192
193 def handleColumnDown(self, event) :
194 col = event.column
195 if col.state:
196 self.synth.noteon(0, col.tone.midi, DEFAULT_MIDI_VELOCITY)
197 self.currentNotePlayed = True
198
199 def handleColumnUp(self, event) :
200 if self.currentNotePlayed :
201 self.synth.noteoff(0, self.currentColumn.tone.midi)
202 self.displayNext()
203
204 def handleColumnOver(self, event) :
205 col = event.column
206 if col.state and not self.currentNotePlayed :
207 self.synth.noteon(0, col.tone.midi, DEFAULT_MIDI_VELOCITY)
208 SongPlayingScreen.setNoteTimeout(int(self.currentNote.duration * 600))
209 self.currentNotePlayed = True
210
211 @event_handler(events.NOTEEND)
212 def clearTimeOutAndDisplayNext(self, evt) :
213 pygame.time.set_timer(evt.type, 0)
214 self.displayNext()
215
216 @staticmethod
217 def setNoteTimeout(delay) :
218 print 'duration', delay
219 pygame.time.set_timer(events.NOTEEND, delay)
220