split editor
This commit is contained in:
294
racing-tools/README.md
Normal file
294
racing-tools/README.md
Normal file
@@ -0,0 +1,294 @@
|
||||
# 🏁 Racing Tools - Инструменты для "Гонки на бумаге"
|
||||
|
||||
Веб-приложения для создания карт и визуализации решений. Работают без сервера, просто откройте в браузере.
|
||||
|
||||
## 📦 Что внутри
|
||||
|
||||
Два веб-приложения в одном проекте:
|
||||
|
||||
- **🏁 Редактор карт** (`editor.html`) - создание и редактирование игровых карт
|
||||
- **🎬 Визуализатор решений** (`player.html`) - анимация траекторий движения
|
||||
|
||||
## 🚀 Быстрый старт
|
||||
|
||||
### Вариант 1: Через скрипты
|
||||
```bash
|
||||
# Редактор карт
|
||||
./open-editor.sh
|
||||
|
||||
# Визуализатор решений
|
||||
./open-player.sh
|
||||
```
|
||||
|
||||
### Вариант 2: Напрямую в браузере
|
||||
```bash
|
||||
firefox editor.html # Редактор карт
|
||||
firefox player.html # Визуализатор решений
|
||||
```
|
||||
|
||||
### Вариант 3: Через Python HTTP сервер
|
||||
```bash
|
||||
python3 -m http.server 8000
|
||||
# Откройте http://localhost:8000/editor.html или http://localhost:8000/player.html
|
||||
```
|
||||
|
||||
## 🏁 Редактор карт
|
||||
|
||||
### Возможности
|
||||
- Создание карт размером от 5×5 до 100×100
|
||||
- Интуитивное рисование мышью (клик или удержание)
|
||||
- 6 типов ячеек: дорога, камень, снег, лёд, чекпоинт, старт
|
||||
- Экспорт/импорт в JSON формате
|
||||
- Изменение размера с сохранением данных
|
||||
|
||||
### Типы ячеек
|
||||
|
||||
| Код | Тип | Описание | Цвет | Маркер |
|
||||
|-----|-----|----------|------|--------|
|
||||
| 0 | Дорога | Обычная дорога | Светло-серый | - |
|
||||
| 1 | Камень | Препятствие (непроходимо) | Тёмно-серый | - |
|
||||
| 2 | Снег | Замедление движения | Голубой | - |
|
||||
| 3 | Лёд | Скользкая поверхность | Светло-голубой | - |
|
||||
| 4 | Чекпоинт | Контрольная точка | Жёлтый | C |
|
||||
| 5 | Старт | Точка старта (обязательно!) | Зелёный | S |
|
||||
|
||||
### Быстрый старт редактора
|
||||
|
||||
1. Откройте `editor.html`
|
||||
2. Установите размеры (по умолчанию 15×15)
|
||||
3. Выберите тип ячейки из палитры
|
||||
4. Рисуйте мышью на карте (обязательно добавьте точку старта - тип 5)
|
||||
5. Нажмите "Экспорт JSON" - файл скачается автоматически
|
||||
|
||||
## 🎬 Визуализатор решений
|
||||
|
||||
### Возможности
|
||||
- Загрузка карты и решения из JSON
|
||||
- Пошаговая анимация траектории
|
||||
- Контроль скорости воспроизведения (1x - 10x)
|
||||
- Ручное управление (шаг вперед/назад)
|
||||
- Отображение позиции, скорости и ускорения
|
||||
|
||||
### Элементы визуализации
|
||||
|
||||
- 🔵 **Синяя линия и точки** - пройденная траектория
|
||||
- 🔴 **Красный круг** - текущая позиция
|
||||
- ➡️ **Красная стрелка** - вектор скорости (направление и величина)
|
||||
- **Панель информации** - шаг, позиция (x, y), скорость (vx, vy), ускорение (ax, ay)
|
||||
|
||||
### Управление
|
||||
|
||||
| Кнопка | Действие |
|
||||
|--------|----------|
|
||||
| ▶ Play | Автоматическое воспроизведение |
|
||||
| ⏸ Pause | Пауза |
|
||||
| ⏮ Reset | Сброс к началу |
|
||||
| ⏪ Back | Шаг назад |
|
||||
| ⏩ Forward | Шаг вперед |
|
||||
| Слайдер | Скорость 1x - 10x |
|
||||
|
||||
### Быстрый старт визуализатора
|
||||
|
||||
1. Откройте `player.html`
|
||||
2. Загрузите карту (📂 Загрузить карту)
|
||||
3. Загрузите решение (🎬 Загрузить решение)
|
||||
4. Нажмите ▶ Play и наблюдайте за движением
|
||||
|
||||
## 📄 Форматы файлов
|
||||
|
||||
### Формат карты (map)
|
||||
|
||||
```json
|
||||
{
|
||||
"map": [
|
||||
[5, 0, 0, 1, 0],
|
||||
[0, 1, 0, 1, 0],
|
||||
[0, 0, 2, 2, 4]
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
**Структура:**
|
||||
- `map` - двумерный массив целых чисел (int[][])
|
||||
- Первая строка = верхняя строка карты
|
||||
- Первый элемент в строке = левая ячейка
|
||||
- Значения: 0-5 (типы ячеек)
|
||||
- **Обязательно наличие точки старта (5)**
|
||||
|
||||
### Формат решения (solution)
|
||||
|
||||
```json
|
||||
{
|
||||
"solution": [
|
||||
[1, 1],
|
||||
[1, 0],
|
||||
[0, 1],
|
||||
[-1, 0]
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
**Структура:**
|
||||
- `solution` - массив векторов ускорения `[[ax, ay], ...]`
|
||||
- `ax`, `ay` - целые числа (обычно от -1 до 1)
|
||||
- Каждый элемент = одно действие игрока
|
||||
|
||||
### Физика движения
|
||||
|
||||
На каждом шаге применяется:
|
||||
```
|
||||
velocity += acceleration
|
||||
position += velocity
|
||||
```
|
||||
|
||||
**Пример:**
|
||||
```
|
||||
Шаг 0: pos=(0,0), vel=(0,0)
|
||||
Шаг 1: acc=(1,1) → vel=(1,1) → pos=(1,1)
|
||||
Шаг 2: acc=(1,0) → vel=(2,1) → pos=(3,2)
|
||||
Шаг 3: acc=(0,0) → vel=(2,1) → pos=(5,3)
|
||||
```
|
||||
|
||||
## 🔗 Интеграция с C#
|
||||
|
||||
### Чтение карты
|
||||
```csharp
|
||||
using System.Text.Json;
|
||||
|
||||
var json = File.ReadAllText("racing-map-15x15.json");
|
||||
var mapData = JsonSerializer.Deserialize<MapData>(json);
|
||||
int[][] map = mapData.map;
|
||||
|
||||
public class MapData
|
||||
{
|
||||
public int[][] map { get; set; }
|
||||
}
|
||||
```
|
||||
|
||||
### Запись решения
|
||||
```csharp
|
||||
var solution = new { solution = new int[][] {
|
||||
new[] { 1, 1 },
|
||||
new[] { 1, 0 },
|
||||
new[] { 0, 1 }
|
||||
}};
|
||||
|
||||
var json = JsonSerializer.Serialize(solution, new JsonSerializerOptions
|
||||
{
|
||||
WriteIndented = true
|
||||
});
|
||||
|
||||
File.WriteAllText("solution.json", json);
|
||||
```
|
||||
|
||||
## 🎯 Структура проекта
|
||||
|
||||
```
|
||||
racing-tools/
|
||||
├── editor.html # Страница редактора карт
|
||||
├── player.html # Страница визуализатора решений
|
||||
├── styles.css # Общие стили для обоих приложений
|
||||
├── common.js # Общие функции и константы
|
||||
├── editor.js # Логика редактора
|
||||
├── player.js # Логика визуализатора
|
||||
├── open-editor.sh # Скрипт запуска редактора
|
||||
├── open-player.sh # Скрипт запуска визуализатора
|
||||
├── demo-with-start.json # Демо-карта 15×15
|
||||
├── demo-with-start-solution.json # Демо-решение
|
||||
└── README.md # Этот файл
|
||||
```
|
||||
|
||||
## 🎨 Технические детали
|
||||
|
||||
### Технологии
|
||||
- **HTML5** - структура страниц
|
||||
- **CSS3** - современный градиентный дизайн
|
||||
- **JavaScript (ES6+)** - вся логика на клиенте
|
||||
- **Canvas API** - отрисовка карт и визуализация
|
||||
|
||||
### Особенности
|
||||
- ✅ Работает без сервера (статические файлы)
|
||||
- ✅ Валидация данных при импорте
|
||||
- ✅ Адаптивная сетка интерфейса
|
||||
- ✅ Общий CSS и JS для уменьшения дублирования
|
||||
- ✅ Модульная архитектура (common.js для общего кода)
|
||||
- ✅ Навигация между страницами
|
||||
- ✅ Визуальная обратная связь (анимации, подсветка)
|
||||
|
||||
### Зависимости
|
||||
- Нет внешних зависимостей
|
||||
- Чистый Vanilla JavaScript
|
||||
- Работает в любом современном браузере
|
||||
|
||||
## 🧪 Быстрый тест
|
||||
|
||||
### Тест редактора
|
||||
1. Откройте `editor.html`
|
||||
2. Нарисуйте простую карту с точкой старта
|
||||
3. Экспортируйте в JSON
|
||||
4. Импортируйте обратно - данные должны сохраниться
|
||||
|
||||
### Тест визуализатора
|
||||
1. Откройте `player.html`
|
||||
2. Загрузите `demo-with-start.json`
|
||||
3. Загрузите `demo-with-start-solution.json`
|
||||
4. Нажмите ▶ Play и экспериментируйте с кнопками и скоростью
|
||||
|
||||
## 📚 Примеры использования
|
||||
|
||||
### Создание карты с чекпоинтами
|
||||
1. Создайте дорогу (тип 0) в виде трассы
|
||||
2. Добавьте препятствия (тип 1) по краям
|
||||
3. Разместите чекпоинты (тип 4) вдоль трассы
|
||||
4. Обозначьте старт (тип 5) в начале
|
||||
5. Экспортируйте и используйте в решателе
|
||||
|
||||
### Визуализация решения A*
|
||||
1. Запустите C# решатель, получите JSON с решением
|
||||
2. Откройте визуализатор
|
||||
3. Загрузите карту и решение
|
||||
4. Наблюдайте за оптимальным путем
|
||||
|
||||
## 🔗 Связанные проекты
|
||||
|
||||
- [Основной проект C#](../README.md) - решатель на основе A*
|
||||
- [Примеры карт](../maps/) - коллекция готовых карт
|
||||
- [Документация формата](../MAP-FORMAT.md) - подробное описание формата
|
||||
|
||||
## 🤝 Советы и трюки
|
||||
|
||||
### Редактор
|
||||
- Используйте Enter в полях размера для быстрого применения
|
||||
- Удерживайте мышь для быстрого рисования линий
|
||||
- JSON также выводится в консоль (F12) для быстрого копирования
|
||||
- При изменении размера существующие данные сохраняются
|
||||
|
||||
### Визуализатор
|
||||
- Используйте пошаговый режим для детального анализа
|
||||
- Скорость 1x подходит для медленного разбора
|
||||
- Скорость 10x для быстрого просмотра длинных решений
|
||||
- Можно загрузить новое решение без перезагрузки карты
|
||||
|
||||
## 🐛 Решение проблем
|
||||
|
||||
**Карта не загружается?**
|
||||
- Проверьте формат JSON
|
||||
- Убедитесь, что все значения от 0 до 5
|
||||
- Размеры должны быть от 5×5 до 100×100
|
||||
|
||||
**Решение не работает?**
|
||||
- Убедитесь, что на карте есть точка старта (5)
|
||||
- Проверьте формат: массив массивов [[ax, ay], ...]
|
||||
- Сначала загрузите карту, потом решение
|
||||
|
||||
**Визуализация странная?**
|
||||
- Возможно, решение выходит за границы карты
|
||||
- Проверьте корректность векторов ускорений
|
||||
|
||||
---
|
||||
|
||||
**Версия:** 2.0 (Объединенная)
|
||||
**Дата:** 2025
|
||||
**Лицензия:** MIT
|
||||
**Автор:** Racing Team
|
||||
|
||||
111
racing-tools/common.js
Normal file
111
racing-tools/common.js
Normal file
@@ -0,0 +1,111 @@
|
||||
// Общие константы для редактора и плеера
|
||||
const CELL_SIZE = 30;
|
||||
const GRID_COLOR = '#dee2e6';
|
||||
const COLORS = {
|
||||
0: '#f8f9fa', // Дорога
|
||||
1: '#6c757d', // Камень
|
||||
2: '#e3f2fd', // Снег
|
||||
3: '#b3e5fc', // Лёд
|
||||
4: '#fff3cd', // Чекпоинт
|
||||
5: '#d4edda' // Старт
|
||||
};
|
||||
|
||||
// Общие функции для работы с canvas
|
||||
function drawGrid(ctx, width, height) {
|
||||
ctx.strokeStyle = GRID_COLOR;
|
||||
ctx.lineWidth = 1;
|
||||
|
||||
// Вертикальные линии
|
||||
for (let x = 0; x <= width; x++) {
|
||||
ctx.beginPath();
|
||||
ctx.moveTo(x * CELL_SIZE, 0);
|
||||
ctx.lineTo(x * CELL_SIZE, height * CELL_SIZE);
|
||||
ctx.stroke();
|
||||
}
|
||||
|
||||
// Горизонтальные линии
|
||||
for (let y = 0; y <= height; y++) {
|
||||
ctx.beginPath();
|
||||
ctx.moveTo(0, y * CELL_SIZE);
|
||||
ctx.lineTo(width * CELL_SIZE, y * CELL_SIZE);
|
||||
ctx.stroke();
|
||||
}
|
||||
}
|
||||
|
||||
function drawCells(ctx, map, width, height) {
|
||||
// Рисуем ячейки
|
||||
for (let y = 0; y < height; y++) {
|
||||
for (let x = 0; x < width; x++) {
|
||||
const cellType = map[y][x];
|
||||
ctx.fillStyle = COLORS[cellType];
|
||||
ctx.fillRect(x * CELL_SIZE, y * CELL_SIZE, CELL_SIZE, CELL_SIZE);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function drawMarkers(ctx, map, width, height) {
|
||||
// Рисуем маркеры для чекпоинтов и старта
|
||||
ctx.font = 'bold 16px Arial';
|
||||
ctx.textAlign = 'center';
|
||||
ctx.textBaseline = 'middle';
|
||||
|
||||
for (let y = 0; y < height; y++) {
|
||||
for (let x = 0; x < width; x++) {
|
||||
if (map[y][x] === 4) {
|
||||
ctx.fillStyle = '#856404';
|
||||
ctx.fillText('C', x * CELL_SIZE + CELL_SIZE / 2, y * CELL_SIZE + CELL_SIZE / 2);
|
||||
} else if (map[y][x] === 5) {
|
||||
ctx.fillStyle = '#155724';
|
||||
ctx.fillText('S', x * CELL_SIZE + CELL_SIZE / 2, y * CELL_SIZE + CELL_SIZE / 2);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function validateMap(data) {
|
||||
if (!data.map || !Array.isArray(data.map)) {
|
||||
throw new Error('Неверный формат: отсутствует массив map');
|
||||
}
|
||||
|
||||
const newMap = data.map;
|
||||
|
||||
// Валидация
|
||||
if (!newMap.every(row => Array.isArray(row))) {
|
||||
throw new Error('Неверный формат: map должен быть двумерным массивом');
|
||||
}
|
||||
|
||||
const newHeight = newMap.length;
|
||||
const newWidth = newMap[0].length;
|
||||
|
||||
if (newHeight < 5 || newHeight > 100 || newWidth < 5 || newWidth > 100) {
|
||||
throw new Error('Размеры карты должны быть от 5 до 100');
|
||||
}
|
||||
|
||||
if (!newMap.every(row => row.length === newWidth)) {
|
||||
throw new Error('Все строки должны иметь одинаковую длину');
|
||||
}
|
||||
|
||||
// Проверка значений ячеек
|
||||
const validValues = [0, 1, 2, 3, 4, 5];
|
||||
for (let y = 0; y < newHeight; y++) {
|
||||
for (let x = 0; x < newWidth; x++) {
|
||||
if (!validValues.includes(newMap[y][x])) {
|
||||
throw new Error(`Недопустимое значение ячейки: ${newMap[y][x]} на позиции [${y}][${x}]`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return { map: newMap, width: newWidth, height: newHeight };
|
||||
}
|
||||
|
||||
function findStartPosition(map, width, height) {
|
||||
for (let y = 0; y < height; y++) {
|
||||
for (let x = 0; x < width; x++) {
|
||||
if (map[y][x] === 5) {
|
||||
return { x, y };
|
||||
}
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
32
racing-tools/demo-with-start-solution.json
Normal file
32
racing-tools/demo-with-start-solution.json
Normal file
@@ -0,0 +1,32 @@
|
||||
{
|
||||
"solution": [
|
||||
[
|
||||
0,
|
||||
0
|
||||
],
|
||||
[
|
||||
2,
|
||||
2
|
||||
],
|
||||
[
|
||||
2,
|
||||
-1
|
||||
],
|
||||
[
|
||||
-2,
|
||||
-1
|
||||
],
|
||||
[
|
||||
0,
|
||||
2
|
||||
],
|
||||
[
|
||||
0,
|
||||
2
|
||||
],
|
||||
[
|
||||
0,
|
||||
-1
|
||||
]
|
||||
]
|
||||
}
|
||||
21
racing-tools/demo-with-start.json
Normal file
21
racing-tools/demo-with-start.json
Normal file
@@ -0,0 +1,21 @@
|
||||
{
|
||||
"map": [
|
||||
[5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
|
||||
[0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0],
|
||||
[0, 0, 0, 1, 0, 0, 0, 2, 2, 2, 0, 0, 0, 0, 0],
|
||||
[0, 0, 0, 1, 0, 0, 0, 2, 4, 2, 0, 0, 0, 0, 0],
|
||||
[0, 0, 0, 0, 0, 0, 0, 2, 2, 2, 0, 0, 1, 1, 0],
|
||||
[0, 0, 0, 0, 3, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0],
|
||||
[0, 0, 0, 0, 3, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0],
|
||||
[0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0],
|
||||
[0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 2, 2, 2, 0],
|
||||
[0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 2, 4, 2, 0],
|
||||
[0, 0, 0, 0, 0, 3, 3, 3, 0, 0, 0, 2, 2, 2, 0],
|
||||
[0, 0, 0, 0, 0, 3, 1, 3, 0, 0, 0, 0, 0, 0, 0],
|
||||
[0, 0, 0, 0, 0, 3, 3, 3, 0, 0, 0, 0, 0, 0, 4],
|
||||
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
|
||||
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
|
||||
]
|
||||
}
|
||||
|
||||
|
||||
125
racing-tools/editor.html
Normal file
125
racing-tools/editor.html
Normal file
@@ -0,0 +1,125 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="ru">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>Редактор карт - Гонки на бумаге</title>
|
||||
<link rel="stylesheet" href="styles.css">
|
||||
</head>
|
||||
<body>
|
||||
<div class="container">
|
||||
<h1>🏁 Редактор карт</h1>
|
||||
<p class="subtitle">Гонки на бумаге / Paper Racing</p>
|
||||
|
||||
<div class="nav-links">
|
||||
<a href="editor.html">🏁 Редактор карт</a>
|
||||
<a href="player.html">🎬 Визуализатор решений</a>
|
||||
</div>
|
||||
|
||||
<div class="controls">
|
||||
<div class="control-group">
|
||||
<h3>📐 Размеры карты</h3>
|
||||
<div class="size-inputs">
|
||||
<div class="input-wrapper">
|
||||
<label for="width">Ширина:</label>
|
||||
<input type="number" id="width" min="5" max="100" value="15">
|
||||
</div>
|
||||
<div class="input-wrapper">
|
||||
<label for="height">Высота:</label>
|
||||
<input type="number" id="height" min="5" max="100" value="15">
|
||||
</div>
|
||||
</div>
|
||||
<div class="buttons">
|
||||
<button class="btn-primary" onclick="resizeMap()">Применить</button>
|
||||
<button class="btn-danger" onclick="clearMap()">Очистить</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="control-group">
|
||||
<h3>🎨 Тип ячейки</h3>
|
||||
<div class="palette">
|
||||
<div class="cell-type road active" data-type="0" onclick="selectCellType(0)">
|
||||
<span>Дорога</span>
|
||||
<span class="code">(0)</span>
|
||||
</div>
|
||||
<div class="cell-type stone" data-type="1" onclick="selectCellType(1)">
|
||||
<span>Камень</span>
|
||||
<span class="code">(1)</span>
|
||||
</div>
|
||||
<div class="cell-type snow" data-type="2" onclick="selectCellType(2)">
|
||||
<span>Снег</span>
|
||||
<span class="code">(2)</span>
|
||||
</div>
|
||||
<div class="cell-type ice" data-type="3" onclick="selectCellType(3)">
|
||||
<span>Лёд</span>
|
||||
<span class="code">(3)</span>
|
||||
</div>
|
||||
<div class="cell-type checkpoint" data-type="4" onclick="selectCellType(4)">
|
||||
<span>Чекпоинт</span>
|
||||
<span class="code">(4)</span>
|
||||
</div>
|
||||
<div class="cell-type start" data-type="5" onclick="selectCellType(5)">
|
||||
<span>Старт</span>
|
||||
<span class="code">(5)</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="control-group">
|
||||
<h3>💾 Импорт / Экспорт</h3>
|
||||
<div class="buttons">
|
||||
<button class="btn-success" onclick="exportMap()">📥 Экспорт JSON</button>
|
||||
<button class="btn-warning" onclick="document.getElementById('fileInput').click()">📤 Импорт JSON</button>
|
||||
</div>
|
||||
<input type="file" id="fileInput" accept=".json" onchange="importMap(event)">
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="canvas-wrapper">
|
||||
<canvas id="mapCanvas"></canvas>
|
||||
</div>
|
||||
|
||||
<div class="info">
|
||||
<strong>💡 Подсказки:</strong>
|
||||
• Кликайте по ячейкам для изменения типа<br>
|
||||
• Удерживайте кнопку мыши для рисования<br>
|
||||
• Экспортируйте карту в JSON для использования в игре<br>
|
||||
• Для визуализации решений используйте <a href="player.html" style="color: #0d47a1; font-weight: bold;">Визуализатор решений</a>
|
||||
</div>
|
||||
|
||||
<div class="control-group">
|
||||
<h3>📖 Легенда цветов</h3>
|
||||
<div class="legend">
|
||||
<div class="legend-item">
|
||||
<div class="legend-color road"></div>
|
||||
<span>Дорога (0)</span>
|
||||
</div>
|
||||
<div class="legend-item">
|
||||
<div class="legend-color stone"></div>
|
||||
<span>Камень (1)</span>
|
||||
</div>
|
||||
<div class="legend-item">
|
||||
<div class="legend-color snow"></div>
|
||||
<span>Снег (2)</span>
|
||||
</div>
|
||||
<div class="legend-item">
|
||||
<div class="legend-color ice"></div>
|
||||
<span>Лёд (3)</span>
|
||||
</div>
|
||||
<div class="legend-item">
|
||||
<div class="legend-color checkpoint"></div>
|
||||
<span>Чекпоинт (4)</span>
|
||||
</div>
|
||||
<div class="legend-item">
|
||||
<div class="legend-color start"></div>
|
||||
<span>Старт (5)</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<script src="common.js"></script>
|
||||
<script src="editor.js"></script>
|
||||
</body>
|
||||
</html>
|
||||
|
||||
253
racing-tools/editor.js
Normal file
253
racing-tools/editor.js
Normal file
@@ -0,0 +1,253 @@
|
||||
// Состояние редактора
|
||||
let width = 15;
|
||||
let height = 15;
|
||||
let map = [];
|
||||
let selectedType = 0;
|
||||
let isDrawing = false;
|
||||
|
||||
let scale = 1;
|
||||
let offsetX = 0;
|
||||
let offsetY = 0;
|
||||
let isPanning = false;
|
||||
let startPanX = 0;
|
||||
let startPanY = 0;
|
||||
|
||||
// Canvas элементы
|
||||
const canvas = document.getElementById('mapCanvas');
|
||||
const ctx = canvas.getContext('2d');
|
||||
|
||||
// Инициализация
|
||||
function init() {
|
||||
width = parseInt(document.getElementById('width').value);
|
||||
height = parseInt(document.getElementById('height').value);
|
||||
initMap();
|
||||
resizeCanvas();
|
||||
drawMap();
|
||||
}
|
||||
|
||||
// Инициализация карты
|
||||
function initMap() {
|
||||
map = Array(height).fill(null).map(() => Array(width).fill(0));
|
||||
}
|
||||
|
||||
function resizeCanvas() {
|
||||
const wrapper = canvas.parentElement;
|
||||
canvas.width = Math.max(1000, wrapper.clientWidth || 1000);
|
||||
canvas.height = Math.max(1000, wrapper.clientHeight || 1000);
|
||||
}
|
||||
|
||||
// Отрисовка карты
|
||||
function drawMap() {
|
||||
ctx.setTransform(1, 0, 0, 1, 0, 0);
|
||||
ctx.clearRect(0, 0, canvas.width, canvas.height);
|
||||
ctx.translate(offsetX, offsetY);
|
||||
ctx.scale(scale, scale);
|
||||
drawCells(ctx, map, width, height);
|
||||
drawGrid(ctx, width, height);
|
||||
drawMarkers(ctx, map, width, height);
|
||||
}
|
||||
|
||||
// Выбор типа ячейки
|
||||
function selectCellType(type) {
|
||||
selectedType = type;
|
||||
|
||||
// Обновляем UI
|
||||
document.querySelectorAll('.cell-type').forEach(el => {
|
||||
el.classList.remove('active');
|
||||
});
|
||||
document.querySelector(`[data-type="${type}"]`).classList.add('active');
|
||||
}
|
||||
|
||||
// Получение координат ячейки по клику
|
||||
function getCellCoords(event) {
|
||||
const rect = canvas.getBoundingClientRect();
|
||||
const canvasX = (event.clientX - rect.left - offsetX) / scale;
|
||||
const canvasY = (event.clientY - rect.top - offsetY) / scale;
|
||||
const x = Math.floor(canvasX / CELL_SIZE);
|
||||
const y = Math.floor(canvasY / CELL_SIZE);
|
||||
|
||||
if (x >= 0 && x < width && y >= 0 && y < height) {
|
||||
return { x, y };
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
// Установка типа ячейки
|
||||
function setCellType(x, y) {
|
||||
if (x >= 0 && x < width && y >= 0 && y < height) {
|
||||
map[y][x] = selectedType;
|
||||
drawMap();
|
||||
}
|
||||
}
|
||||
|
||||
// Обработчики событий мыши
|
||||
canvas.addEventListener('mousedown', (e) => {
|
||||
if (e.button === 2 || e.shiftKey) {
|
||||
isPanning = true;
|
||||
startPanX = e.clientX - offsetX;
|
||||
startPanY = e.clientY - offsetY;
|
||||
canvas.style.cursor = 'grabbing';
|
||||
} else {
|
||||
isDrawing = true;
|
||||
const coords = getCellCoords(e);
|
||||
if (coords) {
|
||||
setCellType(coords.x, coords.y);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
canvas.addEventListener('mousemove', (e) => {
|
||||
if (isPanning) {
|
||||
offsetX = e.clientX - startPanX;
|
||||
offsetY = e.clientY - startPanY;
|
||||
drawMap();
|
||||
} else if (isDrawing) {
|
||||
const coords = getCellCoords(e);
|
||||
if (coords) {
|
||||
setCellType(coords.x, coords.y);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
canvas.addEventListener('mouseup', () => {
|
||||
isDrawing = false;
|
||||
isPanning = false;
|
||||
canvas.style.cursor = 'default';
|
||||
});
|
||||
|
||||
canvas.addEventListener('mouseleave', () => {
|
||||
isDrawing = false;
|
||||
isPanning = false;
|
||||
canvas.style.cursor = 'default';
|
||||
});
|
||||
|
||||
canvas.addEventListener('wheel', (e) => {
|
||||
e.preventDefault();
|
||||
const rect = canvas.getBoundingClientRect();
|
||||
const mouseX = e.clientX - rect.left;
|
||||
const mouseY = e.clientY - rect.top;
|
||||
const zoom = e.deltaY < 0 ? 1.1 : 0.9;
|
||||
const newScale = Math.min(Math.max(0.1, scale * zoom), 5);
|
||||
|
||||
offsetX = mouseX - (mouseX - offsetX) * (newScale / scale);
|
||||
offsetY = mouseY - (mouseY - offsetY) * (newScale / scale);
|
||||
scale = newScale;
|
||||
|
||||
drawMap();
|
||||
});
|
||||
|
||||
canvas.addEventListener('contextmenu', (e) => e.preventDefault());
|
||||
|
||||
// Изменение размера карты
|
||||
function resizeMap() {
|
||||
const newWidth = parseInt(document.getElementById('width').value);
|
||||
const newHeight = parseInt(document.getElementById('height').value);
|
||||
|
||||
if (newWidth < 5 || newWidth > 100 || newHeight < 5 || newHeight > 100) {
|
||||
alert('Размеры должны быть от 5 до 100');
|
||||
return;
|
||||
}
|
||||
|
||||
const newMap = Array(newHeight).fill(null).map(() => Array(newWidth).fill(0));
|
||||
|
||||
// Копируем существующие данные
|
||||
const minHeight = Math.min(height, newHeight);
|
||||
const minWidth = Math.min(width, newWidth);
|
||||
|
||||
for (let y = 0; y < minHeight; y++) {
|
||||
for (let x = 0; x < minWidth; x++) {
|
||||
newMap[y][x] = map[y][x];
|
||||
}
|
||||
}
|
||||
|
||||
width = newWidth;
|
||||
height = newHeight;
|
||||
map = newMap;
|
||||
|
||||
resizeCanvas();
|
||||
drawMap();
|
||||
}
|
||||
|
||||
// Очистка карты
|
||||
function clearMap() {
|
||||
if (confirm('Вы уверены, что хотите очистить всю карту?')) {
|
||||
initMap();
|
||||
drawMap();
|
||||
}
|
||||
}
|
||||
|
||||
// Экспорт карты в JSON
|
||||
function exportMap() {
|
||||
const data = {
|
||||
map: map
|
||||
};
|
||||
|
||||
const json = JSON.stringify(data, null, 2);
|
||||
const blob = new Blob([json], { type: 'application/json' });
|
||||
const url = URL.createObjectURL(blob);
|
||||
|
||||
const a = document.createElement('a');
|
||||
a.href = url;
|
||||
a.download = `racing-map-${width}x${height}.json`;
|
||||
document.body.appendChild(a);
|
||||
a.click();
|
||||
document.body.removeChild(a);
|
||||
URL.revokeObjectURL(url);
|
||||
|
||||
// Также выводим в консоль для быстрого копирования
|
||||
console.log('Экспортированная карта:', json);
|
||||
alert('Карта экспортирована! JSON также выведен в консоль браузера (F12)');
|
||||
}
|
||||
|
||||
// Импорт карты из JSON
|
||||
function importMap(event) {
|
||||
const file = event.target.files[0];
|
||||
if (!file) return;
|
||||
|
||||
const reader = new FileReader();
|
||||
reader.onload = (e) => {
|
||||
try {
|
||||
const data = JSON.parse(e.target.result);
|
||||
const validated = validateMap(data);
|
||||
|
||||
// Импортируем карту
|
||||
height = validated.height;
|
||||
width = validated.width;
|
||||
map = validated.map;
|
||||
|
||||
// Обновляем UI
|
||||
document.getElementById('width').value = width;
|
||||
document.getElementById('height').value = height;
|
||||
|
||||
resizeCanvas();
|
||||
drawMap();
|
||||
|
||||
alert('Карта успешно импортирована!');
|
||||
} catch (error) {
|
||||
alert('Ошибка при импорте: ' + error.message);
|
||||
console.error('Ошибка импорта:', error);
|
||||
}
|
||||
};
|
||||
|
||||
reader.readAsText(file);
|
||||
|
||||
// Сброс input для возможности повторного импорта того же файла
|
||||
event.target.value = '';
|
||||
}
|
||||
|
||||
// Обработчики изменения размеров
|
||||
document.getElementById('width').addEventListener('keypress', (e) => {
|
||||
if (e.key === 'Enter') resizeMap();
|
||||
});
|
||||
|
||||
document.getElementById('height').addEventListener('keypress', (e) => {
|
||||
if (e.key === 'Enter') resizeMap();
|
||||
});
|
||||
|
||||
window.addEventListener('resize', () => {
|
||||
resizeCanvas();
|
||||
drawMap();
|
||||
});
|
||||
|
||||
init();
|
||||
|
||||
43
racing-tools/open-editor.sh
Executable file
43
racing-tools/open-editor.sh
Executable file
@@ -0,0 +1,43 @@
|
||||
#!/bin/bash
|
||||
|
||||
# Скрипт для запуска редактора карт в браузере
|
||||
# Автоматически определяет доступный браузер и открывает страницу
|
||||
|
||||
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
|
||||
HTML_FILE="$SCRIPT_DIR/editor.html"
|
||||
|
||||
echo "🏁 Запуск редактора карт..."
|
||||
echo "📁 Путь: $HTML_FILE"
|
||||
|
||||
# Проверяем наличие файла
|
||||
if [ ! -f "$HTML_FILE" ]; then
|
||||
echo "❌ Ошибка: Файл $HTML_FILE не найден"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
# Функция для открытия в браузере
|
||||
open_browser() {
|
||||
if command -v xdg-open &> /dev/null; then
|
||||
xdg-open "$HTML_FILE"
|
||||
elif command -v firefox &> /dev/null; then
|
||||
firefox "$HTML_FILE"
|
||||
elif command -v google-chrome &> /dev/null; then
|
||||
google-chrome "$HTML_FILE"
|
||||
elif command -v chromium &> /dev/null; then
|
||||
chromium "$HTML_FILE"
|
||||
else
|
||||
echo "❌ Браузер не найден. Откройте вручную: $HTML_FILE"
|
||||
exit 1
|
||||
fi
|
||||
}
|
||||
|
||||
# Открываем браузер
|
||||
open_browser
|
||||
|
||||
echo "✅ Редактор открыт в браузере"
|
||||
echo ""
|
||||
echo "💡 Подсказки:"
|
||||
echo " • Нарисуйте карту, обязательно добавьте точку старта (тип 5)"
|
||||
echo " • Экспортируйте в JSON для использования в решателе"
|
||||
echo " • Для визуализации решений откройте ./open-player.sh"
|
||||
|
||||
44
racing-tools/open-player.sh
Executable file
44
racing-tools/open-player.sh
Executable file
@@ -0,0 +1,44 @@
|
||||
#!/bin/bash
|
||||
|
||||
# Скрипт для запуска визуализатора решений в браузере
|
||||
# Автоматически определяет доступный браузер и открывает страницу
|
||||
|
||||
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
|
||||
HTML_FILE="$SCRIPT_DIR/player.html"
|
||||
|
||||
echo "🎬 Запуск визуализатора решений..."
|
||||
echo "📁 Путь: $HTML_FILE"
|
||||
|
||||
# Проверяем наличие файла
|
||||
if [ ! -f "$HTML_FILE" ]; then
|
||||
echo "❌ Ошибка: Файл $HTML_FILE не найден"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
# Функция для открытия в браузере
|
||||
open_browser() {
|
||||
if command -v xdg-open &> /dev/null; then
|
||||
xdg-open "$HTML_FILE"
|
||||
elif command -v firefox &> /dev/null; then
|
||||
firefox "$HTML_FILE"
|
||||
elif command -v google-chrome &> /dev/null; then
|
||||
google-chrome "$HTML_FILE"
|
||||
elif command -v chromium &> /dev/null; then
|
||||
chromium "$HTML_FILE"
|
||||
else
|
||||
echo "❌ Браузер не найден. Откройте вручную: $HTML_FILE"
|
||||
exit 1
|
||||
fi
|
||||
}
|
||||
|
||||
# Открываем браузер
|
||||
open_browser
|
||||
|
||||
echo "✅ Визуализатор открыт в браузере"
|
||||
echo ""
|
||||
echo "💡 Подсказки:"
|
||||
echo " • Сначала загрузите карту (📂 Загрузить карту)"
|
||||
echo " • Затем загрузите решение (🎬 Загрузить решение)"
|
||||
echo " • Используйте кнопки управления для анимации"
|
||||
echo " • Демо-файлы: demo-with-start.json и demo-with-start-solution.json"
|
||||
|
||||
117
racing-tools/player.html
Normal file
117
racing-tools/player.html
Normal file
@@ -0,0 +1,117 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="ru">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>Визуализатор решений - Гонки на бумаге</title>
|
||||
<link rel="stylesheet" href="styles.css">
|
||||
</head>
|
||||
<body>
|
||||
<div class="container">
|
||||
<h1>🎬 Визуализатор решений</h1>
|
||||
<p class="subtitle">Гонки на бумаге / Paper Racing</p>
|
||||
|
||||
<div class="nav-links">
|
||||
<a href="editor.html">🏁 Редактор карт</a>
|
||||
<a href="player.html">🎬 Визуализатор решений</a>
|
||||
</div>
|
||||
|
||||
<div class="controls">
|
||||
<div class="control-group">
|
||||
<h3>📂 Загрузка файлов</h3>
|
||||
<div class="buttons">
|
||||
<button class="btn-primary" id="loadMapBtn" onclick="document.getElementById('mapInput').click()">📂 Загрузить карту</button>
|
||||
<button class="btn-success" id="loadSolutionBtn" onclick="document.getElementById('solutionInput').click()">🎬 Загрузить решение</button>
|
||||
</div>
|
||||
<input type="file" id="mapInput" accept=".json" onchange="loadMap(event)">
|
||||
<input type="file" id="solutionInput" accept=".json" onchange="loadSolution(event)">
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="canvas-wrapper">
|
||||
<canvas id="mapCanvas"></canvas>
|
||||
</div>
|
||||
|
||||
<div id="playbackControls" class="visualization-panel hidden">
|
||||
<h3>🎮 Управление воспроизведением</h3>
|
||||
|
||||
<div class="playback-controls">
|
||||
<button class="playback-btn" onclick="playVisualization()" id="playBtn">▶ Play</button>
|
||||
<button class="playback-btn" onclick="pauseVisualization()" id="pauseBtn" disabled>⏸ Pause</button>
|
||||
<button class="playback-btn" onclick="resetVisualization()">⏮ Reset</button>
|
||||
<button class="playback-btn" onclick="stepBackward()">⏪ Back</button>
|
||||
<button class="playback-btn" onclick="stepForward()">⏩ Forward</button>
|
||||
|
||||
<div class="speed-control">
|
||||
<label for="speedSlider">Скорость:</label>
|
||||
<input type="range" id="speedSlider" min="1" max="10" value="5" onchange="updateSpeed()">
|
||||
<span id="speedValue">5x</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div id="stepInfo" class="step-info hidden">
|
||||
<div class="info-item">
|
||||
<span class="info-label">Шаг</span>
|
||||
<span class="info-value" id="stepNumber">0 / 0</span>
|
||||
</div>
|
||||
<div class="info-item">
|
||||
<span class="info-label">Позиция (x, y)</span>
|
||||
<span class="info-value" id="positionValue">(0, 0)</span>
|
||||
</div>
|
||||
<div class="info-item">
|
||||
<span class="info-label">Скорость (vx, vy)</span>
|
||||
<span class="info-value" id="velocityValue">(0, 0)</span>
|
||||
</div>
|
||||
<div class="info-item">
|
||||
<span class="info-label">Ускорение (ax, ay)</span>
|
||||
<span class="info-value" id="accelerationValue">(0, 0)</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="info">
|
||||
<strong>💡 Инструкция:</strong>
|
||||
• Сначала загрузите карту с точкой старта (тип 5)<br>
|
||||
• Затем загрузите файл решения с векторами ускорений<br>
|
||||
• Используйте кнопки управления для просмотра анимации<br>
|
||||
• 🔵 Синяя линия - пройденная траектория<br>
|
||||
• 🔴 Красный круг - текущая позиция<br>
|
||||
• ➡️ Красная стрелка - направление и скорость движения
|
||||
</div>
|
||||
|
||||
<div class="control-group">
|
||||
<h3>📖 Легенда цветов</h3>
|
||||
<div class="legend">
|
||||
<div class="legend-item">
|
||||
<div class="legend-color road"></div>
|
||||
<span>Дорога (0)</span>
|
||||
</div>
|
||||
<div class="legend-item">
|
||||
<div class="legend-color stone"></div>
|
||||
<span>Камень (1)</span>
|
||||
</div>
|
||||
<div class="legend-item">
|
||||
<div class="legend-color snow"></div>
|
||||
<span>Снег (2)</span>
|
||||
</div>
|
||||
<div class="legend-item">
|
||||
<div class="legend-color ice"></div>
|
||||
<span>Лёд (3)</span>
|
||||
</div>
|
||||
<div class="legend-item">
|
||||
<div class="legend-color checkpoint"></div>
|
||||
<span>Чекпоинт (4)</span>
|
||||
</div>
|
||||
<div class="legend-item">
|
||||
<div class="legend-color start"></div>
|
||||
<span>Старт (5)</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<script src="common.js"></script>
|
||||
<script src="player.js"></script>
|
||||
</body>
|
||||
</html>
|
||||
|
||||
413
racing-tools/player.js
Normal file
413
racing-tools/player.js
Normal file
@@ -0,0 +1,413 @@
|
||||
// Состояние плеера
|
||||
let width = 15;
|
||||
let height = 15;
|
||||
let map = [];
|
||||
let solution = null;
|
||||
let trajectory = [];
|
||||
let currentStep = 0;
|
||||
let isPlaying = false;
|
||||
let playbackSpeed = 5;
|
||||
let playbackInterval = null;
|
||||
let startPosition = null;
|
||||
|
||||
let scale = 1;
|
||||
let offsetX = 0;
|
||||
let offsetY = 0;
|
||||
let isPanning = false;
|
||||
let startPanX = 0;
|
||||
let startPanY = 0;
|
||||
|
||||
// Canvas элементы
|
||||
const canvas = document.getElementById('mapCanvas');
|
||||
const ctx = canvas.getContext('2d');
|
||||
|
||||
// Инициализация
|
||||
function init() {
|
||||
initMap();
|
||||
resizeCanvas();
|
||||
drawMap();
|
||||
}
|
||||
|
||||
// Инициализация пустой карты
|
||||
function initMap() {
|
||||
map = Array(height).fill(null).map(() => Array(width).fill(0));
|
||||
}
|
||||
|
||||
function resizeCanvas() {
|
||||
const wrapper = canvas.parentElement;
|
||||
canvas.width = Math.max(1000, wrapper.clientWidth || 1000);
|
||||
canvas.height = Math.max(1000, wrapper.clientHeight || 1000);
|
||||
}
|
||||
|
||||
// Отрисовка карты
|
||||
function drawMap() {
|
||||
ctx.setTransform(1, 0, 0, 1, 0, 0);
|
||||
ctx.clearRect(0, 0, canvas.width, canvas.height);
|
||||
ctx.translate(offsetX, offsetY);
|
||||
ctx.scale(scale, scale);
|
||||
drawCells(ctx, map, width, height);
|
||||
drawGrid(ctx, width, height);
|
||||
drawMarkers(ctx, map, width, height);
|
||||
|
||||
if (trajectory.length > 0) {
|
||||
drawTrajectory();
|
||||
}
|
||||
}
|
||||
|
||||
// Рисование траектории решения
|
||||
function drawTrajectory() {
|
||||
if (!trajectory || trajectory.length === 0) return;
|
||||
|
||||
// Рисуем все предыдущие позиции как след
|
||||
ctx.strokeStyle = '#667eea';
|
||||
ctx.lineWidth = 3;
|
||||
ctx.lineCap = 'round';
|
||||
ctx.lineJoin = 'round';
|
||||
|
||||
ctx.beginPath();
|
||||
for (let i = 0; i <= currentStep && i < trajectory.length; i++) {
|
||||
const pos = trajectory[i];
|
||||
const screenX = pos.x * CELL_SIZE + CELL_SIZE / 2;
|
||||
const screenY = pos.y * CELL_SIZE + CELL_SIZE / 2;
|
||||
|
||||
if (i === 0) {
|
||||
ctx.moveTo(screenX, screenY);
|
||||
} else {
|
||||
ctx.lineTo(screenX, screenY);
|
||||
}
|
||||
}
|
||||
ctx.stroke();
|
||||
|
||||
// Рисуем точки на каждом шаге
|
||||
for (let i = 0; i <= currentStep && i < trajectory.length; i++) {
|
||||
const pos = trajectory[i];
|
||||
const screenX = pos.x * CELL_SIZE + CELL_SIZE / 2;
|
||||
const screenY = pos.y * CELL_SIZE + CELL_SIZE / 2;
|
||||
|
||||
ctx.beginPath();
|
||||
ctx.arc(screenX, screenY, 4, 0, Math.PI * 2);
|
||||
ctx.fillStyle = '#667eea';
|
||||
ctx.fill();
|
||||
ctx.strokeStyle = 'white';
|
||||
ctx.lineWidth = 2;
|
||||
ctx.stroke();
|
||||
}
|
||||
|
||||
// Рисуем текущую позицию большим кругом
|
||||
if (currentStep < trajectory.length) {
|
||||
const current = trajectory[currentStep];
|
||||
const screenX = current.x * CELL_SIZE + CELL_SIZE / 2;
|
||||
const screenY = current.y * CELL_SIZE + CELL_SIZE / 2;
|
||||
|
||||
// Пульсирующий эффект
|
||||
ctx.beginPath();
|
||||
ctx.arc(screenX, screenY, 10, 0, Math.PI * 2);
|
||||
ctx.fillStyle = '#f5576c';
|
||||
ctx.fill();
|
||||
ctx.strokeStyle = 'white';
|
||||
ctx.lineWidth = 3;
|
||||
ctx.stroke();
|
||||
|
||||
// Стрелка направления скорости
|
||||
if (current.vx !== 0 || current.vy !== 0) {
|
||||
const arrowLen = 20;
|
||||
const angle = Math.atan2(current.vy, current.vx);
|
||||
const endX = screenX + Math.cos(angle) * arrowLen;
|
||||
const endY = screenY + Math.sin(angle) * arrowLen;
|
||||
|
||||
ctx.beginPath();
|
||||
ctx.moveTo(screenX, screenY);
|
||||
ctx.lineTo(endX, endY);
|
||||
ctx.strokeStyle = '#f5576c';
|
||||
ctx.lineWidth = 3;
|
||||
ctx.stroke();
|
||||
|
||||
// Наконечник стрелки
|
||||
const headLen = 8;
|
||||
const headAngle = Math.PI / 6;
|
||||
ctx.beginPath();
|
||||
ctx.moveTo(endX, endY);
|
||||
ctx.lineTo(
|
||||
endX - headLen * Math.cos(angle - headAngle),
|
||||
endY - headLen * Math.sin(angle - headAngle)
|
||||
);
|
||||
ctx.moveTo(endX, endY);
|
||||
ctx.lineTo(
|
||||
endX - headLen * Math.cos(angle + headAngle),
|
||||
endY - headLen * Math.sin(angle + headAngle)
|
||||
);
|
||||
ctx.stroke();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Симуляция траектории на основе векторов ускорений
|
||||
function simulateTrajectory(accelerations, start) {
|
||||
const traj = [];
|
||||
let x = start.x;
|
||||
let y = start.y;
|
||||
let vx = 0;
|
||||
let vy = 0;
|
||||
|
||||
// Начальная позиция
|
||||
traj.push({ x, y, vx, vy, ax: 0, ay: 0 });
|
||||
|
||||
// Применяем каждое ускорение
|
||||
for (let i = 0; i < accelerations.length; i++) {
|
||||
const [ax, ay] = accelerations[i];
|
||||
|
||||
// Обновляем скорость
|
||||
vx += ax;
|
||||
vy += ay;
|
||||
|
||||
// Обновляем позицию
|
||||
x += vx;
|
||||
y += vy;
|
||||
|
||||
traj.push({ x, y, vx, vy, ax, ay });
|
||||
}
|
||||
|
||||
return traj;
|
||||
}
|
||||
|
||||
// Загрузка карты из JSON
|
||||
function loadMap(event) {
|
||||
const file = event.target.files[0];
|
||||
if (!file) return;
|
||||
|
||||
const reader = new FileReader();
|
||||
reader.onload = (e) => {
|
||||
try {
|
||||
const data = JSON.parse(e.target.result);
|
||||
const validated = validateMap(data);
|
||||
|
||||
// Импортируем карту
|
||||
height = validated.height;
|
||||
width = validated.width;
|
||||
map = validated.map;
|
||||
|
||||
// Очищаем траекторию при загрузке новой карты
|
||||
clearVisualization();
|
||||
|
||||
resizeCanvas();
|
||||
drawMap();
|
||||
|
||||
document.getElementById('loadMapBtn').textContent = '✓ Карта загружена';
|
||||
setTimeout(() => {
|
||||
document.getElementById('loadMapBtn').textContent = '📂 Загрузить карту';
|
||||
}, 2000);
|
||||
|
||||
alert('Карта успешно загружена!');
|
||||
} catch (error) {
|
||||
alert('Ошибка при загрузке карты: ' + error.message);
|
||||
console.error('Ошибка загрузки:', error);
|
||||
}
|
||||
};
|
||||
|
||||
reader.readAsText(file);
|
||||
event.target.value = '';
|
||||
}
|
||||
|
||||
// Загрузка решения из JSON
|
||||
function loadSolution(event) {
|
||||
const file = event.target.files[0];
|
||||
if (!file) return;
|
||||
|
||||
const reader = new FileReader();
|
||||
reader.onload = (e) => {
|
||||
try {
|
||||
const data = JSON.parse(e.target.result);
|
||||
|
||||
if (!data.solution || !Array.isArray(data.solution)) {
|
||||
throw new Error('Неверный формат: отсутствует массив solution');
|
||||
}
|
||||
|
||||
// Проверяем, что это массив массивов из двух чисел
|
||||
if (!data.solution.every(acc => Array.isArray(acc) && acc.length === 2)) {
|
||||
throw new Error('Неверный формат: solution должен быть массивом [[ax, ay], ...]');
|
||||
}
|
||||
|
||||
// Находим стартовую позицию
|
||||
startPosition = findStartPosition(map, width, height);
|
||||
if (!startPosition) {
|
||||
throw new Error('На карте не найдена точка старта (тип 5). Сначала загрузите карту с точкой старта.');
|
||||
}
|
||||
|
||||
solution = data.solution;
|
||||
trajectory = simulateTrajectory(solution, startPosition);
|
||||
currentStep = 0;
|
||||
|
||||
// Показываем панель визуализации
|
||||
document.getElementById('playbackControls').classList.remove('hidden');
|
||||
document.getElementById('stepInfo').classList.remove('hidden');
|
||||
|
||||
// Обновляем информацию
|
||||
updateStepInfo();
|
||||
drawMap();
|
||||
|
||||
document.getElementById('loadSolutionBtn').textContent = '✓ Решение загружено';
|
||||
setTimeout(() => {
|
||||
document.getElementById('loadSolutionBtn').textContent = '🎬 Загрузить решение';
|
||||
}, 2000);
|
||||
|
||||
alert(`Решение загружено! ${solution.length} шагов.`);
|
||||
} catch (error) {
|
||||
alert('Ошибка при загрузке решения: ' + error.message);
|
||||
console.error('Ошибка загрузки:', error);
|
||||
}
|
||||
};
|
||||
|
||||
reader.readAsText(file);
|
||||
event.target.value = '';
|
||||
}
|
||||
|
||||
// Обновление информации о текущем шаге
|
||||
function updateStepInfo() {
|
||||
if (!trajectory || trajectory.length === 0) return;
|
||||
|
||||
const current = trajectory[currentStep];
|
||||
|
||||
document.getElementById('stepNumber').textContent = `${currentStep} / ${trajectory.length - 1}`;
|
||||
document.getElementById('positionValue').textContent = `(${current.x}, ${current.y})`;
|
||||
document.getElementById('velocityValue').textContent = `(${current.vx}, ${current.vy})`;
|
||||
document.getElementById('accelerationValue').textContent = `(${current.ax}, ${current.ay})`;
|
||||
}
|
||||
|
||||
// Воспроизведение визуализации
|
||||
function playVisualization() {
|
||||
if (!trajectory || trajectory.length === 0) return;
|
||||
|
||||
isPlaying = true;
|
||||
document.getElementById('playBtn').disabled = true;
|
||||
document.getElementById('pauseBtn').disabled = false;
|
||||
|
||||
playbackInterval = setInterval(() => {
|
||||
if (currentStep < trajectory.length - 1) {
|
||||
currentStep++;
|
||||
updateStepInfo();
|
||||
drawMap();
|
||||
} else {
|
||||
pauseVisualization();
|
||||
}
|
||||
}, 1000 / playbackSpeed);
|
||||
}
|
||||
|
||||
// Пауза воспроизведения
|
||||
function pauseVisualization() {
|
||||
isPlaying = false;
|
||||
document.getElementById('playBtn').disabled = false;
|
||||
document.getElementById('pauseBtn').disabled = true;
|
||||
|
||||
if (playbackInterval) {
|
||||
clearInterval(playbackInterval);
|
||||
playbackInterval = null;
|
||||
}
|
||||
}
|
||||
|
||||
// Сброс визуализации
|
||||
function resetVisualization() {
|
||||
pauseVisualization();
|
||||
currentStep = 0;
|
||||
updateStepInfo();
|
||||
drawMap();
|
||||
}
|
||||
|
||||
// Шаг вперед
|
||||
function stepForward() {
|
||||
if (!trajectory || trajectory.length === 0) return;
|
||||
|
||||
if (currentStep < trajectory.length - 1) {
|
||||
currentStep++;
|
||||
updateStepInfo();
|
||||
drawMap();
|
||||
}
|
||||
}
|
||||
|
||||
// Шаг назад
|
||||
function stepBackward() {
|
||||
if (!trajectory || trajectory.length === 0) return;
|
||||
|
||||
if (currentStep > 0) {
|
||||
currentStep--;
|
||||
updateStepInfo();
|
||||
drawMap();
|
||||
}
|
||||
}
|
||||
|
||||
// Обновление скорости воспроизведения
|
||||
function updateSpeed() {
|
||||
playbackSpeed = parseInt(document.getElementById('speedSlider').value);
|
||||
document.getElementById('speedValue').textContent = `${playbackSpeed}x`;
|
||||
|
||||
// Если воспроизведение идет, перезапускаем с новой скоростью
|
||||
if (isPlaying) {
|
||||
pauseVisualization();
|
||||
playVisualization();
|
||||
}
|
||||
}
|
||||
|
||||
// Очистка визуализации
|
||||
function clearVisualization() {
|
||||
pauseVisualization();
|
||||
solution = null;
|
||||
trajectory = [];
|
||||
currentStep = 0;
|
||||
startPosition = null;
|
||||
|
||||
document.getElementById('playbackControls').classList.add('hidden');
|
||||
document.getElementById('stepInfo').classList.add('hidden');
|
||||
|
||||
drawMap();
|
||||
}
|
||||
|
||||
canvas.addEventListener('mousedown', (e) => {
|
||||
if (e.button === 2 || e.shiftKey) {
|
||||
isPanning = true;
|
||||
startPanX = e.clientX - offsetX;
|
||||
startPanY = e.clientY - offsetY;
|
||||
canvas.style.cursor = 'grabbing';
|
||||
}
|
||||
});
|
||||
|
||||
canvas.addEventListener('mousemove', (e) => {
|
||||
if (isPanning) {
|
||||
offsetX = e.clientX - startPanX;
|
||||
offsetY = e.clientY - startPanY;
|
||||
drawMap();
|
||||
}
|
||||
});
|
||||
|
||||
canvas.addEventListener('mouseup', () => {
|
||||
isPanning = false;
|
||||
canvas.style.cursor = 'default';
|
||||
});
|
||||
|
||||
canvas.addEventListener('mouseleave', () => {
|
||||
isPanning = false;
|
||||
canvas.style.cursor = 'default';
|
||||
});
|
||||
|
||||
canvas.addEventListener('wheel', (e) => {
|
||||
e.preventDefault();
|
||||
const rect = canvas.getBoundingClientRect();
|
||||
const mouseX = e.clientX - rect.left;
|
||||
const mouseY = e.clientY - rect.top;
|
||||
const zoom = e.deltaY < 0 ? 1.1 : 0.9;
|
||||
const newScale = Math.min(Math.max(0.1, scale * zoom), 5);
|
||||
|
||||
offsetX = mouseX - (mouseX - offsetX) * (newScale / scale);
|
||||
offsetY = mouseY - (mouseY - offsetY) * (newScale / scale);
|
||||
scale = newScale;
|
||||
|
||||
drawMap();
|
||||
});
|
||||
|
||||
canvas.addEventListener('contextmenu', (e) => e.preventDefault());
|
||||
|
||||
window.addEventListener('resize', () => {
|
||||
resizeCanvas();
|
||||
drawMap();
|
||||
});
|
||||
|
||||
init();
|
||||
|
||||
366
racing-tools/styles.css
Normal file
366
racing-tools/styles.css
Normal file
@@ -0,0 +1,366 @@
|
||||
* {
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
box-sizing: border-box;
|
||||
}
|
||||
|
||||
body {
|
||||
font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
|
||||
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
|
||||
min-height: 100vh;
|
||||
padding: 20px;
|
||||
display: flex;
|
||||
justify-content: center;
|
||||
align-items: flex-start;
|
||||
}
|
||||
|
||||
.container {
|
||||
background: white;
|
||||
border-radius: 20px;
|
||||
box-shadow: 0 20px 60px rgba(0, 0, 0, 0.3);
|
||||
padding: 30px;
|
||||
width: 100%;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
min-height: calc(100vh - 40px);
|
||||
}
|
||||
|
||||
h1 {
|
||||
text-align: center;
|
||||
color: #333;
|
||||
margin-bottom: 10px;
|
||||
font-size: 2em;
|
||||
}
|
||||
|
||||
.subtitle {
|
||||
text-align: center;
|
||||
color: #666;
|
||||
margin-bottom: 20px;
|
||||
font-size: 0.9em;
|
||||
}
|
||||
|
||||
.nav-links {
|
||||
text-align: center;
|
||||
margin-bottom: 20px;
|
||||
padding: 15px;
|
||||
background: #f8f9fa;
|
||||
border-radius: 10px;
|
||||
}
|
||||
|
||||
.nav-links a {
|
||||
margin: 0 15px;
|
||||
padding: 10px 20px;
|
||||
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
|
||||
color: white;
|
||||
text-decoration: none;
|
||||
border-radius: 8px;
|
||||
font-weight: 600;
|
||||
transition: all 0.3s;
|
||||
display: inline-block;
|
||||
}
|
||||
|
||||
.nav-links a:hover {
|
||||
transform: translateY(-2px);
|
||||
box-shadow: 0 5px 15px rgba(0, 0, 0, 0.2);
|
||||
}
|
||||
|
||||
.controls {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
|
||||
gap: 20px;
|
||||
margin-bottom: 30px;
|
||||
}
|
||||
|
||||
.control-group {
|
||||
background: #f8f9fa;
|
||||
padding: 20px;
|
||||
border-radius: 12px;
|
||||
border: 2px solid #e9ecef;
|
||||
}
|
||||
|
||||
.control-group h3 {
|
||||
margin-bottom: 15px;
|
||||
color: #495057;
|
||||
font-size: 1.1em;
|
||||
border-bottom: 2px solid #dee2e6;
|
||||
padding-bottom: 8px;
|
||||
}
|
||||
|
||||
.size-inputs {
|
||||
display: flex;
|
||||
gap: 15px;
|
||||
margin-bottom: 15px;
|
||||
}
|
||||
|
||||
.input-wrapper {
|
||||
flex: 1;
|
||||
}
|
||||
|
||||
.input-wrapper label {
|
||||
display: block;
|
||||
margin-bottom: 5px;
|
||||
color: #495057;
|
||||
font-weight: 500;
|
||||
font-size: 0.9em;
|
||||
}
|
||||
|
||||
.input-wrapper input {
|
||||
width: 100%;
|
||||
padding: 10px;
|
||||
border: 2px solid #dee2e6;
|
||||
border-radius: 8px;
|
||||
font-size: 16px;
|
||||
transition: border-color 0.3s;
|
||||
}
|
||||
|
||||
.input-wrapper input:focus {
|
||||
outline: none;
|
||||
border-color: #667eea;
|
||||
}
|
||||
|
||||
.palette {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(auto-fit, minmax(100px, 1fr));
|
||||
gap: 10px;
|
||||
}
|
||||
|
||||
.cell-type {
|
||||
padding: 15px;
|
||||
border: 3px solid #dee2e6;
|
||||
border-radius: 10px;
|
||||
cursor: pointer;
|
||||
transition: all 0.3s;
|
||||
text-align: center;
|
||||
font-weight: 600;
|
||||
position: relative;
|
||||
}
|
||||
|
||||
.cell-type:hover {
|
||||
transform: translateY(-3px);
|
||||
box-shadow: 0 5px 15px rgba(0, 0, 0, 0.2);
|
||||
}
|
||||
|
||||
.cell-type.active {
|
||||
border-color: #667eea;
|
||||
box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.2);
|
||||
transform: scale(1.05);
|
||||
}
|
||||
|
||||
.cell-type .code {
|
||||
font-size: 0.8em;
|
||||
color: #6c757d;
|
||||
display: block;
|
||||
margin-top: 5px;
|
||||
}
|
||||
|
||||
.road { background: #f8f9fa; color: #495057; }
|
||||
.stone { background: #6c757d; color: white; }
|
||||
.snow { background: #e3f2fd; color: #1976d2; }
|
||||
.ice { background: #b3e5fc; color: #0277bd; }
|
||||
.checkpoint { background: #fff3cd; color: #856404; border-color: #ffc107 !important; }
|
||||
.start { background: #d4edda; color: #155724; border-color: #28a745 !important; }
|
||||
|
||||
.buttons {
|
||||
display: flex;
|
||||
gap: 10px;
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
|
||||
button {
|
||||
flex: 1;
|
||||
padding: 12px 24px;
|
||||
border: none;
|
||||
border-radius: 8px;
|
||||
font-size: 16px;
|
||||
font-weight: 600;
|
||||
cursor: pointer;
|
||||
transition: all 0.3s;
|
||||
min-width: 120px;
|
||||
}
|
||||
|
||||
button:hover {
|
||||
transform: translateY(-2px);
|
||||
box-shadow: 0 5px 15px rgba(0, 0, 0, 0.2);
|
||||
}
|
||||
|
||||
button:active {
|
||||
transform: translateY(0);
|
||||
}
|
||||
|
||||
button:disabled {
|
||||
opacity: 0.5;
|
||||
cursor: not-allowed;
|
||||
transform: none;
|
||||
}
|
||||
|
||||
.btn-primary {
|
||||
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
|
||||
color: white;
|
||||
}
|
||||
|
||||
.btn-success {
|
||||
background: linear-gradient(135deg, #43e97b 0%, #38f9d7 100%);
|
||||
color: #333;
|
||||
}
|
||||
|
||||
.btn-warning {
|
||||
background: linear-gradient(135deg, #fa709a 0%, #fee140 100%);
|
||||
color: #333;
|
||||
}
|
||||
|
||||
.btn-danger {
|
||||
background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
|
||||
color: white;
|
||||
}
|
||||
|
||||
.canvas-wrapper {
|
||||
margin-top: 30px;
|
||||
display: flex;
|
||||
justify-content: center;
|
||||
align-items: center;
|
||||
background: #f8f9fa;
|
||||
padding: 20px;
|
||||
border-radius: 12px;
|
||||
overflow: hidden;
|
||||
flex: 1;
|
||||
min-height: 1000px;
|
||||
position: relative;
|
||||
}
|
||||
|
||||
canvas {
|
||||
border: 3px solid #dee2e6;
|
||||
border-radius: 8px;
|
||||
cursor: crosshair;
|
||||
box-shadow: 0 5px 20px rgba(0, 0, 0, 0.1);
|
||||
max-width: 100%;
|
||||
max-height: 100%;
|
||||
}
|
||||
|
||||
.info {
|
||||
margin-top: 20px;
|
||||
padding: 15px;
|
||||
background: #e7f3ff;
|
||||
border-left: 4px solid #2196f3;
|
||||
border-radius: 8px;
|
||||
color: #0d47a1;
|
||||
}
|
||||
|
||||
.info strong {
|
||||
display: block;
|
||||
margin-bottom: 5px;
|
||||
}
|
||||
|
||||
#fileInput, #mapInput, #solutionInput {
|
||||
display: none;
|
||||
}
|
||||
|
||||
.legend {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(auto-fit, minmax(150px, 1fr));
|
||||
gap: 10px;
|
||||
margin-top: 15px;
|
||||
}
|
||||
|
||||
.legend-item {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 10px;
|
||||
padding: 8px;
|
||||
background: white;
|
||||
border-radius: 6px;
|
||||
}
|
||||
|
||||
.legend-color {
|
||||
width: 30px;
|
||||
height: 30px;
|
||||
border-radius: 4px;
|
||||
border: 2px solid #dee2e6;
|
||||
}
|
||||
|
||||
/* Стили для визуализатора */
|
||||
.playback-controls {
|
||||
display: flex;
|
||||
gap: 10px;
|
||||
align-items: center;
|
||||
flex-wrap: wrap;
|
||||
margin-top: 15px;
|
||||
}
|
||||
|
||||
.playback-btn {
|
||||
padding: 10px 20px;
|
||||
border: none;
|
||||
border-radius: 8px;
|
||||
font-size: 16px;
|
||||
font-weight: 600;
|
||||
cursor: pointer;
|
||||
transition: all 0.3s;
|
||||
background: #667eea;
|
||||
color: white;
|
||||
min-width: auto;
|
||||
}
|
||||
|
||||
.playback-btn:hover {
|
||||
transform: translateY(-2px);
|
||||
box-shadow: 0 5px 15px rgba(0, 0, 0, 0.2);
|
||||
}
|
||||
|
||||
.playback-btn:disabled {
|
||||
opacity: 0.5;
|
||||
cursor: not-allowed;
|
||||
transform: none;
|
||||
}
|
||||
|
||||
.speed-control {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 10px;
|
||||
}
|
||||
|
||||
.speed-control input[type="range"] {
|
||||
width: 150px;
|
||||
}
|
||||
|
||||
.step-info {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
|
||||
gap: 15px;
|
||||
margin-top: 15px;
|
||||
padding: 15px;
|
||||
background: white;
|
||||
border-radius: 8px;
|
||||
}
|
||||
|
||||
.info-item {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
}
|
||||
|
||||
.info-label {
|
||||
font-size: 0.85em;
|
||||
color: #6c757d;
|
||||
margin-bottom: 5px;
|
||||
}
|
||||
|
||||
.info-value {
|
||||
font-size: 1.2em;
|
||||
font-weight: 600;
|
||||
color: #333;
|
||||
}
|
||||
|
||||
.hidden {
|
||||
display: none;
|
||||
}
|
||||
|
||||
.visualization-panel {
|
||||
margin-top: 20px;
|
||||
padding: 20px;
|
||||
background: #f8f9fa;
|
||||
border-radius: 12px;
|
||||
border: 2px solid #dee2e6;
|
||||
}
|
||||
|
||||
.visualization-panel h3 {
|
||||
margin-bottom: 15px;
|
||||
color: #495057;
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user