SyntaxSquad/DADProject#15 feat: Initial Idea
This commit is contained in:
@@ -29,11 +29,22 @@ class Game extends Model
|
||||
'match_id'
|
||||
];
|
||||
|
||||
protected $casts = [
|
||||
'began_at' => 'datetime',
|
||||
'ended_at' => 'datetime',
|
||||
'is_draw' => 'boolean',
|
||||
];
|
||||
|
||||
public function winner()
|
||||
{
|
||||
return $this->belongsTo(User::class, "winner_user_id");
|
||||
}
|
||||
|
||||
public function loser()
|
||||
{
|
||||
return $this->belongsTo(User::class, "loser_user_id");
|
||||
}
|
||||
|
||||
public function player1()
|
||||
{
|
||||
return $this->belongsTo(User::class, 'player1_user_id');
|
||||
|
||||
+25
-13
@@ -46,24 +46,36 @@ Route::prefix('v1')->group(function () {
|
||||
Route::get('/{user}/transactions', [UserController::class, 'getTransactions']);
|
||||
});
|
||||
|
||||
// Game Resources
|
||||
Route::prefix('games')->group(function () {
|
||||
Route::apiResource('/', GameController::class)->parameters([
|
||||
'' => 'game',
|
||||
]);
|
||||
Route::post('/{game}/join', [GameController::class, 'join']);
|
||||
// Host a new multiplayer game
|
||||
Route::post('/host', function (\Illuminate\Http\Request $request) {
|
||||
$request->validate([
|
||||
'type' => 'required|in:3,9'
|
||||
]);
|
||||
|
||||
$game = \App\Models\Game::create([
|
||||
'type' => $request->type,
|
||||
'status' => 'Pending',
|
||||
'player1_user_id' => $request->user()->id,
|
||||
'player2_user_id' => 1, // Ghost player
|
||||
'began_at' => now(),
|
||||
]);
|
||||
|
||||
return response()->json($game);
|
||||
});
|
||||
|
||||
Route::get('/', [GameController::class, 'index']);
|
||||
Route::get('/{game}', [GameController::class, 'show']);
|
||||
Route::post('/', [GameController::class, 'store']);
|
||||
Route::put('/{game}', [GameController::class, 'update']);
|
||||
Route::delete('/{game}', [GameController::class, 'destroy']);
|
||||
Route::post('/{game}/resign', [GameController::class, 'resign']);
|
||||
Route::post('/{game}/join', [GameController::class, 'join']);
|
||||
});
|
||||
|
||||
// Match Resources
|
||||
Route::prefix('matches')->group(function () {
|
||||
Route::apiResource('/', MatchController::class)->parameters([
|
||||
'' => 'match',
|
||||
]);
|
||||
Route::post('/{match}/join', [
|
||||
MatchController::class,
|
||||
'join',
|
||||
]);
|
||||
Route::apiResource('/', MatchController::class)->parameters(['' => 'match']);
|
||||
Route::post('/{match}/join', [MatchController::class, 'join']);
|
||||
});
|
||||
|
||||
// Admin Routes
|
||||
|
||||
@@ -44,7 +44,8 @@ const logout = () => {
|
||||
|
||||
onMounted(async () => {
|
||||
await authStore.restoreSession()
|
||||
socketStore.handleConnection()
|
||||
// REMOVED - The WebSocket for multiplayer is handled separately in the WebSocketStore
|
||||
// socketStore.handleConnection()
|
||||
})
|
||||
</script>
|
||||
|
||||
|
||||
@@ -67,11 +67,13 @@ const props = defineProps({
|
||||
default: 'player',
|
||||
validator: (value) => ['player', 'opponent'].includes(value),
|
||||
},
|
||||
isMyTurn: { type: Boolean, default: false },
|
||||
})
|
||||
|
||||
const emit = defineEmits(['play-card'])
|
||||
|
||||
const handleCardClick = (payload) => {
|
||||
if (!props.isMyTurn) return
|
||||
emit('play-card', payload.card)
|
||||
}
|
||||
</script>
|
||||
</script>
|
||||
|
||||
@@ -51,6 +51,10 @@ const props = defineProps({
|
||||
default: 3,
|
||||
validator: (value) => [3, 9].includes(value),
|
||||
},
|
||||
isDisabled: {
|
||||
type: Boolean,
|
||||
default: false,
|
||||
},
|
||||
})
|
||||
|
||||
const emit = defineEmits(['card-clicked'])
|
||||
@@ -81,7 +85,7 @@ const overlapPercentage = computed(() => {
|
||||
return props.maxCards === 3 ? 0.7 : 0.85
|
||||
})
|
||||
|
||||
const cardWidth = 128
|
||||
const cardWidth = 128
|
||||
const getCardStyle = (index) => {
|
||||
const totalCards = props.cards.length
|
||||
const overlapOffset = cardWidth * (1 - overlapPercentage.value)
|
||||
@@ -105,4 +109,4 @@ const getCardStyle = (index) => {
|
||||
zIndex: hoveredIndex.value === index ? 50 : index + 1,
|
||||
}
|
||||
}
|
||||
</script>
|
||||
</script>
|
||||
|
||||
@@ -0,0 +1,304 @@
|
||||
<template>
|
||||
<div class="relative min-h-screen overflow-hidden">
|
||||
<!-- Surrender Button -->
|
||||
<div v-if="isGameRunning && !gameOver" class="absolute top-4 right-4 z-50">
|
||||
<button
|
||||
@click="handleSurrender"
|
||||
class="bg-red-600 hover:bg-red-700 text-white font-bold py-2 px-4 rounded-lg shadow-lg border-2 border-red-800 transition-all transform hover:scale-105 flex items-center gap-2"
|
||||
>
|
||||
<span>🏳️</span> Surrender
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<!-- Connection Status -->
|
||||
<div class="absolute top-4 left-4 z-50 flex items-center gap-2 bg-gray-800 px-4 py-2 rounded-lg border border-gray-700">
|
||||
<div :class="['w-3 h-3 rounded-full', wsStore.connected ? 'bg-green-500' : 'bg-red-500']"></div>
|
||||
<span class="text-white text-sm">{{ wsStore.connected ? 'Connected' : 'Disconnected' }}</span>
|
||||
</div>
|
||||
|
||||
<!-- Timer -->
|
||||
<div v-if="isMyTurn && isGameRunning && !gameOver" class="absolute top-4 left-1/2 -translate-x-1/2 z-50">
|
||||
<div class="bg-gray-800 px-6 py-3 rounded-lg border-2" :class="timeLeft <= 5 ? 'border-red-500 animate-pulse' : 'border-gray-700'">
|
||||
<div class="flex items-center gap-3">
|
||||
<svg class="w-6 h-6 text-white" viewBox="0 0 24 24" fill="none" stroke="currentColor">
|
||||
<circle cx="12" cy="12" r="10" stroke-width="2"/>
|
||||
<polyline points="12 6 12 12 16 14" stroke-width="2"/>
|
||||
</svg>
|
||||
<span :class="['text-3xl font-mono font-bold', timeLeft <= 5 ? 'text-red-500' : 'text-white']">
|
||||
{{ timeLeft }}s
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Game Board -->
|
||||
<div v-if="isGameRunning">
|
||||
<GameBoard
|
||||
:trump-card="trumpCard"
|
||||
:cards-remaining="deckCount"
|
||||
:player-hand="playerHand"
|
||||
:opponent-hand="opponentHand"
|
||||
:player-score="playerScore"
|
||||
:opponent-score="opponentScore"
|
||||
:current-turn="currentTurn"
|
||||
:current-trick="currentTrick"
|
||||
:is-my-turn="isMyTurn"
|
||||
@play-card="handlePlayCard"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<!-- Loading State -->
|
||||
<div v-else-if="!gameOver" class="flex h-screen items-center justify-center bg-green-900 text-white">
|
||||
<div class="text-center">
|
||||
<div class="animate-spin h-12 w-12 border-4 border-white border-t-transparent rounded-full mx-auto mb-4"></div>
|
||||
<div class="text-xl">Connecting to game...</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Trick Result Modal -->
|
||||
<div v-if="showTrickResult" class="fixed inset-0 bg-black bg-opacity-70 flex items-center justify-center z-50">
|
||||
<div class="bg-gray-800 border-4 border-yellow-500 p-8 max-w-md rounded-lg">
|
||||
<h3 class="text-3xl font-bold mb-4 text-center text-white">
|
||||
{{ trickWinnerId === authStore.currentUser?.id ? '🎉 You won the trick!' : '😞 Opponent won the trick' }}
|
||||
</h3>
|
||||
<div class="text-center mb-4">
|
||||
<div class="text-5xl font-bold text-yellow-500">+{{ trickPoints }} points</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Game Over Modal -->
|
||||
<GameOver
|
||||
:is-visible="gameOver"
|
||||
:winner="gameResult"
|
||||
:player-score="playerScore"
|
||||
:opponent-score="opponentScore"
|
||||
:stats="{ playerTricks: 0, opponentTricks: 0 }"
|
||||
:is-logging-out="false"
|
||||
@play-again="handlePlayAgain"
|
||||
@close="handleCloseModal"
|
||||
/>
|
||||
|
||||
<!-- Error Notification -->
|
||||
<div v-if="wsStore.lastError" class="fixed bottom-4 right-4 bg-red-600 border-2 border-red-500 p-4 max-w-sm z-50 rounded-lg">
|
||||
<div class="flex items-start gap-3">
|
||||
<svg class="w-6 h-6 flex-shrink-0 text-white" viewBox="0 0 24 24" fill="none" stroke="currentColor">
|
||||
<circle cx="12" cy="12" r="10" stroke-width="2"/>
|
||||
<line x1="12" y1="8" x2="12" y2="12" stroke-width="2"/>
|
||||
<line x1="12" y1="16" x2="12.01" y2="16" stroke-width="2"/>
|
||||
</svg>
|
||||
<div class="text-white">
|
||||
<div class="font-semibold">Error</div>
|
||||
<div class="text-sm">{{ wsStore.lastError }}</div>
|
||||
</div>
|
||||
<button @click="wsStore.lastError = null" class="ml-auto text-white">
|
||||
<svg class="w-5 h-5" viewBox="0 0 24 24" fill="none" stroke="currentColor">
|
||||
<line x1="18" y1="6" x2="6" y2="18" stroke-width="2"/>
|
||||
<line x1="6" y1="6" x2="18" y2="18" stroke-width="2"/>
|
||||
</svg>
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup>
|
||||
import { ref, computed, onMounted, onUnmounted, watch, onBeforeMount } from 'vue'
|
||||
import { useRoute, useRouter, onBeforeRouteLeave } from 'vue-router'
|
||||
import { useSocketStore } from '@/stores/socket'
|
||||
import { useAuthStore } from '@/stores/auth'
|
||||
import { toast } from 'vue-sonner'
|
||||
import GameBoard from '@/components/game/GameBoard.vue'
|
||||
import GameOver from '@/components/game/GameOver.vue'
|
||||
|
||||
const route = useRoute()
|
||||
const router = useRouter()
|
||||
const wsStore = useWebSocketStore()
|
||||
const authStore = useAuthStore()
|
||||
|
||||
const gameId = ref(route.params.id)
|
||||
const gameType = ref(route.query.type || '9')
|
||||
const timeLeft = ref(20)
|
||||
const timerInterval = ref(null)
|
||||
const isCardAnimating = ref(false)
|
||||
const showTrickResult = ref(false)
|
||||
const trickWinnerId = ref(null)
|
||||
const trickPoints = ref(0)
|
||||
const gameOver = ref(false)
|
||||
const gameResult = ref(null)
|
||||
const isGameRunning = ref(false)
|
||||
|
||||
// Computed properties from game state
|
||||
const trumpCard = computed(() => wsStore.gameState?.trumpCard || null)
|
||||
const deckCount = computed(() => wsStore.gameState?.deckCount || 0)
|
||||
const playerHand = computed(() => wsStore.gameState?.hand || [])
|
||||
const opponentHand = computed(() => {
|
||||
const count = wsStore.gameState?.opponent?.cardCount || 0
|
||||
return Array(count).fill({ id: 'back', suit: 'back', rank: 0 })
|
||||
})
|
||||
const playerScore = computed(() => wsStore.gameState?.points || 0)
|
||||
const opponentScore = computed(() => wsStore.gameState?.opponent?.points || 0)
|
||||
const currentTurn = computed(() => wsStore.gameState?.currentTurn)
|
||||
const currentTrick = computed(() => ({
|
||||
playerCard: wsStore.gameState?.table?.playerCard || null,
|
||||
opponentCard: wsStore.gameState?.table?.opponentCard || null
|
||||
}))
|
||||
|
||||
const isMyTurn = computed(() => {
|
||||
return currentTurn.value == authStore.currentUser?.id
|
||||
})
|
||||
|
||||
const startTimer = () => {
|
||||
stopTimer()
|
||||
timeLeft.value = 20
|
||||
|
||||
timerInterval.value = setInterval(() => {
|
||||
timeLeft.value--
|
||||
|
||||
if (timeLeft.value <= 0) {
|
||||
stopTimer()
|
||||
handleTimeout()
|
||||
}
|
||||
}, 1000)
|
||||
}
|
||||
|
||||
const stopTimer = () => {
|
||||
if (timerInterval.value) {
|
||||
clearInterval(timerInterval.value)
|
||||
timerInterval.value = null
|
||||
}
|
||||
}
|
||||
|
||||
const handleTimeout = () => {
|
||||
if (playerHand.value.length > 0) {
|
||||
const randomCard = playerHand.value[0]
|
||||
handlePlayCard(randomCard)
|
||||
toast.warning('Time\'s up!', {
|
||||
description: 'Auto-played first card'
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
const handlePlayCard = (card) => {
|
||||
if (!isMyTurn.value || isCardAnimating.value || gameOver.value) return
|
||||
|
||||
isCardAnimating.value = true
|
||||
wsStore.playCard(gameId.value, card.id)
|
||||
stopTimer()
|
||||
|
||||
setTimeout(() => {
|
||||
isCardAnimating.value = false
|
||||
}, 500)
|
||||
}
|
||||
|
||||
const handleSurrender = () => {
|
||||
const confirmSurrender = window.confirm(
|
||||
'Are you sure you want to surrender? Your opponent will be awarded the win.'
|
||||
)
|
||||
|
||||
if (!confirmSurrender) return
|
||||
|
||||
toast.error('Game Surrendered', {
|
||||
description: 'You forfeited the match.'
|
||||
})
|
||||
|
||||
wsStore.disconnect()
|
||||
router.push({ name: 'home' })
|
||||
}
|
||||
|
||||
const handlePlayAgain = () => {
|
||||
wsStore.disconnect()
|
||||
router.push({ name: 'home' })
|
||||
}
|
||||
|
||||
const handleCloseModal = () => {
|
||||
wsStore.disconnect()
|
||||
router.push({ name: 'home' })
|
||||
}
|
||||
|
||||
const handleBrowserUnload = (event) => {
|
||||
if (isGameRunning.value && !gameOver.value) {
|
||||
event.preventDefault()
|
||||
event.returnValue = ''
|
||||
}
|
||||
}
|
||||
|
||||
// Watch for turn changes
|
||||
watch(() => currentTurn.value, (newTurn, oldTurn) => {
|
||||
if (newTurn == authStore.currentUser?.id && newTurn !== oldTurn) {
|
||||
startTimer()
|
||||
} else {
|
||||
stopTimer()
|
||||
}
|
||||
})
|
||||
|
||||
// Watch for game state to mark game as running
|
||||
watch(() => wsStore.gameState, (state) => {
|
||||
if (state && !isGameRunning.value) {
|
||||
isGameRunning.value = true
|
||||
}
|
||||
})
|
||||
|
||||
onBeforeMount(() => {
|
||||
gameOver.value = false
|
||||
})
|
||||
|
||||
onMounted(() => {
|
||||
wsStore.connect()
|
||||
|
||||
setTimeout(() => {
|
||||
wsStore.joinGame(gameId.value)
|
||||
}, 500)
|
||||
|
||||
wsStore.onTrickEnd((result) => {
|
||||
trickWinnerId.value = result.winnerId
|
||||
trickPoints.value = result.points
|
||||
showTrickResult.value = true
|
||||
|
||||
setTimeout(() => {
|
||||
showTrickResult.value = false
|
||||
}, 3000)
|
||||
})
|
||||
|
||||
wsStore.onGameOver((result) => {
|
||||
stopTimer()
|
||||
gameOver.value = true
|
||||
|
||||
if (result.isDraw) {
|
||||
gameResult.value = 'draw'
|
||||
} else if (result.winnerId === authStore.currentUser?.id) {
|
||||
gameResult.value = 'player'
|
||||
} else {
|
||||
gameResult.value = 'opponent'
|
||||
}
|
||||
})
|
||||
|
||||
window.addEventListener('beforeunload', handleBrowserUnload)
|
||||
})
|
||||
|
||||
onUnmounted(() => {
|
||||
stopTimer()
|
||||
wsStore.offTrickEnd()
|
||||
wsStore.offGameOver()
|
||||
wsStore.disconnect()
|
||||
window.removeEventListener('beforeunload', handleBrowserUnload)
|
||||
})
|
||||
|
||||
onBeforeRouteLeave((to, from, next) => {
|
||||
if (!isGameRunning.value || gameOver.value) {
|
||||
next()
|
||||
return
|
||||
}
|
||||
|
||||
const confirmExit = window.confirm(
|
||||
'⚠️ Game in Progress!\n\nIf you leave now, you will forfeit the match.\n\nAre you sure you want to leave?'
|
||||
)
|
||||
|
||||
if (confirmExit) {
|
||||
wsStore.disconnect()
|
||||
next()
|
||||
} else {
|
||||
next(false)
|
||||
}
|
||||
})
|
||||
</script>
|
||||
@@ -12,6 +12,7 @@ import {
|
||||
import { useAPIStore } from '@/stores/api'
|
||||
import { useRouter } from 'vue-router'
|
||||
import { useAuthStore } from '@/stores/auth'
|
||||
import axios from 'axios'
|
||||
|
||||
const API_BASE_URL = inject('apiBaseURL')
|
||||
const apiStore = useAPIStore()
|
||||
@@ -159,6 +160,52 @@ onMounted(async () => {
|
||||
await nextTick();
|
||||
setupGamesObserver();
|
||||
})
|
||||
|
||||
const hostGame = async () => {
|
||||
showHostModal.value = true
|
||||
|
||||
try {
|
||||
const response = await axios.post(`${API_BASE_URL}/games/host`, {
|
||||
type: selectedMode.value
|
||||
})
|
||||
|
||||
const gameId = response.data.id
|
||||
|
||||
console.log('Game hosted:', gameId)
|
||||
|
||||
router.push({
|
||||
name: 'multiplayer-game',
|
||||
params: { id: gameId },
|
||||
query: { type: selectedMode.value }
|
||||
})
|
||||
} catch (error) {
|
||||
console.error('Failed to host game:', error)
|
||||
console.error('Error details:', error.response?.data)
|
||||
showHostModal.value = false
|
||||
alert('Failed to host game: ' + (error.response?.data?.message || error.message))
|
||||
}
|
||||
}
|
||||
|
||||
const joinGame = async (game) => {
|
||||
selectedGame.value = game
|
||||
|
||||
try {
|
||||
await axios.post(`${API_BASE_URL}/games/${game.id}/join`)
|
||||
|
||||
console.log('Joined game:', game.id)
|
||||
|
||||
router.push({
|
||||
name: 'multiplayer-game',
|
||||
params: { id: game.id },
|
||||
query: { type: selectedMode.value }
|
||||
})
|
||||
} catch (error) {
|
||||
console.error('Failed to join game:', error)
|
||||
console.error('Error details:', error.response?.data)
|
||||
alert('Failed to join game: ' + (error.response?.data?.message || error.message))
|
||||
}
|
||||
}
|
||||
|
||||
</script>
|
||||
|
||||
<template>
|
||||
@@ -212,7 +259,7 @@ onMounted(async () => {
|
||||
<Card class="w-full max-w-2xl">
|
||||
<CardHeader>
|
||||
<CardTitle class="text-3xl font-bold text-center">
|
||||
MultiPlayer
|
||||
Multi Player
|
||||
</CardTitle>
|
||||
<CardDescription class="text-center">
|
||||
Go one on one with another player!
|
||||
@@ -226,7 +273,7 @@ onMounted(async () => {
|
||||
</div>
|
||||
<div v-else class="max-h-[350px] overflow-y-auto custom-scrollbar p-1">
|
||||
|
||||
<div v-for="(game, index) in openGames" :key="game.id" @click="JoinGameModal(game)"
|
||||
<div v-for="(game, index) in openGames" :key="game.id" @click="joinGame(game)"
|
||||
class="flex items-center justify-between p-3 mb-2 border border-transparent rounded-lg transition-all hover:bg-muted/50 hover:border-purple-500">
|
||||
|
||||
<div class="flex items-center gap-3">
|
||||
@@ -249,7 +296,7 @@ onMounted(async () => {
|
||||
</div>
|
||||
</div>
|
||||
<div class="flex justify-center">
|
||||
<Button @click="hostGameModal()" size="lg" variant="secondary"
|
||||
<Button @click="hostGame()" size="lg" variant="secondary"
|
||||
class="hover:bg-purple-500 hover:text-slate-200">
|
||||
Host Game
|
||||
</Button>
|
||||
|
||||
@@ -9,6 +9,7 @@ import TestDealing from '@/pages/TestDealing.vue'
|
||||
import TestAllAnimations from '@/pages/TestAllAnimations.vue'
|
||||
import TestGameBoard from '@/pages/TestGameBoard.vue'
|
||||
import SinglePlayerGamePage from '@/pages/game/SinglePlayerGamePage.vue'
|
||||
import MultiplayerGamePage from '@/pages/game/MultiplayerGamePage.vue'
|
||||
import RegisterPage from '@/pages/register/RegisterPage.vue'
|
||||
import CoinsPurchasePage from '@/pages/purchase/CoinPurchasePage.vue'
|
||||
|
||||
@@ -44,6 +45,12 @@ const router = createRouter({
|
||||
props: { gameType: 9 },
|
||||
meta: { requiresAuth: true },
|
||||
},
|
||||
{
|
||||
path: '/game/multiplayer/:id',
|
||||
name: 'multiplayer-game',
|
||||
component: MultiplayerGamePage,
|
||||
meta: { requiresAuth: true }
|
||||
},
|
||||
{
|
||||
path: '/user',
|
||||
component: UserPage,
|
||||
|
||||
+129
-15
@@ -1,24 +1,138 @@
|
||||
import { defineStore } from 'pinia'
|
||||
import { inject } from 'vue'
|
||||
import { ref } from 'vue'
|
||||
import { io } from 'socket.io-client'
|
||||
import { useAuthStore } from './auth'
|
||||
|
||||
export const useSocketStore = defineStore('socket', () => {
|
||||
const socket = inject('socket')
|
||||
export const useSocketStore = defineStore('websocket', () => {
|
||||
const authStore = useAuthStore()
|
||||
|
||||
const handleConnection = () => {
|
||||
try {
|
||||
socket.on('connect', () => {
|
||||
console.log(`[Socket] Connected -- ${socket.id}`)
|
||||
})
|
||||
socket.on('disconnect', () => {
|
||||
console.log(`[Socket] Disconnected -- ${socket.id}`)
|
||||
})
|
||||
} catch (error) {
|
||||
console.error('[Socket] Connection error:', error)
|
||||
const socket = ref(null)
|
||||
const connected = ref(false)
|
||||
const gameState = ref(null)
|
||||
const lastError = ref(null)
|
||||
|
||||
const WS_URL = 'http://localhost:3000'
|
||||
|
||||
const connect = () => {
|
||||
if (socket.value?.connected) return
|
||||
|
||||
const token = authStore.getToken()
|
||||
if (!token) {
|
||||
console.error('No token available for WebSocket connection')
|
||||
return
|
||||
}
|
||||
|
||||
socket.value = io(WS_URL, {
|
||||
auth: {
|
||||
token: `Bearer ${token}`
|
||||
},
|
||||
reconnection: true,
|
||||
reconnectionAttempts: 5,
|
||||
reconnectionDelay: 1000
|
||||
})
|
||||
|
||||
// Connection events
|
||||
socket.value.on('connect', () => {
|
||||
connected.value = true
|
||||
console.log('[WebSocket] Connected:', socket.value.id)
|
||||
})
|
||||
|
||||
socket.value.on('disconnect', (reason) => {
|
||||
connected.value = false
|
||||
console.log('[WebSocket] Disconnected:', reason)
|
||||
})
|
||||
|
||||
socket.value.on('connect_error', (error) => {
|
||||
console.error('[WebSocket] Connection error:', error.message)
|
||||
lastError.value = error.message
|
||||
})
|
||||
|
||||
// Heartbeat
|
||||
socket.value.on('heartbeat', () => {
|
||||
socket.value.emit('heartbeat_ack')
|
||||
})
|
||||
|
||||
// Game events
|
||||
socket.value.on('game-state', (state) => {
|
||||
gameState.value = state
|
||||
console.log('[Game] State updated:', state)
|
||||
})
|
||||
|
||||
socket.value.on('game-error', (data) => {
|
||||
lastError.value = data.message
|
||||
console.error('[Game] Error:', data.message)
|
||||
})
|
||||
|
||||
socket.value.on('error', (data) => {
|
||||
lastError.value = data.message
|
||||
console.error('[Socket] Error:', data.message)
|
||||
})
|
||||
}
|
||||
|
||||
const disconnect = () => {
|
||||
if (socket.value) {
|
||||
socket.value.disconnect()
|
||||
socket.value = null
|
||||
connected.value = false
|
||||
gameState.value = null
|
||||
lastError.value = null
|
||||
}
|
||||
}
|
||||
|
||||
const joinGame = (gameId) => {
|
||||
if (!socket.value?.connected) {
|
||||
console.error('[Game] Socket not connected')
|
||||
return
|
||||
}
|
||||
console.log('[Game] Joining game:', gameId)
|
||||
socket.value.emit('join-game', { gameId })
|
||||
}
|
||||
|
||||
const playCard = (gameId, cardId) => {
|
||||
if (!socket.value?.connected) {
|
||||
console.error('[Game] Socket not connected')
|
||||
return
|
||||
}
|
||||
console.log('[Game] Playing card:', cardId)
|
||||
socket.value.emit('play-card', { gameId, cardId })
|
||||
}
|
||||
|
||||
const onTrickEnd = (callback) => {
|
||||
if (socket.value) {
|
||||
socket.value.on('trick-end', callback)
|
||||
}
|
||||
}
|
||||
|
||||
const onGameOver = (callback) => {
|
||||
if (socket.value) {
|
||||
socket.value.on('game-over', callback)
|
||||
}
|
||||
}
|
||||
|
||||
const offTrickEnd = () => {
|
||||
if (socket.value) {
|
||||
socket.value.off('trick-end')
|
||||
}
|
||||
}
|
||||
|
||||
const offGameOver = () => {
|
||||
if (socket.value) {
|
||||
socket.value.off('game-over')
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
handleConnection,
|
||||
socket,
|
||||
connected,
|
||||
gameState,
|
||||
lastError,
|
||||
connect,
|
||||
disconnect,
|
||||
joinGame,
|
||||
playCard,
|
||||
onTrickEnd,
|
||||
onGameOver,
|
||||
offTrickEnd,
|
||||
offGameOver
|
||||
}
|
||||
|
||||
})
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { addUser, removeUser } from "../state/connection";
|
||||
import { addUser, removeUser } from "../state/connection.js";
|
||||
|
||||
const HEARTBEAT_INTERVAL = 30000; // 30 seconds
|
||||
const HEARTBEAT_TIMEOUT = 10000; // 10 seconds
|
||||
|
||||
@@ -14,4 +14,4 @@ export const removeUser = (socketId) => {
|
||||
|
||||
export const getUserCount = () => {
|
||||
return users.size;
|
||||
};
|
||||
};
|
||||
|
||||
Reference in New Issue
Block a user