騎士
CoddyのPygameジャーニー「プロジェクト」セクションの一部。レッスン 23/33。
騎士はマップのPからスタートします。
騎士の画像はタイル全体と同じ48×48で、壁の間隔も同じです。48ピクセルのRectでは、ピクセル単位で正確に位置を合わせた場合にしか隙間を通れません。そこで、騎士のRectは画像より小さい32×32にし、その中央に画像を描画します。衝突判定に使うのはRectで、目に見えるのは画像です。
def draw(image, rect):
screen.blit(image, image.get_rect(center=rect.center))
def cell_rect(col, row):
rect = pygame.Rect(0, 0, 32, 32)
rect.center = (col * TILE + 24, row * TILE + 24)
return rectcell_rect(col, row)は、タイルの中央にある32×32のRectです。騎士は、Sky Runnerのランナーのように、ある地点に配置されるスプライトです。
class Knight(pygame.sprite.Sprite):
def __init__(self, center):
super().__init__()
self.image = knight_img
self.rect = pygame.Rect(0, 0, 32, 32)
self.rect.center = centerチャレンジ
中級騎士を最初の部屋に配置し、Pの上に立たせます。
- 上記の
draw関数とcell_rect関数を追加します。 Room内で、self.start = (72, 72)を設定します。Pの場合はself.start = cell_rect(col, row).centerを設定します。- 上記の
Knightクラスを書き、部屋の後にknight = Knight(room.start)を記述します。 - 壁の描画後に、
draw(knight.image, knight.rect)を呼び出します。
「プレイ」を押します。騎士がPの上に立ちます。その後、「確認」を押します。
自分で試してみよう
import pygame
TILE = 48
MAP = [
"##############",
"#............#",
"#.P......K...#",
"#............#",
"#....##......D",
"#....##......#",
"##.#######.###",
"#............#",
"#...S....H...#",
"##############",
]
pygame.init()
screen = pygame.display.set_mode((672, 480))
pygame.display.set_caption("Rune Keep")
clock = pygame.time.Clock()
font = pygame.font.Font("assets/fonts/pixel.ttf", 32)
def load(name):
return pygame.image.load("assets/images/" + name).convert_alpha()
floor_img = load("floor.png")
wall_img = load("wall.png")
knight_img = load("knight.png")
door_img = load("dungeon_door.png")
key_img = load("key.png")
slime_img = load("slime.png")
spider_img = load("spider.png")
heart_img = load("heart.png")
empty_img = load("heart_empty.png")
sword_img = load("sword.png")
potion_img = load("potion_red.png")
class Room:
def __init__(self, lines):
self.walls = []
for row, line in enumerate(lines):
for col, char in enumerate(line):
if char == "#":
self.walls.append(pygame.Rect(col * TILE, row * TILE, TILE, TILE))
room = Room(MAP)
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
for row in range(10):
for col in range(14):
screen.blit(floor_img, (col * TILE, row * TILE))
for wall in room.walls:
screen.blit(wall_img, wall)
pygame.display.flip()
clock.tick(60)
pygame.quit()
プロジェクトのすべてのレッスン
自分で練習してみよう: Pygameプレイグラウンド