-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.ts
336 lines (303 loc) · 8.22 KB
/
index.ts
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
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
import { SVG, Timeline, Svg } from "@svgdotjs/svg.js";
const IMPOSSIBLE = [15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0];
const GOAL_ORDINAL = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 0, 15];
let currentState = [];
const DIRECTIONS = {
l: { text: "left", id: "l", emoji: "⬅", key: 37 },
u: { text: "up", id: "u", emoji: "⬆", key: 38 },
r: { text: "right", id: "r", emoji: "⮕", key: 39 },
d: { text: "down", id: "d", emoji: "⬇ ", key: 40 },
};
let board;
function getXforMN(m, n) {
return (index) => index % n;
}
function getYforMN(m, n) {
return (index) => Math.floor(index / m);
}
function repeat(elem, times) {
return Array(times).fill(elem);
}
function calculateNextSteps(
{
currentState,
m,
n,
getY,
}: { currentState: number[]; m: number; n: number; getY: (a: number) => any },
pressedTile: number
) {
let steps = [];
if (pressedTile !== 0) {
const indexOfPressedTile = currentState.indexOf(pressedTile);
console.log(indexOfPressedTile);
//Check horizon axis
for (let i = 1; i < m; i++) {
const row = getY(indexOfPressedTile);
const nextR = row * m + ((indexOfPressedTile + i) % m);
if (currentState[nextR] === 0) {
const diff = indexOfPressedTile - nextR;
steps = repeat(
diff < 0 ? DIRECTIONS["r"].id : DIRECTIONS["l"].id,
Math.abs(diff)
);
continue;
}
}
if (!steps.length) {
//Check vertical axis
for (let j = 1; j < n; j++) {
const nextC = (indexOfPressedTile + j * n) % (m * n);
if (currentState[nextC] === 0) {
const diff = (indexOfPressedTile - nextC) / 4;
steps = repeat(
diff < 0 ? DIRECTIONS["d"].id : DIRECTIONS["u"].id,
Math.abs(diff)
);
continue;
}
}
}
}
return steps;
}
function executeSteps({ currentState }, steps) {
let newState = currentState;
for (let i = 0; i < steps.length; i++) {
newState = executeStep(newState, steps[i]);
}
return newState;
}
function executeStep(currentState, step) {
let i0 = currentState.indexOf(0);
let newState = [...currentState];
let temp, newPosition;
switch (step) {
case DIRECTIONS["u"].id:
newPosition = i0 + 4;
break;
case DIRECTIONS["r"].id:
newPosition = i0 - 1;
break;
case DIRECTIONS["d"].id:
newPosition = i0 - 4;
break;
case DIRECTIONS["l"].id:
newPosition = i0 + 1;
break;
default:
break;
}
newState[i0] = newState[newPosition];
newState[newPosition] = 0;
if (arraysEqual(newState, IMPOSSIBLE)) {
alert("You made the impossible, possible!!");
}
return newState;
}
function tilePressed(index) {
return (e) => {
const newSteps = calculateNextSteps(board, index);
const newState = executeSteps(board, newSteps);
console.log({ newState, newSteps });
animateToNewState(newState).play();
board.currentState = [...newState];
board.steps = [...board.steps, ...newSteps];
console.log(board.steps.map((s) => DIRECTIONS[s].emoji));
};
}
function createBoard() {
const squareSize = 70;
const m = 4,
n = 4;
const getX = getXforMN(m, n),
getY = getYforMN(m, n);
var draw = SVG()
.addTo("#puzzle-15")
.size(m * squareSize, n * squareSize);
let board = {
m,
n,
getX,
getY,
squareSize,
currentState: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 0],
tiles: {},
steps: [],
};
for (let i = 0; i < board.currentState.length; i++) {
const tileId = i === m * n - 1 ? 0 : i + 1;
const tile = draw
.nested()
.size(squareSize, squareSize)
.move(getX(i) * squareSize, getY(i) * squareSize)
.on("click", tilePressed(tileId));
const rect = tile
.rect(squareSize, squareSize)
.radius(10)
.addClass("tile")
.addClass(i % 2 ? "tile-a" : "tile-b");
if (i + 1 === m * n) {
tile.addClass("empty-tile");
tile.back();
}
tile.plain(String(tileId)).attr({
x: "50%",
y: "50%",
"alignment-baseline": "middle",
"text-anchor": "middle",
});
tile.plain(",").attr({
x: "80%",
y: "50%",
"alignment-baseline": "middle",
"text-anchor": "middle",
opacity: 0,
});
tile.data("tileId", tileId);
board.tiles[tileId] = tile;
}
return board;
}
function animateToNewState(newState) {
const moves = {};
var timeline = new Timeline();
timeline.pause();
for (let index = 0; index < board.currentState.length; index++) {
const currentTileId = board.currentState[index];
const tile = board.tiles[currentTileId] as Svg;
if (tile.data("tileId") !== newState[index]) {
board.tiles[newState[index]]
.timeline(timeline)
.animate(200, 0, "absolute")
.move(
board.getX(index) * board.squareSize,
board.getY(index) * board.squareSize
);
//Move the the tile from newState to to new state (index)
}
}
//Return timeline to give control. .play is necessary
return timeline;
}
function moveCommand(direction, steps) {
switch (direction) {
case DIRECTIONS["u"].id:
break;
case DIRECTIONS["r"].id:
break;
case DIRECTIONS["d"].id:
break;
case DIRECTIONS["l"].id:
break;
default:
break;
}
}
function addKeyboardListeners() {
document.onkeydown = checkKey;
}
function checkKey(e) {
e = e || window.event;
let validDirection;
switch (e.keyCode) {
case DIRECTIONS["l"].key:
console.log(DIRECTIONS["l"].emoji);
validDirection = DIRECTIONS["l"];
break;
case DIRECTIONS["u"].key:
console.log(DIRECTIONS["u"].emoji);
validDirection = DIRECTIONS["u"];
break;
case DIRECTIONS["d"].key:
console.log(DIRECTIONS["d"].emoji);
validDirection = DIRECTIONS["d"];
break;
case DIRECTIONS["r"].key:
console.log(DIRECTIONS["r"].emoji);
validDirection = DIRECTIONS["r"];
break;
default:
break;
}
if (validDirection) {
//Todo:refactor to something more comprehensible and safe
const newState = executeStep(board.currentState, validDirection.id);
animateToNewState(newState).play();
board.currentState = [...newState];
board.steps = [...board.steps, validDirection.id];
}
}
function arraysEqual(a1, a2) {
return JSON.stringify(a1) == JSON.stringify(a2);
}
function getValidShuffle(currentState = GOAL_ORDINAL) {
let newState = randomSwap(randomSwap(currentState));
console.log({newState});
const originalSolvability = isSolvableToOriginal(currentState);
while(isSolvableToOriginal(newState)!==originalSolvability ){
newState = randomSwap(currentState);
console.log({newState});
}
return newState;
}
/* New array with random swapped elements. */
function randomSwap(arr) {
const a = getRandomInt(0, arr.length);
let b = a;
while (b === a) {
b = getRandomInt(0, arr.length);
}
const newArr = [...arr];
newArr[a] = newArr[b];
newArr[b] = arr[a];
return newArr;
}
function calculateHeuristic(objectiveState, currentState) {
let h = 0;
currentState.forEach((e, i) => {});
return h;
}
function getRandomInt(min, max) {
return Math.floor(Math.random() * (max - min)) + min;
}
function prepareShuffleControl() {
document.getElementById("shuffle").addEventListener(
"click",
() => {
console.log("Shuffle");
const newState = getValidShuffle(board.currentState);
animateToNewState(newState).play();
board.currentState = newState;
},
false
);
}
function getInversionCount(state) {
//TODO: find O(nLogn) solution
let count = 0;
for (let i = 0; i < state.length - 1; i++) {
const ti = state[i];
for (let j = i + 1; j < state.length; j++) {
const tj = state[j];
if (ti && tj && ti > tj) {
count++;
}
}
}
return count;
}
function isSolvableToOriginal(state) {
const inversionCount = getInversionCount(state);
// As puzzle15 is 4x4, the pos of the empty cell matters.
const zeroTilePosition = state.indexOf(0);
// xor
return !!((Math.floor(zeroTilePosition / 4)& 1) ^ (inversionCount & 1));
}
function main() {
board = createBoard();
addKeyboardListeners();
prepareShuffleControl();
console.log({ getValidShuffle, calculateHeuristic });
}
main();