Il cavaliere
Fa parte della sezione Progetti del percorso Pygame di Coddy. Lezione 23 di 33.
Il cavaliere inizia sulla P della mappa.
La sua immagine occupa una tessera intera, 48 per 48, e lo stesso vale per gli spazi tra i muri. Un Rect di 48 pixel entrerebbe in uno spazio solo se allineato al pixel esatto. Perciò il Rect del cavaliere è più piccolo della sua immagine, 32 per 32, e l'immagine viene disegnata al centro del Rect. È il Rect a entrare in collisione; l'immagine è ciò che vedi.
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) è il Rect di 32 per 32 al centro di una tessera. Il cavaliere è uno sprite, come il corridore di Sky Runner, creato in un punto:
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 = centerSfida
MedioPosiziona il cavaliere nella prima stanza, sulla P.
- Aggiungi le funzioni
drawecell_rectsopra. - In
Room, impostaself.start = (72, 72); unaPimpostaself.start = cell_rect(col, row).center. - Scrivi sopra la classe
Knighte, dopo la stanza, creaknight = Knight(room.start). - Dopo i muri, chiama
draw(knight.image, knight.rect).
Premi «Gioca»: il cavaliere si trova sulla P. Poi premi «Verifica».
Provalo tu
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()
Tutte le lezioni di Progetti
Esercitati da solo: Playground Pygame