-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathscript.js
296 lines (250 loc) · 9.05 KB
/
script.js
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
// DOM elements
let formDiv = document.querySelector("#inputForm");
let backBtnDiv = document.querySelector("#backBtnDiv");
let backBtn = document.querySelector("#backBtn");
// Event listener for back button
backBtn.addEventListener("click", () => {
backBtnDiv.style.display = "none";
formDiv.style.display = "block";
renderBuilding(0, 0);
});
// Generate UI based on user input
function generateUI(event) {
event.preventDefault();
let numFloorsInput = document.querySelector("#num_floors");
let numLiftsInput = document.querySelector("#num_lifts");
let numFloors = parseInt(numFloorsInput.value);
let numLifts = parseInt(numLiftsInput.value);
if (validateInput(numFloors, numLifts)) {
formDiv.style.display = "none";
backBtnDiv.style.display = "block";
renderBuilding(numFloors, numLifts);
}
}
// Screen size check
let screenWidth = window.innerWidth;
let screenHeight = window.innerHeight;
window.addEventListener("load", () => {
if (screenWidth < 220) {
alert("Screen size is too small. Lift simulation wouldn't work on this device.");
}
});
// Form submission event listener
let form = document.querySelector("form");
form.addEventListener("submit", generateUI);
// Calculate and set max input values
function calculateMaxInputValues() {
let numFloorsInput = document.querySelector("#num_floors");
let numLiftsInput = document.querySelector("#num_lifts");
numFloorsInput.placeholder = "Enter number of floors";
numLiftsInput.placeholder = "Enter number of lifts";
}
window.addEventListener("resize", calculateMaxInputValues);
window.addEventListener("load", calculateMaxInputValues);
// Validate user input
function validateInput(numFloors, numLifts) {
if (isNaN(numLifts) || isNaN(numFloors)) {
alert("Input fields cannot be empty");
return false;
} else if (numFloors <= 0 || numLifts <= 0) {
alert("Number of floors and number of lifts must be a positive integer");
return false;
}
return true;
}
// Handle lift button click
function handleButtonClick(event) {
let floorId = getNumFromIdString(event.id);
let direction = event.id.includes("up") ? "up" : "down";
let request = { floor: floorId, direction: direction };
if (!pendingRequests.some(req => req.floor === floorId && req.direction === direction) &&
!servingRequests.some(req => req && req.floor === floorId && req.direction === direction)) {
pendingRequests.push(request);
event.target.classList.add('active-' + direction);
}
}
// Find the nearest available lift
function getNearestAvailableLift(request) {
let nearestLiftDistance = 999;
let nearestLift = null;
for (let i = 0; i < lifts.length; i++) {
let lift = lifts[i];
if (lift.isBusy) {
// Check if the busy lift is moving in the same direction and can stop at the requested floor
if (canStopAtFloor(lift, request)) {
return lift;
}
continue;
}
const liftDistance = Math.abs(request.floor - lift.currFloor);
if (liftDistance < nearestLiftDistance) {
nearestLiftDistance = liftDistance;
nearestLift = lift;
}
}
return nearestLift;
}
// Check if a busy lift can stop at the requested floor
function canStopAtFloor(lift, request) {
let liftRequest = servingRequests[lift.htmlEl.id.slice(4) - 1];
if (!liftRequest) return false;
if (request.direction === 'up') {
return liftRequest.direction === 'up' &&
request.floor > lift.currFloor &&
request.floor < liftRequest.floor;
} else {
return liftRequest.direction === 'down' &&
request.floor < lift.currFloor &&
request.floor > liftRequest.floor;
}
}
// Move the lift
function moveLift(liftId, request) {
pendingRequests = pendingRequests.filter(req => !(req.floor === request.floor && req.direction === request.direction));
const lift = lifts[liftId - 1];
if (!lift.isBusy) {
servingRequests[liftId - 1] = request;
lift.isBusy = true;
} else {
// Add intermediate stop
lift.intermediateStops.push(request);
lift.intermediateStops.sort((a, b) => request.direction === 'up' ? a.floor - b.floor : b.floor - a.floor);
}
const moveToFloor = (floor) => {
const y = (floor - 1) * liftHeight * -1;
const x = Math.abs(floor - lift.currFloor) * 2;
lift.htmlEl.style.transform = `translateY(${y}px)`;
lift.htmlEl.style.transition = `${x}s linear`;
openCloseLift(liftId, x * 1000);
setTimeout(() => {
lift.currFloor = floor;
// Remove active class from button
let btn = document.querySelector(`#${request.direction}Btn${floor}`);
if (btn) btn.classList.remove('active-' + request.direction);
if (lift.intermediateStops.length > 0) {
let nextStop = lift.intermediateStops.shift();
moveToFloor(nextStop.floor);
} else {
lift.isBusy = false;
servingRequests[liftId - 1] = null;
}
}, x * 1000 + 5000);
};
moveToFloor(request.floor);
}
// Open and close lift doors
function openCloseLift(liftId, duration) {
setTimeout(() => {
openLift(liftId);
}, duration);
setTimeout(() => {
closeLift(liftId);
}, duration + 2500);
}
// Open lift doors
function openLift(liftId) {
lifts[liftId - 1].htmlEl.querySelector(`#left-door${liftId}`).classList.remove(`left-door-close`);
lifts[liftId - 1].htmlEl.querySelector(`#right-door${liftId}`).classList.remove(`right-door-close`);
lifts[liftId - 1].htmlEl.querySelector(`#left-door${liftId}`).classList.add(`left-door-open`);
lifts[liftId - 1].htmlEl.querySelector(`#right-door${liftId}`).classList.add(`right-door-open`);
}
// Close lift doors
function closeLift(liftId) {
lifts[liftId - 1].htmlEl.querySelector(`#left-door${liftId}`).classList.remove(`left-door-open`);
lifts[liftId - 1].htmlEl.querySelector(`#right-door${liftId}`).classList.remove(`right-door-open`);
lifts[liftId - 1].htmlEl.querySelector(`#left-door${liftId}`).classList.add(`left-door-close`);
lifts[liftId - 1].htmlEl.querySelector(`#right-door${liftId}`).classList.add(`right-door-close`);
}
// Lift controller
function liftController() {
if (pendingRequests.length > 0) {
for (let request of pendingRequests) {
const nearestLift = getNearestAvailableLift(request);
if (nearestLift) {
let liftId = getNumFromIdString(nearestLift.htmlEl.id);
moveLift(liftId, request);
break; // Move one lift at a time
}
}
}
}
// Render the building
function renderBuilding(no_of_floors, no_of_lifts) {
let building = document.querySelector("#building");
building.innerHTML = "";
for (let i = no_of_floors; i >= 1; i--) {
let floor = document.createElement("div");
floor.classList.add("floor");
const floorWidth = 100 + (no_of_lifts * 100);
floor.style.width = `${floorWidth}px`;
let liftLabels = document.createElement("div");
liftLabels.classList.add("lift-labels");
let floorLabel = document.createElement("span");
floorLabel.textContent = "Floor " + i;
liftLabels.appendChild(floorLabel);
let buttonsContainer = document.createElement("div");
buttonsContainer.classList.add("buttons-container");
if (i !== no_of_floors) {
let upBtn = document.createElement("button");
upBtn.id = "upBtn" + i;
upBtn.classList.add("upBtn");
upBtn.onclick = () => handleButtonClick(upBtn);
upBtn.innerHTML = "↑";
buttonsContainer.appendChild(upBtn);
}
if (i !== 1) {
let downBtn = document.createElement("button");
downBtn.id = "downBtn" + i;
downBtn.classList.add("downBtn");
downBtn.onclick = () => handleButtonClick(downBtn);
downBtn.innerHTML = "↓";
buttonsContainer.appendChild(downBtn);
}
liftLabels.appendChild(buttonsContainer);
floor.appendChild(liftLabels);
if (i === 1) {
for (let j = 1; j <= no_of_lifts; j++) {
let lift = document.createElement("div");
lift.id = "lift" + j;
lift.classList.add("lift");
let leftDoor = document.createElement("div");
leftDoor.id = "left-door" + j;
leftDoor.classList.add("left-door");
let rightDoor = document.createElement("div");
rightDoor.id = "right-door" + j;
rightDoor.classList.add("right-door");
lift.appendChild(leftDoor);
lift.appendChild(rightDoor);
floor.appendChild(lift);
}
}
building.appendChild(floor);
}
lifts = Array.from(document.querySelectorAll(".lift"), (el) => ({
htmlEl: el,
isBusy: false,
currFloor: 1,
intermediateStops: []
}));
pendingRequests = [];
servingRequests = Array(lifts.length).fill(null);
}
// Global variables
let lifts = [];
const liftHeight = 90.8; // units in px
let pendingRequests = [];
let servingRequests = [];
// Start the lift controller
setInterval(liftController, 50);
// Helper function to extract number from ID string
function getNumFromIdString(string) {
const regex = /\d+/;
const match = regex.exec(string);
return match ? parseInt(match[0], 10) : null;
}
// Add this CSS to your stylesheet
/*
.upBtn.active-up, .downBtn.active-down {
background-color: #ff0000;
}
*/