Para corregir el código y verificar que los movimientos sean válidos, de manera que no se corrompa el juego tras arrastrar las piezas, se necesita realizar varios ajustes. En particular, añadir una verificación adecuada antes de permitir el intercambio de gemas para crear coincidencias. También es esencial gestionar las coincidencias correctamente y restaurar el tablero si el intercambio no tiene éxito en crear una coincidencia. Aquí tienes el código ajustado:
import pygame
import random
import sys
from pygame.locals import *
# Inicialización de Pygame
pygame.init()
# Constantes del juego
SCREEN_WIDTH = 600
SCREEN_HEIGHT = 600
GRID_SIZE = 8 # 8x8 tablero
GEM_SIZE = SCREEN_WIDTH // GRID_SIZE
FPS = 60
MOVE_SPEED = 15 # Velocidad de movimiento de las gemas
# Definición de colores para las gemas
GEM_COLORS = {
"red": (255, 0, 0),
"green": (0, 255, 0),
"blue": (0, 0, 255),
"yellow": (255, 255, 0),
"purple": (128, 0, 128),
"cyan": (0, 255, 255)
}
GEM_TYPES = list(GEM_COLORS.keys())
# Configuración de la pantalla
screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
pygame.display.set_caption("GemBlast Match-3")
clock = pygame.time.Clock()
# Clase Gem representando cada gema en el tablero
class Gem:
def __init__(self, gem_type, row, col):
self.type = gem_type
self.row = row
self.col = col
self.color = GEM_COLORS[gem_type]
self.x = col * GEM_SIZE
self.y = row * GEM_SIZE
self.target_x = self.x
self.target_y = self.y
self.moving = False
self.moving_to = None # Tupla (new_row, new_col)
self.selected = False
def draw(self, surface):
pygame.draw.rect(surface, self.color, (self.x, self.y, GEM_SIZE, GEM_SIZE))
pygame.draw.rect(surface, (0, 0, 0), (self.x, self.y, GEM_SIZE, GEM_SIZE), 2) # Borde negro
if self.selected:
pygame.draw.rect(surface, (255, 255, 255), (self.x, self.y, GEM_SIZE, GEM_SIZE), 4) # Borde de selección
def update(self):
if self.moving:
# Movimiento hacia la posición objetivo
dx = self.target_x - self.x
dy = self.target_y - self.y
distance = (dx ** 2 + dy ** 2) ** 0.5
if distance < MOVE_SPEED:
self.x = self.target_x
self.y = self.target_y
self.moving = False
if self.moving_to:
self.row, self.col = self.moving_to
self.moving_to = None
else:
self.x += MOVE_SPEED if dx > 0 else -MOVE_SPEED if dx < 0 else 0
self.y += MOVE_SPEED if dy > 0 else -MOVE_SPEED if dy < 0 else 0
def set_position(self, row, col):
self.target_x = col * GEM_SIZE
self.target_y = row * GEM_SIZE
if self.x != self.target_x or self.y != self.target_y:
self.moving = True
self.moving_to = (row, col)
else:
self.moving = False
self.moving_to = None
# Patrón de Diseño Factory para crear gemas
class GemFactory:
@staticmethod
def create_gem(gem_type, row, col):
return Gem(gem_type, row, col)
# Función para verificar si agregar una gema de cierto tipo causará una coincidencia
def causes_match(board, row, col, gem_type):
# Verificar horizontalmente
match_count = 1
# Izquierda
c = col - 1
while c >= 0 and board[row][c].type == gem_type:
match_count += 1
c -= 1
# Derecha
c = col + 1
while c < GRID_SIZE and board[row][c].type == gem_type:
match_count += 1
c += 1
if match_count >= 3:
return True
# Verificar verticalmente
match_count = 1
# Arriba
r = row - 1
while r >= 0 and board[r][col].type == gem_type:
match_count += 1
r -= 1
# Abajo
r = row + 1
while r < GRID_SIZE and board[r][col].type == gem_type:
match_count += 1
r += 1
if match_count >= 3:
return True
return False
# Función para generar el tablero inicial sin coincidencias
def generate_initial_board():
board = [[None for _ in range(GRID_SIZE)] for _ in range(GRID_SIZE)]
for row in range(GRID_SIZE):
for col in range(GRID_SIZE):
possible_gems = GEM_TYPES.copy()
# Excluir gemas que causarían coincidencias horizontales
if col >= 2 and board[row][col - 1].type == board[row][col - 2].type:
if board[row][col - 1].type in possible_gems:
possible_gems.remove(board[row][col - 1].type)
# Excluir gemas que causarían coincidencias verticales
if row >= 2 and board[row - 1][col].type == board[row - 2][col].type:
if board[row - 1][col].type in possible_gems:
possible_gems.remove(board[row - 1][col].type)
# Elegir aleatoriamente una gema válida
selected_gem = random.choice(possible_gems)
board[row][col] = GemFactory.create_gem(selected_gem, row, col)
return board
# Función para dibujar el tablero
def draw_board(board, surface):
surface.fill((255, 255, 255)) # Fondo blanco
for row in board:
for gem in row:
gem.draw(surface)
pygame.display.flip()
# Función para buscar todas las coincidencias en el tablero
def find_matches(board):
matches = set()
# Buscar coincidencias horizontales
for row in range(GRID_SIZE):
match_length = 1
for col in range(1, GRID_SIZE):
if board[row][col].type == board[row][col - 1].type:
match_length += 1
else:
if match_length >= 3:
for k in range(col - match_length, col):
matches.add(board[row][k])
match_length = 1
if match_length >= 3:
for k in range(GRID_SIZE - match_length, GRID_SIZE):
matches.add(board[row][k])
# Buscar coincidencias verticales
for col in range(GRID_SIZE):
match_length = 1
for row in range(1, GRID_SIZE):
if board[row][col].type == board[row - 1][col].type:
match_length += 1
else:
if match_length >= 3:
for k in range(row - match_length, row):
matches.add(board[k][col])
match_length = 1
if match_length >= 3:
for k in range(GRID_SIZE - match_length, GRID_SIZE):
matches.add(board[k][col])
return matches
# Función para intercambiar dos gemas en el tablero
def swap_gems(board, gem1, gem2):
board[gem1.row][gem1.col], board[gem2.row][gem2.col] = board[gem2.row][gem2.col], board[gem1.row][gem1.col]
# Actualizar las posiciones de las gemas
gem1.set_position(gem2.row, gem2.col)
gem2.set_position(gem1.row, gem1.col)
board[gem1.row][gem1.col] = gem1
board[gem2.row][gem2.col] = gem2
# Función principal del juego
def main():
board = generate_initial_board()
selected_gem = None
dragging = False
drag_offset_x = 0
drag_offset_y = 0
swap_in_progress = False
swap_revert = False
gem1_swapped = None
gem2_swapped = None
while True:
clock.tick(FPS)
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
sys.exit()
elif event.type == MOUSEBUTTONDOWN and not swap_in_progress:
mouse_x, mouse_y = pygame.mouse.get_pos()
selected_col = mouse_x // GEM_SIZE
selected_row = mouse_y // GEM_SIZE
if 0 <= selected_row < GRID_SIZE and 0 <= selected_col < GRID_SIZE:
selected_gem = board[selected_row][selected_col]
selected_gem.selected = True
dragging = True
drag_offset_x = selected_gem.x - mouse_x
drag_offset_y = selected_gem.y - mouse_y
elif event.type == MOUSEMOTION and dragging and selected_gem and not swap_in_progress:
mouse_x, mouse_y = pygame.mouse.get_pos()
# Actualizar la posición de la gema seleccionada al seguir el puntero
new_x = mouse_x + drag_offset_x
new_y = mouse_y + drag_offset_y
selected_gem.x = new_x
selected_gem.y = new_y
elif event.type == MOUSEBUTTONUP and dragging and selected_gem and not swap_in_progress:
dragging = False
selected_gem.selected = False
mouse_x, mouse_y = pygame.mouse.get_pos()
released_col = mouse_x // GEM_SIZE
released_row = mouse_y // GEM_SIZE
# Determinar la gema objetivo adyacente
dr = released_row - selected_gem.row
dc = released_col - selected_gem.col
if (abs(dr) == 1 and dc == 0) or (abs(dc) == 1 and dr == 0):
target_row = selected_gem.row + dr
target_col = selected_gem.col + dc
if 0 <= target_row < GRID_SIZE and 0 <= target_col < GRID_SIZE:
target_gem = board[target_row][target_col]
# Intercambiar gemas
swap_gems(board, selected_gem, target_gem)
swap_in_progress = True
swap_revert = False
gem1_swapped = selected_gem
gem2_swapped = target_gem
# Verificar si el intercambio forma una coincidencia
matches = find_matches(board)
if not matches:
# El intercambio no es válido, revertir después de un breve retraso
pygame.time.set_timer(pygame.USEREVENT + 1, 300) # Revertir después de 300 ms
swap_revert = True
else:
# Aquí se podrían manejar las gemas que hacen match
# Por ahora, simplemente se mantiene el intercambio
swap_in_progress = False
elif event.type == (pygame.USEREVENT + 1) and swap_in_progress and swap_revert:
# Revertir el intercambio
if gem1_swapped and gem2_swapped:
swap_gems(board, gem1_swapped, gem2_swapped)
# Resetear
swap_in_progress = False
swap_revert = False
gem1_swapped = None
gem2_swapped = None
pygame.time.set_timer(pygame.USEREVENT + 1, 0) # Desactivar el temporizador
# Actualizar gemas
for row in board:
for gem in row:
gem.update()
# Dibujar tablero
draw_board(board, screen)
if __name__ == "__main__":
main()
Cambios Clave:
-
Verificación Bidireccional de Coincidencias: Corrige la función causes_match para que verifique tanto horizontal como verticalmente en ambas direcciones alrededor de la posición dada.
-
Reversión del Intercambio: Utiliza un temporizador para revertir el intercambio si no se forma una coincidencia.
-
Gestión de Eventos: Asegúrate de que todos los eventos de movimiento y selección de las gemas se manejen correctamente, e implementa una lógica clara para la selección y reposicionamiento de las gemas.
-
Verificación Adecuada de Coordenadas: Asegúrate de que todas las verificaciones de coordenadas estén bien protegidas para evitar accesos fuera de los límites de la matriz.
Estos cambios evitan que el tablero se corrompa al asegurar que los movimientos son válidos o que, en su defecto, se revierten adecuadamente.