Spaces:
Running
Running
import json | |
from flask import Flask, request, jsonify | |
from routes import app | |
# Directions mapping | |
DIRECTION_DELTAS = { | |
'N': (-1, 0), | |
'S': (1, 0), | |
'W': (0, -1), | |
'E': (0, 1) | |
} | |
class Block: | |
def __init__(self, name, cells): | |
self.name = name | |
self.cells = set(cells) # Set of (row, col) tuples | |
self.update_dimensions() | |
def update_dimensions(self): | |
rows = [r for r, c in self.cells] | |
cols = [c for r, c in self.cells] | |
self.top = min(rows) | |
self.bottom = max(rows) | |
self.left = min(cols) | |
self.right = max(cols) | |
self.height = self.bottom - self.top + 1 | |
self.width = self.right - self.left + 1 | |
def move(self, direction, grid): | |
delta_row, delta_col = DIRECTION_DELTAS[direction] | |
new_cells = set() | |
for r, c in self.cells: | |
new_r, new_c = r + delta_row, c + delta_col | |
new_cells.add((new_r, new_c)) | |
# Check boundaries and collisions | |
for r, c in new_cells: | |
if not (0 <= r < 5 and 0 <= c < 4): | |
raise ValueError("Move out of bounds") | |
if grid[r][c] not in ('@', self.name): | |
raise ValueError("Collision detected") | |
# Update grid | |
for r, c in self.cells: | |
grid[r][c] = '@' | |
for r, c in new_cells: | |
grid[r][c] = self.name | |
self.cells = new_cells | |
self.update_dimensions() | |
def parse_board(board_str): | |
grid = [] | |
for i in range(0, 20, 4): | |
grid.append(list(board_str[i:i+4])) | |
blocks = {} | |
for r in range(5): | |
for c in range(4): | |
char = grid[r][c] | |
if char != '@': | |
if char not in blocks: | |
blocks[char] = set() | |
blocks[char].add((r, c)) | |
block_objects = {} | |
for name, cells in blocks.items(): | |
block_objects[name] = Block(name, cells) | |
return grid, block_objects | |
def serialize_grid(grid): | |
return ''.join([''.join(row) for row in grid]) | |
def klotski(): | |
data = request.get_json() | |
result = [] | |
for item in data: | |
board_str = item['board'] | |
moves_str = item['moves'] | |
grid, blocks = parse_board(board_str) | |
# Process moves in pairs | |
for i in range(0, len(moves_str), 2): | |
block_name = moves_str[i] | |
direction = moves_str[i+1] | |
block = blocks.get(block_name) | |
if not block: | |
raise ValueError(f"Block {block_name} not found") | |
block.move(direction, grid) | |
result.append(serialize_grid(grid)) | |
return jsonify(result) | |