-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.html
532 lines (459 loc) · 21.4 KB
/
index.html
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
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Flappy Owl - Welcome</title>
<script src="https://cdn.jsdelivr.net/npm/@supabase/supabase-js@2"></script>
<link rel="stylesheet" href="css/styles.css">
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
<link rel="icon" type="image/png" href="/favicon.png">
<link rel="stylesheet" href="css/championship.css">
<script src="js/championship.js" defer></script>
<script src="js/config.js"></script>
<script src="js/maintenance.js"></script>
<script src="js/newsletter.js"></script>
</head>
<body>
<div class="container">
<div class="header-container">
<img src="assets/title.png" alt="Flappy Owl" class="logo">
<div class="feature-request-container">
<button id="featureRequestBtn">
<span class="button-text">Ask/Vote for Feature</span>
<span class="button-emoji">💡</span>
</button>
</div>
</div>
<div class="announcement">
<h2>Annonces</h2>
<div id="announcement-content">
🎮 Sur ordinateur, utilisez la barre d'espace pour jouer !
</div>
</div>
<div class="countdown">
<h2>Le vrai maitre de la Chouette sera proclamé dans...</h2>
<div id="timer">Loading...</div>
</div>
<div class="match-count">
<div class="gold-bar">
<span>Matches Played:</span>
<div id="matchCount" class="count-number">Loading...</div>
</div>
<div class="gold-bar" style="margin-top: 10px;">
<span>Last match by</span>
<div id="lastPlayer" class="count-number">Loading...</div>
</div>
</div>
<div class="leaderboard">
<h2>Leaderboard</h2>
<ul class="score-list" id="leaderboardList">
<li>No scores yet - Be the first!</li>
</ul>
</div>
<div class="auth-section">
<div class="username-input">
<input type="text"
id="usernameInput"
placeholder="Enter your username (3-20 characters)"
minlength="3"
maxlength="20">
</div>
<button id="playButton" disabled onclick="handlePlay()">Play Game</button>
<div id="errorMessage" class="error-message"></div>
</div>
</div>
<div class="modal fade" id="featureModal" tabindex="-1">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title">Feature Requests</h5>
<button type="button" class="btn-close" data-bs-dismiss="modal"></button>
</div>
<div class="modal-body">
<div id="featureList" class="mb-4"></div>
<div class="feature-input">
<textarea id="newFeature"
maxlength="120"
placeholder="Your feature idea (max 120 chars)"
rows="2"></textarea>
<button id="submitFeature">Submit</button>
</div>
</div>
</div>
</div>
</div>
<div class="newsletter-signup medieval-box">
<p class="newsletter-title">Stay in touch!</p>
<p class="newsletter-text">Sign up to stay updated on next championships:</p>
<div class="signup-form">
<input type="email" id="emailInput" placeholder="Your email address" class="email-input">
<button id="subscribeButton" class="subscribe-button">Subscribe</button>
</div>
<div id="subscribeMessage" class="subscribe-message"></div>
</div>
<script>
// Initialize Supabase
const supabaseClient = supabase.createClient(
'https://jkvwfawlgpxtvtxjlsjr.supabase.co',
'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6ImprdndmYXdsZ3B4dHZ0eGpsc2pyIiwicm9sZSI6ImFub24iLCJpYXQiOjE3MzQyMjE3MjMsImV4cCI6MjA0OTc5NzcyM30.yKURsZiOq3Vz71Om4xtnpK3xNHHnCnJAYdmExFzfYFI'
);
// Generate UUID function
function generateUUID() {
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
var r = Math.random() * 16 | 0,
v = c == 'x' ? r : (r & 0x3 | 0x8);
return v.toString(16);
});
}
// Username validation
function validateUsername(username) {
return username && username.length >= 3 && username.length <= 20;
}
// Handle username input
const usernameInput = document.getElementById('usernameInput');
const playButton = document.getElementById('playButton');
const errorMessage = document.getElementById('errorMessage');
usernameInput.addEventListener('input', function() {
const username = this.value.trim();
playButton.disabled = !validateUsername(username);
errorMessage.textContent = '';
});
// Load saved username if exists
window.onload = async () => {
const savedUsername = localStorage.getItem('username');
if (savedUsername) {
usernameInput.value = savedUsername;
playButton.disabled = !validateUsername(savedUsername);
}
// Update leaderboard and match count
await Promise.all([
updateLeaderboard(),
updateMatchCount()
]);
setInterval(updateLeaderboard, 30000);
setInterval(updateMatchCount, 30000);
};
// Handle play button click
async function handlePlay() {
const username = usernameInput.value.trim();
if (!validateUsername(username)) {
errorMessage.textContent = 'Username must be 3-20 characters';
return;
}
// Generate or get existing user_id
let userId = localStorage.getItem('userId');
if (!userId) {
userId = generateUUID();
localStorage.setItem('userId', userId);
}
// Save to localStorage
localStorage.setItem('username', username);
localStorage.setItem('isAuthenticated', 'true');
// Redirect to game
const baseUrl = window.location.origin;
window.location.href = `${baseUrl}/game.html`;
}
// Update leaderboard function
async function updateLeaderboard() {
try {
const { data: scores, error } = await supabaseClient
.from('scores')
.select('username, score')
.order('score', { ascending: false })
.limit(1000)
.then(response => {
if (response.error) throw response.error;
const uniqueScores = response.data.reduce((acc, current) => {
if (!acc[current.username] || acc[current.username].score < current.score) {
acc[current.username] = current;
}
return acc;
}, {});
return {
data: Object.values(uniqueScores)
.sort((a, b) => b.score - a.score)
.slice(0, 15)
};
});
if (error) throw error;
const leaderboardList = document.getElementById('leaderboardList');
if (!scores || scores.length === 0) {
leaderboardList.innerHTML = '<li class="score-item"><span>No scores yet - Be the first!</span></li>';
return;
}
leaderboardList.innerHTML = '';
// Estimate duration based on score with 5 second initial delay
const estimateDuration = (score) => {
const initialDelay = 5; // 5 seconds before first point
const secondsPerPoint = 0.89; // (13 - 5) seconds / 9 points
const estimatedSeconds = Math.round(initialDelay + (score * secondsPerPoint));
const minutes = Math.floor(estimatedSeconds / 60);
const seconds = estimatedSeconds % 60;
return `(~${minutes}:${seconds.toString().padStart(2, '0')})`;
};
// Top 3 podium with estimated duration
const topThree = scores.slice(0, 3);
const podiumHTML = `
<div class="top-three">
${topThree.map((entry, index) => `
<div class="podium-item podium-${index + 1}">
<div class="podium-rank">#${index + 1}</div>
<div class="podium-username">${entry.username}</div>
<div class="podium-score">${entry.score} ${estimateDuration(entry.score)} min</div>
</div>
`).join('')}
</div>
`;
// Regular scores (4-15)
const restScores = scores.slice(3);
const regularScoresHTML = `
<div class="regular-scores">
${restScores.map((entry, index) => `
<div class="score-item">
<span class="rank">${index + 4}</span>
<span class="username">${entry.username}</span>
<span class="score">${entry.score}</span>
</div>
`).join('')}
</div>
`;
// Combine both sections
leaderboardList.innerHTML = podiumHTML + regularScoresHTML;
} catch (error) {
console.error('Error fetching leaderboard:', error);
}
}
// Countdown timer
function updateCountdown() {
const targetDate = new Date('2024-12-20T14:00:00');
const now = new Date();
const difference = targetDate - now;
if (difference <= 0) {
document.getElementById('timer').innerHTML = "C'est l'heure!";
return;
}
const days = Math.floor(difference / (1000 * 60 * 60 * 24));
const hours = Math.floor((difference % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
const minutes = Math.floor((difference % (1000 * 60 * 60)) / (1000 * 60));
const seconds = Math.floor((difference % (1000 * 60)) / 1000);
document.getElementById('timer').innerHTML = `
<div class="timer-group">
<span class="countdown-number">${days}</span>
<span class="timer-label">jours</span>
</div>
<div class="timer-group">
<span class="countdown-number">${hours}</span>
<span class="timer-label">heures</span>
</div>
<div class="timer-group">
<span class="countdown-number">${minutes}</span>
<span class="timer-label">minutes</span>
</div>
<div class="timer-group">
<span class="countdown-number">${seconds}</span>
<span class="timer-label">secondes</span>
</div>
`;
}
updateCountdown();
setInterval(updateCountdown, 1000);
// Add this after the supabaseClient initialization
async function updateMatchCount() {
try {
const { data, error } = await supabaseClient
.from('scores')
.select('id, username')
.order('created_at', { ascending: false })
.limit(1);
if (error) {
console.error('Error fetching match count:', error);
return;
}
const matchCount = data[0]?.id || 0;
const lastPlayer = data[0]?.username || 'No one yet';
const matchCountElement = document.getElementById('matchCount');
const lastPlayerElement = document.getElementById('lastPlayer');
// Update last player
lastPlayerElement.textContent = lastPlayer;
// Animate the number counting up
const startNumber = 0;
const duration = 2000; // 2 seconds
const steps = 60;
const increment = matchCount / steps;
let currentNumber = startNumber;
let step = 0;
const animation = setInterval(() => {
step++;
currentNumber = Math.min(matchCount, Math.floor(increment * step));
matchCountElement.textContent = currentNumber.toLocaleString();
if (step >= steps) {
clearInterval(animation);
}
}, duration / steps);
} catch (error) {
console.error('Error:', error);
}
}
// Initialize feature modal functionality
let featureModal;
// Initialize userVotes from localStorage
const userVotes = new Map(
JSON.parse(localStorage.getItem('featureVotes') || '[]')
);
// Helper function to save votes to localStorage
function saveVotesToStorage() {
localStorage.setItem('featureVotes', JSON.stringify([...userVotes]));
}
async function loadFeatures() {
const { data: features, error } = await supabaseClient
.from('feature_requests')
.select('*')
.order('votes', { ascending: false });
if (error) {
console.error('Error loading features:', error);
return;
}
const featureList = document.getElementById('featureList');
featureList.innerHTML = '';
features.forEach(feature => {
const currentVote = userVotes.get(feature.id);
const featureElement = document.createElement('div');
featureElement.className = 'feature-item';
featureElement.setAttribute('data-feature-id', feature.id);
featureElement.innerHTML = `
<div class="vote-buttons">
<button class="btn btn-sm btn-outline-primary vote-up ${currentVote === 1 ? 'active' : ''}"
onclick="vote(${feature.id}, 1)">
👍
</button>
<button class="btn btn-sm btn-outline-primary vote-down ${currentVote === -1 ? 'active' : ''}"
onclick="vote(${feature.id}, -1)">
👎
</button>
</div>
<div class="feature-content">
<div class="feature-text">${feature.feature_text}</div>
<div class="feature-creator">by ${feature.created_by}</div>
</div>
<div class="vote-count">${feature.votes}</div>
`;
featureList.appendChild(featureElement);
});
}
async function vote(featureId, voteValue) {
const username = localStorage.getItem('username');
if (!username) {
alert('Please enter a username first!');
return;
}
const previousVote = userVotes.get(featureId);
let voteChange;
// If clicking the same button again, remove the vote
if (previousVote === voteValue) {
voteChange = -voteValue; // Reverse the previous vote
userVotes.delete(featureId); // Remove the vote from tracking
} else {
// If changing vote or voting for first time
voteChange = previousVote ? (voteValue - previousVote) : voteValue;
userVotes.set(featureId, voteValue);
}
try {
// Update the vote count
const { data: feature, error: getError } = await supabaseClient
.from('feature_requests')
.select('votes')
.eq('id', featureId)
.single();
if (getError) throw getError;
const { error: updateError } = await supabaseClient
.from('feature_requests')
.update({ votes: feature.votes + voteChange })
.eq('id', featureId);
if (updateError) throw updateError;
// Save to localStorage
saveVotesToStorage();
// Refresh the feature list to show new order
const { data: features, error: featuresError } = await supabaseClient
.from('feature_requests')
.select('*')
.order('votes', { ascending: false });
if (featuresError) throw featuresError;
const featureList = document.getElementById('featureList');
featureList.innerHTML = '';
features.forEach(feature => {
const currentVote = userVotes.get(feature.id);
const featureElement = document.createElement('div');
featureElement.className = 'feature-item';
featureElement.setAttribute('data-feature-id', feature.id);
featureElement.innerHTML = `
<div class="vote-buttons">
<button class="btn btn-sm btn-outline-primary vote-up ${currentVote === 1 ? 'active' : ''}"
onclick="vote(${feature.id}, 1)">
👍
</button>
<button class="btn btn-sm btn-outline-primary vote-down ${currentVote === -1 ? 'active' : ''}"
onclick="vote(${feature.id}, -1)">
👎
</button>
</div>
<div class="feature-content">
<div class="feature-text">${feature.feature_text}</div>
<div class="feature-creator">by ${feature.created_by}</div>
</div>
<div class="vote-count">${feature.votes}</div>
`;
featureList.appendChild(featureElement);
});
} catch (error) {
console.error('Error voting:', error);
alert('Error while voting. Please try again.');
}
}
async function submitFeature() {
const input = document.getElementById('newFeature');
const featureText = input.value.trim();
const username = localStorage.getItem('username');
if (!featureText || !username) return;
const { error } = await supabaseClient
.from('feature_requests')
.insert({
feature_text: featureText,
created_by: username
});
if (error) {
console.error('Error submitting feature:', error);
return;
}
input.value = '';
loadFeatures();
}
document.addEventListener('DOMContentLoaded', () => {
// Initialize the modal
featureModal = new bootstrap.Modal(document.getElementById('featureModal'));
// Add button click handler
document.getElementById('featureRequestBtn').addEventListener('click', () => {
loadFeatures();
featureModal.show();
});
// Add submit button handler
document.getElementById('submitFeature').addEventListener('click', submitFeature);
// Add input validation
document.getElementById('newFeature').addEventListener('input', (e) => {
if (e.target.value.length > 120) {
e.target.value = e.target.value.slice(0, 120);
}
});
});
// Initialize championship popup when document is ready
document.addEventListener('DOMContentLoaded', () => {
// Show championship popup if maintenance mode is ON
if (CONFIG.MAINTENANCE_MODE) {
const championship = new ChampionshipPopup();
championship.initialize();
}
});
</script>
</body>
</html>