Точки привязки
Часть раздела Правила игры путешествия по Pygame на Coddy. Урок 7 из 29.
Счёт, нарисованный в точке (10, 10), начинается у левого края. Чтобы вместо этого выровнять его по правому краю, нужна его ширина, а ширина меняется вместе с числом. Rect выполнит все вычисления за тебя.
text.get_rect() принимает именованные аргументы для любой из своих точек: center, topleft, topright, midtop, midbottom и другие. Rect размещается так, чтобы указанная точка оказалась в заданном тобой месте:
score_rect = score_text.get_rect(topright=(470, 10))
screen.blit(score_text, score_rect)Теперь правый край счёта остаётся на отметке 470, независимо от того, отображается 0 или 1000.
Текст на пёстром фоне легче читать на подложке. inflate(12, 8) возвращает копию Rect на 12 пикселей шире и на 8 пикселей выше, сохраняя тот же центр. Сначала нарисуй её, а затем поверх — текст:
pygame.draw.rect(screen, PLATE, score_rect.inflate(12, 8))Правый край подложки находится на 6 пикселей правее текста, на отметке 476, а её верхний край — на 4 пикселя выше, на отметке 6.
Задание
Средне- Добавь
PLATE = (60, 60, 90). - Размести счёт с помощью
topright=(470, 10)и нарисуй позади него прямоугольникPLATE: его Rect, увеличенный на (12, 8). - В меню нарисуй прямоугольник
PLATEпозадиMeteor Dodge: Rect заголовка с центром в (240, 140), увеличенный на (24, 12).
Попробуйте сами
import random
import pygame
pygame.init()
screen = pygame.display.set_mode((480, 360))
pygame.display.set_caption("Meteor Dodge")
clock = pygame.time.Clock()
font = pygame.font.Font("assets/fonts/pixel.ttf", 24)
big_font = pygame.font.Font("assets/fonts/pixel.ttf", 48)
WHITE = (240, 240, 240)
def reset():
global player, rock, score
player = pygame.Rect(220, 300, 40, 40)
rock = pygame.Rect(random.randint(0, 456), -24, 24, 24)
score = 0
def draw_menu():
screen.fill((30, 30, 46))
title = big_font.render("Meteor Dodge", True, WHITE)
screen.blit(title, title.get_rect(center=(240, 140)))
hint = font.render("Press Enter to play", True, WHITE)
screen.blit(hint, hint.get_rect(center=(240, 200)))
def draw_game():
screen.fill((30, 30, 46))
pygame.draw.rect(screen, (255, 196, 0), player)
pygame.draw.rect(screen, (235, 80, 80), rock)
score_text = font.render(f"Score: {score}", True, WHITE)
screen.blit(score_text, (10, 10))
def play_frame():
global score, state
keys = pygame.key.get_pressed()
if keys[pygame.K_LEFT]:
player.x -= 6
if keys[pygame.K_RIGHT]:
player.x += 6
player.clamp_ip(screen.get_rect())
rock.y += 4
if rock.top > 360:
rock.y = -24
rock.x = random.randint(0, 456)
score += 1
if rock.colliderect(player):
state = "over"
draw_game()
def draw_over():
draw_game()
message = big_font.render("Game over", True, WHITE)
screen.blit(message, message.get_rect(center=(240, 160)))
hint = font.render("Press R to play again", True, WHITE)
screen.blit(hint, hint.get_rect(center=(240, 200)))
reset()
state = "menu"
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_RETURN and state == "menu":
state = "play"
elif event.key == pygame.K_r and state == "over":
reset()
state = "play"
if state == "menu":
draw_menu()
elif state == "play":
play_frame()
else:
draw_over()
pygame.display.flip()
clock.tick(60)
pygame.quit()
В этом уроке есть небольшой тест. Начните урок, чтобы ответить на вопросы и сохранить прогресс.
Все уроки раздела Правила игры
Потренируйтесь самостоятельно: Песочница Pygame