יהלום מתחת לארגז
חלק מהיחידה לולאת המשחק במסלול ה-Pygame של Coddy. שיעור 19 מתוך 35.
עכשיו הארגז הופך למשחק. כל אבן חן מופיעה מתחת לארגז: גררו את הארגז הצידה ולחצו על אבן החן, והארגז יעבור אל האבן הבאה.
ל־Rect יש center, הנקודה שבמרכז שלו. אם נותנים ל־Rect אחד את המרכז של Rect אחר, הוא יושב בדיוק מעליו, בלי קשר לגודל שלהם:
gem = pygame.Rect(300, 120, 30, 30)
crate = pygame.Rect(0, 0, 60, 60)
crate.center = gem.centerרק crate זז, אל (285, 105, 60, 60). עשו זאת פעם אחת לפני הלולאה עבור אבן החן הראשונה, ושוב בכל פעם שאבן חן מקבלת מיקום חדש.
אתגר
קלהסתר כל אבן חן מתחת לארגז.
- מיד אחרי יצירת
crate, הגדרcrate.center = gem.center. - בענף של אבן החן, אחרי
gem.yהחדש, הגדר שובcrate.center = gem.center.
לחץ על "שחק", גרור את הארגז הצידה ולחץ על אבן החן: הארגז יקפוץ אל האבן הבאה. ואז לחץ על "בדיקה".
נסו בעצמכם
import random
import pygame
pygame.init()
screen = pygame.display.set_mode((480, 360))
pygame.display.set_caption("Gem Hunt")
clock = pygame.time.Clock()
gem = pygame.Rect(225, 165, 30, 30)
crate = pygame.Rect(40, 230, 60, 60)
dragging = False
score = 0
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
elif event.type == pygame.MOUSEBUTTONDOWN:
if crate.collidepoint(event.pos):
dragging = True
elif gem.collidepoint(event.pos):
score += 1
gem.x = random.randint(15, 435)
gem.y = random.randint(55, 315)
elif event.type == pygame.MOUSEBUTTONUP:
dragging = False
elif event.type == pygame.MOUSEMOTION and dragging:
crate.move_ip(event.rel)
screen.fill((30, 30, 46))
gem_points = [gem.midtop, gem.midright, gem.midbottom, gem.midleft]
pygame.draw.polygon(screen, (80, 220, 255), gem_points)
if gem.collidepoint(pygame.mouse.get_pos()):
pygame.draw.rect(screen, (255, 196, 0), gem.inflate(10, 10), 2)
pygame.draw.rect(screen, (150, 100, 50), crate)
pygame.draw.rect(screen, (110, 70, 35), crate, 3)
for i in range(score):
pygame.draw.rect(screen, (240, 110, 180), (10 + 10 * i, 14, 8, 8))
mouse_x, mouse_y = pygame.mouse.get_pos()
pygame.draw.circle(screen, (240, 240, 240), (mouse_x, mouse_y), 10, 2)
pygame.display.flip()
clock.tick(60)
pygame.quit()
כל השיעורים ביחידה לולאת המשחק
תרגלו בעצמכם: Pygame אונליין