This commit is contained in:
wittmannzl103469 committed 2026-11-05 15:08:42 +01:00
1 parent de41a02749
commit 9af09cebd3
764 files changed
+54218 -78859

No files matched your search

@@ -1,5 +1,5 @@
#!/usr/bin/env python
"""pygame.examples.midi
""" pygame.examples.midi
midi input, and a separate example of midi output.
@@ -10,10 +10,12 @@ python -m pygame.examples.midi --input
python -m pygame.examples.midi --input
"""
import os
from dataclasses import dataclass
import sys
import os
from typing import Any, Dict, List, Literal, Optional, Set, Tuple, Union
import pygame
import pygame as pg
import pygame.midi
# black and white piano keys use b/w color values directly
@@ -44,7 +46,7 @@ def _print_device_info():
def input_main(device_id=None):
pygame.init()
pg.init()
pygame.midi.init()
@@ -58,15 +60,15 @@ def input_main(device_id=None):
print(f"using input_id :{input_id}:")
i = pygame.midi.Input(input_id)
pygame.display.set_mode((1, 1))
pg.display.set_mode((1, 1))
going = True
while going:
events = pygame.event.get()
for e in events:
if e.type in [pygame.QUIT]:
if e.type in [pg.QUIT]:
going = False
if e.type in [pygame.KEYDOWN]:
if e.type in [pg.KEYDOWN]:
going = False
if e.type in [pygame.midi.MIDIIN]:
print(e)
@@ -135,35 +137,35 @@ def output_main(device_id=None):
key_mapping = make_key_mapping(
[
pygame.K_TAB,
pygame.K_1,
pygame.K_q,
pygame.K_2,
pygame.K_w,
pygame.K_3,
pygame.K_e,
pygame.K_r,
pygame.K_5,
pygame.K_t,
pygame.K_6,
pygame.K_y,
pygame.K_u,
pygame.K_8,
pygame.K_i,
pygame.K_9,
pygame.K_o,
pygame.K_0,
pygame.K_p,
pygame.K_LEFTBRACKET,
pygame.K_EQUALS,
pygame.K_RIGHTBRACKET,
pygame.K_BACKSPACE,
pygame.K_BACKSLASH,
pg.K_TAB,
pg.K_1,
pg.K_q,
pg.K_2,
pg.K_w,
pg.K_3,
pg.K_e,
pg.K_r,
pg.K_5,
pg.K_t,
pg.K_6,
pg.K_y,
pg.K_u,
pg.K_8,
pg.K_i,
pg.K_9,
pg.K_o,
pg.K_0,
pg.K_p,
pg.K_LEFTBRACKET,
pg.K_EQUALS,
pg.K_RIGHTBRACKET,
pg.K_BACKSPACE,
pg.K_BACKSLASH,
],
start_note,
)
pygame.init()
pg.init()
pygame.midi.init()
_print_device_info()
@@ -180,25 +182,25 @@ def output_main(device_id=None):
midi_out.set_instrument(instrument)
keyboard = Keyboard(start_note, n_notes)
screen = pygame.display.set_mode(keyboard.rect.size)
screen = pg.display.set_mode(keyboard.rect.size)
screen.fill(BACKGROUNDCOLOR)
pygame.display.flip()
pg.display.flip()
background = pygame.Surface(screen.get_size())
background = pg.Surface(screen.get_size())
background.fill(BACKGROUNDCOLOR)
dirty_rects = []
keyboard.draw(screen, background, dirty_rects)
pygame.display.update(dirty_rects)
pg.display.update(dirty_rects)
regions = pygame.Surface(screen.get_size()) # initial color (0,0,0)
regions = pg.Surface(screen.get_size()) # initial color (0,0,0)
keyboard.map_regions(regions)
pygame.event.set_blocked(pygame.MOUSEMOTION)
pg.event.set_blocked(pg.MOUSEMOTION)
mouse_note = 0
on_notes = set()
while True:
e = pygame.event.wait()
if e.type == pygame.MOUSEBUTTONDOWN:
e = pg.event.wait()
if e.type == pg.MOUSEBUTTONDOWN:
mouse_note, velocity, __, __ = regions.get_at(e.pos)
if mouse_note and mouse_note not in on_notes:
keyboard.key_down(mouse_note)
@@ -206,16 +208,16 @@ def output_main(device_id=None):
on_notes.add(mouse_note)
else:
mouse_note = 0
elif e.type == pygame.MOUSEBUTTONUP:
elif e.type == pg.MOUSEBUTTONUP:
if mouse_note:
midi_out.note_off(mouse_note)
keyboard.key_up(mouse_note)
on_notes.remove(mouse_note)
mouse_note = 0
elif e.type == pygame.QUIT:
elif e.type == pg.QUIT:
break
elif e.type == pygame.KEYDOWN:
if e.key == pygame.K_ESCAPE:
elif e.type == pg.KEYDOWN:
if e.key == pg.K_ESCAPE:
break
try:
note, velocity = key_mapping[e.key]
@@ -226,7 +228,7 @@ def output_main(device_id=None):
keyboard.key_down(note)
midi_out.note_on(note, velocity)
on_notes.add(note)
elif e.type == pygame.KEYUP:
elif e.type == pg.KEYUP:
try:
note, __ = key_mapping[e.key]
except KeyError:
@@ -239,7 +241,7 @@ def output_main(device_id=None):
dirty_rects = []
keyboard.draw(screen, background, dirty_rects)
pygame.display.update(dirty_rects)
pg.display.update(dirty_rects)
finally:
del midi_out
pygame.midi.quit()
@@ -254,7 +256,7 @@ def make_key_mapping(keys, start_note):
class NullKey:
"""A null key that ignores events passed to it by other keys
"""A dummy key that ignores events passed to it by other keys
A NullKey instance is the left key instance used by default
for the left most keyboard key.
@@ -277,7 +279,169 @@ class NullKey:
null_key = NullKey()
def key_class(updates, image_strip, image_rects, is_white_key=True):
@dataclass
class KeyData:
"""Used for passing in data to subclasses of the Key class."""
is_white_key: bool
c_width: int
c_height: int
c_down_state_initial: int
c_down_state_rect_initial: pg.Rect
c_notify_down_method: str
c_notify_up_method: str
c_updates: Set[Any]
c_event_down: Dict[int, Tuple[int, pg.Rect]]
c_event_up: Dict[int, Tuple[int, pg.Rect]]
c_image_strip: pg.Surface
c_event_right_white_down: Dict[int, Tuple[int, Union[pg.Rect, None]]]
c_event_right_white_up: Dict[int, Tuple[int, Union[pg.Rect, None]]]
c_event_right_black_down: Dict[int, Tuple[int, Union[pg.Rect, None]]]
c_event_right_black_up: Dict[int, Tuple[int, Union[pg.Rect, None]]]
class Key:
"""A key widget, maintains key state and draws the key's image
Constructor arguments:
ident - A unique key identifier. Any immutable type suitable as a key.
posn - The location of the key on the display surface.
key_left - Optional, the adjacent white key to the left. Changes in
up and down state are propagated to that key.
A key has an associated position and state. Related to state is the
image drawn. State changes are managed with method calls, one method
per event type. The up and down event methods are public. Other
internal methods are for passing on state changes to the key_left
key instance.
"""
key_data: KeyData
def __init__(self, ident, posn, key_left=None):
"""Return a new Key instance
The initial state is up, with all adjacent keys to the right also
up.
"""
if key_left is None:
key_left = null_key
rect = pg.Rect(posn[0], posn[1], self.key_data.c_width, self.key_data.c_height)
self.rect = rect
self._state = self.key_data.c_down_state_initial
self._source_rect = self.key_data.c_down_state_rect_initial
self._ident = ident
self._hash = hash(ident)
self._notify_down = getattr(key_left, self.key_data.c_notify_down_method)
self._notify_up = getattr(key_left, self.key_data.c_notify_up_method)
self._key_left = key_left
self._background_rect = pg.Rect(
rect.left, rect.bottom - 10, self.key_data.c_width, 10
)
self.key_data.c_updates.add(self)
self.is_white = self.key_data.is_white_key
def down(self):
"""Signal that this key has been depressed (is down)"""
self._state, source_rect = self.key_data.c_event_down[self._state]
if source_rect is not None:
self._source_rect = source_rect
self.key_data.c_updates.add(self)
self._notify_down()
def up(self):
"""Signal that this key has been released (is up)"""
self._state, source_rect = self.key_data.c_event_up[self._state]
if source_rect is not None:
self._source_rect = source_rect
self.key_data.c_updates.add(self)
self._notify_up()
def _right_white_down(self):
"""Signal that the adjacent white key has been depressed
This method is for internal propagation of events between
key instances.
"""
self._state, source_rect = self.key_data.c_event_right_white_down[self._state]
if source_rect is not None:
self._source_rect = source_rect
self.key_data.c_updates.add(self)
def _right_white_up(self):
"""Signal that the adjacent white key has been released
This method is for internal propagation of events between
key instances.
"""
self._state, source_rect = self.key_data.c_event_right_white_up[self._state]
if source_rect is not None:
self._source_rect = source_rect
self.key_data.c_updates.add(self)
def _right_black_down(self):
"""Signal that the adjacent black key has been depressed
This method is for internal propagation of events between
key instances.
"""
self._state, source_rect = self.key_data.c_event_right_black_down[self._state]
if source_rect is not None:
self._source_rect = source_rect
self.key_data.c_updates.add(self)
def _right_black_up(self):
"""Signal that the adjacent black key has been released
This method is for internal propagation of events between
key instances.
"""
self._state, source_rect = self.key_data.c_event_right_black_up[self._state]
if source_rect is not None:
self._source_rect = source_rect
self.key_data.c_updates.add(self)
def __eq__(self, other):
"""True if same identifiers"""
return self._ident == other._ident
def __hash__(self):
"""Return the immutable hash value"""
return self._hash
def __str__(self):
"""Return the key's identifier and position as a string"""
return "<Key %s at (%d, %d)>" % (self._ident, self.rect.top, self.rect.left)
def draw(self, surf, background, dirty_rects):
"""Redraw the key on the surface surf
The background is redrawn. The altered region is added to the
dirty_rects list.
"""
surf.blit(background, self._background_rect, self._background_rect)
surf.blit(self.key_data.c_image_strip, self.rect, self._source_rect)
dirty_rects.append(self.rect)
def key_class(updates, image_strip, image_rects: List[pg.Rect], is_white_key=True):
"""Return a keyboard key widget class
Arguments:
@@ -362,9 +526,13 @@ def key_class(updates, image_strip, image_rects, is_white_key=True):
# along with corresponding image, for the related event. If no redrawing
# is required for the state change then the image rect is simply None.
#
c_event_down = {down_state_none: (down_state_self, image_rects[1])}
c_event_up = {down_state_self: (down_state_none, image_rects[0])}
c_event_right_white_down = {
c_event_down: Dict[int, Tuple[int, pygame.Rect]] = {
down_state_none: (down_state_self, image_rects[1])
}
c_event_up: Dict[int, Tuple[int, pygame.Rect]] = {
down_state_self: (down_state_none, image_rects[0])
}
c_event_right_white_down: Dict[int, Tuple[int, Union[pygame.Rect, None]]] = {
down_state_none: (down_state_none, None),
down_state_self: (down_state_self, None),
}
@@ -424,153 +592,32 @@ def key_class(updates, image_strip, image_rects, is_white_key=True):
)
c_event_right_black_up[down_state_all] = (down_state_self_white, image_rects[2])
class Key:
"""A key widget, maintains key state and draws the key's image
class OurKey(Key):
key_data = KeyData(
is_white_key,
c_width,
c_height,
c_down_state_initial,
c_down_state_rect_initial,
c_notify_down_method,
c_notify_up_method,
c_updates,
c_event_down,
c_event_up,
c_image_strip,
c_event_right_white_down,
c_event_right_white_up,
c_event_right_black_down,
c_event_right_black_up,
)
Constructor arguments:
ident - A unique key identifier. Any immutable type suitable as a key.
posn - The location of the key on the display surface.
key_left - Optional, the adjacent white key to the left. Changes in
up and down state are propagated to that key.
A key has an associated position and state. Related to state is the
image drawn. State changes are managed with method calls, one method
per event type. The up and down event methods are public. Other
internal methods are for passing on state changes to the key_left
key instance.
"""
is_white = is_white_key
def __init__(self, ident, posn, key_left=None):
"""Return a new Key instance
The initial state is up, with all adjacent keys to the right also
up.
"""
if key_left is None:
key_left = null_key
rect = pygame.Rect(posn[0], posn[1], c_width, c_height)
self.rect = rect
self._state = c_down_state_initial
self._source_rect = c_down_state_rect_initial
self._ident = ident
self._hash = hash(ident)
self._notify_down = getattr(key_left, c_notify_down_method)
self._notify_up = getattr(key_left, c_notify_up_method)
self._key_left = key_left
self._background_rect = pygame.Rect(
rect.left, rect.bottom - 10, c_width, 10
)
c_updates.add(self)
def down(self):
"""Signal that this key has been depressed (is down)"""
self._state, source_rect = c_event_down[self._state]
if source_rect is not None:
self._source_rect = source_rect
c_updates.add(self)
self._notify_down()
def up(self):
"""Signal that this key has been released (is up)"""
self._state, source_rect = c_event_up[self._state]
if source_rect is not None:
self._source_rect = source_rect
c_updates.add(self)
self._notify_up()
def _right_white_down(self):
"""Signal that the adjacent white key has been depressed
This method is for internal propagation of events between
key instances.
"""
self._state, source_rect = c_event_right_white_down[self._state]
if source_rect is not None:
self._source_rect = source_rect
c_updates.add(self)
def _right_white_up(self):
"""Signal that the adjacent white key has been released
This method is for internal propagation of events between
key instances.
"""
self._state, source_rect = c_event_right_white_up[self._state]
if source_rect is not None:
self._source_rect = source_rect
c_updates.add(self)
def _right_black_down(self):
"""Signal that the adjacent black key has been depressed
This method is for internal propagation of events between
key instances.
"""
self._state, source_rect = c_event_right_black_down[self._state]
if source_rect is not None:
self._source_rect = source_rect
c_updates.add(self)
def _right_black_up(self):
"""Signal that the adjacent black key has been released
This method is for internal propagation of events between
key instances.
"""
self._state, source_rect = c_event_right_black_up[self._state]
if source_rect is not None:
self._source_rect = source_rect
c_updates.add(self)
def __eq__(self, other):
"""True if same identifiers"""
return self._ident == other._ident
def __hash__(self):
"""Return the immutable hash value"""
return self._hash
def __str__(self):
"""Return the key's identifier and position as a string"""
return "<Key %s at (%d, %d)>" % (self._ident, self.rect.top, self.rect.left)
def draw(self, surf, background, dirty_rects):
"""Redraw the key on the surface surf
The background is redrawn. The altered region is added to the
dirty_rects list.
"""
surf.blit(background, self._background_rect, self._background_rect)
surf.blit(c_image_strip, self.rect, self._source_rect)
dirty_rects.append(self.rect)
return Key
return OurKey
def key_images():
def key_images() -> Tuple[pg.Surface, Dict[str, pg.Rect]]:
"""Return a keyboard keys image strip and a mapping of image locations
The return tuple is a surface and a dictionary of rects mapped to key
type.
The return tuple is a pygame.Surface and a dictionary keyed by key name and valued by a pygame.Rect.
This function encapsulates the constants relevant to the keyboard image
file. There are five key types. One is the black key. The other four
@@ -583,12 +630,12 @@ def key_images():
"""
my_dir = os.path.split(os.path.abspath(__file__))[0]
strip_file = os.path.join(my_dir, "data", "midikeys.webp")
strip_file = os.path.join(my_dir, "data", "midikeys.png")
white_key_width = 42
white_key_height = 160
black_key_width = 22
black_key_height = 94
strip = pygame.image.load(strip_file)
strip = pg.image.load(strip_file)
names = [
"black none",
"black self",
@@ -613,11 +660,11 @@ def key_images():
]
rects = {}
for i in range(2):
rects[names[i]] = pygame.Rect(
rects[names[i]] = pg.Rect(
i * white_key_width, 0, black_key_width, black_key_height
)
for i in range(2, len(names)):
rects[names[i]] = pygame.Rect(
rects[names[i]] = pg.Rect(
i * white_key_width, 0, white_key_width, white_key_height
)
return strip, rects
@@ -641,7 +688,7 @@ class Keyboard:
white_key_width, white_key_height = _rects["white none"].size
black_key_width, black_key_height = _rects["black none"].size
_updates = set()
_updates: Set[Any] = set()
# There are five key classes, representing key shape:
# black key (BlackKey), plain white key (WhiteKey), white key to the left
@@ -690,14 +737,14 @@ class Keyboard:
],
)
def __init__(self, start_note, n_notes):
def __init__(self, start_note: int, n_notes: int):
"""Return a new Keyboard instance with n_note keys"""
self._start_note = start_note
self._end_note = start_note + n_notes - 1
self._add_keys()
def _add_keys(self):
def _add_keys(self) -> None:
"""Populate the keyboard with key instances
Set the _keys and rect attributes.
@@ -709,7 +756,7 @@ class Keyboard:
# note positions should never be accessed, so are set None to ensure
# the bug is quickly detected.
#
key_map = [None] * 128
key_map: list[Key | Literal[None]] = [None] * 128
start_note = self._start_note
end_note = self._end_note
@@ -743,9 +790,13 @@ class Keyboard:
key_map[note] = key
self._keys = key_map
kb_width = key_map[self._end_note].rect.right
the_key = key_map[self._end_note]
if the_key is None:
kb_width = 0
else:
kb_width = the_key.rect.right
kb_height = self.white_key_height
self.rect = pygame.Rect(0, 0, kb_width, kb_height)
self.rect = pg.Rect(0, 0, kb_width, kb_height)
def map_regions(self, regions):
"""Draw the key regions onto surface regions.
@@ -763,12 +814,13 @@ class Keyboard:
black_keys = []
for note in range(self._start_note, self._end_note + 1):
key = self._keys[note]
if key.is_white:
if key is not None and key.is_white:
fill_region(regions, note, key.rect, cutoff)
else:
black_keys.append((note, key))
for note, key in black_keys:
fill_region(regions, note, key.rect, cutoff)
if key is not None:
fill_region(regions, note, key.rect, cutoff)
def draw(self, surf, background, dirty_rects):
"""Redraw all altered keyboard keys"""
@@ -779,13 +831,15 @@ class Keyboard:
def key_down(self, note):
"""Signal a key down event for note"""
self._keys[note].down()
key = self._keys[note]
if key is not None:
key.down()
def key_up(self, note):
"""Signal a key up event for note"""
self._keys[note].up()
key = self._keys[note]
if key is not None:
key.up()
def fill_region(regions, note, rect, cutoff):
@@ -859,6 +913,7 @@ def main(mode="output", device_id=None):
if __name__ == "__main__":
device_id: Optional[int] = None
try:
device_id = int(sys.argv[-1])
except ValueError:
@@ -874,4 +929,4 @@ if __name__ == "__main__":
else:
usage()
pygame.quit()
pg.quit()