소리 불러오기
Coddy Pygame 여정의 사운드와 게임의 손맛 섹션에 포함된 레슨. 23개 중 1번째.
pygame은 pygame.mixer.Sound를 통해 짧은 사운드를 재생합니다. 사운드 파일의 경로를 전달하면 Sound 객체를 얻을 수 있습니다.
jump_sound = pygame.mixer.Sound("assets/sounds/jump.ogg")pygame.init()은 믹서를 시작하므로 그 뒤에 사운드를 만드세요. 반복문에 들어가기 전에 각 사운드를 한 번씩 만드세요. 불러오기는 디스크에서 파일을 읽습니다. 반복문 안에서 불러오면 초당 60번 파일을 읽게 됩니다.
사운드를 재생할 순간이 오면 play()를 호출하세요.
jump_sound.play()play()는 사운드 재생을 시작하고 즉시 반환합니다. 사운드가 들리는 동안에도 게임은 계속 실행되며, 같은 사운드가 끝나기 전에 다시 재생될 수도 있습니다.
assets/sounds/ 폴더에는 사용할 수 있는 사운드가 들어 있습니다. 점프, 코인, 파워업, 레이저, 폭발, 피격 등 다양한 사운드가 모두 .ogg 파일입니다. 게임 옆의 에셋 탭을 열어 사운드를 들어 보세요.
챌린지
쉬움초록색 사각형이 점프할 때 소리가 나도록 만드세요.
- 반복문 앞에서
assets/sounds/jump.ogg를jump_sound에 불러오세요. - 점프가 시작되는 곳에서
speed_y = -14옆에jump_sound.play()를 호출하세요.
‘플레이’를 누르고 스페이스 키를 누르면 점프 소리가 들립니다. 그런 다음 ‘확인’을 누르세요.
직접 해보기
import pygame
pygame.init()
screen = pygame.display.set_mode((480, 360))
pygame.display.set_caption("Jump")
clock = pygame.time.Clock()
player = pygame.Rect(220, 280, 40, 40)
speed_y = 0
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_SPACE and player.bottom == 320:
speed_y = -14
speed_y += 1
player.y += speed_y
if player.bottom > 320:
player.bottom = 320
speed_y = 0
screen.fill((30, 30, 46))
pygame.draw.rect(screen, (80, 80, 100), (0, 320, 480, 40))
pygame.draw.rect(screen, (90, 200, 120), player)
pygame.display.flip()
clock.tick(60)
pygame.quit()
사운드와 게임의 손맛의 모든 레슨
직접 연습해 보세요: Pygame 플레이그라운드