I have been doing some modifications to my proyect but still I can´t solve why a fetch executes twice and other times doesn’t. I am trying to figure it out but no success. I am using Socket.io and API Rest
This is what I tried to do:
This is the client
socket.on('connect', () => {
socket.emit('joinGame', { gameID: gameID, page: page });
socket.on('role', (data) => {
if (data.host === socket.id){
//Determina a quien le toca primero
fetch(`http://localhost:3000/players/turn?idG=${gameID}`, {
method: 'GET',
headers: {
'Content-Type': 'application/json'
},
})
.then(res => res.json())
.then(data => {
currentPlayerFront = data.name
localStorage.setItem('currentPlayer', currentPlayerFront);
console.log('currentPlayerFront: ', currentPlayerFront)
socket.emit('sendCurrentPlayer', { gameID: gameID, player: currentPlayerFront});
if (currentPlayerFront === getCurrentPlayer()){
diceButton.disabled = false;
}
})
.catch(error => {
console.error(error)
})
}
})
})
Server where the emits happen
io.on('connection', (socket) => {
// JoinRoom: un jugador se une a la partida, busca la patida por su gameID y genera un emit para actualizar a los juagadores en la lista de juagadores de la partida
socket.on('joinRoom', async (data) => {
socket.join(data.gameID);
const game = await Game.findOne({ gameID: data.gameID });
if (game) {
io.to(data.gameID).emit('updatePlayers', {
gameID: data.gameID,
players: game.players,
playerCount: game.players.length,
});
players.push({ id: socket.id, name: game.players[game.players.length - 1].name, page: data.page, gameID: data.gameID });
}
});
// determineHost: determina cual jugador es el host de la partida segun su socket.id
socket.on('determineHost', async (data) => {
const game = await Game.findOne({ gameID: data.gameID })
if (game) {
if (!game.host){
game.host = socket.id
await game.save()
}
io.to(data.gameID).emit('role', { host: game.host })
}
})
// startGame: redirige a todos los jugadores a game.html y coloca a todos los jugadores en la primera casilla con su color correspondiente
socket.on('startGame', async (data) => {
const game = await Game.findOne({ gameID: data.gameID })
if (game) {
game.start = true
game.host = null
await game.save()
}
players.length = 0
const html = fs.readFileSync(path.join(__dirname, '..', 'views', 'game.html'), 'utf8');
io.to(data.gameID).emit('startGame', {site: `http://localhost:3000/game?gameID=${data.gameID}`, html: html });
})
// JoinGame: al Generarse una conexion en el front-end se une a uan partida con id
socket.on('joinGame', async (data) => {
socket.join(data.gameID)
const game = await Game.findOne({ gameID: data.gameID })
if (game){
if (game.host == null){
game.host = socket.id
await game.save()
io.to(data.gameID).emit('role', { host: game.host })
}
}
players.push({ id: socket.id, page: data.page, gameID: data.gameID })
})
socket.on('sendCurrentPlayer', (data) => {
io.to(data.gameID).emit('sendCurrentPlayer', { player: data.player })
})
socket.on('newQuestion', (data) => {
io.to(data.gameID).emit('updateQuestion', {question: data.question , player: data.player, gameID: data.gameID})
})
// Escuchar evento para actualizar la posición del jugador
socket.on('updatePlayerPosition', (data) => {
// Emitir el evento a todos los clientes conectados
io.to(data.gameID).emit('updatePlayerPosition', { player: data.player, points: data.points});
});
socket.on('clearTimer', (data) => {
io.to(data.gameID).emit('clearTimer');
})
// NextTurn: Accediendo a la base de datos le notifica a los jugadores quien es el siguiente en jugar
socket.on('nextTurn', async (data) => {
const game = await Game.findOne({ gameID: data.gameID })
if (game && game.start) {
console.log('nuevo turno: ', game.turn)
let currentPlayer = {id: players[game.turn].id, name: game.players[game.turn].name}
console.log(currentPlayer)
io.to(data.gameID).emit('getCurrentPlayer', currentPlayer)
}
})
// Blockbuttons: bloquea los botones de respuesta para los jugadores que no tienen el turno
socket.on('blockbuttons', (data) => {
const game = Game.findOne({ gameID: data.gameID })
if (game) {
let currentPlayer = {id: players[game.turn].id}
io.to(data.gameID).emit('blockbuttons', currentPlayer)
}
})
// Answer: verifica si la respuesta es correcta o incorrecta y emite el evento correspondiente
socket.on('answer', (data) => {
if (data.response === 'correct') {
io.to(data.gameID).emit('correctAnswer')
} else if (data.response === 'incorrect') {
io.to(data.gameID).emit('incorrectAnswer')
}
})
// EndGame: al finalizar el juego determina quien es el ganador y redirige a los jugadores a la pagina de resultados
socket.on('endGame', async (data) => {
const game = await Game.findOne({ gameID: data.gameID })
if (game) {
game.winner = data.player.name
await game.save()
io.to(data.gameID).emit('cleanBoard', {winner: game.winner})
}
})
And the route where the game determines the turn
router.get('/turn', async (req, res) => {
const game = await Game.findOne({ gameID: req.query.idG })
if (game && game.start) {
if (game.players.length != 0) {
game.turn = Math.floor(Math.random() * game.players.length)
await game.save()
console.log('turno: ' , game.turn)
res.status(200).json({ name: game.players[game.turn].name })
} else {
res.status(404).send('No hay jugadores')
}
} else {
res.status(404).send('Juego no encontrado y no empezado')
}
})
I am expecting to get it to work in all situations, because is for a university assigment that I have to hand in
Mateo Nicolas Suarez is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.