騎士が歩く
CoddyのPygameジャーニー「プロジェクト」セクションの一部。レッスン 22/31。
騎士はマップのPの位置から始まり、矢印キーで1フレームあたり3ピクセル移動します。
騎士の画像はタイル全体と同じ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 rect壁との衝突処理は、Moss Cavesのプラットフォームと同じです。x方向に移動し、重なった壁から押し戻してから、同じ処理をy方向にも行います。軸を1つずつ処理することで、どちら側にぶつかったかがわかります。
def move(self, dx, dy, blocks):
self.rect.x += dx
for block in blocks:
if self.rect.colliderect(block):
if dx > 0:
self.rect.right = block.left
elif dx < 0:
self.rect.left = block.right
# 次にdyについても同様に、bottomとtopを使って処理するチャレンジ
難しいdraw関数とcell_rect関数を上に追加します。Roomでは、ループの前にself.start = (72, 72)を設定し、Pの場合はself.start = cell_rect(col, row).centerを設定します。class Knight(pygame.sprite.Sprite)を記述します。その__init__(self, center)では、self.image = knight_imgを設定し、centerを中心とする32×32のself.rectを設定します。上記のmove(dx, dy, blocks)メソッドを追加し、y方向の処理も含めます。- 部屋の後に
knight = Knight(room.start)を記述します。 - 各フレームで、Leftキーなら
dxを-3、Rightキーなら3に設定し、Upキーならdyを-3、Downキーなら3に設定します(それ以外の場合は0)。次に、knight.move(dx, dy, room.walls)を呼び出します。 - 壁の後に騎士を描画します。
draw(knight.image, knight.rect)
自分で試してみよう
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プレイグラウンド