Menu
CoddyTech

Tạm dừng nhạc

Thuộc phần Âm thanh và cảm giác chơi trong hành trình Pygame của Coddy. Bài học 7 trên 23.

Khi trò chơi tạm dừng, nhạc cũng nên tạm dừng và tiếp tục từ đúng vị trí đó khi trò chơi chạy lại. Trình phát nhạc có hai lệnh gọi để làm việc này:

pygame.mixer.music.pause()
pygame.mixer.music.unpause()

pause() giữ bản nhạc tại vị trí hiện tại. unpause() tiếp tục từ đó. Đừng dùng stop() và play() cho việc này: play() phát lại bản nhạc từ đầu, khiến người chơi phải nghe những nhịp đầu tiên mỗi lần tạm dừng.

Gọi chúng ngay khi trạng thái tạm dừng thay đổi, lúc P đảo ngược giá trị của paused:

paused = not paused
if paused:
    pygame.mixer.music.pause()
else:
    pygame.mixer.music.unpause()

Các hiệu ứng âm thanh đang phát khi bạn tạm dừng sẽ tự phát hết vì chúng rất ngắn. Trò chơi đang tạm dừng sẽ không phát hiệu ứng âm thanh mới vì đoạn code phát chúng không chạy.

challenge icon

Thử thách

Trung bình

Tạm dừng nhạc cùng với trò chơi.

  1. Khi nhấn P để tạm dừng, hãy gọi pygame.mixer.music.pause().
  2. Khi nhấn P để tiếp tục, hãy gọi pygame.mixer.music.unpause().

Nhấn Chơi rồi nhấn P: nhạc sẽ dừng, nhấn P lần nữa để phát lại. Sau đó nhấn Kiểm tra.

Tự làm thử

import pygame

pygame.init()
screen = pygame.display.set_mode((480, 360))
pygame.display.set_caption("Lava Run")
clock = pygame.time.Clock()
font = pygame.font.Font(None, 32)


def play_music(path, loops=-1):
    pygame.mixer.music.load(path)
    pygame.mixer.music.play(loops)


play_music("assets/music/theme.ogg")

player = pygame.Rect(40, 160, 30, 30)
goal = pygame.Rect(420, 160, 30, 30)
lava = pygame.Rect(0, 320, 480, 40)
state = "menu"
paused = False

running = True
while running:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
        elif event.type == pygame.KEYDOWN and event.key == pygame.K_p:
            if state == "play":
                paused = not paused
        elif event.type == pygame.KEYDOWN and event.key == pygame.K_RETURN:
            if state == "menu":
                state = "play"
                play_music("assets/music/level.ogg")
                player.topleft = (40, 160)
            elif state in ("win", "lose"):
                state = "menu"
                play_music("assets/music/theme.ogg")

    if state == "play" and not paused:
        keys = pygame.key.get_pressed()
        if keys[pygame.K_LEFT]:
            player.x -= 4
        if keys[pygame.K_RIGHT]:
            player.x += 4
        if keys[pygame.K_UP]:
            player.y -= 4
        if keys[pygame.K_DOWN]:
            player.y += 4
        player.clamp_ip(screen.get_rect())
        if player.colliderect(goal):
            state = "win"
            play_music("assets/music/win.ogg", 0)
        elif player.colliderect(lava):
            state = "lose"
            play_music("assets/music/lose.ogg", 0)

    screen.fill((30, 30, 46))
    if state == "menu":
        title = font.render("Press Enter to start", True, (240, 240, 240))
        screen.blit(title, title.get_rect(center=(240, 180)))
    else:
        pygame.draw.rect(screen, (230, 90, 40), lava)
        pygame.draw.rect(screen, (90, 200, 120), goal)
        pygame.draw.rect(screen, (80, 160, 255), player)
        if state == "win":
            message = font.render("You win!", True, (240, 240, 240))
            screen.blit(message, message.get_rect(center=(240, 100)))
        elif state == "lose":
            message = font.render("Game over", True, (240, 240, 240))
            screen.blit(message, message.get_rect(center=(240, 100)))
        elif paused:
            message = font.render("Paused", True, (240, 240, 240))
            screen.blit(message, message.get_rect(center=(240, 100)))
    pygame.display.flip()
    clock.tick(60)

pygame.quit()
quiz iconTự kiểm tra

Bài học này có một bài trắc nghiệm ngắn. Bắt đầu bài học để trả lời và theo dõi tiến độ.

Tất cả bài học trong Âm thanh và cảm giác chơi

Tự luyện tập: Playground Pygame