-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.html
More file actions
622 lines (530 loc) · 35.1 KB
/
index.html
File metadata and controls
622 lines (530 loc) · 35.1 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
<!DOCTYPE html>
<html lang="zh-TW">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
<title>Bottom of the 9th - Synced Fix</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/ethers/6.7.0/ethers.umd.min.js"></script>
<style>
:root { --grass: #1b5e20; --dirt: #5d4037; --line: rgba(255,255,255,0.7); --gold: #ffd700; --red: #ff5252; --blue: #2196f3; --dark: #0f0f0f; }
body { background: var(--dark); color: white; font-family: 'Microsoft JhengHei', 'Segoe UI', sans-serif; text-align: center; margin: 0; padding: 10px; overflow-x: hidden; touch-action: manipulation; user-select: none; }
.container { max-width: 500px; margin: 0 auto; position: relative; padding-bottom: 30px; }
/* 頂部導航 */
.top-bar { display: flex; justify-content: space-between; align-items: center; margin-bottom: 15px; padding: 0 5px; }
.pool-box { font-size: 0.9em; color: var(--gold); border: 1px solid var(--gold); padding: 5px 12px; border-radius: 20px; background: rgba(255, 215, 0, 0.1); font-weight: bold; }
.right-tools { display: flex; gap: 8px; align-items: center; }
.connect-btn { background: #333; color: white; border: 1px solid #555; padding: 6px 10px; border-radius: 6px; font-size: 0.8em; cursor: pointer; transition: 0.2s; }
.connect-btn.connected { background: #1b5e20; border-color: #4caf50; color: #fff; }
.icon-btn { cursor: pointer; font-size: 1.1em; border: 1px solid #555; width: 32px; height: 32px; border-radius: 50%; background: #222; display: flex; justify-content: center; align-items: center; }
.balance-row { text-align: right; font-size: 0.85em; color: #aaa; margin-bottom: 10px; padding-right: 5px; }
.balance-val { color: #fff; font-weight: bold; font-size: 1.1em; }
/* 記分板 */
.scoreboard { display: grid; grid-template-columns: 1fr 1fr 1.2fr 1.5fr; background: #000; border: 3px solid #444; border-radius: 8px; padding: 10px; margin-bottom: 15px; box-shadow: 0 5px 15px rgba(0,0,0,0.5); font-family: 'Courier New', monospace; }
.score-box { text-align: center; border-right: 1px solid #333; display: flex; flex-direction: column; justify-content: center; }
.score-box:last-child { border: none; }
.label { font-size: 0.65em; color: #888; margin-bottom: 2px; letter-spacing: 1px; }
.value { font-size: 1.8em; font-weight: bold; color: #fff; }
.home-score { color: var(--gold); text-shadow: 0 0 10px var(--gold); }
.outs { color: var(--red); letter-spacing: 4px; }
/* 球評框 */
.commentary-box { background: #222; border-left: 5px solid var(--gold); color: #ddd; font-size: 1em; padding: 15px; margin-bottom: 20px; text-align: left; min-height: 60px; display: flex; align-items: center; box-shadow: 0 4px 6px rgba(0,0,0,0.3); border-radius: 0 8px 8px 0; transition: border-color 0.3s ease; line-height: 1.4; }
.commentator-name { color: #888; font-weight: bold; margin-right: 10px; font-size: 0.9em; white-space: nowrap; }
#commentaryText { transition: opacity 0.3s ease-in-out; }
/* 球場 */
.field-container { width: 100%; aspect-ratio: 1/1; position: relative; margin-bottom: 20px; }
.field { width: 100%; height: 100%; background: radial-gradient(circle at 50% 30%, #388e3c 0%, #1b5e20 90%); border-radius: 12px 12px 50% 50%; position: relative; overflow: hidden; border: 5px solid #444; box-shadow: inset 0 0 80px rgba(0,0,0,0.8); }
.infield { position: absolute; bottom: 0; left: 50%; transform: translateX(-50%); width: 72%; height: 72%; background: var(--dirt); border-radius: 50% 50% 0 0; border-top: 2px dashed rgba(255,255,255,0.4); }
.diamond-wrap { position: absolute; bottom: 12%; left: 50%; width: 42%; height: 42%; transform: translateX(-50%) rotate(45deg); border: 2px solid var(--line); box-sizing: border-box; z-index: 5; }
.base { width: 26px; height: 26px; background: #ddd; position: absolute; transform: translate(-50%, -50%) rotate(-45deg); box-shadow: 3px 3px 6px rgba(0,0,0,0.6); transition: 0.3s; z-index: 10; border: 1px solid #999; }
.base.active { background: var(--gold); box-shadow: 0 0 20px var(--gold); border: 2px solid #fff; }
#base1 { top: 0; right: 0; } #base2 { top: 0; left: 0; } #base3 { bottom: 0; left: 0; } #baseH { bottom: 0; right: 0; background: #fff; clip-path: polygon(50% 0%, 100% 50%, 50% 100%, 0% 50%); border-radius: 0; }
.runner-dot { position: absolute; width: 18px; height: 18px; background: var(--gold); border: 2px solid white; border-radius: 50%; z-index: 20; box-shadow: 0 0 10px var(--gold); top: 0; left: 0; margin-top: -9px; margin-left: -9px; animation: runBase 0.6s linear forwards; }
@keyframes runBase { from { top: var(--startY); left: var(--startX); } to { top: var(--endY); left: var(--endX); } }
.pitch-ball { width: 12px; height: 12px; background: white; border-radius: 50%; position: absolute; display: none; z-index: 15; left: 50%; bottom: 34%; transform: translateX(-50%); box-shadow: 0 0 5px white; }
.message { position: absolute; top: 40%; left: 50%; transform: translate(-50%, -50%); font-size: 3em; font-weight: 900; color: white; text-shadow: 0 5px 0 #000, 0 0 30px rgba(255,255,255,1); display: none; z-index: 30; white-space: nowrap; pointer-events: none; font-style: italic; }
.hit-ani { animation: popIn 0.8s cubic-bezier(0.175, 0.885, 0.32, 1.275) forwards; }
@keyframes popIn { 0% { transform: translate(-50%, -50%) scale(0); opacity: 0; } 50% { transform: translate(-50%, -50%) scale(1.2); opacity: 1; } 100% { transform: translate(-50%, -50%) scale(1); opacity: 0; } }
/* 按鈕區 */
.controls-label { font-size: 0.85em; color: #888; margin-bottom: 8px; text-transform: uppercase; letter-spacing: 1px; }
.controls { display: grid; grid-template-columns: 1fr 1fr 1fr; gap: 12px; margin-top: 5px; }
.btn-action { border: none; height: 55px; color: white; font-size: 0.95em; border-radius: 12px; cursor: pointer; font-weight: bold; position: relative; overflow: hidden; display: flex; flex-direction: column; justify-content: center; align-items: center; box-shadow: 0 4px 0 rgba(0,0,0,0.3); transition: 0.1s; }
.btn-action:active { transform: translateY(4px); box-shadow: none; }
.btn-action:disabled { background: #333 !important; color: #555; transform: translateY(4px); box-shadow: none; cursor: default; }
.btn-power { background: linear-gradient(to bottom, #d32f2f, #b71c1c); }
.btn-bunt { background: linear-gradient(to bottom, #1976d2, #0d47a1); }
.btn-take { background: linear-gradient(to bottom, #388e3c, #1b5e20); }
.btn-sub { font-size: 0.7em; opacity: 0.8; font-weight: normal; margin-top: 2px; }
/* 遮罩層 (Start Screen) */
.start-overlay { position: absolute; top: 0; left: 0; width: 100%; height: 100%; background: rgba(0,0,0,0.88); z-index: 50; display: flex; flex-direction: column; justify-content: center; align-items: center; border-radius: 10px; backdrop-filter: blur(3px); }
.start-btn { background: linear-gradient(to bottom, #ff9800, #f57c00); font-size: 1.8em; padding: 15px 40px; border-radius: 50px; color: #fff; border: 4px solid #fff; animation: pulse 1.5s infinite; cursor: pointer; font-weight: 900; text-transform: uppercase; box-shadow: 0 0 25px rgba(255, 152, 0, 0.6); margin-top: 15px; }
.start-btn:disabled { animation: none; background: #555; border-color: #777; box-shadow: none; cursor: not-allowed; opacity: 0.7; }
@keyframes pulse { 0% { transform: scale(1); } 50% { transform: scale(1.05); } 100% { transform: scale(1); } }
.status-bar { background: #222; color: #aaa; font-size: 0.95em; padding: 8px; margin-bottom: 15px; border-radius: 6px; min-height: 24px; font-weight: bold; letter-spacing: 0.5px; }
/* 規則 Modal */
.modal { display: none; position: fixed; top: 0; left: 0; width: 100%; height: 100%; background: rgba(0,0,0,0.9); z-index: 100; justify-content: center; align-items: center; }
.modal-content { background: #222; padding: 20px; border-radius: 10px; border: 1px solid #444; width: 85%; max-width: 400px; text-align: center; position: relative; }
.close-btn { position: absolute; top: 10px; right: 15px; font-size: 1.5em; cursor: pointer; color: #aaa; }
.payout-table { width: 100%; font-size: 0.9em; color: #ccc; border-collapse: collapse; margin-top: 10px; }
.payout-table td { padding: 8px; border-bottom: 1px solid #444; }
.highlight { color: var(--gold); font-weight: bold; }
/* 種子碼顯示區 */
.seed-box { margin-top: 20px; font-size: 0.75em; color: #666; background: rgba(0,0,0,0.5); padding: 8px; border-radius: 5px; width: 90%; word-break: break-all; }
.seed-label { color: #888; font-weight: bold; display: block; margin-bottom: 3px; }
</style>
</head>
<body>
<div class="container">
<div class="top-bar">
<div class="pool-box">POOL: <span id="jackpot">Loading...</span></div>
<div class="right-tools">
<button id="connectBtn" class="connect-btn" onclick="connectWallet()">🔗 Connect</button>
<div class="icon-btn" onclick="toggleRule()">?</div>
<div class="icon-btn" onclick="toggleLang()" style="font-size:0.8em">🌐</div>
</div>
</div>
<div class="balance-row">
<span id="txtBalance">Balance</span>: <span id="balance" class="balance-val">--</span> CRO
</div>
<div class="scoreboard">
<div class="score-box"> <span class="label">GUEST</span> <span class="value">2</span> </div>
<div class="score-box"> <span class="label">HOME</span> <span class="value home-score" id="homeScore">0</span> </div>
<div class="score-box"> <span class="label">INNING</span> <span class="value inning">9▼</span> </div>
<div class="score-box"> <span class="label">OUTS</span> <span class="value outs" id="outs">○○○</span> </div>
</div>
<div class="status-bar" id="gameStatus">Waiting...</div>
<div class="commentary-box">
<span class="commentator-name" id="casterTitle">Broadcaster:</span>
<span id="commentaryText">Welcome to the ballpark! Connect wallet to play.</span>
</div>
<div class="field-container">
<div class="start-overlay" id="startScreen">
<div style="margin-bottom:10px; color:#aaa; font-weight:bold;" id="txtBetAmt">BET: 2 CRO</div>
<button class="start-btn" id="playBtn" onclick="startGame()" disabled>PLAY BALL</button>
<div style="margin-top:5px; font-size:0.7em; color:#666;" id="txtWalletHint">(Please connect wallet first)</div>
<div id="lastSeedDisplay" style="display:none;" class="seed-box">
<span class="seed-label">Last Game Seed (For Verification):</span>
<span id="seedValue"></span>
</div>
</div>
<div class="field">
<div class="infield"></div>
<div class="mound"></div>
<div class="pitch-ball" id="pitchBall"></div>
<div class="message" id="msg">HOME RUN!</div>
</div>
<div class="diamond-wrap">
<div class="base" id="base2"></div>
<div class="base" id="base1"></div>
<div class="base" id="base3"></div>
<div class="base" id="baseH"></div>
</div>
</div>
<div class="controls-label" id="txtStrategy">Batting Strategy</div>
<div class="controls">
<button class="btn-action btn-power" id="btnPower" onclick="playTurn('POWER')" disabled>
<span id="lblPower">Power</span>
</button>
<button class="btn-action btn-bunt" id="btnBunt" onclick="playTurn('BUNT')" disabled>
<span id="lblBunt">Bunt</span>
</button>
<button class="btn-action btn-take" id="btnTake" onclick="playTurn('TAKE')" disabled>
<span id="lblTake">Take</span>
</button>
</div>
</div>
<div id="ruleModal" class="modal">
<div class="modal-content">
<span class="close-btn" onclick="toggleRule()">×</span>
<h3 style="color:var(--gold); margin-top:0;">Game Rules</h3>
<p id="ruleDetail" style="font-size:0.9em; line-height:1.5; color:#ccc;">
Bottom of the 9th, bases empty, trailing by 2 runs.<br>
Score more than 2 runs to win!
</p>
<table class="payout-table">
<tr><td>0-1 Runs</td><td style="color:#666;">Loss</td></tr>
<tr><td>2 Runs (Tie)</td><td>Refund</td></tr>
<tr><td>3 Runs</td><td class="highlight">2x Payout</td></tr>
<tr><td>4 Runs</td><td class="highlight" style="color:#ff9800">5x Payout</td></tr>
<tr><td>5+ Runs</td><td class="highlight" style="color:#e040fb">10x Jackpot</td></tr>
</table>
</div>
</div>
<script>
// 🔥 合約設定
const GAME_CONTRACT_ADDRESS = "0xDdDf7eBBcC42d933B1e2A43d5dD43d0BB5a63471";
const BANKROLL_ADDRESS = "0x7A427604Ff8Ce728A60cF5cB247B30C0cE29188B";
const GAME_ABI = [
"function play() external payable",
"event GameResult(address indexed player, uint256 payout, uint256 seed, uint256 finalScore)"
];
let provider, signer, gameContract;
let userAddress = null;
let curLang = 'zh';
// 機率設定 (累積機率 0-99)
// HR: <1 (1%), 3B: <4 (3%), 2B: <14 (10%), 1B: <43 (29%), OUT: >=43
const PROBS = { HR: 1, TRIPLE: 3, DOUBLE: 10, SINGLE: 29, OUT: 57 };
let currentRandom = BigInt(0);
let outs = 0; let homeScore = 0; let bases = [0, 0, 0];
let isGameActive = false; let isAnimating = false; let currentStrategy = "POWER";
const basePos = { 0: { t: '100%', l: '100%' }, 1: { t: '0%', l: '100%' }, 2: { t: '0%', l: '0%' }, 3: { t: '100%', l: '0%' }, 4: { t: '120%', l: '50%' } };
const TEXT = {
zh: {
pool: "累積獎池", connect: "連結", balance: "餘額", bet: "下注: 2 CRO",
walletHint: "(請先連結錢包以開始)",
strategy: "選擇打擊策略",
btnPower: "全力揮棒", btnBunt: "短打/收打", btnTake: "謹慎選球",
caster: "球評:",
waiting: "等待比賽開始...",
intro: "比賽即將開始!請按 PLAY BALL!",
ruleTitle: "遊戲規則",
ruleDetail: "九局下半,無人出局,落後兩分。<br>分數超過 2 分即為獲勝!",
payout: ["輸掉本金", "退還本金", "2倍 獎金", "5倍 獎金", "10倍 大獎"],
status: { lose: "落後 {s} 分,逆轉吧!", tie: "✨ 平手!下一分直接贏!", win: "🏆 比賽結束!逆轉勝!" },
comments: {
START: ["九局下半,落後兩分!關鍵時刻!", "教練臉色很難看,這局一定要得分!", "阿娘喂!現場球迷都站起來了!"],
SWING_POWER: ["大棒一揮!(等待結果...)", "想要一棒扛到停車場!", "用盡吃奶力氣揮棒!"],
SWING_BUNT: ["擺出短棒...(等待結果)", "突然收打!", "想要點個內野安打!"],
SWING_TAKE: ["仔細選球...(等待結果)", "這球很接近...", "忍住不出棒!"],
OUT: ["便當便當!揮棒落空!", "不可能!野手竟然...撲接到了!", "兩個字,大中計!", "打得軟趴趴,刺殺出局!"],
DP: ["中了滿壘計!瓦解了!", "哎呀!雙殺打!最壞的結果!", "6-4-3 雙殺!攻勢瓦解!"],
BB: ["選得好!四壞球保送!", "投手煮粥了,保送上壘!"],
HBP: ["觸身球!好痛!", "砸在身上!保送上一壘!"],
HIT: ["內野亂成一鍋粥了!", "安打啦!穿越安打!", "水喔!這球打得非常結實!"],
DOUBLE: ["深遠的長打!二壘安打!", "球滾到全壘打牆邊!跑者衝啊!"],
TRIPLE: ["三壘安打!跑者跑得跟飛的一樣!", "球在角落處理很久!三壘安打!"],
HR: ["這只是一個飛球......阿娘喂!飛出去了!", "變了心的女朋友!回不來了!紅不讓!", "來囉~ㄛㄛㄛㄛ~從東京打到北京!", "真的有天天過年的啦!全壘打!"],
HR_BUNT: ["假點真打!投手被騙了!出去了!", "這顆失投球被逮中!全壘打!"],
HR_TAKE: ["球太甜了忍不住!轟出牆外!", "教練叫你等球你還打?但結果是全壘打!"],
TIE: ["追平了!死裡逃生!", "現在雙方回到原點!"],
WIN: ["再見安打!比賽結束!今晚吃雞!", "逆轉勝!我們贏了!"],
LOSE: ["這場比賽...吃鍋貼了。", "留下殘壘,輸掉了比賽。"]
}
},
en: {
pool: "PRIZE POOL", connect: "Connect", balance: "Balance", bet: "BET: 2 CRO",
walletHint: "(Connect wallet to play)",
strategy: "Batting Strategy",
btnPower: "Power Swing", btnBunt: "Bunt/Contact", btnTake: "Take Pitch",
caster: "Broadcaster:",
waiting: "Waiting for game...",
intro: "Welcome to the ballpark! Click PLAY BALL!",
ruleTitle: "Game Rules",
ruleDetail: "Bottom of the 9th, bases empty, trailing by 2 runs.<br>Score more than 2 runs to win!",
payout: ["Loss", "Refund (Push)", "2x Payout", "5x Payout", "10x Jackpot"],
status: { lose: "Trailing by {s}, Rally time!", tie: "✨ TIE GAME! Next run wins!", win: "🏆 WALK-OFF WIN!" },
comments: {
START: ["Bottom of the 9th, down by 2. Rally caps on!", "Last chance for the home team!", "The crowd is on their feet!"],
SWING_POWER: ["Swinging for the fences!", "He's hacking at that one!", "Power swing!"],
SWING_BUNT: ["Squaring around to bunt...", "Showing bunt...", "Contact swing!"],
SWING_TAKE: ["Taking all the way...", "Watching it closely...", "Waiting for his pitch..."],
OUT: ["Strike three! He got him looking!", "Can of corn! Easy out.", "Ground ball, routine play."],
DP: ["Oh no! Twin killing! Double Play!", "6-4-3! Pitcher's best friend!"],
BB: ["Ball four! Take your base.", "Good eye! That's a walk."],
HBP: ["Ouch! Hit by pitch.", "Plunked him! Take first base."],
HIT: ["Base hit! Through the infield!", "Line drive! A frozen rope!"],
DOUBLE: ["Gapped it! Going for two!", "Off the wall! Stand-up double!"],
TRIPLE: ["Triple! He's flying around the bases!", "Down the line! Going for three!"],
HR: ["Going, Going, GONE! Goodbye!", "Santa Maria! That ball is crushed!", "Upper deck! WALK-OFF HOMER!"],
HR_BUNT: ["Fake bunt! He hammers the hanger! GONE!", "He shows bunt but blasts it deep! HOME RUN!"],
HR_TAKE: ["Green light 3-0? He swings and CRUSHES it!", "He couldn't resist that cookie! HOME RUN!"],
TIE: ["TIE GAME! Brand new ballgame!", "He tied it up!"],
WIN: ["WALK-OFF WINNER! BALLGAME OVER!", "The crowd goes wild! We win!"],
LOSE: ["Strike three! Ballgame over.", "The rally falls short. Game over."]
}
}
};
function toggleLang() {
curLang = (curLang === 'zh') ? 'en' : 'zh';
refreshText();
}
function toggleRule() {
const modal = document.getElementById('ruleModal');
modal.style.display = (modal.style.display === 'flex') ? 'none' : 'flex';
}
window.onclick = function(event) {
const modal = document.getElementById('ruleModal');
if (event.target == modal) {
modal.style.display = "none";
}
}
function refreshText() {
const t = TEXT[curLang];
document.getElementById('jackpot').previousSibling.textContent = t.pool + ": ";
document.getElementById('connectBtn').innerText = userAddress ? (userAddress.slice(0,6)+'...'+userAddress.slice(-4)) : ("🔗 " + t.connect);
document.getElementById('txtBalance').innerText = t.balance;
const elBet = document.getElementById('txtBetAmt');
if(elBet) elBet.innerText = t.bet;
const elHint = document.getElementById('txtWalletHint');
if(elHint) elHint.innerText = userAddress ? "" : t.walletHint;
document.getElementById('txtStrategy').innerText = t.strategy;
document.getElementById('btnPower').innerHTML = `<span>${t.btnPower}</span>`;
document.getElementById('btnBunt').innerHTML = `<span>${t.btnBunt}</span>`;
document.getElementById('btnTake').innerHTML = `<span>${t.btnTake}</span>`;
document.getElementById('casterTitle').innerText = t.caster;
document.getElementById('gameStatus').innerText = isGameActive ? document.getElementById('gameStatus').innerText : t.waiting;
document.querySelector('#ruleModal h3').innerText = t.ruleTitle;
document.getElementById('ruleDetail').innerHTML = t.ruleDetail;
const rows = document.querySelectorAll('.payout-table tr td:nth-child(2)');
t.payout.forEach((txt, i) => { if(rows[i]) rows[i].innerText = txt; });
if(!isGameActive) document.getElementById('commentaryText').innerText = t.intro;
}
async function connectWallet() {
if (!window.ethereum) return alert("Please install MetaMask / DeFi Wallet");
try {
provider = new ethers.BrowserProvider(window.ethereum);
signer = await provider.getSigner();
userAddress = await signer.getAddress();
gameContract = new ethers.Contract(GAME_CONTRACT_ADDRESS, GAME_ABI, signer);
document.getElementById('connectBtn').classList.add('connected');
const playBtn = document.getElementById('playBtn');
if(playBtn) playBtn.disabled = false;
refreshText();
updateInfo();
} catch (e) {
console.error(e);
alert("Connect Failed");
}
}
async function updateInfo() {
if(!provider || !userAddress) return;
const bal = await provider.getBalance(userAddress);
document.getElementById('balance').innerText = parseFloat(ethers.formatEther(bal)).toFixed(2);
const poolBal = await provider.getBalance(BANKROLL_ADDRESS);
document.getElementById('jackpot').innerText = Math.floor(parseFloat(ethers.formatEther(poolBal))).toLocaleString();
}
async function startGame() {
if(!gameContract) {
alert("Please connect wallet first!");
return;
}
const seedDisp = document.getElementById('lastSeedDisplay');
if(seedDisp) seedDisp.style.display = 'none';
document.getElementById('startScreen').innerHTML = "<div style='color:white; font-size:1.2em;'>Processing...<br><span style='font-size:0.8em; color:#aaa'>Confirm transaction in wallet</span></div>";
try {
// 🔥 [FIX] 強制設定 Gas Limit 以解決 Internal JSON-RPC error
const tx = await gameContract.play({
value: ethers.parseEther("2"),
gasLimit: 300000
});
document.getElementById('startScreen').innerHTML = "<div style='color:white; font-size:1.2em;'>⚾ Pitching...<br><span style='font-size:0.8em; color:#aaa'>Waiting for block confirmation</span></div>";
const receipt = await tx.wait();
let foundSeed = null;
receipt.logs.forEach(log => {
try {
const parsed = gameContract.interface.parseLog(log);
if(parsed.name === "GameResult") foundSeed = parsed.args.seed;
} catch(e){}
});
if(!foundSeed) throw new Error("No Seed Found");
currentRandom = foundSeed;
outs = 0; homeScore = 0; bases = [0, 0, 0];
isGameActive = true;
document.getElementById('startScreen').style.display = 'none';
setTimeout(() => {
const t = TEXT[curLang];
document.getElementById('startScreen').innerHTML = `
<div style="margin-bottom:10px; color:#aaa; font-weight:bold;" id="txtBetAmt">${t.bet}</div>
<button class="start-btn" id="playBtn" onclick="startGame()">PLAY BALL</button>
<div style="margin-top:5px; font-size:0.7em; color:#666;" id="txtWalletHint"></div>
<div id="lastSeedDisplay" style="display:none;" class="seed-box">
<span class="seed-label">Last Game Seed (For Verification):</span>
<span id="seedValue"></span>
</div>
`;
}, 1000);
enableBtns(true);
updateUI();
speak("START");
} catch (e) {
console.error(e);
alert("Error: " + (e.reason || e.message));
const t = TEXT[curLang];
document.getElementById('startScreen').innerHTML = `
<div style="margin-bottom:10px; color:#aaa; font-weight:bold;" id="txtBetAmt">${t.bet}</div>
<button class="start-btn" id="playBtn" onclick="startGame()">PLAY BALL</button>
<div style="margin-top:20px; font-size:0.8em; color:#ccc;">Transaction Cancelled</div>
<div id="txtWalletHint" style="display:none"></div>
<div id="lastSeedDisplay" style="display:none;" class="seed-box"><span id="seedValue"></span></div>
`;
if(userAddress) document.getElementById('playBtn').disabled = false;
}
}
function nextRandom() {
// [FIX] 確保使用與 Solidity 相同的 Hash 算法
const newHash = ethers.solidityPackedKeccak256(["uint256"], [currentRandom]);
currentRandom = BigInt(newHash);
// 使用餘數 100 來取得 0-99 的數值
return Number(currentRandom % 100n);
}
function enableBtns(enable) {
document.getElementById('btnPower').disabled = !enable;
document.getElementById('btnBunt').disabled = !enable;
document.getElementById('btnTake').disabled = !enable;
}
function playTurn(strategy) {
if (!isGameActive || isAnimating) return;
isAnimating = true; enableBtns(false); currentStrategy = strategy;
if(strategy === 'POWER') speak("SWING_POWER");
else if(strategy === 'BUNT') speak("SWING_BUNT");
else speak("SWING_TAKE");
const ball = document.getElementById('pitchBall');
ball.style.display = 'block'; ball.style.bottom = '34%'; ball.style.transition = 'none';
void ball.offsetWidth;
ball.style.transition = 'bottom 0.6s linear'; ball.style.bottom = '10%';
setTimeout(() => {
ball.style.display = 'none';
handleResult(getResult());
}, 800);
}
// 🔥 [FIX] 核心修正:移除 Math.random(),確保與鏈上同步
function getResult() {
const r = nextRandom();
let outcome = 'OUT'; let c = 0;
// 機率累積檢查 (0-99)
if(r < (c += PROBS.HR)) outcome = 'HR'; // 0
else if(r < (c += PROBS.TRIPLE)) outcome = '3B'; // 1-3
else if(r < (c += PROBS.DOUBLE)) outcome = '2B'; // 4-13
else if(r < (c += PROBS.SINGLE)) { // 14-42
// 將一壘安打區間細分為 BB/HBP/1B,使用同一個 r,保證決定性
// 區間大小 29 (14到42)
// 假設定義: r=14~17 (4個) 為 BB, r=18 (1個) 為 HBP, 其餘為 1B
// 這樣在區塊鏈邏輯中它們都是 "Single" (上一壘),但前端顯示有變化
if (r >= 14 && r <= 17) outcome = 'BB';
else if (r === 18) outcome = 'HBP';
else outcome = '1B';
}
else outcome = 'OUT'; // 43-99
if (outcome === 'OUT' && bases[0] === 1 && outs < 2) {
// 雙殺檢查:使用同一個 r (範圍 43-99)
// 假設合約也是用同樣的閾值
if (r >= 88) return 'DP';
}
return outcome;
}
function handleResult(type) {
if (type === 'OUT' || type === 'DP') {
let addOuts = 1; let text = "OUT!"; let color = "#ff5252";
if (type === 'DP') { addOuts = 2; text = "DOUBLE PLAY!"; speak("DP"); bases[0] = 0; }
else { speak("OUT"); }
outs += addOuts; showHitText(text, color); updateUI();
setTimeout(() => {
isAnimating = false;
if (outs >= 3) endGame(false); else enableBtns(true);
}, 1500);
} else {
let hitBases = 1, text = "HIT!", color = "#fff";
if (type === 'BB') { text = "WALK"; speak("BB"); color="#4caf50"; }
else if (type === 'HBP') { text = "HBP"; speak("HBP"); color="#ff9800"; }
else if (type === '1B') { text = "HIT"; speak("HIT"); }
else if (type === '2B') { text="DOUBLE"; hitBases=2; speak("DOUBLE"); color="#4caf50"; }
else if (type === '3B') { text="TRIPLE"; hitBases=3; speak("TRIPLE"); color="#ffd700"; }
else if (type === 'HR') {
text="HOME RUN"; hitBases=4; color="#e040fb";
if (currentStrategy === 'BUNT') speak("HR_BUNT");
else if (currentStrategy === 'TAKE') speak("HR_TAKE");
else speak("HR");
}
showHitText(text, color); advanceRunners(hitBases);
}
}
async function advanceRunners(hitBases) {
let movers = [];
if(bases[2]) movers.push({s:3}); if(bases[1]) movers.push({s:2}); if(bases[0]) movers.push({s:1}); movers.push({s:0});
let runs = 0; let nextBases = [0, 0, 0]; let promises = [];
movers.forEach(m => {
let e = m.s + hitBases;
promises.push(animateRunner(m.s, e));
if (e > 3) runs++; else nextBases[e-1] = 1;
});
await Promise.all(promises);
bases = nextBases; homeScore += runs; updateUI();
if (homeScore > 2) { speak("WIN"); setTimeout(() => endGame(true), 2000); }
else if (homeScore === 2) { speak("TIE"); isAnimating = false; enableBtns(true); }
else { isAnimating = false; enableBtns(true); }
}
function animateRunner(start, end) {
return new Promise(resolve => {
const wrap = document.querySelector('.diamond-wrap');
const dot = document.createElement('div');
dot.className = 'runner-dot';
let tIdx = end > 3 ? 4 : end;
dot.style.setProperty('--startX', basePos[start].l); dot.style.setProperty('--startY', basePos[start].t);
dot.style.setProperty('--endX', basePos[tIdx].l); dot.style.setProperty('--endY', basePos[tIdx].t);
wrap.appendChild(dot); dot.addEventListener('animationend', () => { dot.remove(); resolve(); });
});
}
function speak(key) {
const t = TEXT[curLang];
const lines = t.comments[key]; if(!lines) return;
const text = lines[Math.floor(Math.random() * lines.length)];
const box = document.getElementById('commentaryText');
box.style.opacity = 0;
const boxDiv = document.querySelector('.commentary-box');
if(key.includes('WIN') || key.includes('HR')) boxDiv.style.borderLeftColor = "#ff5252";
else if(key === 'TIE' || key === 'BB') boxDiv.style.borderLeftColor = "#4caf50";
else boxDiv.style.borderLeftColor = "#ffd700";
setTimeout(() => { box.innerText = text; box.style.opacity = 1; }, 300);
}
function updateUI() {
const t = TEXT[curLang];
document.getElementById('homeScore').innerText = homeScore;
document.getElementById('outs').innerHTML = "●".repeat(outs > 3 ? 3 : outs) + "<span style='color:#333'>○</span>".repeat(Math.max(0, 3-outs));
document.getElementById('base1').className = bases[0] ? 'base active' : 'base';
document.getElementById('base2').className = bases[1] ? 'base active' : 'base';
document.getElementById('base3').className = bases[2] ? 'base active' : 'base';
const status = document.getElementById('gameStatus');
if(homeScore < 2) {
status.style.background = "#222"; status.style.color="#aaa";
status.innerText = t.status.lose.replace("{s}", 2-homeScore);
}
else if(homeScore === 2) {
status.style.background = "#1b5e20"; status.style.color="#fff";
status.innerText = t.status.tie;
}
else {
status.style.background = "linear-gradient(90deg, #ffd700, #ff9800)"; status.style.color="#000";
status.innerText = t.status.win;
}
document.querySelectorAll('.payout-table tr').forEach(tr => tr.style.background = "");
if(homeScore >= 2) {
let idx = homeScore >= 5 ? 4 : (homeScore >= 4 ? 3 : (homeScore >= 3 ? 2 : 1));
let rows = document.querySelectorAll('.payout-table tr');
if(rows[idx]) rows[idx].style.background = "rgba(255, 215, 0, 0.2)";
}
}
function showHitText(text, color) {
const msg = document.getElementById('msg');
msg.innerText = text; msg.style.color = color;
msg.style.display = 'block';
msg.classList.remove('hit-ani');
void msg.offsetWidth;
msg.classList.add('hit-ani');
}
function endGame(isWin) {
isGameActive = false;
let msg = "";
const t = TEXT[curLang];
if (!isWin) {
if (homeScore === 2) { speak("TIE"); msg = t.payout[1]; }
else { speak("LOSE"); msg = t.payout[0]; }
} else {
speak("WIN");
let m = 2; if(homeScore === 4) m = 5; if(homeScore >= 5) m = 10;
msg = (curLang === 'zh') ? `贏得 ${m}倍 獎金!` : `You Won ${m}x Payout!`;
}
setTimeout(() => {
alert(msg);
updateInfo();
document.getElementById('startScreen').style.display = 'flex';
const seedDisp = document.getElementById('lastSeedDisplay');
const seedVal = document.getElementById('seedValue');
if(seedDisp && seedVal) {
seedVal.innerText = currentRandom.toString();
seedDisp.style.display = 'block';
}
}, 500);
}
toggleLang();
</script>
</body>
</html>