-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest-pathfinder.html
More file actions
244 lines (226 loc) · 8.05 KB
/
test-pathfinder.html
File metadata and controls
244 lines (226 loc) · 8.05 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
<!DOCTYPE html>
<html lang="ru">
<head>
<meta charset="UTF-8" />
<title>05 Pathfinder Test</title>
<style>
body { background: #111; color: white; font-family: sans-serif; margin: 0; padding: 0; }
canvas { display: block; margin: 20px auto; background: #222; border: 1px solid #666; }
.toolbar {
display: flex;
flex-wrap: wrap;
gap: 8px;
justify-content: center;
margin: 10px auto;
max-width: 800px;
}
.toolbar > * {
margin: 4px;
}
button, select, input[type="number"] {
padding: 6px;
font-size: 14px;
background: #333;
color: white;
border: 1px solid #666;
border-radius: 4px;
cursor: pointer;
}
.labelled {
display: flex;
align-items: center;
gap: 4px;
color: white;
}
.log {
max-width: 800px;
margin: 0 auto;
background: #1a1a1a;
padding: 10px;
font-size: 12px;
height: 100px;
overflow-y: auto;
border-top: 1px solid #333;
white-space: pre-wrap;
font-family: monospace;
}
</style>
</head>
<body>
<h2 align="center">05 🧝 Pathfinder UI Тест</h2>
<canvas id="grid-canvas" width="480" height="480"></canvas>
<div class="toolbar">
<button id="tool-wall">🧱 Стена</button>
<button id="tool-start">🟢 Старт</button>
<button id="tool-goal">🔴 Финиш</button>
<!-- кнопка добавления спавна не используется в test-pathfinder.js, можно убрать или оставить -->
<!--<button id="addSpawnerBtn">➕ Добавить спавн</button>-->
<button id="resetBtn">♻️ Сброс</button>
<button id="runBtn">▶️ Пуск</button>
<div class="labelled">
<label for="speedRange">Скорость:</label>
<input type="range" id="speedRange" min="1" max="10" value="5" />
<input type="number" id="speedInput" min="1" max="10" value="5" />
</div>
<div class="labelled">
<label for="moveMode">Режим перемещения:</label>
<select id="moveMode">
<option value="4">4 стороны</option>
<option value="8">8 сторон</option>
<option value="8nc">8 сторон (без проверки диагоналей)</option>
<option value="16">16 направлений</option>
<option value="32">32 направления</option>
</select>
</div>
</div>
<div class="log" id="log"></div>
<script type="module">
import {
selectTool,
updateSpeed,
updateMoveMode,
resetGrid,
draw,
startOrders,
addSpawner,
setPathForSpawner,
updateGrid,
getPathForSpawner
} from './test-pathfinder.js';
const logElem = document.getElementById('log');
const canvas = document.getElementById('grid-canvas');
const ctx = canvas.getContext('2d');
let currentSpawnerId = 1;
let movementMode = '4'; // строка для удобства работы с новыми режимами
let speed = 5;
let selectedToolName = 'wall';
let goal = { x: 14, y: 7 };
let gridWidth = 15;
let gridHeight = 15;
const cellSize = 32;
let spawnersUI = {};
function log(message) {
const time = new Date().toLocaleTimeString();
logElem.textContent += `[${time}] ${message}\n`;
logElem.scrollTop = logElem.scrollHeight;
console.info(message);
}
function getRandomColor() {
const colors = ['#007bff', '#28a745', '#dc3545', '#ffc107', '#6f42c1'];
return colors[Math.floor(Math.random() * colors.length)];
}
function onSpeedChange(value) {
speed = Math.max(1, Math.min(10, parseInt(value)));
document.getElementById('speedRange').value = speed;
document.getElementById('speedInput').value = speed;
updateSpeed(speed);
log(`Скорость установлена: ${speed}`);
}
function onMoveModeChange() {
const modeSelect = document.getElementById('moveMode');
movementMode = modeSelect.value; // строка: '4', '8', '8nc', '16', '32'
updateMoveMode(movementMode); // Передаем текущий режим
// Для корректного отображения режима в логе берём текст выбранного option
const modeText = modeSelect.options[modeSelect.selectedIndex].text;
log(`Режим перемещения установлен: ${modeText}`);
for (const id in spawnersUI) {
setPathForSpawner(id, spawnersUI[id].pos, goal, movementMode);
}
draw();
}
canvas.addEventListener('click', e => {
const rect = canvas.getBoundingClientRect();
const x = Math.floor((e.clientX - rect.left) / cellSize);
const y = Math.floor((e.clientY - rect.top) / cellSize);
if (x < 0 || y < 0 || x >= gridWidth || y >= gridHeight) return;
switch (selectedToolName) {
case 'wall': toggleWallAt(x, y); break;
case 'goal': goal = { x, y }; log(`Новая точка финиша: (${x},${y})`); break;
case 'start': addNewSpawner(x, y); break;
}
updateGridState();
draw();
});
function toggleWallAt(x, y) {
if (!window._grid) {
window._grid = Array.from({ length: gridHeight }, () => Array(gridWidth).fill(0));
}
window._grid[y][x] = window._grid[y][x] === 1 ? 0 : 1;
updateGrid(window._grid);
log(`Стена ${window._grid[y][x] === 1 ? 'установлена' : 'удалена'} в (${x},${y})`);
}
function addNewSpawner(x, y) {
const id = `S${currentSpawnerId++}`;
const color = getRandomColor();
spawnersUI[id] = { pos: { x, y }, color };
addSpawner(id, { x, y }, goal, movementMode);
log(`Спавн "${id}" добавлен на (${x},${y})`);
}
function updateGridState() {
for (const id in spawnersUI) {
setPathForSpawner(id, spawnersUI[id].pos, goal, movementMode);
}
}
// Используйте addEventListener вместо прямого присвоения обработчиков, чтобы избежать возможных конфликтов и улучшить читаемость
document.getElementById('tool-wall').addEventListener('click', () => {
selectedToolName = 'wall';
selectTool('wall');
log('Выбран инструмент: Стена');
});
document.getElementById('tool-start').addEventListener('click', () => {
selectedToolName = 'start';
selectTool('start');
log('Выбран инструмент: Старт');
});
document.getElementById('tool-goal').addEventListener('click', () => {
selectedToolName = 'goal';
selectTool('goal');
log('Выбран инструмент: Финиш');
});
document.getElementById('resetBtn').addEventListener('click', () => {
resetGrid();
window._grid = Array.from({ length: gridHeight }, () => Array(gridWidth).fill(0));
spawnersUI = {};
currentSpawnerId = 1;
goal = { x: 14, y: 7 };
log('Сетка и спавны сброшены');
redraw();
});
document.getElementById('runBtn').addEventListener('click', () => {
if (Object.keys(spawnersUI).length === 0) {
log('Нет спавнов для движения');
return;
}
startOrders();
log('Движение запущено');
});
document.getElementById('speedRange').addEventListener('input', e => onSpeedChange(e.target.value));
document.getElementById('speedInput').addEventListener('change', e => onSpeedChange(e.target.value));
document.getElementById('moveMode').addEventListener('change', onMoveModeChange);
(function init() {
window._grid = Array.from({ length: gridHeight }, () => Array(gridWidth).fill(0));
resetGrid();
redraw();
log('Инициализация завершена. Выберите инструмент и начните работу.');
})();
(function verifyFunctions() {
const funcs = [
'selectTool',
'updateSpeed',
'updateMoveMode',
'resetGrid',
'draw',
'startOrders',
'addSpawner',
'setPathForSpawner',
'updateGrid',
'getPathForSpawner'
];
funcs.forEach(fnName => {
if (typeof window[fnName] !== 'function') {
log(`[❌] Функция \`${fnName}()\` не определена`);
} else {
log(`[✅] \`${fnName}()\` готова`);
}
});
})();