Skip to content
Snippets Groups Projects
Commit 1fdcd9ec authored by ea654's avatar ea654
Browse files

Upload New File

parent 24cf9856
Branches
No related tags found
No related merge requests found
server.js 0 → 100644
const express = require('express');
const http = require('http');
const socketIo = require('socket.io');
const axios = require('axios');
const app = express();
const server = http.createServer(app);
const io = socketIo(server);
const PORT = process.env.PORT || 3000;
const rooms = {};
app.use(express.static('public'));
io.on('connection', (socket) => {
console.log('A user connected:', socket.id);
socket.on('createRoom', () => {
const roomCode = Math.random().toString(36).substring(2, 7).toUpperCase();
rooms[roomCode] = { players: [], questions: [] };
socket.join(roomCode);
socket.emit('roomCreated', roomCode);
console.log(`Room created with code ${roomCode}`);
});
socket.on('joinRoom', (roomCode) => {
if (rooms[roomCode]) {
socket.join(roomCode);
socket.emit('roomJoined');
console.log(`User ${socket.id} joined room ${roomCode}`);
} else {
socket.emit('error', 'Room not found');
}
});
socket.on('startGame', ({ roomCode, category, difficulty }) => {
fetchQuestions(category, difficulty).then((questions) => {
if (!questions || questions.length === 0) {
socket.emit('error', 'Failed to load questions');
return;
}
rooms[roomCode].questions = questions;
io.in(roomCode).emit('newQuestion', questions[0]); // Send the first question
});
});
socket.on('submitAnswer', (data) => {
const room = rooms[data.roomCode];
if (!room || !room.questions || room.questions.length === 0) {
socket.emit('error', 'No questions available');
return;
}
const question = room.questions[0];
const correct = question.correctAnswer === data.answer;
socket.emit('answerResult', { correct, correctAnswer: question.correctAnswer });
});
socket.on('nextQuestion', (roomCode) => {
const room = rooms[roomCode];
if (room && room.questions.length > 0) {
room.questions.shift();
if (room.questions.length > 0) {
io.in(roomCode).emit('newQuestion', room.questions[0]);
} else {
io.in(roomCode).emit('gameOver');
}
} else {
io.in(roomCode).emit('gameOver');
}
});
socket.on('disconnect', () => {
console.log('User disconnected:', socket.id);
});
});
function fetchQuestions(category, difficulty) {
return axios.get(`https://opentdb.com/api.php`, {
params: {
amount: 5,
category,
difficulty,
type: 'multiple',
},
})
.then((response) => {
return response.data.results.map((q) => {
let options = [q.correct_answer]; // Start with the correct answer
for (let incorrect of q.incorrect_answers) {
options.push(incorrect); // Add each incorrect answer
}
options = shuffleArray(options); // Shuffle the combined array
return {
question: q.question,
options: options,
correctAnswer: q.correct_answer,
};
});
})
.catch((error) => {
console.error('Error fetching questions:', error);
return [];
});
}
function shuffleArray(array) {
for (let i = array.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1));
[array[i], array[j]] = [array[j], array[i]];
}
return array;
}
server.listen(PORT, () => console.log(`Server is running on http://localhost:${PORT}`));
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment