-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
460 lines (392 loc) · 16.9 KB
/
script.js
File metadata and controls
460 lines (392 loc) · 16.9 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
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
class GarageSystem {
constructor() {
this.parkingQueue = [];
this.carCounters = {};
this.totalCounters = { arrivalCount: 0, departureCount: 0 };
this.MAX_CAPACITY = 10;
this.circlingCars = []; // Track cars that are temporarily removed
}
isFull() {
return this.parkingQueue.length >= this.MAX_CAPACITY;
}
handleArrival(plateNumber) {
if (this.isFull()) {
return { success: false, message: "Sorry, parking is full!" };
}
this.parkingQueue.push(plateNumber);
this.carCounters[plateNumber] = (this.carCounters[plateNumber] || 0) + 1;
this.totalCounters.arrivalCount++;
return {
success: true,
message: `Car with plate number ${plateNumber} has arrived and parked.`
};
}
handleDeparture(plateNumber) {
if (!this.parkingQueue.length) {
return { success: false, message: "Error: Parking is empty!" };
}
const carIndex = this.parkingQueue.indexOf(plateNumber);
if (carIndex === -1) {
return {
success: false,
message: `Error: Car with plate number ${plateNumber} is not in the parking garage.`
};
}
// If car is at exit, simply remove it
if (carIndex === 0) {
this.parkingQueue.shift();
this.totalCounters.departureCount++;
this.carCounters[plateNumber] = (this.carCounters[plateNumber] || 0) + 1;
return {
success: true,
message: `Car with plate number ${plateNumber} has departed.`,
carsToCircle: []
};
}
// If car is not at exit, we need to move cars in front of it
const carsToMove = this.parkingQueue.slice(0, carIndex);
this.circlingCars = [...carsToMove];
// Remove cars that need to circle and the departing car
this.parkingQueue.splice(0, carIndex + 1);
// Add circling cars back to the queue
this.parkingQueue.push(...carsToMove);
// Update counters
this.totalCounters.departureCount++;
this.carCounters[plateNumber] = (this.carCounters[plateNumber] || 0) + 1;
carsToMove.forEach(car => {
this.carCounters[car] = (this.carCounters[car] || 0) + 2; // +2 for exit and re-entry
this.totalCounters.arrivalCount++;
this.totalCounters.departureCount++;
});
return {
success: true,
message: `Car with plate number ${plateNumber} has departed.`,
carsToCircle: carsToMove
};
}
getStatus() {
return {
parkedCars: [...this.parkingQueue],
totalArrivals: this.totalCounters.arrivalCount,
totalDepartures: this.totalCounters.departureCount,
totalMovements: Object.values(this.carCounters).reduce((a, b) => a + b, 0)
};
}
}
class ParkingGarageUI {
constructor() {
this.garage = new GarageSystem();
this.initializeElements();
this.attachEventListeners();
this.initializeGarageVisualization();
this.updateUI();
this.isAnimating = false;
}
initializeElements() {
// Input elements
this.plateInput = document.getElementById('plateNumber');
this.parkButton = document.getElementById('parkButton');
this.removeButton = document.getElementById('removeButton');
this.randomPlateButton = document.getElementById('randomPlateButton');
this.themeToggle = document.getElementById('themeToggle');
// Display elements
this.capacityBar = document.getElementById('capacityBar');
this.capacityLabel = document.getElementById('capacityLabel');
this.totalArrivals = document.getElementById('totalArrivals');
this.totalDepartures = document.getElementById('totalDepartures');
this.totalMovements = document.getElementById('totalMovements');
this.parkedCarsList = document.getElementById('parkedCarsList');
this.noticeMessage = document.getElementById('noticeMessage');
this.modalMessage = document.getElementById('modalMessage');
this.modal = document.getElementById('messageModal');
this.modalClose = document.getElementById('modalClose');
// Add visualization elements
this.garageQueue = document.getElementById('garageQueue');
this.initializeGarageVisualization();
// Initialize theme
this.initializeTheme();
}
initializeGarageVisualization() {
this.garageQueue.innerHTML = '';
for (let i = 0; i < this.garage.MAX_CAPACITY; i++) {
const spot = document.createElement('div');
spot.className = 'parking-spot';
spot.dataset.index = i;
this.garageQueue.appendChild(spot);
}
}
generateRandomPlate() {
const letters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
const numbers = '0123456789';
let plate = '';
// Generate 3 random letters
for (let i = 0; i < 3; i++) {
plate += letters.charAt(Math.floor(Math.random() * letters.length));
}
plate += ' '; // Add space
// Generate 3 random numbers
for (let i = 0; i < 3; i++) {
plate += numbers.charAt(Math.floor(Math.random() * numbers.length));
}
return plate;
}
async animateCarEntry(plateNumber) {
const emptySpotIndex = this.garage.MAX_CAPACITY - this.garage.parkingQueue.length;
const spot = this.garageQueue.children[emptySpotIndex];
// Set up the spot with the plate number but keep it invisible
spot.classList.add('occupied');
spot.textContent = plateNumber;
spot.style.opacity = '0';
// Small delay to ensure styles are applied
await new Promise(resolve => setTimeout(resolve, 50));
// Make visible and start animation
spot.style.opacity = '1';
spot.classList.add('entering');
// Wait for animation to complete
await new Promise(resolve => {
spot.addEventListener('animationend', () => {
spot.classList.remove('entering');
resolve();
}, { once: true });
});
}
async animateCarExit(plateNumber) {
const carIndex = this.garage.parkingQueue.indexOf(plateNumber);
const result = this.garage.handleDeparture(plateNumber);
if (!result.success) {
return result;
}
if (result.carsToCircle.length === 0) {
// Simple exit animation for car at exit
const spot = this.garageQueue.children[9];
spot.classList.add('exiting');
await new Promise(resolve => {
spot.addEventListener('animationend', () => {
spot.classList.remove('occupied', 'exiting');
spot.textContent = '';
resolve();
}, { once: true });
});
} else {
// Animate cars that need to circle
for (let i = 0; i < result.carsToCircle.length; i++) {
const spot = this.garageQueue.children[9 - i];
const car = result.carsToCircle[i];
// Exit animation
spot.classList.add('exiting');
await new Promise(resolve => {
spot.addEventListener('animationend', () => {
spot.classList.remove('occupied', 'exiting');
spot.textContent = '';
resolve();
}, { once: true });
});
}
// Animate the departing car
const departingSpot = this.garageQueue.children[9 - result.carsToCircle.length];
departingSpot.classList.add('exiting');
await new Promise(resolve => {
departingSpot.addEventListener('animationend', () => {
departingSpot.classList.remove('occupied', 'exiting');
departingSpot.textContent = '';
resolve();
}, { once: true });
});
// Animate cars re-entering
for (let i = result.carsToCircle.length - 1; i >= 0; i--) {
const spot = this.garageQueue.children[9 - i];
const car = result.carsToCircle[i];
// Re-entry animation
spot.classList.add('occupied');
spot.textContent = car;
spot.style.opacity = '0';
spot.classList.add('entering');
await new Promise(resolve => {
spot.addEventListener('animationend', () => {
spot.classList.remove('entering');
spot.style.opacity = '1';
resolve();
}, { once: true });
});
}
}
// Move remaining cars down
const promises = [];
const startIndex = 8 - (result.carsToCircle ? result.carsToCircle.length : 0);
for (let i = startIndex; i >= this.garage.MAX_CAPACITY - this.garage.parkingQueue.length; i--) {
const currentSpot = this.garageQueue.children[i];
const nextSpot = this.garageQueue.children[i + 1];
if (currentSpot.classList.contains('occupied')) {
currentSpot.classList.add('shifting');
promises.push(new Promise(resolve => {
currentSpot.addEventListener('animationend', () => {
currentSpot.classList.remove('shifting', 'occupied');
nextSpot.classList.add('occupied');
nextSpot.textContent = currentSpot.textContent;
currentSpot.textContent = '';
resolve();
}, { once: true });
}));
}
}
await Promise.all(promises);
return result;
}
showNotice(message, isError = false) {
this.noticeMessage.textContent = message;
this.noticeMessage.className = 'notice-message ' + (isError ? 'error' : 'success');
}
clearNotice() {
this.noticeMessage.textContent = '';
this.noticeMessage.className = 'notice-message';
}
updateUI() {
const status = this.garage.getStatus();
// Update statistics
this.totalArrivals.textContent = `Total Arrivals: ${status.totalArrivals}`;
this.totalDepartures.textContent = `Total Departures: ${status.totalDepartures}`;
this.totalMovements.textContent = `Total Movements: ${status.totalMovements}`;
// Update capacity indicator
const capacityPercentage = (this.garage.parkingQueue.length / this.garage.MAX_CAPACITY) * 100;
this.capacityBar.style.width = `${capacityPercentage}%`;
this.capacityLabel.textContent = `Available Spaces: ${this.garage.MAX_CAPACITY - this.garage.parkingQueue.length}/${this.garage.MAX_CAPACITY}`;
// Update capacity bar color based on fullness
if (capacityPercentage >= 80) {
this.capacityBar.style.background = '#ea4335'; // Red when nearly full
} else if (capacityPercentage >= 50) {
this.capacityBar.style.background = '#fbbc04'; // Yellow when half full
} else {
this.capacityBar.style.background = '#27ae60'; // Green when mostly empty
}
// Update visualization
this.garageQueue.querySelectorAll('.parking-spot').forEach((spot, index) => {
const carIndex = this.garage.MAX_CAPACITY - 1 - index;
const car = status.parkedCars[carIndex];
if (car) {
spot.classList.add('occupied');
spot.textContent = car;
} else {
spot.classList.remove('occupied');
spot.textContent = '';
}
});
// Update parked cars list
if (status.parkedCars.length > 0) {
const carsList = status.parkedCars.map((plate, index) => `
<div class="car-list-item">
<div class="car-info">
<span>${plate}</span>
<span class="position-label">${index === 0 ? '(Exit)' : index === status.parkedCars.length - 1 ? '(Entrance)' : ''}</span>
</div>
<button class="btn danger remove-car-btn" data-plate="${plate}">
<i class="fas fa-sign-out-alt"></i>
</button>
</div>
`).join('');
this.parkedCarsList.innerHTML = carsList;
// Add event listeners to remove buttons
this.parkedCarsList.querySelectorAll('.remove-car-btn').forEach(button => {
button.addEventListener('click', () => {
const plateNumber = button.dataset.plate;
this.plateInput.value = plateNumber;
this.handleRemoveCar();
});
});
} else {
this.parkedCarsList.innerHTML = '<p class="empty-message">No cars currently parked</p>';
}
}
async handleParkCar() {
if (this.isAnimating) return;
const plateNumber = this.plateInput.value.trim();
if (!plateNumber) {
this.showNotice('Please enter a plate number', true);
return;
}
this.isAnimating = true;
const result = this.garage.handleArrival(plateNumber);
if (result.success) {
await this.animateCarEntry(plateNumber);
this.showNotice(result.message);
this.updateExplanationPane(`Car with plate number ${plateNumber} parked using FIFO (First In, First Out) strategy.`);
} else {
this.showNotice(result.message, true);
}
this.plateInput.value = '';
this.updateUI();
this.isAnimating = false;
}
async handleRemoveCar() {
if (this.isAnimating) return;
const plateNumber = this.plateInput.value.trim();
if (!plateNumber) {
this.showNotice('Please enter a plate number', true);
return;
}
this.isAnimating = true;
const result = await this.animateCarExit(plateNumber);
if (result.success) {
this.showNotice(result.message);
this.updateExplanationPane(`Car with plate number ${plateNumber} removed using FIFO (First In, First Out) strategy.`);
} else {
this.showNotice(result.message, true);
}
this.plateInput.value = '';
this.updateUI();
this.isAnimating = false;
}
initializeTheme() {
const currentTheme = localStorage.getItem('theme') || 'light';
document.documentElement.setAttribute('data-theme', currentTheme);
this.updateThemeIcon(currentTheme);
}
updateThemeIcon(theme) {
const icon = this.themeToggle.querySelector('i');
if (theme === 'dark') {
icon.className = 'fas fa-moon';
} else {
icon.className = 'fas fa-sun';
}
}
toggleTheme() {
const currentTheme = document.documentElement.getAttribute('data-theme');
const newTheme = currentTheme === 'dark' ? 'light' : 'dark';
document.documentElement.setAttribute('data-theme', newTheme);
localStorage.setItem('theme', newTheme);
this.updateThemeIcon(newTheme);
}
attachEventListeners() {
this.parkButton.addEventListener('click', () => this.handleParkCar());
this.removeButton.addEventListener('click', () => this.handleRemoveCar());
this.randomPlateButton.addEventListener('click', () => {
this.plateInput.value = this.generateRandomPlate();
this.clearNotice();
});
this.themeToggle.addEventListener('click', () => this.toggleTheme());
this.modalClose.addEventListener('click', () => this.modal.classList.remove('show'));
// Add keyboard shortcuts
document.addEventListener('keydown', (e) => {
if (e.key === 'Enter' && document.activeElement === this.plateInput) {
if (e.shiftKey) {
this.handleRemoveCar();
} else {
this.handleParkCar();
}
}
});
}
updateExplanationPane(message) {
const explanationText = document.getElementById('explanationText');
explanationText.textContent = message;
}
}
// Initialize the application
const app = new ParkingGarageUI();
function updateNotice(message) {
const noticeMessage = document.getElementById('noticeMessage');
if (message) {
noticeMessage.textContent = message;
} else {
noticeMessage.textContent = 'No current notices';
}
}