锚点
本课属于 Coddy Pygame 学习旅程的“游戏规则”单元。第 7 课,共 30 课。
在 (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)现在,无论分数是 0 还是 1000,它的右边缘都保持在 470。
在繁杂的背景上,文字加上底板会更容易阅读。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)。 - 在菜单中,在
Meteor Dodge后面绘制一个PLATE矩形:标题的 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 在线编辑器