-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
457 lines (399 loc) · 20.4 KB
/
Copy pathscript.js
File metadata and controls
457 lines (399 loc) · 20.4 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
const TRANSLATIONS = {
ua: {
title: "Для мого кохання ❤️",
subtitle_start: "Вибери одну картку і дізнайся, що я відчуваю... 💝",
subtitle_scratch: "Зітри одну картку пальцем... ✨",
start_btn: "Почати гру",
scratch_text: "Зітри мене",
restart_btn: "Ще раз",
sentences: [
"Ти найкраще, що траплялося зі мною ❤️",
"Твоя усмішка робить мій день яскравішим ✨",
"Я кохаю тебе більше, ніж учора, а там як карта ляже 💖",
"Відстань ніщо, коли ти поруч у моєму серці 🌍💕",
"Ти моя найрідніша людина 🫂❤️",
"З тобою кожна мить особлива 🌟",
"Моє серце належить тільки тобі 💘",
"Я сумую за тобою щосекунди 🥺❤️",
"Ти робиш мене найщасливішою людиною у світі 🥰",
"Моя любов до тебе не має меж ♾️💖",
"Ти — моя мрія, яка стала реальністю ✨💕",
"Дякую за те, що ти є в моєму житті 💝",
"Твої очі — мій улюблений всесвіт 🌌❤️",
"Кожна думка про тебе гріє мені душу ☕💖",
"Я завжди буду поруч, незважаючи ні на що 🤝❤️",
"Обіцяю віддавати тобі останній шматочок піци 🍕😏",
"Буду любити тебе, навіть якщо ти з'їси мої смаколики 🍫🙄",
"Обіцяю сміятися з твоїх жартів, навіть не дуже смішних 😅❤️",
"Твій масаж — це святе (але і ти мені зробиш, почухаєш спинку?) 🖐️✨",
"Я люблю тебе більше, ніж спати до обіду 🛌💖",
"Обіцяю слухати твою музику, яку ти мені надсилаєш (а можна щось крім k-pop?) ❤️🎧",
"Ти мій улюблений головний біль 🤕💘",
"Обіцяю ділитися ковдрою (ну, хоча б 30% ковдри) 🥶💕",
"Люблю тебе так сильно, що готовий дивитися з тобою мелодрами та серіали 🍿😭",
"З тобою навіть похід в магазин за хлібом — це пригода 🛒✨",
"Обіцяю відповідати на повідомлення швидше (ну, або хоча б намагатися) 📱💨",
"Знайду більше часу для твоїх дзвінків і нескінченних історій 📞💕",
"Я теж буду дивитися в Rave все що завгодно (навіть якщо ти будеш засинати) 😴💕",
"У мене постійно сни про тебе (навіть якщо не дуже пристойні) 💭💖",
"Хочу частіше грати з тобою в Roblox і Minecraft... сумую за нашими безсонними ночами 🎮🥺",
"Обіцяю підтримувати тебе, коли ти плачеш (навіть якщо ти плачеш через дурниці) 🤧💖"
]
},
en: {
title: "For My Love ❤️",
subtitle_start: "Choose a card and see how I feel... 💝",
subtitle_scratch: "Scratch a card with your finger... ✨",
start_btn: "Start Game",
scratch_text: "Scratch Me",
restart_btn: "Play Again",
sentences: [
"You are the best thing that ever happened to me ❤️",
"Your smile brightens my day ✨",
"I love you more than yesterday, and I'll love you more tomorrow 💖",
"Distance is nothing when you're in my heart 🌍💕",
"You are my dearest person 🫂❤️",
"Every moment with you is special 🌟",
"My heart belongs only to you 💘",
"I miss you every second 🥺❤️",
"You make me the happiest person in the world 🥰",
"My love for you has no limits ♾️💖",
"You are a dream come true ✨💕",
"Thank you for being in my life 💝",
"Your eyes are my favorite universe 🌌❤️",
"Every thought of you warms my soul ☕💖",
"I will always be there, no matter what 🤝❤️",
"I promise to give you the last slice of pizza 🍕😏",
"I will love you even if you eat my snacks 🍫🙄",
"I promise to laugh at your jokes, even the bad ones 😅❤️",
"Your massages are sacred (but you owe me one) 🖐️✨",
"I love you more than sleeping until noon 🛌💖",
"I promise to listen to your music that you send me (but can it be something other than k-pop?) ❤️🎧",
"You are my favorite headache 🤕💘",
"I promise to share the blanket (at least 30% of it) 🥶💕",
"I love you so much I'm willing to watch melodramas and series with you 🍿😭",
"Even going to the store for bread is an adventure with you 🛒✨",
"I promise to reply to your messages faster (well, or at least try to) 📱💨",
"I will find more time for your calls and endless stories 📞💕",
"I will also watch anything on Rave with you (even if you fall asleep) 😴💕",
"I constantly have dreams about you (even if they are not very appropriate) 💭💖",
"I want to play Roblox and Minecraft with you more often... I miss our sleepless nights 🎮🥺",
"I promise to support you when you cry (even if you're crying over nonsense) 🤧💖"
]
}
};
let currentLang = 'ua';
let gameActive = false;
let selectedCardIndex = null;
let currentShuffledSentences = [];
document.addEventListener('DOMContentLoaded', () => {
const startScreen = document.getElementById('start-screen');
const resultScreen = document.getElementById('result-screen');
const cardGrid = document.getElementById('card-grid');
const startBtn = document.getElementById('start-btn');
const restartBtn = document.getElementById('restart-btn');
const floatingHeartsContainer = document.getElementById('floating-hearts');
const langBtn = document.getElementById('lang-btn');
function createFloatingHearts() {
const heartCount = 15;
for (let i = 0; i < heartCount; i++) {
const heart = document.createElement('div');
heart.classList.add('heart');
heart.style.left = Math.random() * 100 + 'vw';
heart.style.animationDuration = (Math.random() * 10 + 10) + 's';
heart.style.animationDelay = (Math.random() * 5) + 's';
floatingHeartsContainer.appendChild(heart);
}
}
function toggleLanguage() {
console.log(`[toggleLanguage] Switching language from ${currentLang}`);
currentLang = currentLang === 'ua' ? 'en' : 'ua';
console.log(`[toggleLanguage] New language is ${currentLang}`);
langBtn.textContent = currentLang === 'ua' ? '🇺🇦 UA' : '🇬🇧 EN';
updateUIText();
// If cards are currently generated, we need to translate their hidden text
if (currentShuffledSentences.length > 0) {
const cards = document.querySelectorAll('.card');
cards.forEach((card, index) => {
const inner = card.querySelector('.card-inner');
if (inner) {
// Find the original index of this sentence in the TRANSLATIONS array
const originalSentenceIndex = currentShuffledSentences[index];
inner.textContent = TRANSLATIONS[currentLang].sentences[originalSentenceIndex];
// Note: HTML5 Canvas text cannot be updated easily once drawn without redrawing the whole scratch layer.
// Instead of redrawing the canvas and losing the user's progress if they are scratching,
// we accept that the "Зітри мене / Scratch Me" canvas text stays in the language it was generated in.
}
});
// If the result screen is showing, update that sentence too
if (resultScreen.classList.contains('active')) {
const activeCardInner = document.querySelector('.card.selected .card-inner');
if (activeCardInner) {
document.getElementById('result-text').textContent = activeCardInner.textContent;
}
}
}
}
function updateUIText() {
console.log(`[updateUIText] Updating static UI text for ${currentLang}`);
const t = TRANSLATIONS[currentLang];
document.getElementById('title-text').textContent = t.title;
document.getElementById('start-text').textContent = t.start_btn;
document.getElementById('restart-text').textContent = t.restart_btn;
if (gameActive) {
document.getElementById('subtitle-text').textContent = t.subtitle_scratch;
} else {
document.getElementById('subtitle-text').textContent = t.subtitle_start;
}
}
function init() {
console.log('[init] Initializing game components, adding event listeners');
createFloatingHearts();
startBtn.addEventListener('click', startGame);
restartBtn.addEventListener('click', resetGame);
langBtn.addEventListener('click', toggleLanguage);
// Auto-detect browser language
const userLang = (navigator.language || navigator.userLanguage || '').toLowerCase();
// Use Ukrainian if the browser is Ukrainian or Russian
if (userLang && !(userLang.startsWith('uk') || userLang.startsWith('ru'))) {
console.log(`[init] Non-Ukrainian/Russian browser language detected (${userLang}), switching default to English`);
currentLang = 'en';
langBtn.textContent = '🇬🇧 EN';
updateUIText();
} else {
console.log(`[init] Ukrainian or Russian browser language detected (${userLang}), keeping default`);
}
}
function startGame() {
console.log('[startGame] Start button clicked, initializing game grid');
startScreen.classList.remove('active');
startScreen.classList.add('hidden');
cardGrid.classList.remove('hidden');
generateCards();
const cards = document.querySelectorAll('.card');
cards.forEach(card => card.classList.add('shuffling'));
setTimeout(() => {
cards.forEach(card => card.classList.remove('shuffling'));
gameActive = true;
document.getElementById('subtitle-text').textContent = TRANSLATIONS[currentLang].subtitle_scratch;
}, 1200);
}
function generateCards() {
console.log('[generateCards] Generating new set of scratch cards');
cardGrid.innerHTML = '';
selectedCardIndex = null;
gameActive = false;
window.easterEggTriggered = false;
// Generate an array of indices [0...totalSentences.length-1] and shuffle them
const totalSentences = TRANSLATIONS[currentLang].sentences.length;
const indices = Array.from({ length: totalSentences }, (_, i) => i);
indices.sort(() => 0.5 - Math.random());
// Save the first 9 shuffled indices so we can translate them on-the-fly later
currentShuffledSentences = indices.slice(0, 9);
currentShuffledSentences.forEach((sentenceIndex, displayIndex) => {
const sentence = TRANSLATIONS[currentLang].sentences[sentenceIndex];
const card = document.createElement('div');
card.className = 'card';
card.dataset.index = displayIndex;
const inner = document.createElement('div');
inner.className = 'card-inner';
inner.textContent = sentence;
const canvas = document.createElement('canvas');
canvas.className = 'scratch-layer';
canvas.dataset.index = displayIndex;
card.appendChild(inner);
card.appendChild(canvas);
cardGrid.appendChild(card);
// Wait for DOM insertion and layout sizing
requestAnimationFrame(() => {
requestAnimationFrame(() => {
setupScratchCanvas(canvas, card, TRANSLATIONS[currentLang].scratch_text);
});
});
});
}
function setupScratchCanvas(canvas, containerElement, scratchText) {
const ctx = canvas.getContext('2d');
const width = containerElement.offsetWidth || 100;
const height = containerElement.offsetHeight || 100;
const dpr = window.devicePixelRatio || 1;
canvas.width = width * dpr;
canvas.height = height * dpr;
canvas.style.width = width + 'px';
canvas.style.height = height + 'px';
ctx.scale(dpr, dpr);
const gradient = ctx.createLinearGradient(0, 0, width, height);
gradient.addColorStop(0, '#ff9a9e');
gradient.addColorStop(1, '#fecfef');
ctx.fillStyle = gradient;
ctx.fillRect(0, 0, width, height);
ctx.fillStyle = 'rgba(255, 255, 255, 0.9)';
ctx.font = 'bold 16px Montserrat';
ctx.textAlign = 'center';
ctx.textBaseline = 'middle';
ctx.fillText(scratchText, width / 2, height / 2);
let isDrawing = false;
let isRevealed = false;
function getPointerPos(e) {
const rect = canvas.getBoundingClientRect();
// Fallbacks for both desktop and mobile
const clientX = e.touches && e.touches.length > 0 ? e.touches[0].clientX : e.clientX;
const clientY = e.touches && e.touches.length > 0 ? e.touches[0].clientY : e.clientY;
return {
x: clientX - rect.left,
y: clientY - rect.top
};
}
function handleStart(e) {
if (!gameActive || isRevealed) return;
const cardIndex = canvas.dataset.index;
if (selectedCardIndex === null) {
console.log(`[scratchStart] Card selected: ${cardIndex}`);
selectedCardIndex = cardIndex;
disableOtherCards(selectedCardIndex);
} else if (selectedCardIndex !== cardIndex) {
return;
}
isDrawing = true;
const pos = getPointerPos(e);
scratch(pos.x, pos.y);
if (e.cancelable) e.preventDefault(); // Prevent scroll
}
function handleMove(e) {
if (!isDrawing || !gameActive || isRevealed) return;
if (e.cancelable) e.preventDefault(); // Prevent scroll while drawing
const pos = getPointerPos(e);
scratch(pos.x, pos.y);
}
function handleEnd() {
if (!isDrawing) return;
isDrawing = false;
console.log('[scratchEnd] Finished scratching stroke, checking reveal percentage');
checkReveal();
}
function scratch(x, y) {
ctx.globalCompositeOperation = 'destination-out';
ctx.beginPath();
ctx.arc(x, y, 18, 0, Math.PI * 2);
ctx.fill();
}
function checkReveal() {
const imageData = ctx.getImageData(0, 0, canvas.width, canvas.height);
const data = imageData.data;
let transparentPixels = 0;
const stride = 32;
let sampledPixels = 0;
for (let i = 0; i < data.length; i += 4 * stride) {
sampledPixels++;
if (data[i + 3] < 128) {
transparentPixels++;
}
}
const percentage = (transparentPixels / Math.max(1, sampledPixels)) * 100;
if (percentage > 45 && !isRevealed) {
console.log(`[checkReveal] Card completely revealed! Percentage: ${percentage.toFixed(2)}%`);
isRevealed = true;
// Easter Egg check at exactly 67% (rounded)
if (Math.round(percentage) === 67 && !window.easterEggTriggered) {
window.easterEggTriggered = true;
triggerEasterEgg();
}
canvas.style.transition = 'opacity 0.6s ease';
canvas.style.opacity = '0';
setTimeout(() => {
canvas.style.display = 'none';
const sentence = containerElement.querySelector('.card-inner').textContent;
showRestartButton(sentence);
}, 600);
}
}
// Mouse Events
canvas.addEventListener('mousedown', handleStart);
document.addEventListener('mousemove', handleMove);
document.addEventListener('mouseup', handleEnd);
// Touch Events
canvas.addEventListener('touchstart', handleStart, { passive: false });
canvas.addEventListener('touchmove', handleMove, { passive: false });
document.addEventListener('touchend', handleEnd);
canvas.addEventListener('touchcancel', handleEnd);
}
function disableOtherCards(selectedIndex) {
const cards = document.querySelectorAll('.card');
cards.forEach(card => {
if (card.dataset.index !== selectedIndex) {
card.classList.add('disabled');
} else {
card.classList.add('selected');
}
});
}
function showRestartButton(sentence) {
setTimeout(() => {
document.getElementById('result-text').textContent = sentence;
resultScreen.classList.remove('hidden');
resultScreen.classList.add('active');
}, 2000);
}
function triggerEasterEgg() {
console.log('[triggerEasterEgg] 67% reached! Triggering Easter Egg.');
// Confetti
if (typeof confetti === 'function') {
confetti({
particleCount: 150,
spread: 80,
origin: { y: 0.6 },
colors: ['#ff4b72', '#ffd8df', '#ffffff', '#d4af37'],
zIndex: 2000
});
}
// Audio
const audio = document.getElementById('easter-egg-audio');
if (audio) {
audio.currentTime = 0;
audio.play().catch(e => console.log('Audio play blocked:', e));
}
// Image
const container = document.getElementById('easter-egg-container');
if (container) {
container.classList.remove('hidden');
container.classList.add('active');
}
// Hide after audio ends
if (audio) {
audio.onended = () => {
if (container) {
container.classList.remove('active');
container.classList.add('hidden');
}
};
} else {
// Fallback if audio fails to load or play
setTimeout(() => {
if (container) {
container.classList.remove('active');
container.classList.add('hidden');
}
}, 5000);
}
}
function resetGame() {
console.log('[resetGame] Restarting the game completely');
resultScreen.classList.remove('active');
resultScreen.classList.add('hidden');
const easterEggContainer = document.getElementById('easter-egg-container');
if (easterEggContainer) {
easterEggContainer.classList.remove('active');
easterEggContainer.classList.add('hidden');
}
const audio = document.getElementById('easter-egg-audio');
if (audio) {
audio.pause();
audio.currentTime = 0;
}
document.getElementById('subtitle-text').textContent = TRANSLATIONS[currentLang].subtitle_start;
document.getElementById('result-text').textContent = "";
startGame();
}
// Initialize application
init();
});