import pygame
import numpy as np
pygame.init()
screen = pygame.display.set_mode((800, 300))
pygame.display.set_caption("ارگ پایدار با Pygame")
fs = 44100
volume = 0.5
duration = 0.3 # کوتاه برای لمس سریع
# نتها
notes = {
'C4':261.63, 'C#4':277.18, 'D4':293.66, 'D#4':311.13,
'E4':329.63, 'F4':349.23, 'F#4':369.99, 'G4':392.00,
'G#4':415.30, 'A4':440.00, 'A#4':466.16, 'B4':493.88,
'C5':523.25, 'C#5':554.37, 'D5':587.33, 'D#5':622.25,
'E5':659.25, 'F5':698.46, 'F#5':739.99, 'G5':783.99,
'G#5':830.61, 'A5':880.00, 'A#5':932.33, 'B5':987.77
}
# --- تابع ساخت صدا ---
def make_sound(freq):
t = np.linspace(0, duration, int(fs*duration), False)
wave = np.sin(2*np.pi*freq*t) * 32767
wave = wave.astype(np.int16)
# استریو پایدار با column_stack و C-contiguous
stereo_wave = np.column_stack((wave, wave)).copy()
sound = pygame.sndarray.make_sound(stereo_wave)
return sound
# --- ساخت صدای همه نتها ---
sounds = {note: make_sound(freq) for note, freq in notes.items()}
# کلیدها
white_keys = ['C4','D4','E4','F4','G4','A4','B4','C5','D5','E5','F5','G5','A5','B5']
black_keys = ['C#4','D#4','F#4','G#4','A#4','C#5','D#5','F#5','G#5','A#5']
key_width = 50
key_height = 200
black_width = 30
black_height = 120
black_positions = [0.7,1.7,3.7,4.7,5.7,7.7,8.7,10.7,11.7,12.7]
# --- حلقه اصلی ---
running = True
while running:
screen.fill((0,0,0))
# سفیدها
for i, key in enumerate(white_keys):
rect = pygame.Rect(i*key_width, 0, key_width, key_height)
pygame.draw.rect(screen, (255,255,255), rect)
pygame.draw.rect(screen, (0,0,0), rect, 2)
# سیاهها
for i, key in enumerate(black_keys):
rect = pygame.Rect(int(black_positions[i]*key_width), 0, black_width, black_height)
pygame.draw.rect(screen, (0,0,0), rect)
pygame.draw.rect(screen, (0,0,0), rect, 2)
pygame.display.flip()
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
elif event.type == pygame.KEYDOWN:
key_map = {
pygame.K_z:'C4', pygame.K_s:'C#4', pygame.K_x:'D4', pygame.K_d:'D#4',
pygame.K_c:'E4', pygame.K_v:'F4', pygame.K_g:'F#4', pygame.K_b:'G4',
pygame.K_h:'G#4', pygame.K_n:'A4', pygame.K_j:'A#4', pygame.K_m:'B4',
pygame.K_q:'C5', pygame.K_2:'C#5', pygame.K_w:'D5', pygame.K_3:'D#5',
pygame.K_e:'E5', pygame.K_r:'F5', pygame.K_5:'F#5', pygame.K_t:'G5',
pygame.K_6:'G#5', pygame.K_y:'A5', pygame.K_7:'A#5', pygame.K_u:'B5'
}
note = key_map.get(event.key)
if note:
sounds[note].play()
elif event.type == pygame.MOUSEBUTTONDOWN:
x, y = event.pos
for i, key in enumerate(white_keys):
rect = pygame.Rect(i*key_width, 0, key_width, key_height)
if rect.collidepoint(x,y):
sounds[key].play()
for i, key in enumerate(black_keys):
rect = pygame.Rect(int(black_positions[i]*key_width), 0, black_width, black_height)
if rect.collidepoint(x,y):
sounds[key].play()
pygame.quit()