木箱の下の宝石
CoddyのPygameジャーニー「ゲームループ」セクションの一部。レッスン 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プレイグラウンド