generated from EnclaveGames/Enclave-Phaser-Template
-
Notifications
You must be signed in to change notification settings - Fork 5
/
computerdraft.html
685 lines (631 loc) · 25.4 KB
/
computerdraft.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
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Basketball Player Draft</title>
<style>
body {
font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
margin: 0;
padding: 0;
background-color: #f8f8f8;
}
h1, h2 {
text-align: center;
margin-bottom: 20px;
}
.container {
display: flex;
justify-content: center;
align-items: flex-start;
margin-top: 30px;
}
.side {
width: 45%;
margin: 0 10px;
background-color: #fff;
border-radius: 10px;
box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
padding: 20px;
}
.slots {
display: grid;
grid-template-columns: repeat(3, 1fr);
gap: 10px;
}
.slot {
background-color: #eee;
border: 1px solid #ddd;
border-radius: 5px;
padding: 15px;
text-align: center;
cursor: pointer;
transition: background-color 0.3s ease;
position: relative; /* Added for positioning tooltip */
}
.slot:hover {
background-color: #f0f0f0;
}
.selectedSlot {
background-color: lightblue;
}
.playerSelected {
background-color: lightgreen;
}
.playerStats {
position: absolute;
top: calc(100% + 5px);
left: 50%;
transform: translateX(-50%);
background-color: rgba(255, 255, 255, 0.9);
padding: 10px;
border-radius: 5px;
box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
display: none;
z-index: 100;
}
.slot:hover .playerStats {
display: block;
}
#playerSearchContainer {
display: none;
margin-top: 20px;
text-align: center;
}
#playerSearchInput {
padding: 10px;
border: 1px solid #ddd;
border-radius: 5px;
width: 70%;
margin-right: 10px;
}
#searchResults {
margin-top: 10px;
max-height: 200px;
overflow-y: auto;
padding-right: 10px; /* Adjust for scrollbar */
}
.searchResult {
padding: 10px;
margin-bottom: 5px;
cursor: pointer;
background-color: #f9f9f9;
border: 1px solid #ddd;
border-radius: 5px;
transition: background-color 0.3s ease;
}
.searchResult:hover {
background-color: #f0f0f0;
}
#turnIndicator {
font-size: 20px;
font-weight: bold;
color: #333;
text-align: center;
margin-top: 30px;
}
#submitTeams {
display: block;
margin: 20px auto;
padding: 10px 20px;
background-color: #4CAF50;
color: white;
border: none;
border-radius: 5px;
cursor: pointer;
font-size: 16px;
transition: background-color 0.3s ease;
}
#submitTeams:hover {
background-color: #45a049;
}
.resultContainer {
margin-top: 20px;
text-align: center;
}
.result {
margin-bottom: 10px;
font-size: 18px;
font-weight: bold;
}
#comment-section {
margin: auto;
width: 50%;
padding: 10px;
}
#comments {
margin-bottom: 20px;
}
.comment {
background-color: #f2f2f2;
padding: 10px;
margin-bottom: 10px;
}
input, textarea {
width: 100%;
margin-bottom: 10px;
}
button {
width: 100%;
padding: 10px;
background-color: blue;
color: white;
cursor: pointer;
}
.exitButton {
position: absolute;
top: 0;
right: 0;
width: 50px !important;
background-color: red !important;
}
.resetButton {
position: absolute;
top: 0;
right: 50px;
width: 50px !important;
background-color: rgb(115, 0, 255) !important;
}
#drawSpace {
position: fixed;
bottom: 10%;
left: 24.5%;
z-index: 9999;
background-color: #000;
border: 10px solid #0000FF;
height: 800px;
width: 50%;
border-radius: 10px;
}
</style>
</head>
<body>
<h1>Basketball Player Draft</h1>
<div id="turnIndicator">Player A's Turn</div>
<div id="projectedFantasyPoints"></div>
<div id="playerSearchContainer">
<input type="text" id="playerSearchInput" placeholder="Enter player name">
<div id="searchResults"></div>
</div>
<div class="container">
<div class="side sideA">
<h2>Team A</h2>
<div class="slots">
<div class="slot" id="pg1Slot">Point Guard 1</div>
<div class="slot" id="pf1Slot">Power Forward 1</div>
<div class="slot" id="pf2Slot">Power Forward 2</div>
<div class="slot" id="cSlot">Center</div>
<div class="slot" id="sf1Slot">Small Forward 1</div>
<div class="slot" id="sf2Slot">Small Forward 2</div>
<div class="slot" id="sgSlot">Shooting Guard</div>
<div class="slot" id="benchASlot1">Bench</div>
<div class="slot" id="benchASlot2">Bench</div>
<div class="slot" id="benchASlot3">Bench</div>
<div class="slot" id="benchASlot4">Bench</div>
<div class="slot" id="benchASlot5">Bench</div>
<div class="slot" id="benchASlot6">Bench</div>
</div>
</div>
<div class="side sideB">
<h2>CPU Team</h2>
<div>
<label for="cpuDraftChoice">CPU Draft From:</label>
<select id="cpuDraftChoice">
<option value="current">Current Players</option>
<option value="allTime">All Time Players</option>
</select>
</div>
<div class="slots">
<div class="slot" id="pg2Slot">Point Guard 1</div>
<div class="slot" id="pf3Slot">Power Forward 1</div>
<div class="slot" id="pf4Slot">Power Forward 2</div>
<div class="slot" id="c2Slot">Center</div>
<div class="slot" id="sf3Slot">Small Forward 1</div>
<div class="slot" id="sf4Slot">Small Forward 2</div>
<div class="slot" id="sg2Slot">Shooting Guard</div>
<div class="slot" id="benchBSlot1">Bench</div>
<div class="slot" id="benchBSlot2">Bench</div>
<div class="slot" id="benchBSlot3">Bench</div>
<div class="slot" id="benchBSlot4">Bench</div>
<div class="slot" id="benchBSlot5">Bench</div>
<div class="slot" id="benchBSlot6">Bench</div>
</div>
</div>
</div>
<button id="submitTeams">Submit Teams</button>
<div id="comment-section">
<h2>Comments</h2>
<input type="text" id="gameNameInput" placeholder="Enter game name to view comments">
<button onclick="fetchComments()">Load Comments</button>
<div id="comments"></div>
<h3>Add a comment</h3>
<input type="text" id="userName" placeholder="Your name">
<textarea id="text" placeholder="Your comment"></textarea>
<button onclick="addDrawing()" id="drawButton">Add Drawing</button>
<button onclick="sent()">Post Comment</button>
</div>
<div id="drawSpace">
<button class="exitButton" id="Exit" onclick="exitDrawing()">Exit</button>
<button class="resetButton" id="Reset" onclick="reset()">Reset</button>
<br>
<canvas id="Board" left="10%" width="700px" height="700px" style="border:3px solid #548BC2;" onmousemove="coordinate(event)" onmousedown="mousedown()" onmouseup="mouseup()"></canvas>
<button id="saveButton" onclick="saveDrawing()">Save</button>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script>
const apiKey = "4517a956-607b-4c63-ac89-1cd44e7dcaad";
let currentSlot;
let currentPlayer = 'A';
let selectedPlayers = []; // Array to keep track of selected players
let projectedScore = 0;
$(document).ready(function() {
$(".slot").click(function() {
if ((currentPlayer === 'A' && $(this).closest('.side').hasClass('sideA'))) {
if(currentSlot) {
currentSlot.removeClass('selectedSlot');
}
currentSlot = $(this);
currentSlot.addClass('selectedSlot');
$("#playerSearchContainer").show();
} else {
alert("It's not your turn!");
}
});
$("#playerSearchInput").on('input', function() {
const searchQuery = $(this).val();
if(searchQuery.length >= 3) { // Only search if the query is 3 or more characters
searchPlayer(searchQuery);
} else {
$("#searchResults").empty(); // Clear previous search results
}
});
$("#submitTeams").click(function() {
sendTeamData();
prepareAndSendTeamData();
});
$("#searchResults").on('click', '.searchResult', function() {
const playerName = $(this).text();
const names = playerName.split(" "); // Assuming names are separated by a space
const firstName = names[0];
const lastName = names[1] || ''; // Handle potential single-name scenarios
if(selectedPlayers.includes(playerName)) {
alert("This player has already been selected!");
return;
}
$.ajax({
beforeSend: function(request) {
request.setRequestHeader("Authorization", '4517a956-607b-4c63-ac89-1cd44e7dcaad');
},
dataType: "json",
url: `https://api.balldontlie.io/v1/players?first_name=${firstName}&last_name=${lastName}`,
success: function(data) {
if (data && data.data.length > 0) {
const player = data.data[0];
// Now that we have the player's ID, we can store it alongside the player's name
currentSlot.text(playerName);
currentSlot.data('player-id', player.id); // Store the player's ID in the slot's data
currentSlot.removeClass('selectedSlot').addClass('playerSelected');
$("#playerSearchContainer").hide();
$("#playerSearchInput").val(''); // Clear the search input
$("#searchResults").empty(); // Clear previous search results
selectedPlayers.push(playerName); // Add player to selectedPlayers list
toggleTurn(); // Switch the turn to the other player after successful selection
} else {
alert("Player not found.");
}
}
});
});
});
function toggleTurn() {
if(currentPlayer === 'A') {
currentPlayer = 'CPU';
$("#turnIndicator").text("CPU's Turn"); // Update the turn indicator on the page
setTimeout(() => {
cpuPick(currentSlot.attr('id')); // Pass the slot ID to the CPU pick function
}, 1000); // Simulate a delay for CPU pick
} else {
currentPlayer = 'A';
$("#turnIndicator").text("Player A's Turn"); // Update the turn indicator on the page
$("#playerSearchContainer").hide();
}
console.log("Turn toggled, now it's Player " + currentPlayer + "'s turn"); // Log for debugging
}
function searchPlayer(query) {
$.ajax({
beforeSend: function(request) {
request.setRequestHeader("Authorization", '4517a956-607b-4c63-ac89-1cd44e7dcaad');
},
dataType: "json",
url: `https://api.balldontlie.io/v1/players?search=${query}`,
success: function(data) {
const searchResultsContainer = $("#searchResults");
searchResultsContainer.empty(); // Clear previous search results
data.data.forEach(player => {
const playerName = `${player.first_name} ${player.last_name}`;
const searchResult = $("<div>").addClass("searchResult").text(playerName);
searchResultsContainer.append(searchResult);
});
}
});
}
function fetchGameStats(playerId) {
const currentYear = new Date().getFullYear();
const seasonYear = (new Date().getMonth() >= 9) ? currentYear : currentYear - 1; // NBA season starts in October
return $.ajax({
beforeSend: function(request) {
request.setRequestHeader("Authorization", '4517a956-607b-4c63-ac89-1cd44e7dcaad');
},
dataType: "json",
url: `https://api.balldontlie.io/v1/stats?seasons[]=${seasonYear}&player_ids[]=${playerId}&per_page=1`,
}).then(gamesData => {
if (gamesData.data && gamesData.data.length > 0) {
const game = gamesData.data[0]; // Take the most recent game
const stats = {
points: game.pts ?? 0,
rebounds: game.reb ?? 0,
assists: game.ast ?? 0
};
return stats;
} else {
console.log("Game stats not available for this player:", playerId);
return { points: 0, rebounds: 0, assists: 0 }; // Return default stats if not available
}
}).catch(error => {
console.error("Error fetching game stats for player ID:", playerId);
return { points: 0, rebounds: 0, assists: 0 }; // Return default stats on failure
});
}
async function prepareTeamData() {
let teamA = [];
let teamB = [];
// Process Team A
const teamASlots = $('.sideA .slot.playerSelected');
for (let i = 0; i < teamASlots.length; i++) {
let slot = teamASlots[i];
let playerName = $(slot).text(); // Assuming player's name is directly in the text
let playerId = $(slot).data('player-id'); // Assuming you store player IDs in data attributes
let playerStats = await fetchGameStats(playerId); // Fetch stats asynchronously
teamA.push({ name: playerName, stats: playerStats });
}
// Process CPU Team
const teamBSlots = $('.sideB .slot.playerSelected');
for (let i = 0; i < teamBSlots.length; i++) {
let slot = teamBSlots[i];
let playerName = $(slot).text();
let playerId = $(slot).data('player-id'); // Again, assuming player IDs are stored
let playerStats = await fetchGameStats(playerId);
teamB.push({ name: playerName, stats: playerStats });
}
let teamData = {
teamA: teamA,
teamB: teamB
};
return teamData;
}
async function sendTeamData() {
let dataToSend = await prepareTeamData();
let jsonString = JSON.stringify(dataToSend);
console.log("Sending JSON payload to backend:", jsonString);
fetch("http://localhost:6942/api/simulateup", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: jsonString
})
.then(response => {
if (!response.ok) {
throw new Error('Network response was not ok');
}
return response.json(); // Parse response body as JSON
})
.then(data => {
console.log("Successfully sent team data to backend", data);
// Handle the response data
// Access projected fantasy points for each team from 'data' object
const projectedFantasyPointsTeamA = data.projectedFantasyPointsTeamA;
const projectedFantasyPointsTeamB = data.projectedFantasyPointsTeamB;
// Update the HTML to display the projected fantasy scores
$("#projectedFantasyPoints").empty(); // Clear previous content
const resultContainer = $("<div>").addClass("resultContainer");
const teamAResult = $("<div>").addClass("result").text("Team A Projected Fantasy Score: " + projectedFantasyPointsTeamA);
const teamBResult = $("<div>").addClass("result").text("CPU Projected Fantasy Score: " + projectedFantasyPointsTeamB);
projectedScore = projectedFantasyPointsTeamA[0];
resultContainer.append(teamAResult, teamBResult);
$("#projectedFantasyPoints").append(resultContainer);
})
.catch((error) => {
console.error("Error sending team data to backend", error);
// Handle the error
});
}
function fetchComments() {
const gameName = document.getElementById('gameNameInput').value;
fetch(`http://localhost:6942/api/comments/${encodeURIComponent(gameName)}`)
.then(response => response.json())
.then(data => {
const commentsDiv = document.getElementById('comments');
commentsDiv.innerHTML = ''; // Clear existing comments
data.forEach(comment => {
const commentDiv = document.createElement('div');
commentDiv.classList.add('comment');
commentDiv.innerHTML = `<strong>${comment.userName}</strong>: ${comment.text}`;
commentsDiv.appendChild(commentDiv);
});
})
.catch(error => console.error('Error fetching comments:', error));
}
var b = document.getElementById("Board");
var board = b.getContext("2d");
var down;
var size = 3;
let drawSpace = document.getElementById("drawSpace");
drawSpace.setAttribute("hidden", "hidden");
function addDrawing(){
let ishidden = drawSpace.getAttribute("hidden");
if (ishidden) {
drawSpace.removeAttribute("hidden");
} else {
drawSpace.setAttribute("hidden", "hidden");
}
}
function exitDrawing(){
drawSpace.setAttribute("hidden", "hidden");
}
function reset(){
board.clearRect(0, 0, b.width, b.height);
}
function mousedown(){
down = 1;
}
function mouseup(){
down = 0;
}
function coordinate(event){
let rect = Board.getBoundingClientRect();
var x=event.clientX - rect.left;
var y=event.clientY - rect.top;
if(down){
board.fillStyle = "#FFFFFF";
board.fillRect(x,y,size,size);
}
}
function saveDrawing(){
const dataURL = b.toDataURL('image/jpeg', 0.5);
console.log(dataURL);
reset();
exitDrawing();
const drawingStuff = `<img src="${dataURL}" style="background-color: white; width: 500px;"/>`;
console.log(drawingStuff);
postComment(drawingStuff);
}
function postComment(input) {
const userName = document.getElementById('userName').value;
const gameName = document.getElementById('gameNameInput').value; // Use the same game name for posting
const text = String(input);
const comment = { userName, gameName, text, timestamp: new Date().toISOString() };
fetch('http://localhost:6942/api/comments/', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(comment),
})
.then(response => response.json())
.then(data => {
console.log('Success:', data);
fetchComments(); // Refresh comments after posting ok
})
.catch((error) => {
console.error('Error posting comment:', error);
});
}
async function cpuPick(slotId) {
const slotMapping = {
pg1Slot: "pg2Slot",
pf1Slot: "pf3Slot",
pf2Slot: "pf4Slot",
cSlot: "c2Slot",
sf1Slot: "sf3Slot",
sf2Slot: "sf4Slot",
sgSlot: "sg2Slot",
benchASlot1: "benchBSlot1",
benchASlot2: "benchBSlot2",
benchASlot3: "benchBSlot3",
benchASlot4: "benchBSlot4",
benchASlot5: "benchBSlot5",
benchASlot6: "benchBSlot6"
};
const cpuSlotId = slotMapping[slotId];
const cpuSlot = $("#" + cpuSlotId);
const listChoice = $("#cpuDraftChoice").val();
if (cpuSlot.hasClass('playerSelected')) {
console.error("Slot already selected by CPU.");
return;
}
const response = await fetch("http://localhost:6942/api/player-vs-computer", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({ player: "", list: listChoice }) // Use the selected list (current or all time)
});
const data = await response.json();
const cpuPlayerName = data.computerChoice;
cpuSlot.text(cpuPlayerName);
cpuSlot.removeClass('selectedSlot').addClass('playerSelected');
selectedPlayers.push(cpuPlayerName);
toggleTurn(); // Switch the turn to Team A after CPU selection
}
async function prepareAndSendTeamData() {
try {
const teamData = await prepareTeamData();
console.log("Team data:", teamData);
const email = localStorage.getItem("Email");
const playersData = {
"email": email
};
$('.sideA .slot').each(function() {
const slotId = $(this).attr('id');
const playerName = $(this).hasClass('playerSelected') ? $(this).text() : null;
if (playerName) {
playersData[slotId] = playerName;
}
});
console.log("Players data:", playersData);
// Prepare data for the fantasy score
const fantasyScoreData = {
"email": email,
"score": projectedScore
};
console.log("Fantasy score data:", fantasyScoreData);
// Send the players data to the backend
await sendPlayersData(playersData);
// Send the fantasy score data to the backend
await sendFantasyScore(fantasyScoreData);
console.log("Team data and fantasy score submitted successfully!");
} catch (error) {
console.error("Error preparing and sending team data:", error);
}
}
function getPlayerName(team, position) {
const player = team.find(player => player.position === position);
return player ? player.name : "";
}
async function sendPlayersData(playersData) {
try {
const response = await fetch("http://localhost:6942/api/person/setPlayers", {
method: "PUT",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify(playersData)
});
if (!response.ok) {
throw new Error("Failed to send players data to the backend");
}
} catch (error) {
console.error("Error sending players data:", error);
}
}
async function sendFantasyScore(fantasyScoreData) {
try {
const response = await fetch("http://localhost:6942/api/person/setFantasyScore/", {
method: "PUT",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify(fantasyScoreData)
});
if (!response.ok) {
throw new Error("Failed to send fantasy score data to the backend");
}
} catch (error) {
console.error("Error sending fantasy score data:", error);
}
}
</script>
</body>
</html>