Menu
CoddyTech

إيقاف مؤقت

جزء من قسم حلقة اللعبة في رحلة Pygame على Coddy. الدرس 30 من 32.

هناك طريقتان لقراءة لوحة المفاتيح. تُظهر pygame.key.get_pressed() ما إذا كان المفتاح مضغوطًا الآن، في كل إطار: وهذا مناسب للحركة. يصل حدث KEYDOWN مرة واحدة، في الإطار الذي يُضغط فيه المفتاح، مثلما يحدث مع MOUSEBUTTONDOWN عند النقر: وهذا مناسب للإجراءات التي تحدث مرة واحدة لكل ضغطة.

الإيقاف المؤقت إجراء يحدث مرة واحدة لكل ضغطة. باستخدام get_pressed، سيؤدي الضغط على P للحظة إلى تشغيل الإيقاف المؤقت وإيقافه في كل إطار. أما باستخدام الحدث، فيتبدل مرة واحدة:

for event in pygame.event.get():
    if event.type == pygame.QUIT:
        running = False
    elif event.type == pygame.KEYDOWN:
        if event.key == pygame.K_p:
            paused = not paused

تحوّل not paused القيمة True إلى False والعكس. أضف حالة الإيقاف المؤقت إلى الشرط الذي يشغّل اللعبة، واعرض Paused أثناء تفعيله.

challenge icon

التحدي

متوسط
  1. قبل الحلقة، عيّن paused = False.
  2. في حلقة الأحداث، بدّل قيمة paused عندما يكون مفتاح حدث KEYDOWN هو pygame.K_p.
  3. شغّل اللعبة فقط عندما لا تكون متوقفة مؤقتًا: if lives > 0 and score < 10 and not paused:.
  4. عندما تكون قيمة paused صحيحة، اعرض Paused في المنتصف عند (240, 160).

جرّب بنفسك

import random
import pygame

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

basket = pygame.Rect(200, 330, 80, 16)
block = pygame.Rect(220, 0, 20, 20)
score = 0
lives = 3

running = True
while running:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False

    if lives > 0 and score < 10:
        keys = pygame.key.get_pressed()
        if keys[pygame.K_LEFT]:
            basket.x -= 8
        if keys[pygame.K_RIGHT]:
            basket.x += 8
        basket.clamp_ip(screen.get_rect())

        block.y += 3
        if block.top > 360:
            block.y = -20
            block.x = random.randint(0, 460)
            lives -= 1
        if block.colliderect(basket):
            block.y = -20
            block.x = random.randint(0, 460)
            score += 1

    screen.fill((30, 30, 46))
    pygame.draw.rect(screen, (80, 160, 255), basket)
    pygame.draw.rect(screen, (235, 80, 80), block)
    score_text = font.render(f"Score: {score}", True, (240, 240, 240))
    screen.blit(score_text, (10, 10))
    lives_text = font.render(f"Lives: {lives}", True, (240, 240, 240))
    screen.blit(lives_text, (370, 10))
    if lives == 0:
        message = font.render("Game over", True, (240, 240, 240))
        screen.blit(message, message.get_rect(center=(240, 160)))
    elif score == 10:
        message = font.render("You win!", True, (240, 240, 240))
        screen.blit(message, message.get_rect(center=(240, 160)))
    pygame.display.flip()
    clock.tick(60)

pygame.quit()

جميع دروس حلقة اللعبة

تدرّب بنفسك: Playground لـ Pygame