56 lines
1.8 KiB
Python
56 lines
1.8 KiB
Python
# app.py
|
|
from flask import Flask, render_template, request, jsonify
|
|
import random
|
|
|
|
app = Flask(__name__)
|
|
|
|
def create_puzzle():
|
|
"""Создаёт случайную, но решаемую расстановку плиток."""
|
|
puzzle = list(range(1, 16)) + [0] # 0 — пустая ячейка
|
|
while True:
|
|
random.shuffle(puzzle)
|
|
if is_solvable(puzzle):
|
|
break
|
|
return puzzle
|
|
|
|
def is_solvable(puzzle):
|
|
"""Проверяет, можно ли решить пазл (на основе инверсий)."""
|
|
inversions = 0
|
|
flat = [n for n in puzzle if n != 0]
|
|
for i in range(len(flat)):
|
|
for j in range(i + 1, len(flat)):
|
|
if flat[i] > flat[j]:
|
|
inversions += 1
|
|
return inversions % 2 == 0
|
|
|
|
def find_empty(puzzle):
|
|
"""Находит индекс пустой ячейки (0)."""
|
|
return puzzle.index(0)
|
|
|
|
@app.route('/')
|
|
def index():
|
|
puzzle = create_puzzle()
|
|
return render_template('index.html', puzzle=puzzle)
|
|
|
|
@app.route('/move', methods=['POST'])
|
|
def move():
|
|
puzzle = request.json['puzzle']
|
|
empty_idx = find_empty(puzzle)
|
|
move_idx = request.json['index']
|
|
|
|
# Проверяем, можно ли переместить (соседняя ячейка по вертикали или горизонтали)
|
|
row, col = move_idx // 4, move_idx % 4
|
|
empty_row, empty_col = empty_idx // 4, empty_idx % 4
|
|
|
|
if (abs(row - empty_row) + abs(col - empty_col) == 1): # Соседняя
|
|
puzzle[empty_idx], puzzle[move_idx] = puzzle[move_idx], puzzle[empty_idx]
|
|
|
|
# Проверка на победу
|
|
if puzzle[:-1] == list(range(1, 16)) and puzzle[-1] == 0:
|
|
return jsonify({'puzzle': puzzle, 'winner': True})
|
|
|
|
return jsonify({'puzzle': puzzle, 'winner': False})
|
|
|
|
if __name__ == '__main__':
|
|
app.run(debug=True)
|