-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
1536 lines (1273 loc) · 51.3 KB
/
script.js
File metadata and controls
1536 lines (1273 loc) · 51.3 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
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
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
let selectedHandLocation = 'your-hand'; // Default to Your Hand
let useShortNames = false; // Global variable to track short name display
let fullCardData = {}; // Store full card data by name for lookup
let selectedType = '-'; // Selected type filter
let selectedRegion = '-'; // Selected region filter
let midWarAdded = false; // Track if mid war cards have been added
let lateWarAdded = false; // Track if late war cards have been added
// Undo system
let actionHistory = [];
const MAX_HISTORY_SIZE = 20;
let lastUndoTime = 0;
const UNDO_RATE_LIMIT_MS = 100; // Prevent accidental rapid undos
// Action types for undo system
const ACTION_TYPES = {
MOVE_CARD: 'move_card',
ADD_UNKNOWN: 'add_unknown',
REMOVE_UNKNOWN: 'remove_unknown',
ADD_DISCARDS: 'add_discards',
ADD_MID_WAR: 'add_mid_war',
ADD_LATE_WAR: 'add_late_war',
REORDER_HAND: 'reorder_hand'
};
function createCardElement(cardData, currentLocation = null) {
const cardDiv = document.createElement('div');
cardDiv.className = 'card';
cardDiv.dataset.war = cardData.war || 'early';
cardDiv.dataset.canBeRemoved = cardData.canBeRemoved ? 'true' : 'false';
// Store full card data for name switching
cardDiv.dataset.cardName = cardData.name || '';
cardDiv.dataset.cardShort = cardData.short || '';
// Store types and regions for filtering
cardDiv.dataset.types = JSON.stringify(cardData.types || []);
cardDiv.dataset.regions = JSON.stringify(cardData.regions || []);
const actionsDiv = document.createElement('div');
actionsDiv.className = 'card-actions';
// Check if this is Shuttle Diplomacy card
const isShuttleDiplomacy = cardData.name === 'Shuttle Diplomacy';
// Create airplane icon for Shuttle Diplomacy, otherwise create remove icon
const removeIcon = document.createElement('div');
if (isShuttleDiplomacy) {
removeIcon.className = 'card-icon airplane-icon';
removeIcon.title = 'Move to In Front';
removeIcon.textContent = '✈';
if (currentLocation === 'in-front') {
removeIcon.classList.add('hidden');
}
} else {
removeIcon.className = 'card-icon remove-icon';
removeIcon.title = 'Move to Removed';
removeIcon.textContent = '⊘';
if (!cardData.canBeRemoved || currentLocation === 'removed') {
removeIcon.classList.add('hidden');
}
}
const discardIcon = document.createElement('div');
discardIcon.className = 'card-icon discard-icon';
discardIcon.title = 'Move to Discard';
discardIcon.textContent = '↓';
if (currentLocation === 'discard') {
discardIcon.classList.add('hidden');
}
const cardText = document.createElement('span');
cardText.className = 'card-text';
if (cardData.eventType) {
cardText.classList.add(cardData.eventType);
}
const displayName = useShortNames ? (cardData.short || cardData.name) : cardData.name;
// Show "★" for scoring cards (ops: 0 and vps type), otherwise show ops number
const isScoringCard = cardData.ops === 0 && cardData.types && cardData.types.includes('vps');
const opsDisplay = isScoringCard ? '★' : cardData.ops;
cardText.textContent = `${opsDisplay} ${displayName}`;
actionsDiv.appendChild(removeIcon);
actionsDiv.appendChild(discardIcon);
cardDiv.appendChild(actionsDiv);
cardDiv.appendChild(cardText);
// Add drag functionality for cards in hand locations
if (currentLocation && currentLocation.includes('hand')) {
setupCardDragging(cardDiv);
}
return cardDiv;
}
function setupCardDragging(cardElement) {
cardElement.draggable = true;
cardElement.addEventListener('dragstart', function(e) {
e.dataTransfer.effectAllowed = 'move';
e.dataTransfer.setData('text/html', cardElement.outerHTML);
e.dataTransfer.setData('text/plain', cardElement.dataset.cardName);
cardElement.classList.add('dragging');
// Store reference to dragged element
cardElement._draggedElement = cardElement;
});
cardElement.addEventListener('dragend', function(e) {
cardElement.classList.remove('dragging');
delete cardElement._draggedElement;
// Clean up any drag indicators
document.querySelectorAll('.drag-over').forEach(el => {
el.classList.remove('drag-over');
});
});
}
function setupHandDropZone(handContainer) {
handContainer.addEventListener('dragover', function(e) {
if (!e.dataTransfer.types.includes('text/html')) return;
e.preventDefault();
e.dataTransfer.dropEffect = 'move';
const draggingCard = document.querySelector('.dragging');
if (!draggingCard) return;
// Find the card we're hovering over
const afterElement = getDragAfterElement(handContainer, e.clientY);
if (afterElement == null) {
handContainer.appendChild(draggingCard);
} else {
handContainer.insertBefore(draggingCard, afterElement);
}
});
handContainer.addEventListener('drop', function(e) {
e.preventDefault();
const draggingCard = document.querySelector('.dragging');
if (!draggingCard || !handContainer.contains(draggingCard)) return;
// Record action for undo
const action = recordAction(ACTION_TYPES.REORDER_HAND, {
location: handContainer.id,
cardName: draggingCard.dataset.cardName
});
updateLocationAverages();
updateCardHighlighting();
// Finalize action for undo
if (action) {
finalizeAction(action);
}
// Auto-save current game state
autoSaveIfNeeded();
});
}
function getDragAfterElement(container, y) {
const draggableElements = [...container.querySelectorAll('.card:not(.dragging)')];
return draggableElements.reduce((closest, child) => {
const box = child.getBoundingClientRect();
const offset = y - box.top - box.height / 2;
if (offset < 0 && offset > closest.offset) {
return { offset: offset, element: child };
} else {
return closest;
}
}, { offset: Number.NEGATIVE_INFINITY }).element;
}
function updateCardButtonVisibility(cardElement, newLocationId) {
const removeIcon = cardElement.querySelector('.remove-icon');
const airplaneIcon = cardElement.querySelector('.airplane-icon');
const discardIcon = cardElement.querySelector('.discard-icon');
// Handle airplane icon for Shuttle Diplomacy
if (airplaneIcon) {
if (newLocationId === 'in-front') {
airplaneIcon.classList.add('hidden');
airplaneIcon.style.visibility = 'hidden';
} else {
airplaneIcon.classList.remove('hidden');
airplaneIcon.style.visibility = 'visible';
}
}
// Handle regular remove icon
if (removeIcon) {
const canBeRemoved = cardElement.dataset.canBeRemoved === 'true';
// Hide if card is in removed location OR if card is not removable
if (newLocationId === 'removed' || !canBeRemoved) {
removeIcon.classList.add('hidden');
removeIcon.style.visibility = 'hidden';
} else {
removeIcon.classList.remove('hidden');
removeIcon.style.visibility = 'visible';
}
}
if (discardIcon) {
if (newLocationId === 'discard') {
discardIcon.classList.add('hidden');
discardIcon.style.visibility = 'hidden';
} else {
discardIcon.classList.remove('hidden');
discardIcon.style.visibility = 'visible';
}
}
}
function createUnknownCardElement() {
const cardDiv = document.createElement('div');
cardDiv.className = 'card unknown-card';
const actionsDiv = document.createElement('div');
actionsDiv.className = 'card-actions';
// Empty space where remove button would be (for alignment)
const emptySpace = document.createElement('div');
emptySpace.className = 'card-icon';
emptySpace.style.visibility = 'hidden';
const minusIcon = document.createElement('div');
minusIcon.className = 'card-icon unknown-minus-icon';
minusIcon.title = 'Remove unknown card';
minusIcon.textContent = '−';
const cardText = document.createElement('span');
cardText.className = 'card-text unknown-card-text';
const deckStats = calculateDeckAverage();
cardText.textContent = `${deckStats.average.toFixed(1)} ?`;
actionsDiv.appendChild(emptySpace);
actionsDiv.appendChild(minusIcon);
cardDiv.appendChild(actionsDiv);
cardDiv.appendChild(cardText);
return cardDiv;
}
async function loadCardDatabase() {
try {
console.log('Loading card database from cards.json');
const response = await fetch('cards.json');
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const cards = await response.json();
// Store full card data for lookup by name
cards.forEach(card => {
fullCardData[card.name] = card;
});
console.log('Card database loaded successfully');
return cards;
} catch (error) {
console.error('Error loading card database:', error);
throw error;
}
}
async function loadCards() {
try {
const cards = await loadCardDatabase();
cards.forEach(cardData => {
let targetLocation, targetLocationId;
// Put mid/late war cards in the hidden box, early war cards in deck
if (cardData.war === 'early') {
targetLocation = getDeckSubsection(cardData.eventType);
targetLocationId = targetLocation.id;
} else {
targetLocation = document.getElementById('box');
targetLocationId = 'box';
}
const cardElement = createCardElement(cardData, targetLocationId);
targetLocation.appendChild(cardElement);
});
// Sort cards in each deck subsection
sortAllDeckSubsections();
// Update averages
updateLocationAverages();
// Update highlighting
updateCardHighlighting();
console.log('Cards rendered and sorted in deck');
} catch (error) {
console.error('Error loading cards:', error);
const deckArea = document.getElementById('deck');
deckArea.innerHTML = `<p>Error loading cards: ${error.message}</p>`;
}
}
function getDeckSubsection(eventType) {
switch(eventType) {
case 'us': return document.getElementById('deck-us');
case 'ussr': return document.getElementById('deck-ussr');
case 'neutral': return document.getElementById('deck-neutral');
default: return document.getElementById('deck-neutral');
}
}
function getCardEventType(cardElement) {
const cardTextElement = cardElement.querySelector('.card-text');
if (!cardTextElement) return 'neutral';
if (cardTextElement.classList.contains('us')) {
return 'us';
} else if (cardTextElement.classList.contains('ussr')) {
return 'ussr';
}
return 'neutral';
}
function getCardData(cardElement) {
const cardText = cardElement.querySelector('.card-text').textContent;
// Match either number or star for ops
const opsMatch = cardText.match(/^(\d+(?:\.\d+)?|★) (.+)$/);
if (opsMatch) {
// Convert star back to 0 for internal ops value
const opsValue = opsMatch[1] === '★' ? 0 : parseFloat(opsMatch[1]);
return {
ops: opsValue,
name: cardElement.dataset.cardName || opsMatch[2], // Use stored full name if available
short: cardElement.dataset.cardShort || opsMatch[2] // Include short name too
};
}
return {
ops: 0,
name: cardElement.dataset.cardName || cardText,
short: cardElement.dataset.cardShort || cardText
};
}
function enrichCardData(savedCardData) {
// If we have the full card data for this name, merge it
if (fullCardData[savedCardData.name]) {
return {
...fullCardData[savedCardData.name],
ops: savedCardData.ops // Keep the ops from saved data in case it was modified
};
}
// Fallback to saved data if not found in full data
return savedCardData;
}
function shouldAutoSort(containerId) {
// Don't auto-sort hand locations - allow manual sorting
return !containerId.includes('hand');
}
function sortCardsInContainer(container) {
// Skip sorting for hand locations
if (!shouldAutoSort(container.id)) {
return;
}
const cards = Array.from(container.children);
const isDiscardOrRemovedOrInFront = container.id === 'discard' || container.id === 'removed' || container.id === 'in-front';
cards.sort((a, b) => {
const dataA = getCardData(a);
const dataB = getCardData(b);
// For discard, removed, and in-front: sort by event type first (US, Neutral, USSR)
if (isDiscardOrRemovedOrInFront) {
const typeA = getCardEventType(a);
const typeB = getCardEventType(b);
const typeOrder = { 'us': 0, 'neutral': 1, 'ussr': 2 };
if (typeA !== typeB) {
return typeOrder[typeA] - typeOrder[typeB];
}
}
// Sort by ops (ascending)
if (dataA.ops !== dataB.ops) {
return dataA.ops - dataB.ops;
}
// Then by name (alphabetical)
return dataA.name.localeCompare(dataB.name);
});
// Remove all cards and re-add them in sorted order
cards.forEach(card => card.remove());
cards.forEach(card => container.appendChild(card));
}
function calculateAverageOps(container) {
const cards = Array.from(container.children);
if (cards.length === 0) return { count: 0, sum: 0, average: 0 };
const totalOps = cards.reduce((sum, card) => {
const data = getCardData(card);
return sum + data.ops;
}, 0);
return {
count: cards.length,
sum: totalOps,
average: totalOps / cards.length
};
}
function calculateDeckAverage() {
const deckUS = document.getElementById('deck-us');
const deckNeutral = document.getElementById('deck-neutral');
const deckUSSR = document.getElementById('deck-ussr');
const allDeckCards = [
...Array.from(deckUS.children),
...Array.from(deckNeutral.children),
...Array.from(deckUSSR.children)
];
if (allDeckCards.length === 0) return { count: 0, sum: 0, average: 0 };
const totalOps = allDeckCards.reduce((sum, card) => {
const data = getCardData(card);
return sum + data.ops;
}, 0);
return {
count: allDeckCards.length,
sum: totalOps,
average: totalOps / allDeckCards.length
};
}
// Undo system functions
function getGameSnapshot() {
return {
cardPositions: getCardPositions(),
selectedHandLocation: selectedHandLocation,
midWarAdded: midWarAdded,
lateWarAdded: lateWarAdded,
timestamp: Date.now()
};
}
function recordAction(actionType, actionData = {}) {
// Don't record actions during undo operations
if (actionData.isUndoOperation) {
return null;
}
const beforeState = getGameSnapshot();
const action = {
type: actionType,
timestamp: Date.now(),
beforeState: beforeState,
afterState: null, // Will be set after operation completes
actionData: actionData
};
// Store reference to be filled after operation
actionHistory.push(action);
// Trim history if too large
if (actionHistory.length > MAX_HISTORY_SIZE) {
actionHistory.shift();
}
return action;
}
function finalizeAction(action) {
if (action && !action.afterState) {
action.afterState = getGameSnapshot();
}
updateUndoButtonState();
}
function canUndo() {
return actionHistory.length > 0;
}
function clearActionHistory() {
actionHistory = [];
updateUndoButtonState();
}
function updateUndoButtonState() {
const undoButton = document.getElementById('undo-btn');
if (undoButton) {
undoButton.disabled = !canUndo();
undoButton.style.opacity = canUndo() ? '1' : '0.5';
if (canUndo()) {
const lastAction = actionHistory[actionHistory.length - 1];
const actionName = getActionDisplayName(lastAction.type);
const actionTime = new Date(lastAction.timestamp).toLocaleTimeString();
undoButton.title = `Undo: ${actionName} (${actionTime})\n${actionHistory.length} actions available\nKeyboard: Ctrl+Z`;
} else {
undoButton.title = 'No actions to undo\nKeyboard: Ctrl+Z';
}
}
}
function getActionDisplayName(actionType) {
const displayNames = {
[ACTION_TYPES.MOVE_CARD]: 'Move Card',
[ACTION_TYPES.ADD_UNKNOWN]: 'Add Unknown Card',
[ACTION_TYPES.REMOVE_UNKNOWN]: 'Remove Unknown Card',
[ACTION_TYPES.ADD_DISCARDS]: 'Add Discards',
[ACTION_TYPES.ADD_MID_WAR]: 'Add Mid War Cards',
[ACTION_TYPES.ADD_LATE_WAR]: 'Add Late War Cards',
[ACTION_TYPES.REORDER_HAND]: 'Reorder Hand'
};
return displayNames[actionType] || actionType;
}
function performUndo() {
if (!canUndo()) {
return false;
}
// Rate limiting to prevent accidental rapid undos
const now = Date.now();
if (now - lastUndoTime < UNDO_RATE_LIMIT_MS) {
console.log('Undo rate limited');
return false;
}
lastUndoTime = now;
const lastAction = actionHistory.pop();
if (lastAction && lastAction.beforeState && lastAction.beforeState.cardPositions) {
// Optional confirmation for bulk operations
const isBulkOperation = [
ACTION_TYPES.ADD_DISCARDS,
ACTION_TYPES.ADD_MID_WAR,
ACTION_TYPES.ADD_LATE_WAR
].includes(lastAction.type);
if (isBulkOperation && !confirmBulkUndo(lastAction)) {
// User cancelled, put the action back
actionHistory.push(lastAction);
updateUndoButtonState();
return false;
}
console.log(`Undoing action: ${lastAction.type} from ${new Date(lastAction.timestamp).toLocaleTimeString()}`);
console.log('Before undo - Current state:', getGameSnapshot().cardPositions);
console.log('Restoring to state:', lastAction.beforeState.cardPositions);
// Restore the previous state
restoreGameSnapshot(lastAction.beforeState, { isUndoOperation: true });
// Visual feedback for undo
showUndoFeedback();
updateUndoButtonState();
return true;
} else {
console.error('Cannot undo - invalid action or state:', lastAction);
// Put the action back if it was invalid
if (lastAction) {
actionHistory.push(lastAction);
}
return false;
}
}
function confirmBulkUndo(action) {
// For now, we'll skip confirmation to keep UX simple
// Could add this later with a setting: return confirm(`Undo ${getActionDisplayName(action.type)}?`);
return true;
}
function showUndoFeedback() {
// Flash the main locations area to indicate undo occurred
const locations = document.querySelector('.locations');
if (locations) {
locations.classList.add('undo-flash');
setTimeout(() => {
locations.classList.remove('undo-flash');
}, 300);
}
// Also flash the undo button briefly
const undoButton = document.getElementById('undo-btn');
if (undoButton) {
undoButton.style.transform = 'scale(0.95)';
setTimeout(() => {
undoButton.style.transform = '';
}, 150);
}
}
function restoreGameSnapshot(snapshot, options = {}) {
// Restore card positions
if (snapshot.cardPositions) {
restoreCardPositions(snapshot.cardPositions, options);
}
// Restore selected hand location
if (snapshot.selectedHandLocation) {
selectedHandLocation = snapshot.selectedHandLocation;
selectHandLocation(selectedHandLocation);
}
// Restore war card flags
midWarAdded = snapshot.midWarAdded || false;
lateWarAdded = snapshot.lateWarAdded || false;
updateWarButtonStates();
// Update averages
updateLocationAverages();
// Update highlighting
updateCardHighlighting();
// Auto-save if not during undo operation
if (!options.isUndoOperation) {
autoSaveIfNeeded();
}
}
function updateLocationAverages() {
// First update all unknown cards with current deck average
const deckStats = calculateDeckAverage();
const unknownCards = document.querySelectorAll('.unknown-card-text');
unknownCards.forEach(cardText => {
cardText.textContent = `${deckStats.average.toFixed(1)} ?`;
});
// Update Your Hand average
const yourHandContainer = document.getElementById('your-hand');
const yourHandStats = calculateAverageOps(yourHandContainer);
document.getElementById('your-hand-avg').textContent =
yourHandStats.count > 0 ? `${yourHandStats.count} cards, ${yourHandStats.sum.toFixed(0)} ops, ${yourHandStats.average.toFixed(1)}/card` : '';
// Update Opponent's Hand average
const opponentHandContainer = document.getElementById('opponent-hand');
const opponentHandStats = calculateAverageOps(opponentHandContainer);
document.getElementById('opponent-hand-avg').textContent =
opponentHandStats.count > 0 ? `${opponentHandStats.count} cards, ${opponentHandStats.sum.toFixed(1)} ops, ${opponentHandStats.average.toFixed(1)}/card` : '';
// Update Deck average
document.getElementById('deck-avg').textContent =
deckStats.count > 0 ? `${deckStats.count} cards, ${deckStats.sum.toFixed(0)} ops, ${deckStats.average.toFixed(1)}/card` : '';
// Update Discard count
const discardContainer = document.getElementById('discard');
const discardCount = discardContainer.children.length;
document.getElementById('discard-count').textContent =
discardCount > 0 ? `${discardCount} card${discardCount !== 1 ? 's' : ''}` : '';
// Update Removed count
const removedContainer = document.getElementById('removed');
const removedCount = removedContainer.children.length;
document.getElementById('removed-count').textContent =
removedCount > 0 ? `${removedCount} card${removedCount !== 1 ? 's' : ''}` : '';
// Update In Front count
const inFrontContainer = document.getElementById('in-front');
const inFrontCount = inFrontContainer.children.length;
document.getElementById('in-front-count').textContent =
inFrontCount > 0 ? `${inFrontCount} card${inFrontCount !== 1 ? 's' : ''}` : '';
}
function moveCard(cardElement, targetLocationId, options = {}) {
// Record action for undo
const action = !options.skipUndo ? recordAction(ACTION_TYPES.MOVE_CARD, {
cardName: getCardData(cardElement).name,
fromLocation: cardElement.closest('.card-area')?.id,
toLocation: targetLocationId
}) : null;
cardElement.remove();
let actualLocationId = targetLocationId;
if (targetLocationId === 'deck') {
// Get the card's event type from its text element
const eventType = getCardEventType(cardElement);
const targetLocation = getDeckSubsection(eventType);
actualLocationId = targetLocation.id;
targetLocation.appendChild(cardElement);
sortCardsInContainer(targetLocation);
} else {
const targetLocation = document.getElementById(targetLocationId);
targetLocation.appendChild(cardElement);
sortCardsInContainer(targetLocation);
}
// Update button visibility based on actual final location
updateCardButtonVisibility(cardElement, actualLocationId);
// Enable dragging if moved to a hand location
if (actualLocationId.includes('hand')) {
setupCardDragging(cardElement);
} else {
// Remove dragging if moved away from hand
cardElement.draggable = false;
cardElement.classList.remove('dragging');
}
// Update averages after moving card
updateLocationAverages();
// Update highlighting for the moved card
updateCardHighlighting();
// Special logic: If Middle East or Asia Scoring is moved to discard,
// automatically move Shuttle Diplomacy from "in-front" to discard
if (targetLocationId === 'discard' && !options.skipUndo) {
const cardName = getCardData(cardElement).name;
if (cardName === 'Middle East Scoring' || cardName === 'Asia Scoring') {
const inFrontContainer = document.getElementById('in-front');
const shuttleDiplomacyCard = Array.from(inFrontContainer.children).find(card => {
return getCardData(card).name === 'Shuttle Diplomacy';
});
if (shuttleDiplomacyCard) {
// Move Shuttle Diplomacy to discard automatically
moveCard(shuttleDiplomacyCard, 'discard', { skipUndo: false });
}
}
}
// Finalize action for undo
if (action) {
finalizeAction(action);
}
// Auto-save current game state
autoSaveIfNeeded();
}
function selectHandLocation(locationId, options = {}) {
// Remove selected class from all locations
document.querySelectorAll('.location').forEach(loc => {
loc.classList.remove('selected');
});
// Set the selected hand location
selectedHandLocation = locationId;
// Update selection indicators
const yourHandIndicator = document.getElementById('your-hand-indicator');
const opponentHandIndicator = document.getElementById('opponent-hand-indicator');
if (locationId === 'your-hand') {
const yourHandLocation = document.querySelector('#your-hand').closest('.location');
if (yourHandLocation) {
yourHandLocation.classList.add('selected');
}
if (yourHandIndicator) yourHandIndicator.textContent = '●';
if (opponentHandIndicator) opponentHandIndicator.textContent = '○';
} else if (locationId === 'opponent-hand') {
const opponentHandLocation = document.querySelector('#opponent-hand').closest('.location');
if (opponentHandLocation) {
opponentHandLocation.classList.add('selected');
}
if (yourHandIndicator) yourHandIndicator.textContent = '○';
if (opponentHandIndicator) opponentHandIndicator.textContent = '●';
}
}
document.addEventListener('click', function(e) {
// Handle location header clicks (including clicks on h2 or selection indicator)
const h2Element = e.target.tagName === 'H2' ? e.target : e.target.closest('h2');
if (h2Element) {
// Find the card area - it might be a sibling of the parent container now
let cardArea = h2Element.nextElementSibling;
if (!cardArea || !cardArea.classList.contains('card-area')) {
// Try looking for it as a sibling of the parent
const parentContainer = h2Element.closest('.location-header');
if (parentContainer) {
cardArea = parentContainer.nextElementSibling;
}
}
if (cardArea && cardArea.classList.contains('card-area')) {
const locationId = cardArea.id;
if (locationId === 'your-hand' || locationId === 'opponent-hand') {
selectHandLocation(locationId);
}
}
return;
}
// Handle card actions
if (e.target.classList.contains('discard-icon')) {
e.stopPropagation();
const card = e.target.closest('.card');
moveCard(card, 'discard');
} else if (e.target.classList.contains('airplane-icon')) {
e.stopPropagation();
const card = e.target.closest('.card');
moveCard(card, 'in-front');
} else if (e.target.classList.contains('remove-icon')) {
e.stopPropagation();
const card = e.target.closest('.card');
moveCard(card, 'removed');
} else if (e.target.classList.contains('unknown-minus-icon')) {
e.stopPropagation();
const card = e.target.closest('.card');
// Record action for undo
const action = recordAction(ACTION_TYPES.REMOVE_UNKNOWN);
card.remove();
updateLocationAverages();
updateCardHighlighting();
// Finalize action for undo
finalizeAction(action);
// Auto-save current game state
autoSaveIfNeeded();
} else if (e.target.classList.contains('card-text')) {
e.stopPropagation();
const card = e.target.closest('.card');
// Don't allow unknown cards to be moved via text clicks
if (card.classList.contains('unknown-card')) {
return;
}
const currentLocation = card.closest('.card-area');
// If card is in Deck, move to selected hand location
// Otherwise, move to Deck
if (currentLocation && currentLocation.id.startsWith('deck-')) {
moveCard(card, selectedHandLocation);
} else {
moveCard(card, 'deck');
}
}
});
// Game management state
let currentGameId = null;
let isLoading = false;
let playerSide = null; // 'US' or 'USSR'
// Game management functions
function getGamesList() {
const games = localStorage.getItem('cardCounter_games');
return games ? JSON.parse(games) : [];
}
function saveGamesList(games) {
localStorage.setItem('cardCounter_games', JSON.stringify(games));
}
function getCurrentGameId() {
if (!currentGameId) {
currentGameId = localStorage.getItem('cardCounter_currentGame');
}
return currentGameId;
}
function autoSaveIfNeeded() {
if (getCurrentGameId()) {
saveCurrentGame();
}
}
function setCurrentGameId(gameId) {
currentGameId = gameId;
localStorage.setItem('cardCounter_currentGame', gameId);
}
function getCardPositions() {
const positions = {};
const locations = ['your-hand', 'opponent-hand', 'deck-us', 'deck-neutral', 'deck-ussr', 'discard', 'removed', 'in-front', 'box'];
locations.forEach(locationId => {
const container = document.getElementById(locationId);
if (container) {
positions[locationId] = Array.from(container.children).map(card => {
const data = getCardData(card);
const isUnknown = card.classList.contains('unknown-card');
return {
name: isUnknown ? '?' : data.name,
ops: data.ops,
eventType: getCardEventType(card),
canBeRemoved: !card.querySelector('.remove-icon') || !card.querySelector('.remove-icon').classList.contains('hidden'),
war: card.dataset.war || 'early',
isUnknown: isUnknown
};
});
}
});
return positions;
}
function getGameTitle() {
// Title is now only shown in dropdown, retrieve from game data if needed
const gameId = getCurrentGameId();
if (!gameId) return '';
const games = getGamesList();
const game = games.find(g => g.id === gameId);
return game ? game.name : '';
}
function getGameNotes() {
return document.getElementById('game-notes').value;
}
function setGameUIState(title, notes) {
// Title is now only shown in dropdown, no input field to update
document.getElementById('game-notes').value = notes || '';
}
function saveCurrentGame() {
const gameId = getCurrentGameId();
if (!gameId) return;
const gameData = {
id: gameId,
title: getGameTitle(),
notes: getGameNotes(),
cardPositions: getCardPositions(),
playerSide: playerSide, // Store the player's side
midWarAdded: midWarAdded,
lateWarAdded: lateWarAdded,
lastModified: new Date().toISOString()
// Note: We don't persist undo history with game saves for now
// This keeps save files smaller and avoids complexity
};
console.log('Saving game data:', gameData);
localStorage.setItem(`cardCounter_game_${gameId}`, JSON.stringify(gameData));
}
function loadGameData(gameId) {
const gameData = localStorage.getItem(`cardCounter_game_${gameId}`);
return gameData ? JSON.parse(gameData) : null;
}
function parsePlayerSideFromTitle(title) {
// Parse from format: "Opponent Name v YOUR_SIDE (Game ID)"
const match = title.match(/v\s+(US|USSR)\s+\(/);
return match ? match[1] : null;
}
function applySideColors() {
const yourHandLocation = document.querySelector('#your-hand').closest('.location');
const opponentHandLocation = document.querySelector('#opponent-hand').closest('.location');
// Remove existing side classes
yourHandLocation.classList.remove('side-us', 'side-ussr');
opponentHandLocation.classList.remove('side-us', 'side-ussr');
if (playerSide === 'US') {
yourHandLocation.classList.add('side-us');
opponentHandLocation.classList.add('side-ussr');
} else if (playerSide === 'USSR') {
yourHandLocation.classList.add('side-ussr');
opponentHandLocation.classList.add('side-us');
}
}
function clearAllCards() {
const locations = ['your-hand', 'opponent-hand', 'deck-us', 'deck-neutral', 'deck-ussr', 'discard', 'removed', 'in-front', 'box'];
locations.forEach(locationId => {
const container = document.getElementById(locationId);
if (container) {
container.innerHTML = '';
}
});
}
function restoreCardPositions(positions, options = {}) {
clearAllCards();
// Temporarily flag that we're in a restoration process
// This prevents any action recording during card restoration
const isRestoring = options.isUndoOperation || options.isLoading;
Object.entries(positions).forEach(([locationId, cards]) => {
const container = document.getElementById(locationId);
if (container && cards) {
cards.forEach(cardData => {
let cardElement;
if (cardData.isUnknown || cardData.name === '?') {
cardElement = createUnknownCardElement();