-
Notifications
You must be signed in to change notification settings - Fork 0
/
card.js
462 lines (444 loc) · 18.3 KB
/
card.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
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
let gameActive = false;
let playerStand = false;
let opponentButtonClicked = false;
let challengerStand = false;
let rounds = 0; // Initialize rounds counter
let gameEndTimeout = null;
let gameStopped = false;
let turn = "player";
let aiActionPending = false;
let bestOf = 3; // Can only be an odd number
let deck = [], deckData = [], deckCenterStack = []; // Combining similar variables
let playerCards = [], challengerCards = [], playerCardPositions = [], challengerCardPositions = []; // Combining similar variables
let playerCardCount = 2, challengerCardCount = 2; // Combining similar variables
let playerWins = 0, challengerWins = 0; // Combining similar variables
let challengerAIs = {debug: debugAI};
const generateFanOutPositions = count => Array.from({length: count}, (_, i) => ({x: (1 - i) * 30, y: 250, rotate: (1 - i) * 5}));
const loadDeck = async () => deckData = await (await fetch('shoe.json')).json();
const shuffleDeck = (deck) => {
if (!Array.isArray(deck)) {
console.error('Invalid input: deck should be an array');
return;
}
for (let i = deck.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1));
[deck[i], deck[j]] = [deck[j], deck[i]];
};
console.log("Shuffled Deck: ", deck);
return deck;
};
const updateTurns = () => {
if(!gameActive) {
console.log("Game is not active");
return;
}
console.log(`Turn before update: ${turn}`);
turn = turn === "player" ? "challenger" : "player";
console.log(`Turn after update: ${turn}`);
if(turn === "player") {
console.log("Player's turn");
} else if(turn === "challenger") {
console.log("Challenger's turn");
challengerTurn();
}
console.log(`Final turn: ${turn}`);
};
function hit() {
return new Promise((resolve, reject) => {
try {
console.log(`[${turn}] [attempt hit]`);
if (!gameActive || deckCenterStack.length === 0) throw new Error("Cannot hit: Game not active or deck is empty");
const newCard = deckCenterStack.pop();
const newCardData = deckData[deckCenterStack.length];
let challenger = sessionStorage.getItem('challenger');
newCard.style.backgroundImage = `url(${newCardData.url})`;
updateScore(newCardData.value, turn === "player");
if (turn === "player") {
playerCards.push(newCard);
playerCardCount++;
playerCardPositions = generateFanOutPositions(playerCards.length);
console.log(`[Player] [hit]`);
} else {
challengerCards.push(newCard);
challengerCardCount++;
challengerCardPositions = generateFanOutPositions(challengerCards.length);
console.log(`[${challenger}] [hit]`);
}
fanOutCards();
let playerScore = parseInt(document.querySelector("#player-score").textContent);
if (turn === "player" && playerScore > 21) {
console.log(`[${turn}] [forced stand]`);
stand().then(resolve); // Wait for the stand promise to resolve before resolving this promise
} else {
updateTurns();
resolve();
}
} catch (err) {
console.error(`Failed to hit: ${err}`);
reject(err);
}
});
}
function stand() {
return new Promise((resolve, reject) => {
try {
if (!gameActive) throw new Error("Cannot stand: Game not active");
if (turn === "player") {
playerStand = true;
turn = "challenger";
console.log(`[${challenger}] [stand]`);
} else if (turn === "challenger") {
challengerStand = true;
turn = "player";
console.log(`[Player] [stand]`);
updateTurns();
resolve();
}
if (playerStand && challengerStand) {
gameEnd();
} else if(turn === "challenger") {
challengerTurn().then(resolve); // Wait for the challengerTurn promise to resolve before resolving this promise
} else {
resolve();
}
} catch (err) {
console.error(`Failed to stand: ${err}`);
reject(err);
}
});
}
async function challengerTurn(round, bestOf, playerWins, challengerWins) {
return new Promise(async (resolve, reject) => {
try {
if (!gameActive || turn !== "challenger" || aiActionPending) {
console.log(`[challengerTurn] [action pending or game not active, skipping turn]`);
return resolve();
}
const scoreElement = document.querySelector("#challenger-score");
if (!scoreElement) {
throw new Error('エラーが発生しました: チャレンジャーのスコア要素が見つかりませんでした (Error occurred: Challenger\'s score element not found)');
}
let score = parseInt(scoreElement.textContent);
let challenger = sessionStorage.getItem('challenger');
if (!challenger) {
throw new Error('エラーが発生しました: チャレンジャーがsessionStorageに見つかりませんでした (Error occurred: Challenger not found in sessionStorage)');
}
const aiFunction = challengerAIs[challenger];
if (!aiFunction) {
throw new Error(`エラーが発生しました: ${challenger}に対応するAI関数が見つかりませんでした (Error occurred: No AI function found for ${challenger})`);
}
console.log(`[${challenger}] [start turn] Score: ${score}`);
aiActionPending = true;
setTimeout(async () => {
let action;
try {
action = await Promise.race([
aiFunction(score, round, bestOf, playerWins, challengerWins),
new Promise((_, reject) => setTimeout(() => reject(new Error('AI decision timeout')), 60000))
]);
} catch (error) {
console.log(`[challengerTurn] [${challenger}] AI decision timeout, falling back to default AI`);
action = score < 17 ? 'hit' : 'stand'; // Fallback AI
}
console.log(`[${challenger}] [action]: ${action}`);
aiActionPending = false;
if (action === 'hit') {
hit(deckData).then(resolve).catch(reject);
} else if (action === 'stand') {
stand().then(resolve).catch(reject);
} else {
throw new Error(`Invalid action: ${action}`);
}
}, 1000);
} catch (err) {
console.error(`Failed to handle action for Challenger: ${err}`);
aiActionPending = false;
reject(err);
}
});
}
function simulateClick(buttonId) {
const button = document.getElementById(buttonId);
if (button) {
button.click();
console.log(`Button with id ${buttonId} clicked`);
} else {
console.log(`Button with id ${buttonId} does not exist`);
}
}
function stopGame() {
let challenger = sessionStorage.getItem('challenger');
const keyMappings = {
'debug': { win: 'A001', loss: 'A002' },
};
if (playerWins > challengerWins) {
console.log(`Player has won against ${challenger}`);
sessionStorage.setItem(keyMappings[challenger].win, 'true');
console.log(`Key '${keyMappings[challenger].win}' set to true`);
unlockAndClickButton(keyMappings[challenger].win);
} else {
console.log(`Player has lost against ${challenger}`);
sessionStorage.setItem(keyMappings[challenger].loss, 'true');
console.log(`Key '${keyMappings[challenger].loss}' set to true`);
unlockAndClickButton(keyMappings[challenger].loss);
}
if (gameEndTimeout !== null) {
clearTimeout(gameEndTimeout);
console.log('Game end timeout cleared');
}
simulateClick('stopButton');
opponentButtonClicked = false;
playerWins = 0;
challengerWins = 0;
gameActive = false;
gameStopped = true;
console.log('Game stopped');
rounds = 0; // Reset the rounds count
}
function unlockAndClickButton(key) {
let button = document.getElementById(key);
if (button) {
button.classList.remove('hidden');
console.log(`Button '${key}' has been unlocked`);
button.click();
console.log(`Button '${key}' has been clicked`);
} else {
console.error(`Button '${key}' not found`);
}
}
const waitForOpponentButtonClick = () => {
return new Promise((resolve) => {
let checkInterval = setInterval(() => {
if (opponentButtonClicked) {
clearInterval(checkInterval);
resolve();
}
}, 1000); // Check every second
});
};
const startGame = async () => {
console.log('startGame running...');
gameStopped = false;
await waitForOpponentButtonClick();
let challenger = sessionStorage.getItem('challenger');
if (challenger == null) {
console.log('Challenger not set, game not starting');
return;
}
if (sessionStorage.getItem('cutActive') === 'true') {
console.log('Cutscene active, waiting to start game...');
let cutActiveCheckInterval = setInterval(() => {
if (sessionStorage.getItem('cutActive') === 'false') {
console.log('Cutscene ended, starting game...');
clearInterval(cutActiveCheckInterval);
beginGame(challenger);
}
}, 1000); // Check every second
} else {beginGame(challenger);}
};
function beginGame(challenger) {
console.log(`Starting game with ${challenger}...`);
gameActive = true;
turn = "player";
deckData = shuffleDeck(deckData);
setCardImagesAndScores();
playerCardPositions = generateFanOutPositions(playerCards.length);
challengerCardPositions = generateFanOutPositions(challengerCards.length);
fanOutCards();
}
async function restartGame() {
console.log('Restarting game...');
let gameEndDiv = document.getElementById('gameEnd');
gameEndDiv.style.animation = '';
gameEndDiv.style.visibility = 'hidden';
gameActive = false;
playerStand = false;
challengerStand = false;
turn = "player";
deckCenterStack = [];
playerCards = [];
challengerCards = [];
playerCardCount = 2;
challengerCardCount = 2;
playerCardPositions = [];
challengerCardPositions = [];
document.querySelector("#player-score").textContent = "0";
document.querySelector("#challenger-score").textContent = "0";
const centerStack = document.querySelector('.center-stack');
while (centerStack.firstChild) {
centerStack.removeChild(centerStack.firstChild);
}
try {
await createCards();
} catch (err) {
console.error(`Failed to create cards: ${err}`);
return;
}
if(gameStopped) {
console.log('Game was stopped, not restarting');
gameStopped = false;
return;
}
setButtonListeners();
playerCardPositions = generateFanOutPositions(playerCards.length);
challengerCardPositions = generateFanOutPositions(challengerCards.length);
setTimeout(startGame, 5200);
console.log('Game restart process completed.');
}
function createCards() {
const centerStack = document.querySelector('.center-stack');
for (let i = 1; i <= 52; i++) {
let card = document.createElement('div');
card.classList.add('card');
card.id = `card-${i}`;
centerStack.appendChild(card);
deckCenterStack.push(card); // Add the card to the deck array
}
}
function applyTransform(cards, positions, yMultiplier) {
cards.forEach((card, i) => {
let pos = positions[i];
card.style.transform = `translate(${pos.x}px, ${yMultiplier * pos.y}px) rotate(${pos.rotate}deg)`;
});
}
function fanOutCards() {
applyTransform(playerCards, playerCardPositions, 1);
applyTransform(challengerCards, challengerCardPositions, -1);
}
function setCardImagesAndScores() {
try {
const playerScoreElement = document.querySelector("#player-score");
const challengerScoreElement = document.querySelector("#challenger-score");
if (!playerScoreElement || !challengerScoreElement) {
throw new Error("Score elements not found");
}
let playerScore = 0;
let challengerScore = 0;
const cards = deckData.slice(0, 4).map((card, index) => {
let cardElement = deckCenterStack[index];
cardElement.style.backgroundImage = `url(${card.url})`;
// Adding onerror event to handle image loading failure
cardElement.onerror = function () {
cardElement.textContent = card.face; // Replace with face text
cardElement.style.backgroundColor = "lightgray"; // Optional: Set a background color
};
if (index < 2) {
challengerCards.push(cardElement);
challengerScore += card.value;
} else {
playerCards.push(cardElement);
playerScore += card.value;
}
return card.value;
});
playerScoreElement.textContent = playerScore; // Update player score element
challengerScoreElement.textContent = `${playerScore} vs ${challengerScore}`; // Update challenger score element
} catch (err) {
console.error(`Error setting scores: ${err}`);
}
}
function updateScore(value, isPlayer) {
const playerScoreElement = document.querySelector("#player-score");
const challengerScoreElement = document.querySelector("#challenger-score");
if (!playerScoreElement || !challengerScoreElement) {
console.error("Score elements not found");
return;
}
let [currentPlayerScore, currentChallengerScore] = challengerScoreElement.textContent.split(" vs ").map(Number);
if (isNaN(currentPlayerScore) || isNaN(currentChallengerScore)) {
console.error("Invalid score format");
return;
}
if (isPlayer) {
currentPlayerScore += value;
} else {
currentChallengerScore += value;
}
playerScoreElement.textContent = currentPlayerScore; // Update player score element
challengerScoreElement.textContent = `${currentPlayerScore} vs ${currentChallengerScore}`; // Update challenger score element
console.log(`${isPlayer ? "Player" : "Challenger"} drew a card: ${value}`);
console.log(`New score: ${currentPlayerScore} vs ${currentChallengerScore}`);
}
function gameEnd() {
return new Promise((resolve, reject) => {
try {
console.log('Ending game...');
let playerScore = parseInt(document.querySelector("#player-score").textContent);
let challengerScore = parseInt(document.querySelector("#challenger-score").textContent);
let challenger = sessionStorage.getItem('challenger');
let gameEndDiv = document.getElementById('gameEnd');
let endStateP = document.getElementById('endState');
let endRatioP = document.getElementById('endRatio');
if (playerScore > 21 && challengerScore > 21) {
console.log(`[Game] [tie]`);
endStateP.textContent = "Tie!";
} else if (playerScore > 21) {
console.log(`[Player] [bust]`);
endStateP.textContent = "Bust!";
challengerWins += 1;
rounds++; // Increment the rounds counter here
} else if (challengerScore > 21) {
console.log(`[${challenger}] [bust]`);
endStateP.textContent = `Bust!`;
playerWins += 1;
rounds++; // And here
} else if (playerScore === challengerScore) {
console.log(`[Game] [tie]`);
endStateP.textContent = "Tie!";
} else if (playerScore > challengerScore) {
console.log(`[Player] [win]`);
endStateP.textContent = "Player won!";
playerWins += 1;
rounds++; // And here
} else {
console.log(`[${challenger}] [win]`);
endStateP.textContent = `${challenger} won!`;
challengerWins += 1;
rounds++; // And here
}
console.log(`Round ${rounds} has started`); // Log the round number
endRatioP.textContent = `${playerWins} : ${challengerWins}`;
gameEndDiv.style.animation = 'zoomIn 2s forwards';
gameEndDiv.style.visibility = 'visible';
if (rounds === bestOf) {
stopGame();
}
gameEndTimeout = setTimeout(() => {
gameEndDiv.style.animation = 'zoomOut 2s forwards';
const restartGameHandler = () => {
if (rounds < bestOf) {
gameEndDiv.style.visibility = 'hidden';
setTimeout(restartGame, 1000);
}
gameEndDiv.removeEventListener('animationend', restartGameHandler);
resolve();
};
gameEndDiv.removeEventListener('animationend', restartGameHandler);
gameEndDiv.addEventListener('animationend', restartGameHandler);
}, 5000);
} catch (err) {
console.error(`Failed to end game: ${err}`);
reject(err);
}
});
}
function setButtonListeners() {
const buttons = {"hitButton": () => hit(deckData),"standButton": stand,};
for (const id in buttons) {
document.getElementById(id).addEventListener('click', function() {
if (turn !== "player") return;
buttons[id]();
});
}
}
document.querySelectorAll('.opponent-button').forEach((button) => {
button.addEventListener('click', async () => {
opponentButtonClicked = true;
createCards();
setButtonListeners();
playerCardPositions = generateFanOutPositions(playerCardCount);
challengerCardPositions = generateFanOutPositions(challengerCardCount);
startGame();
});
});
loadDeck();