Solve turn Assignment

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

New contributor

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.

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật