Menu
CoddyTech

상자 아래 보석

Coddy Pygame 여정의 게임 루프 섹션에 포함된 레슨. 35개 중 19번째.

이제 상자가 게임이 됩니다. 각 보석은 상자 아래에 나타납니다. 상자를 끌어 옮긴 다음 보석을 클릭하면 상자가 다음 보석 위로 이동합니다.

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)으로 이동합니다. 첫 번째 보석에 대해 루프가 시작되기 전에 한 번 실행하고, 보석이 새 위치를 얻을 때마다 다시 실행하세요.

challenge icon

챌린지

쉬움

각 보석을 상자 아래에 숨기세요.

  1. crate를 만든 직후에 crate.center = gem.center를 설정하세요.
  2. 보석 분기에서 새 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 플레이그라운드