Menu
CoddyTech

רשימת אויבים

חלק מהיחידה ספרייטים ותמונות במסלול ה-Pygame של Coddy. שיעור 15 מתוך 39.

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

enemies = [Enemy(red, 100, 50), Enemy(green, 300, 50)]

for enemy in enemies:
    enemy.update()

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

השאירו כל אויב ברשימה פעם אחת בלבד. אויב שמתעדכן גם בנפרד, מחוץ ללולאה, זז פעמיים בכל פריים.

challenge icon

אתגר

בינוני

שמרו את שלושת האויבים ברשימה אחת.

  1. צרו את enemies, רשימה של שלושה אובייקטים מסוג Enemy: האדום במרכז (160, 100), הירוק ב־(320, 100) והצהוב ב־(480, 100).
  2. עדכנו כל אויב ברשימה בלולאה, וציירו את כולם אחרי המילוי.
  3. הסירו את red_enemy, את ה־Rects הירוק והצהוב ואת השורות שלהם.

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

נסו בעצמכם

import pygame

pygame.init()
screen = pygame.display.set_mode((640, 480))
pygame.display.set_caption("Enemy Rain")
clock = pygame.time.Clock()

red = pygame.image.load("assets/images/enemy_red.png").convert_alpha()
green = pygame.image.load("assets/images/enemy_green.png").convert_alpha()
yellow = pygame.image.load("assets/images/enemy_yellow.png").convert_alpha()

class Enemy:
    def __init__(self, image, x, y):
        self.image = image
        self.rect = image.get_rect(center=(x, y))
        self.speed = 2

    def update(self):
        self.rect.y += self.speed
        if self.rect.top > 480:
            self.rect.bottom = 0

    def draw(self, screen):
        screen.blit(self.image, self.rect)


red_enemy = Enemy(red, 160, 100)
green_rect = green.get_rect(center=(320, 100))
yellow_rect = yellow.get_rect(center=(480, 100))

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

    red_enemy.update()
    for rect in (green_rect, yellow_rect):
        rect.y += 2
        if rect.top > 480:
            rect.bottom = 0

    screen.fill((20, 22, 40))
    red_enemy.draw(screen)
    screen.blit(green, green_rect)
    screen.blit(yellow, yellow_rect)
    pygame.display.flip()
    clock.tick(60)

pygame.quit()

כל השיעורים ביחידה ספרייטים ותמונות

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