Introdução
Neste projeto, criaremos um jogo de labirinto usando a biblioteca Pygame em Python. O jogo envolve navegar um jogador por um labirinto para coletar itens de comida, evitando paredes. Dividiremos o processo de desenvolvimento em várias etapas para facilitar a compreensão e o acompanhamento.
👀 Pré-visualização

🎯 Tarefas
Neste projeto, você aprenderá:
- Como configurar o ambiente do jogo usando Pygame
- Como criar o labirinto usando células e paredes
- Como adicionar itens de comida para o jogador coletar
- Como implementar o movimento do jogador e a detecção de colisão
- Como lidar com a lógica do jogo, incluindo pontuação e condições de fim de jogo
- Como manter o controle do recorde do jogador
- Como exibir estatísticas do jogo, como tempo, pontuação e recorde na tela
🏆 Conquistas
Após concluir este projeto, você será capaz de:
- Usar a biblioteca Pygame para desenvolvimento de jogos
- Aplicar conceitos de programação orientada a objetos para criar elementos do jogo
- Demonstrar pensamento algorítmico e habilidades de resolução de problemas para a geração de labirintos
- Lidar com o processamento de eventos e entrada do jogador
- Implementar detecção de colisão e mecânicas de movimento em um ambiente de jogo
- Gerenciar o tratamento de arquivos para armazenar e recuperar recordes do jogo
- Exibir estatísticas e informações do jogo na tela
Configurando o Ambiente
Primeiro, criaremos os arquivos do projeto para o jogo do Labirinto.
cd ~/project
touch maze.py
sudo pip install pygame
Nesta etapa, configuraremos o ambiente Pygame e definiremos constantes.
import pygame
from random import choice, randrange
## Constants for screen dimensions and tile size
RES = WIDTH, HEIGHT = 1202, 902
TILE = 100
cols, rows = WIDTH // TILE, HEIGHT // TILE
## The rest of your code will go here...
Nesta etapa:
- Importamos as bibliotecas necessárias (Pygame e random).
- Definimos constantes para as dimensões da tela e o tamanho do tile (tile size).
- O Pygame é inicializado e a janela do jogo é configurada.
- Carregamos imagens de fundo para o jogo.
Criando a Classe Célula
Nesta etapa, definiremos a classe Cell para representar as células do labirinto.
## Define a class to represent cells in the maze
class Cell:
def __init__(self, x, y):
self.x, self.y = x, y
## Walls represent the boundaries of the cell
self.walls = {"top": True, "right": True, "bottom": True, "left": True}
self.visited = False
self.thickness = 4
## Draw the cell's walls
def draw(self, sc):
x, y = self.x * TILE, self.y * TILE
if self.walls["top"]:
pygame.draw.line(
sc, pygame.Color("darkorange"), (x, y), (x + TILE, y), self.thickness
)
if self.walls["right"]:
pygame.draw.line(
sc,
pygame.Color("darkorange"),
(x + TILE, y),
(x + TILE, y + TILE),
self.thickness,
)
if self.walls["bottom"]:
pygame.draw.line(
sc,
pygame.Color("darkorange"),
(x + TILE, y + TILE),
(x, y + TILE),
self.thickness,
)
if self.walls["left"]:
pygame.draw.line(
sc, pygame.Color("darkorange"), (x, y + TILE), (x, y), self.thickness
)
## Get the rectangles representing each wall of the cell
def get_rects(self):
rects = []
x, y = self.x * TILE, self.y * TILE
if self.walls["top"]:
rects.append(pygame.Rect((x, y), (TILE, self.thickness)))
if self.walls["right"]:
rects.append(pygame.Rect((x + TILE, y), (self.thickness, TILE)))
if self.walls["bottom"]:
rects.append(pygame.Rect((x, y + TILE), (TILE, self.thickness)))
if self.walls["left"]:
rects.append(pygame.Rect((x, y), (self.thickness, TILE)))
return rects
## Check if a neighboring cell exists
def check_cell(self, x, y):
find_index = lambda x, y: x + y * cols
if x < 0 or x > cols - 1 or y < 0 or y > rows - 1:
return False
return self.grid_cells[find_index(x, y)]
## Get neighboring cells that have not been visited
def check_neighbors(self, grid_cells):
self.grid_cells = grid_cells
neighbors = []
top = self.check_cell(self.x, self.y - 1)
right = self.check_cell(self.x + 1, self.y)
bottom = self.check_cell(self.x, self.y + 1)
left = self.check_cell(self.x - 1, self.y)
if top and not top.visited:
neighbors.append(top)
if right and not right.visited:
neighbors.append(right)
if bottom and not bottom.visited:
neighbors.append(bottom)
if left and not left.visited:
neighbors.append(left)
return choice(neighbors) if neighbors else False
## The rest of your code will go here...
Nesta etapa:
- Definimos a classe
Cellcom suas propriedades e métodos para desenhar paredes e verificar vizinhos.
Removendo Paredes e Gerando o Labirinto
Nesta etapa, criaremos funções para remover paredes e gerar o labirinto.
## Function to remove walls between two adjacent cells
def remove_walls(current, next):
dx = current.x - next.x
if dx == 1:
current.walls["left"] = False
next.walls["right"] = False
elif dx == -1:
current.walls["right"] = False
next.walls["left"] = False
dy = current.y - next.y
if dy == 1:
current.walls["top"] = False
next.walls["bottom"] = False
elif dy == -1:
current.walls["bottom"] = False
next.walls["top"] = False
## Function to generate the maze
def generate_maze():
grid_cells = [Cell(col, row) for row in range(rows) for col in range(cols)]
current_cell = grid_cells[0]
array = []
break_count = 1
while break_count != len(grid_cells):
current_cell.visited = True
next_cell = current_cell.check_neighbors(grid_cells)
if next_cell:
next_cell.visited = True
break_count += 1
array.append(current_cell)
remove_walls(current_cell, next_cell)
current_cell = next_cell
elif array:
current_cell = array.pop()
return grid_cells
## The rest of your code will go here...
Nesta etapa:
- Definimos a função
remove_wallspara remover paredes entre células adjacentes. - Criamos a função
generate_mazepara gerar o labirinto usando um algoritmo de busca em profundidade (depth-first search).
Adicionando Comida ao Jogo
Nesta etapa, criaremos uma classe Food para adicionar itens de comida ao jogo.
## Class to represent food in the game
class Food:
def __init__(self):
## Load the food image
self.img = pygame.image.load("img/food.png").convert_alpha()
self.img = pygame.transform.scale(self.img, (TILE - 10, TILE - 10))
self.rect = self.img.get_rect()
self.set_pos()
## Set the position of the food randomly
def set_pos(self):
self.rect.topleft = randrange(cols) * TILE + 5, randrange(rows) * TILE + 5
## Draw the food on the screen
def draw(self):
game_surface.blit(self.img, self.rect)
## The rest of your code will go here...
Nesta etapa:
- Definimos a classe
Foodcom métodos para definir a posição e desenhar os itens de comida.
Movimentação do Jogador e Detecção de Colisão
Nesta etapa, configuraremos os controles do jogador, a movimentação e a detecção de colisão.
## Check if the player collides with walls
def is_collide(x, y):
tmp_rect = player_rect.move(x, y)
if tmp_rect.collidelist(walls_collide_list) == -1:
return False
return True
## The rest of your code will go here...
Nesta etapa:
- Definimos a função
is_collidepara verificar se o jogador colide com as paredes.
Jogabilidade e Pontuação
Nesta etapa, implementaremos a lógica do jogo, incluindo comer comida e pontuação.
## Check if the player has eaten any food
def eat_food():
for food in food_list:
if player_rect.collidepoint(food.rect.center):
food.set_pos()
return True
return False
## Check if the game is over (time runs out)
def is_game_over():
global time, score, record, FPS
if time < 0:
pygame.time.wait(700)
player_rect.center = TILE // 2, TILE // 2
[food.set_pos() for food in food_list]
set_record(record, score)
record = get_record()
time, score, FPS = 60, 0, 60
## The rest of your code will go here...
Nesta etapa:
- Definimos a função
eat_foodpara verificar se o jogador comeu alguma comida. - Criamos a função
is_game_overpara verificar se o jogo acabou quando o tempo se esgota.
Manipulação de Registros
Nesta etapa, implementaremos o gerenciamento de recordes para o jogo.
## Function to get the current record from a file
def get_record():
try:
with open("record") as f:
return f.readline()
except FileNotFoundError:
with open("record", "w") as f:
f.write("0")
return "0"
## Function to set and update the record in a file
def set_record(record, score):
rec = max(int(record), score)
with open("record", "w") as f:
f.write(str(rec))
## The rest of your code will go here...
Nesta etapa:
- Definimos funções para recuperar o recorde atual de um arquivo e atualizá-lo.
Inicialização do Jogo
Nesta etapa, realizaremos tarefas de inicialização do jogo.
## Initialize Pygame and set up the game window
FPS = 60
pygame.init()
game_surface = pygame.Surface(RES)
surface = pygame.display.set_mode((WIDTH + 300, HEIGHT))
clock = pygame.time.Clock()
## Load background images
bg_game = pygame.image.load("img/bg_1.jpg").convert()
bg = pygame.image.load("img/bg_main.jpg").convert()
## Generate the maze
maze = generate_maze()
## Player settings
player_speed = 5
player_img = pygame.image.load("img/0.png").convert_alpha()
player_img = pygame.transform.scale(
player_img, (TILE - 2 * maze[0].thickness, TILE - 2 * maze[0].thickness)
)
player_rect = player_img.get_rect()
player_rect.center = TILE // 2, TILE // 2
directions = {
"a": (-player_speed, 0),
"d": (player_speed, 0),
"w": (0, -player_speed),
"s": (0, player_speed),
}
keys = {"a": pygame.K_LEFT, "d": pygame.K_RIGHT, "w": pygame.K_UP, "s": pygame.K_DOWN}
direction = (0, 0)
## Food settings
food_list = [Food() for i in range(3)]
## Create a list of rectangles representing walls for collision detection
walls_collide_list = sum([cell.get_rects() for cell in maze], [])
## Timer, score, and record
pygame.time.set_timer(pygame.USEREVENT, 1000)
time = 60
score = 0
record = get_record()
## Fonts
font = pygame.font.SysFont("Impact", 150)
text_font = pygame.font.SysFont("Impact", 80)
## The rest of your code will go here...
Nesta etapa:
- Realizamos várias tarefas de inicialização, incluindo a configuração do Pygame, carregamento de imagens, geração do labirinto e inicialização de variáveis relacionadas ao jogador e à comida.
Loop Principal do Jogo
Nesta etapa, configuraremos o loop principal do jogo e exibiremos os elementos do jogo.
## Main game loop
while True:
## Blit background images
surface.blit(bg, (WIDTH, 0))
surface.blit(game_surface, (0, 0))
game_surface.blit(bg_game, (0, 0))
for event in pygame.event.get():
if event.type == pygame.QUIT:
exit()
if event.type == pygame.USEREVENT:
time -= 1
## Handle player controls and movement
pressed_key = pygame.key.get_pressed()
for key, key_value in keys.items():
if pressed_key[key_value] and not is_collide(*directions[key]):
direction = directions[key]
break
if not is_collide(*direction):
player_rect.move_ip(direction)
## Draw the maze
[cell.draw(game_surface) for cell in maze]
## Gameplay: Check if the player has eaten food and if the game is over
if eat_food():
FPS += 10
score += 1
is_game_over()
## Draw the player
game_surface.blit(player_img, player_rect)
## Draw food items
[food.draw() for food in food_list]
## The rest of your code will go here...
Nesta etapa:
- Configuramos o loop principal do jogo que lida com eventos, movimento do jogador e renderização do jogo.
Exibindo Estatísticas do Jogo
Nesta etapa, exibiremos as estatísticas do jogo na tela.
## Draw game statistics
surface.blit(
text_font.render("TIME", True, pygame.Color("cyan"), True), (WIDTH + 70, 30)
)
surface.blit(font.render(f"{time}", True, pygame.Color("cyan")), (WIDTH + 70, 130))
surface.blit(
text_font.render("score:", True, pygame.Color("forestgreen"), True),
(WIDTH + 50, 350),
)
surface.blit(
font.render(f"{score}", True, pygame.Color("forestgreen")), (WIDTH + 70, 430)
)
surface.blit(
text_font.render("record:", True, pygame.Color("magenta"), True),
(WIDTH + 30, 620),
)
surface.blit(
font.render(f"{record}", True, pygame.Color("magenta")), (WIDTH + 70, 700)
)
pygame.display.flip()
clock.tick(FPS)
Nesta etapa:
- Usamos fontes para exibir informações relacionadas ao jogo, como tempo, pontuação e recorde.
- Usamos o método
blit()para desenhar o texto na tela. - Usamos o método
flip()para atualizar a exibição.
Executar o Jogo
Agora que concluímos todas as etapas, podemos executar o jogo Maze usando o seguinte comando:
cd ~/project
python maze.py

Resumo
Neste projeto, dividimos o processo de construção de um jogo de labirinto usando Pygame em dez etapas claras e gerenciáveis. Você aprenderá como configurar o ambiente do jogo, criar células do labirinto, gerar o labirinto, lidar com o movimento do jogador e detecção de colisão, implementar a jogabilidade e pontuação, gerenciar recordes e muito mais. Seguindo estas etapas, você poderá criar um jogo de labirinto totalmente funcional em Python.



