Menu
CoddyTech

רעידת מסך

חלק מהיחידה צליל ותחושת משחק במסלול ה-Pygame של Coddy. שיעור 12 מתוך 23.

ארגז כבד פוגע בקרקע וכל התצוגה מיטלטלת לרגע. זהו טלטול מסך: במשך כמה פריימים, הכול מצויר בהיסט של כמה פיקסלים, ובכל פריים בכיוון אחר.

כדי להזיז הכול בבת אחת, ציירו את העולם על Surface נפרד במקום על המסך, ואז בצעו blit של אותו Surface אל המסך בהיסט:

world = pygame.Surface((480, 360))

בלולאה, קריאות הציור שהשתמשו ב-screen משתמשות עכשיו ב-world. לאחר מכן בחרו את ההיסט:

offset = (0, 0)
if shake > 0:
    amount = shake // 3
    offset = (random.randint(-amount, amount), random.randint(-amount, amount))
    shake -= 1
screen.fill((0, 0, 0))
screen.blit(world, offset)

shake סופר את מספר הפריימים שנותרו לטלטול. נחיתה קובעת אותו ל-12. מכיוון ש-amount הוא shake // 3, בפריימים הראשונים ההזזה היא עד 4 פיקסלים, ולאחר מכן 3, 2, 1 ולבסוף אפס: הטלטול נחלש בהדרגה במקום להיפסק בפתאומיות. מלאו את המסך בשחור תחילה, כי עולם שהוזז ב-4 פיקסלים משאיר רצועה דקה לא מכוסה.

challenge icon

אתגר

בינוני

נער את התצוגה כשארגז נוחת.

  1. לפני הלולאה, צור world = pygame.Surface((480, 360)).
  2. החלף את screen ב-world בחמש שורות הציור.
  3. כל עוד shake גדול מ-0, בחר היסטים של x ו-y בעזרת amount = shake // 3 ו-random.randint(-amount, amount), ואז הקטן את shake ב-1.
  4. מלא את המסך בשחור ובצע blit של world במיקום ההיסט.

לחץ על "שחק" ועל מקש הרווח: הנחיתה מרעידה את התצוגה. לאחר מכן לחץ על "בדיקה".

נסו בעצמכם

import random
import pygame

pygame.init()
screen = pygame.display.set_mode((480, 360))
pygame.display.set_caption("Crate Drop")
clock = pygame.time.Clock()

thud_sound = pygame.mixer.Sound("assets/sounds/thud.ogg")
falling = []
landed = []
shake = 0

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_SPACE:
            falling.append(pygame.Rect(random.randint(140, 400), -40, 40, 40))

    for crate in falling:
        crate.y += 8
        if crate.bottom >= 300:
            crate.bottom = 300
            landed.append(crate)
            thud_sound.play()
            shake = 12
    falling = [crate for crate in falling if crate.bottom < 300]

    screen.fill((30, 30, 46))
    pygame.draw.rect(screen, (80, 80, 100), (0, 300, 480, 60))
    pygame.draw.rect(screen, (80, 160, 255), (60, 220, 30, 80))
    for crate in falling + landed:
        pygame.draw.rect(screen, (170, 110, 60), crate)
    pygame.display.flip()
    clock.tick(60)

pygame.quit()

כל השיעורים ביחידה צליל ותחושת משחק

תרגלו בעצמכם: Pygame אונליין