Repository navigation
Expand file tree
/
Copy pathapp.js
More file actions
353 lines (264 loc) · 10.6 KB
/
Copy pathapp.js
File metadata and controls
353 lines (264 loc) · 10.6 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
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
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
//Listas para valores de colores y alturas de las figuras
const colors = ['red', 'blue', 'green', 'yellow', 'purple', 'orange', 'pink', 'brown', 'black', 'cian', 'gray'];
//Listas de los datos asignados a cada figura
const heights = [];
const colorsAssigned = [];
//Logica para la creacion de contenedores y figuras arrastrables que el jugador eligio
const inputFigures = document.getElementById("inputFigures");
const btnFigures = document.getElementById("btnFigures");
const binToAdd = document.querySelector('.carga');
const containerBins = document.querySelector(".containerBins");
btnFigures.addEventListener("click", function () {
if (isNaN(inputFigures.value) || inputFigures.value <= 0) {
alertsDiv.style.visibility = "visible";
alertMsg.textContent = "Ingrese un número válido mayor que cero.";
} else {
binToAdd.innerHTML = '';
for (let i = 1; i <= inputFigures.value; i++) {
const randomColor = Math.floor((Math.random() * colors.length) + 1);
const randomHeight = Math.floor(Math.random() * 300);
const newDiv = document.createElement('div');
newDiv.setAttribute('class', 'figure');
newDiv.setAttribute('draggable', 'true');
newDiv.setAttribute('ondragstart', 'onDragStart(event);');
newDiv.setAttribute('id', 'draggable-' + i);
newDiv.style.backgroundColor = colors[randomColor];
newDiv.style.height = randomHeight + 'px';
newDiv.textContent = randomHeight;
binToAdd.appendChild(newDiv);
heights.push(randomHeight);
colorsAssigned.push(randomColor);
const figuresCreated = binToAdd.childElementCount;
figuresCreatedInfo.textContent = 'N° paquetes: ' + figuresCreated;
}
}
if (binToAdd.childElementCount > 0) {
btnFigures.disabled = true;
btnFigures.style.cursor = 'not-allowed';
inputBins.disabled = false;
inputFigures.disabled = true;
}
//console.log(colorsAssigned);
console.log(heights);
});
var bins = [];
const inputBins = document.getElementById("inputBins");
const btnBins = document.getElementById("btnBins");
btnBins.addEventListener("click", function () {
if (isNaN(inputBins.value) || inputBins.value <= 0) {
alertsDiv.style.visibility = "visible";
alertMsg.textContent = "Ingrese un número válido mayor que cero.";
}
if (cash >= 10 && inputBins.value <= 10) {
for (let i = 0; i < inputBins.value; i++) {
const newBin = document.createElement('div');
newBin.setAttribute('class', 'bin');
newBin.setAttribute('ondragover', 'onDragOver(event);');
newBin.setAttribute('ondrop', 'onDrop(event);');
newBin.setAttribute('id', 'bin');
containerBins.appendChild(newBin);
cash = cash - 10;
cashInfo.textContent = '$ disponible: $' + cash;
const binsCreated = containerBins.childElementCount;
binsInfo.textContent = 'N° contenedores: ' + binsCreated;
bins.push(newBin);
}
}
else {
alertsDiv.style.visibility = "visible";
alertMsg.textContent = "Excede el limite de dinero disponible.";
}
if (containerBins.childElementCount > 1) {
btnBins.disabled = true;
btnBins.style.cursor = 'not-allowed';
inputBins.disabled = true;
btnExtraBin.disabled = false;
btnExtraBin.style.cursor = 'pointer';
}
});
//Informacion del juego
const divInfoGame = document.querySelector(".info-game");
const figuresCreatedInfo = document.getElementById("figures-created-info");
const figuresInfo = document.getElementById("figures-dropped-info");
const cashInfo = document.getElementById("cash-info");
var cash = 100;
const binsInfo = document.getElementById("used-containers-info");
figuresCreatedInfo.textContent = 'N° paquetes: ';
cashInfo.textContent = '$ disponible: $' + cash + ' (cada contenedor cuesta $10)'
figuresInfo.textContent = 'Capacidad por contenedor: 500';
binsInfo.textContent = 'N° contenedores: ';
// Boton para agregar contenedor extra (A DOBLE DE PRECIO)
const btnExtraBin = document.querySelector('.btnExtraBin')
btnExtraBin.disabled = true;
btnExtraBin.style.cursor = 'not-allowed';
btnExtraBin.addEventListener('click', function () {
if (cash >= 20) {
const newBin = document.createElement('div');
newBin.setAttribute('class', 'bin');
newBin.setAttribute('ondragover', 'onDragOver(event);');
newBin.setAttribute('ondrop', 'onDrop(event);');
newBin.setAttribute('id', 'bin');
containerBins.appendChild(newBin);
cash = cash - 20;
cashInfo.textContent = '$ disponible: $' + cash;
const binsCreated = containerBins.childElementCount;
binsInfo.textContent = 'N° contenedores: ' + binsCreated;
bins.push(newBin);
}
else {
alertsDiv.style.visibility = "visible";
alertMsg.textContent = "Excede el limite de dinero disponible.";
}
});
//Funcion que cambia atributos de CCS cuando se arrastra un elemento
function onDragStart(event) {
event
.dataTransfer
.setData('text/plain', event.target.id);
event
.currentTarget
.style
.opacity = '0.7';
event
.currentTarget
.style
.border = 'none';
}
function onDragOver(event) {
event.preventDefault();
}
let limiteBin = 500;
const containers = document.querySelectorAll('.bin');
function onDrop(event) {
const id = event.dataTransfer.getData('text');
const draggableElement = document.getElementById(id);
const dropzone = event.target;
const currentContainer = dropzone.closest('.bin');
const currentBinLimit = limiteBin;
const figuresInsideBin = currentContainer.querySelectorAll('.figure');
let currentBinUsedSpace = 0;
figuresInsideBin.forEach((figure) => {
currentBinUsedSpace += parseInt(figure.textContent, 10);
});
if (currentBinUsedSpace + parseInt(draggableElement.textContent, 10) <= currentBinLimit) {
dropzone.appendChild(draggableElement);
event.dataTransfer.clearData();
} else {
alertsDiv.style.visibility = "visible";
alertMsg.textContent = "Excede el límite de espacio en el contenedor.";
}
}
//Permitir cambiar el orden de los productos dentro del contenedor
const carga = document.querySelector('.carga');
let draggedElement = null;
carga.addEventListener('dragstart', (event) => {
draggedElement = event.target;
});
carga.addEventListener('dragover', (event) => {
event.preventDefault();
});
carga.addEventListener('drop', handleDrop);
function handleDrop(event) {
event.preventDefault();
const target = event.target;
if (target.classList.contains('figure')) {
carga.insertBefore(draggedElement, target);
} else {
carga.appendChild(draggedElement);
}
}
function allowDrop(event) {
event.preventDefault();
}
// Restaura la capacidad total del contenedor cuando todas las figuras se eliminan
containers.forEach((container) => {
container.addEventListener('DOMNodeRemoved', () => {
limiteBin = 500;
});
});
//Alertas de juego
const alertsDiv = document.getElementById("alertsDiv");
const alertMsg = document.getElementById("alertMsg");
const btnAlertAccept = document.getElementById("btnAlertAccept");
btnAlertAccept.addEventListener("click", function () {
alertsDiv.style.visibility = "hidden";
});
// Quicksort para ordenar las figuras de mayor a menor
function quicksort(arr) {
if (arr.length <= 1) {
return arr;
}
// Elegir un pivote (puede ser el primer elemento)
const pivot = arr[0];
// Dividir el array en dos sub-arrays: elementos menores que el pivote y elementos mayores que el pivote
const left = [];
const right = [];
for (let i = 1; i < arr.length; i++) {
if (arr[i] < pivot) {
left.push(arr[i]);
} else {
right.push(arr[i]);
}
}
// Recursivamente ordenar los sub-arrays
return quicksort(left).concat(pivot, quicksort(right));
}
let emptyBinsCount = 0;
function eliminarContenedoresVacios(bins) {
let emptyBinsCount = 0;
const binsToRemove = [];
// Encuentra y marca los contenedores vacíos para eliminarlos
bins.forEach((bin, index) => {
if (bin.childElementCount === 0) {
emptyBinsCount++;
binsToRemove.push(index);
}
});
// Elimina los contenedores vacíos comenzando desde el final para evitar problemas con los índices
for (let i = binsToRemove.length - 1; i >= 0; i--) {
const indexToRemove = binsToRemove[i];
containerBins.removeChild(bins[indexToRemove]);
bins.splice(indexToRemove, 1);
}
return emptyBinsCount;
}
// Boton para la funcion de solucion
const btnSolution = document.querySelector('.btnSolution');
btnSolution.addEventListener('click', function () {
const sortedArray = quicksort(heights);
console.log(sortedArray);
// Ordenar las figuras de mayor a menor dentro del div de carga
const figures = document.querySelectorAll('.figure');
const figuresArray = Array.from(figures);
figuresArray.sort(function (a, b) {
return b.textContent - a.textContent;
});
figuresArray.forEach((figure) => {
carga.appendChild(figure);
});
// Asignar las figuras en orden de mayor a menor dentro de los contenedores que tengan espacio suficiente para cada una
// Limpiar los contenedores y devolver las figuras dentro de los contenedores a la seccion de carga
bins.forEach((bin) => {
bin.innerHTML = '';
});
bins.reverse();
figuresArray.forEach((figure) => {
bins.forEach((bin) => {
const figuresInsideBin = bin.querySelectorAll('.figure');
let currentBinUsedSpace = 0;
figuresInsideBin.forEach((figure) => {
currentBinUsedSpace += parseInt(figure.textContent, 10);
});
if (currentBinUsedSpace + parseInt(figure.textContent, 10) <= limiteBin) {
bin.appendChild(figure);
}
})
});
// Eliminar los contenedores vacíos al momento de acomodar las figuras
const emptyBinsRemoved = eliminarContenedoresVacios(bins);
// Mostrar mensaje de alerta final con el contador de contenedores vacíos eliminados
alertsDiv.style.visibility = "visible";
alertMsg.textContent = `Se aplicó la mejor solución. Se eliminaron ${emptyBinsRemoved} contenedor(es) vacío(s).`;
btnExtraBin.disabled = true;
btnExtraBin.style.cursor = 'not-allowed';
});