forked from alicalx8/OnlinePinaki
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
832 lines (700 loc) · 30.4 KB
/
Copy pathserver.js
File metadata and controls
832 lines (700 loc) · 30.4 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
const express = require('express');
const http = require('http');
const socketIo = require('socket.io');
const path = require('path');
// PORT değişkenini tanımla
const PORT = process.env.PORT || 3000;
const app = express();
const server = http.createServer(app);
const io = socketIo(server, {
cors: {
origin: "*",
methods: ["GET", "POST"]
},
pingTimeout: 60000,
pingInterval: 25000,
transports: ['websocket', 'polling']
});
// JSON parsing middleware
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
// API route'ları
app.use('/api', (req, res, next) => {
console.log(`API isteği: ${req.method} ${req.path}`);
next();
});
// API endpoint'leri
app.get('/api/health', (req, res) => {
res.json({
status: 'OK',
timestamp: new Date().toISOString(),
uptime: process.uptime()
});
});
app.get('/api/rooms', (req, res) => {
const roomList = Array.from(rooms.keys()).map(roomId => ({
id: roomId,
playerCount: rooms.get(roomId)?.players?.length || 0,
gameState: rooms.get(roomId)?.gameState ? 'active' : 'waiting'
}));
res.json({ rooms: roomList });
});
// Statik dosyaları servis et (CSS, JS, resimler vb.)
app.use('/style.css', express.static(path.join(__dirname, 'build', 'style.css')));
app.use('/online.js', express.static(path.join(__dirname, 'build', 'online.js')));
app.use('/script.js', express.static(path.join(__dirname, 'build', 'script.js')));
app.use('/bot.js', express.static(path.join(__dirname, 'build', 'bot.js')));
// Ana sayfa route'u - online.html'i döndür
app.get('/', (req, res) => {
res.sendFile(path.join(__dirname, 'build', 'online.html'));
});
// SPA routing - tüm diğer route'lar için online.html döndür
app.get('*', (req, res) => {
// API route'ları için online.html döndürme
if (req.path.startsWith('/api/')) {
return res.status(404).json({ error: 'API endpoint bulunamadı' });
}
// Statik dosyalar için online.html döndürme
res.sendFile(path.join(__dirname, 'build', 'online.html'));
});
// Hata yönetimi middleware
app.use((err, req, res, next) => {
console.error('Express hatası:', err);
res.status(500).json({ error: 'Sunucu hatası' });
});
// Kart oyunu sabitleri
const suits = ['♥', '♠', '♦', '♣'];
const ranks = ['9', '10', 'J', 'Q', 'K', 'A'];
// Kart deste oluşturma
function createDeck() {
let deck = [];
for (let d = 0; d < 2; d++) { // iki deste
for (let suit of suits) {
for (let rank of ranks) {
deck.push({ suit, rank });
}
}
}
return deck;
}
// Deste karıştırma
function shuffle(deck) {
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]];
}
return deck;
}
// Kartları dağıtma
function dealCards(deck) {
const players = [[], [], [], []];
let cardIndex = 0;
for (let round = 0; round < 3; round++) { // 3 turda 4'er kart
for (let p = 0; p < 4; p++) {
for (let k = 0; k < 4; k++) {
players[p].push(deck[cardIndex++]);
}
}
}
return players;
}
// Deste oluştur ve karıştır
function createAndShuffleDeck() {
const deck = createDeck();
return shuffle(deck);
}
// Oda yönetimi
const rooms = new Map();
// Oda oluşturma
function createRoom(roomId) {
const room = {
id: roomId,
players: [],
gameState: null,
gameActive: false, // Oyun aktif mi flag'i
currentDealer: 3,
auctionActive: false,
trumpSuit: null,
playedCards: [],
currentPlayer: null,
auctionCurrent: 0,
auctionHighestBid: 150,
auctionWinner: null,
consecutiveBozCount: 0
};
rooms.set(roomId, room);
return room;
}
// Socket bağlantı yönetimi
io.on('connection', (socket) => {
console.log('Yeni bağlantı:', socket.id);
// Bağlantı durumu kontrolü
socket.on('ping', () => {
socket.emit('pong');
});
// Pong yanıtı
socket.on('pong', () => {
// Client'ın pong yanıtını aldık, bağlantı aktif
console.log(`Pong alındı: ${socket.id}`);
});
// Bağlantı kesildiğinde temizlik
socket.on('disconnect', (reason) => {
console.log(`Bağlantı kesildi: ${socket.id}, Sebep: ${reason}`);
// Oyuncuyu tüm odalardan çıkar
for (const [roomId, room] of rooms.entries()) {
const playerIndex = room.players.findIndex(p => p.id === socket.id);
if (playerIndex !== -1) {
const player = room.players[playerIndex];
console.log(`Oyuncu ${player.name} odadan çıktı: ${roomId}`);
// Oyuncuyu listeden çıkar
room.players.splice(playerIndex, 1);
// Diğer oyunculara bildir
socket.to(roomId).emit('playerLeft', {
playerId: playerIndex,
playerName: player.name,
players: room.players.map(p => ({ id: p.id, name: p.name, position: p.position }))
});
// Oda boşsa odayı sil
if (room.players.length === 0) {
rooms.delete(roomId);
console.log(`Oda silindi: ${roomId}`);
}
break;
}
}
});
// Odaya katılma
socket.on('joinRoom', (data) => {
try {
const { roomId, playerName, isSpectator = false } = data;
if (!roomId || !playerName) {
socket.emit('error', { message: 'Geçersiz oda ID veya oyuncu adı' });
return;
}
let room = rooms.get(roomId);
if (!room) {
room = createRoom(roomId);
}
// Seyirci ise sadece odaya katıl, oyuncu ekleme
if (isSpectator) {
socket.join(roomId);
// Misafir oyuncuya mevcut oyun durumunu da gönder
const spectatorData = {
message: 'Seyirci olarak katıldınız',
players: room.players.map(p => ({ id: p.id, name: p.name, position: p.position }))
};
// Eğer oyun başlamışsa ve kartlar dağıtılmışsa, oyun durumunu da gönder
if (room.gameState) {
spectatorData.gameState = room.gameState;
spectatorData.hasGameStarted = true;
spectatorData.playedCards = room.gameState.playedCards || [];
spectatorData.trumpSuit = room.gameState.trumpSuit;
spectatorData.currentPlayer = room.gameState.currentPlayer;
spectatorData.auctionActive = room.gameState.auctionActive;
spectatorData.auctionCurrent = room.gameState.auctionCurrent;
spectatorData.auctionHighestBid = room.gameState.auctionHighestBid;
}
socket.emit('spectatorJoined', spectatorData);
// Diğer oyunculara sadece bilgi mesajı gönder (arayüzü etkilemesin)
socket.to(roomId).emit('spectatorInfo', {
message: 'Yeni seyirci katıldı',
spectatorName: playerName
});
console.log(`Seyirci ${playerName} oda ${roomId}'ye katıldı`);
return;
}
// Aynı isimle oyuncu var mı kontrol et
const existingPlayer = room.players.find(p => p.name === playerName);
if (existingPlayer) {
socket.emit('error', { message: 'Bu isimle bir oyuncu zaten var!' });
return;
}
// Oyuncu sayısı kontrolü
if (room.players.length >= 4) {
socket.emit('roomFull', { message: 'Oda dolu!' });
return;
}
// Oyuncuyu odaya ekle
const player = {
id: socket.id,
name: playerName,
position: room.players.length
};
room.players.push(player);
socket.join(roomId);
// Oyuncuya pozisyonunu bildir
socket.emit('playerJoined', {
playerId: player.position,
players: room.players.map(p => ({ id: p.id, name: p.name, position: p.position }))
});
// Diğer oyunculara yeni oyuncuyu bildir
socket.to(roomId).emit('playerJoined', {
playerId: player.position,
players: room.players.map(p => ({ id: p.id, name: p.name, position: p.position }))
});
console.log(`Oyuncu ${playerName} oda ${roomId}'ye katıldı. Pozisyon: ${player.position}`);
} catch (error) {
console.error('joinRoom hatası:', error);
socket.emit('error', { message: 'Oda katılırken bir hata oluştu.' });
}
});
// Oyun başlatma
socket.on('startGame', (data) => {
const { roomId } = data;
const room = rooms.get(roomId);
if (!room || room.players.length !== 4) {
socket.emit('error', { message: 'Oyun başlatılamaz. 4 oyuncu gerekli.' });
return;
}
// Oyun zaten aktifse tekrar başlatma
if (room.gameActive) {
console.log(`Oda ${roomId}'de oyun zaten aktif, tekrar başlatılmıyor`);
return;
}
// Oyun durumunu başlat (kartlar henüz dağıtılmadı)
room.gameState = {
players: room.players,
currentDealer: room.currentDealer,
auctionActive: false, // İhale henüz aktif değil, kartlar dağıtıldıktan sonra aktif olacak
trumpSuit: null,
playedCards: [],
currentPlayer: null,
auctionCurrent: (room.currentDealer + 1) % 4,
auctionHighestBid: 150,
auctionWinner: null,
auctionTurns: 0,
lastBidderId: null
};
// Oyun durumunu işaretle
room.gameActive = true;
// Debug log
console.log(`Oda ${roomId} oyun durumu:`, {
gameActive: room.gameActive,
playersCount: room.players.length,
auctionActive: room.gameState.auctionActive,
currentDealer: room.currentDealer
});
// Tüm oyunculara oyun başladığını bildir (kartlar henüz dağıtılmadı)
io.to(roomId).emit('gameStarted', {
gameState: room.gameState,
currentDealer: room.currentDealer,
playerCards: [] // Kartlar henüz dağıtılmadı
});
console.log(`Oda ${roomId}'de oyun başladı, kartlar henüz dağıtılmadı`);
});
// Kart oynama
socket.on('playCard', (data) => {
const { roomId, playerId, card } = data;
const room = rooms.get(roomId);
if (!room || !room.gameState) return;
// Koz seçilmeden kart oynanamaz (online kuralı)
if (!room.gameState.trumpSuit) {
console.log(`Oda ${roomId}: Koz seçilmeden kart oynama reddedildi (oyuncu ${playerId + 1})`);
return;
}
// Kartı oyna
room.gameState.playedCards.push({ player: playerId, card });
// Tüm oyunculara kart oynandığını bildir
io.to(roomId).emit('cardPlayed', {
playerId,
card,
playedCards: room.gameState.playedCards
});
// Eğer 4 kart oynandıysa, eli bitir
if (room.gameState.playedCards.length === 4) {
setTimeout(() => {
const winner = findTrickWinner(room.gameState.playedCards, room.gameState.trumpSuit);
room.gameState.currentPlayer = winner;
room.gameState.playedCards = [];
io.to(roomId).emit('trickEnded', {
winner,
currentPlayer: winner
});
}, 1000);
} else {
// Sıradaki oyuncuya geç
room.gameState.currentPlayer = (room.gameState.currentPlayer + 1) % 4;
io.to(roomId).emit('nextPlayer', {
currentPlayer: room.gameState.currentPlayer
});
}
});
// İhale teklifi
socket.on('makeBid', (data) => {
console.log('makeBid mesajı alındı:', data);
const { roomId, playerId, bid } = data;
const room = rooms.get(roomId);
if (!room) {
console.error(`Oda bulunamadı: ${roomId}`);
return;
}
console.log(`Teklif işleniyor - Oda: ${roomId}, Oyuncu: ${playerId}, Teklif: ${bid}`);
if (bid === null) {
// Pas geç
console.log(`Oyuncu ${playerId + 1} pas geçiyor`);
io.to(roomId).emit('playerPassed', {
playerId,
playerName: room.players[playerId]?.name || `Oyuncu ${playerId + 1}`
});
} else {
// Teklif ver
console.log(`Oyuncu ${playerId + 1} teklif veriyor: ${bid}`);
room.gameState.auctionHighestBid = bid;
room.gameState.lastBidderId = playerId;
io.to(roomId).emit('bidMade', {
playerId,
bid,
playerName: room.players[playerId]?.name || `Oyuncu ${playerId + 1}`
});
}
// Sıradaki oyuncuya geç - Sordum/Konuş modunda özel mantık
if (room.gameState && room.gameState.auctionActive) {
const dealer = room.gameState.currentDealer;
const thirdPlayer = (dealer + 3) % 4;
const fourthPlayer = dealer;
// Sordum/Konuş sonrası 3. oyuncu teklif verirse sıra 4. oyuncuya geçer
if (playerId === thirdPlayer && room.gameState.sordumKonusMode && room.gameState.konusPlayer === fourthPlayer) {
console.log(`3. oyuncu konuş sonrası teklif verdi, sıra 4. oyuncuya geçiyor`);
room.gameState.auctionCurrent = fourthPlayer;
} else {
// Normal sıra ilerletme
room.gameState.auctionCurrent = (room.gameState.auctionCurrent + 1) % 4;
}
// Tur sayacı: 4 teklif/pas sonrası ihale biter
room.gameState.auctionTurns = (room.gameState.auctionTurns || 0) + 1;
// 4 adım tamamlandıysa en yüksek teklif veren kazanır
if (room.gameState.auctionTurns >= 4) {
// Basit kural: Herhangi bir yükseltme olduysa son yükselten kazanır, yoksa 4. oyuncu 150
if (room.gameState.auctionHighestBid && room.gameState.auctionHighestBid > 150 && room.gameState.lastBidderId !== null) {
room.gameState.auctionWinner = room.gameState.lastBidderId;
} else {
// Kimse yükseltmediyse 4. oyuncuya 150 kalsın
room.gameState.auctionWinner = fourthPlayer;
room.gameState.auctionHighestBid = 150;
}
room.gameState.auctionActive = false;
console.log(`İhale bitti. Kazanan: ${room.gameState.auctionWinner}, Teklif: ${room.gameState.auctionHighestBid}`);
io.to(roomId).emit('auctionEnded', {
winner: room.gameState.auctionWinner,
winningBid: room.gameState.auctionHighestBid,
playerName: room.players[room.gameState.auctionWinner]?.name || `Oyuncu ${room.gameState.auctionWinner + 1}`,
currentPlayer: room.gameState.auctionWinner
});
return;
}
console.log(`Sıradaki teklifçi: ${room.gameState.auctionCurrent}`);
io.to(roomId).emit('nextBidder', { currentBidder: room.gameState.auctionCurrent });
}
});
// Koz seçimi
socket.on('selectTrump', (data) => {
const { roomId, trumpSuit } = data;
const room = rooms.get(roomId);
if (!room) return;
room.gameState.trumpSuit = trumpSuit;
room.gameState.currentPlayer = room.gameState.auctionWinner;
io.to(roomId).emit('trumpSelected', {
trumpSuit,
currentPlayer: room.gameState.currentPlayer,
auctionWinner: room.gameState.auctionWinner
});
});
// Pota mesajı
socket.on('potaMessage', (data) => {
const { roomId, message, playerId } = data;
const room = rooms.get(roomId);
if (!room) return;
// Tüm oyunculara pota mesajını gönder
io.to(roomId).emit('potaMessage', {
message,
playerId,
playerName: room.players[playerId]?.name || `Oyuncu ${playerId + 1}`
});
// Debug: Oyun durumunu kontrol et
console.log('Pota mesajı işleniyor - Oyun durumu:', {
roomId,
playerId,
gameState: room.gameState,
auctionActive: room.gameState?.auctionActive,
currentDealer: room.gameState?.currentDealer
});
// Eğer ihale aktifse ve ilk 2 oyuncudan biri pota verdiyse, sırayı ilerlet
if (room.gameState && room.gameState.auctionActive) {
const dealer = room.gameState.currentDealer;
const firstPlayer = (dealer + 1) % 4;
const secondPlayer = (dealer + 2) % 4;
console.log(`İhale aktif - Dealer: ${dealer}, First: ${firstPlayer}, Second: ${secondPlayer}, Player: ${playerId}`);
if (playerId === firstPlayer || playerId === secondPlayer) {
console.log(`Oyuncu ${playerId + 1} pota verdi, sıra ilerliyor`);
// Sıradaki oyuncuya geç
room.gameState.auctionCurrent = (room.gameState.auctionCurrent + 1) % 4;
// Tüm oyunculara sıra değişikliğini bildir
io.to(roomId).emit('nextBidder', {
currentBidder: room.gameState.auctionCurrent
});
// İlk 2 oyuncu pota verdikten sonra teklif kontrollerini gizle
// Sadece ikinci oyuncu pota verdikten sonra kontrolleri gizle
if (playerId === secondPlayer) {
io.to(roomId).emit('hideAuctionControls', {
hideControls: true
});
}
}
} else {
console.log('İhale aktif değil veya gameState yok');
}
});
// Sordum mesajı
socket.on('sordumMessage', (data) => {
const { roomId, playerId } = data;
const room = rooms.get(roomId);
if (!room) return;
console.log(`Oyuncu ${playerId + 1} sordum dedi`);
// Tüm oyunculara sordum mesajını gönder
io.to(roomId).emit('sordumMessage', {
playerId,
playerName: room.players[playerId]?.name || `Oyuncu ${playerId + 1}`
});
// Eğer ihale aktifse, sırayı ilerlet
if (room.gameState && room.gameState.auctionActive) {
const dealer = room.gameState.currentDealer;
const thirdPlayer = (dealer + 3) % 4;
if (playerId === thirdPlayer) {
console.log(`Oyuncu ${playerId + 1} sordum dedi, sıra ilerliyor`);
// Sordum/Konuş modunu aktif et
room.gameState.sordumKonusMode = true;
room.gameState.sordumPlayer = playerId;
// Sıradaki oyuncuya geç (4. oyuncuya)
room.gameState.auctionCurrent = (room.gameState.auctionCurrent + 1) % 4;
// Tüm oyunculara sıra değişikliğini bildir
io.to(roomId).emit('nextBidder', {
currentBidder: room.gameState.auctionCurrent
});
}
}
});
// Pas mesajı
socket.on('passMessage', (data) => {
const { roomId, playerId } = data;
const room = rooms.get(roomId);
if (!room) return;
console.log(`Oyuncu ${playerId + 1} pas geçiyor`);
// Tüm oyunculara pas mesajını gönder
io.to(roomId).emit('passMessage', {
playerId,
playerName: room.players[playerId]?.name || `Oyuncu ${playerId + 1}`
});
// Eğer ihale aktifse, özel mantık + tur sayacı kontrol et
if (room.gameState && room.gameState.auctionActive) {
const dealer = room.gameState.currentDealer;
const thirdPlayer = (dealer + 3) % 4;
const fourthPlayer = dealer;
// Sordum/Konuş sonrası 3. oyuncu pas derse, ihale 4. oyuncuya 150'ye kalır
if (playerId === thirdPlayer && room.gameState.sordumKonusMode && room.gameState.konusPlayer === fourthPlayer) {
console.log(`3. oyuncu konuş sonrası pas dedi, ihale 4. oyuncuya 150'ye kalıyor`);
room.gameState.auctionWinner = fourthPlayer;
room.gameState.auctionHighestBid = 150;
room.gameState.auctionActive = false;
room.gameState.sordumKonusMode = false;
// Sırayı kazanan oyuncuya geçir
room.gameState.currentPlayer = fourthPlayer;
// İhale bittiğini bildir
io.to(roomId).emit('auctionEnded', {
winner: fourthPlayer,
winningBid: 150,
playerName: room.players[fourthPlayer]?.name || `Oyuncu ${fourthPlayer + 1}`,
currentPlayer: fourthPlayer
});
return;
}
// Sordum/Konuş sonrası 4. oyuncu pas derse ihale 3. oyuncuya kalır ve biter
if (playerId === fourthPlayer && room.gameState.sordumKonusMode && room.gameState.konusPlayer === fourthPlayer) {
console.log(`4. oyuncu konuş sonrası pas dedi, ihale 3. oyuncuya kalıyor`);
room.gameState.auctionWinner = thirdPlayer;
room.gameState.auctionActive = false;
room.gameState.sordumKonusMode = false;
// Sırayı kazanan oyuncuya geçir
room.gameState.currentPlayer = thirdPlayer;
// İhale bittiğini bildir
io.to(roomId).emit('auctionEnded', {
winner: thirdPlayer,
winningBid: room.gameState.auctionHighestBid,
playerName: room.players[thirdPlayer]?.name || `Oyuncu ${thirdPlayer + 1}`,
currentPlayer: thirdPlayer
});
return;
}
// Normal pas - sırayı ilerlet ve tur say
console.log(`Oyuncu ${playerId + 1} pas geçti, sıra ilerliyor`);
room.gameState.auctionCurrent = (room.gameState.auctionCurrent + 1) % 4;
room.gameState.auctionTurns = (room.gameState.auctionTurns || 0) + 1;
// 4 adım tamamlandıysa ihale biter
if (room.gameState.auctionTurns >= 4) {
if (room.gameState.auctionHighestBid && room.gameState.auctionHighestBid > 150 && room.gameState.lastBidderId !== null) {
room.gameState.auctionWinner = room.gameState.lastBidderId;
} else {
room.gameState.auctionWinner = fourthPlayer;
room.gameState.auctionHighestBid = 150;
}
room.gameState.auctionActive = false;
io.to(roomId).emit('auctionEnded', {
winner: room.gameState.auctionWinner,
winningBid: room.gameState.auctionHighestBid,
playerName: room.players[room.gameState.auctionWinner]?.name || `Oyuncu ${room.gameState.auctionWinner + 1}`,
currentPlayer: room.gameState.auctionWinner
});
return;
}
// Tüm oyunculara sıra değişikliğini bildir
io.to(roomId).emit('nextBidder', {
currentBidder: room.gameState.auctionCurrent
});
}
});
// Konuş mesajı
socket.on('konusMessage', (data) => {
const { roomId, playerId } = data;
const room = rooms.get(roomId);
if (!room) return;
console.log(`Oyuncu ${playerId + 1} konuş dedi`);
// Tüm oyunculara konuş mesajını gönder
io.to(roomId).emit('konusMessage', {
playerId,
playerName: room.players[playerId]?.name || `Oyuncu ${playerId + 1}`
});
// Eğer ihale aktifse, konuş mantığını uygula
if (room.gameState && room.gameState.auctionActive) {
const dealer = room.gameState.currentDealer;
const thirdPlayer = (dealer + 3) % 4;
const fourthPlayer = dealer;
if (playerId === thirdPlayer) {
// 3. oyuncu direkt konuş diyor
console.log(`Oyuncu ${playerId + 1} direkt konuş dedi, sıra ilerliyor`);
room.gameState.auctionCurrent = (room.gameState.auctionCurrent + 1) % 4;
io.to(roomId).emit('nextBidder', {
currentBidder: room.gameState.auctionCurrent
});
} else if (playerId === fourthPlayer) {
// 4. oyuncu 3. oyuncuya konuş diyor
console.log(`Oyuncu ${playerId + 1} 3. oyuncuya konuş dedi, sıra 3. oyuncuya döner`);
room.gameState.auctionCurrent = thirdPlayer;
room.gameState.konusPlayer = playerId; // Sunucuda da konuş player'ı takip et
io.to(roomId).emit('nextBidder', {
currentBidder: room.gameState.auctionCurrent
});
// Konuş player'ı güncelle
io.to(roomId).emit('konusPlayerUpdate', {
konusPlayer: playerId
});
}
}
});
// Kartları dağıtma
socket.on('dealCards', (data) => {
console.log('dealCards mesajı alındı:', data);
const { roomId } = data;
const room = rooms.get(roomId);
if (!room) {
console.error(`Oda bulunamadı: ${roomId}`);
return;
}
console.log(`Kartlar dağıtılıyor - Oda: ${roomId}`);
// Yeni deste oluştur ve karıştır
const deck = createAndShuffleDeck();
const dealtCards = dealCards(deck);
// Oyunculara kartları ata
const playersWithCards = room.players.map((player, index) => ({
...player,
cards: dealtCards[index] || []
}));
// Oyun durumunu güncelle
room.gameState = {
players: playersWithCards,
currentDealer: room.currentDealer || 0,
auctionActive: true, // İhale aktif olmalı
trumpSuit: null,
playedCards: [],
currentPlayer: (room.currentDealer + 1) % 4, // İlk teklifçi
auctionCurrent: (room.currentDealer + 1) % 4,
auctionHighestBid: 150,
auctionWinner: null,
auctionTurns: 0,
consecutiveBozCount: 0,
sordumKonusMode: false,
sordumPlayer: null,
konusPlayer: null
};
// Tüm oyunculara kartları dağıtıldı mesajı gönder
io.to(roomId).emit('cardsDealt', {
players: playersWithCards,
gameState: room.gameState,
auctionState: {
auctionActive: true, // İhale aktif olmalı
auctionCurrent: room.gameState.auctionCurrent,
auctionHighestBid: 150
}
});
// İhale sürecini başlat
io.to(roomId).emit('auctionStarted', {
auctionCurrent: room.gameState.auctionCurrent,
auctionHighestBid: 150,
players: playersWithCards
});
console.log(`Kartlar dağıtıldı ve ihale başladı - Oda: ${roomId}, Dağıtıcı: ${room.currentDealer}, İlk teklifçi: ${room.gameState.auctionCurrent}`);
});
// Oyun yeniden başlatma
socket.on('restartGame', (data) => {
const { roomId } = data;
const room = rooms.get(roomId);
if (!room) {
socket.emit('error', { message: 'Oda bulunamadı' });
return;
}
// Oyun durumunu sıfırla
room.gameState = null;
room.gameActive = false;
room.auctionActive = false;
room.trumpSuit = null;
room.playedCards = [];
room.currentPlayer = null;
room.auctionCurrent = 0;
room.auctionHighestBid = 150;
room.auctionWinner = null;
room.consecutiveBozCount = 0;
// Tüm oyunculara oyun yeniden başlatıldı mesajı gönder
io.to(roomId).emit('gameRestarted', {
message: 'Oyun yeniden başlatıldı',
players: room.players.map(p => ({ id: p.id, name: p.name, position: p.position }))
});
console.log(`Oda ${roomId}'de oyun yeniden başlatıldı`);
});
});
// El kazananını bul
function findTrickWinner(playedCards, trumpSuit) {
if (playedCards.length !== 4) return null;
const leadSuit = playedCards[0].card.suit;
let bestIdx = 0;
let bestCard = playedCards[0].card;
for (let i = 1; i < 4; i++) {
const c = playedCards[i].card;
// Önce koz var mı bak
if (trumpSuit && c.suit === trumpSuit && bestCard.suit !== trumpSuit) {
bestIdx = i;
bestCard = c;
} else if (c.suit === bestCard.suit) {
// Aynı renktense büyüklüğe bak
const rankOrder = ['A', '10', 'K', 'Q', 'J', '9'];
if (rankOrder.indexOf(c.rank) < rankOrder.indexOf(bestCard.rank)) {
bestIdx = i;
bestCard = c;
}
}
}
return playedCards[bestIdx].player;
}
server.listen(PORT, () => {
console.log(`🚀 Sunucu ${PORT} portunda çalışıyor`);
console.log(`📁 Statik dosyalar: ${path.join(__dirname, 'build')}`);
console.log(`🔗 API endpoint'leri: http://localhost:${PORT}/api`);
console.log(`🌐 Web uygulaması: http://localhost:${PORT}`);
});