جوهرة تحت الصندوق
جزء من قسم حلقة اللعبة في رحلة Pygame على Coddy. الدرس 19 من 35.
أصبح الصندوق الآن هو اللعبة. تظهر كل جوهرة أسفل الصندوق: اسحب الصندوق بعيدًا وانقر على الجوهرة، فينتقل الصندوق إلى الجوهرة التالية.
للمستطيل Rect خاصية center، وهي النقطة التي تقع في منتصفه. اجعل مركز أحد المستطيلين مساويًا لمركز الآخر، وسيقع فوقه تمامًا مهما اختلف حجماهما:
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()
جميع دروس حلقة اللعبة
تدرّب بنفسك: Playground لـ Pygame