Let's build a multiplayer movie trivia/quiz game with socket.io, svelte and node. devlog #7

zoppatorsk

Zoppatorsk

Posted on August 22, 2022

Let's build a multiplayer movie trivia/quiz game with socket.io, svelte and node. devlog #7

Saving 100 hours...

So i read this post. It says I will save 100 hours by filling out this form, so yeah let's do it.

  1. What's your idea(one-liner)? A multiplayer movie trivia/quiz game
  2. What's the opportunity size? 0$
  3. Who's your target audience? none, or maybe me..?
  4. What is/are the problem(s)? Me
  5. What is/are the solution(s)? Also me
  6. How do you monetize it? I don't
  7. What are the other alternatives? Watch Korean dramas on Netflix.

Yeah, that only took some seconds, should have done that from the start... I have now saved so much time I can spend the rest of the evening watching Korean dramas on Netflix.

New day, new devlog

So, yeah, I started writing this yesterday and yeah, I mostly spent the evening watching a Korean drama ;) .. but yeah, I did get some refactoring done also.. one of my sons complained that the code was ugly so got rid of some nested if's n put some early returns n stuff instead.

Made some more fault prevention stuff, when working with sockets and those can get undefined at any moment if a user disconnects but you are still running code things crash easily.
I want to prevent as much of that as possible before pulling a

process.on("uncaughtException", function (err) {
console.log("Keep it alive!!: ", err);
});
Enter fullscreen mode Exit fullscreen mode

To prevent server crash when some function cant finish!

What's new!

Well, I have kept working on making the "trivia game engine" more universal.
So I needed a way to be able to easily define new types of questions.

Class was the obvious answer, I like classes in the way I can encapsulate both methods and data into one entity.

So I created a base-class that have the common fields and methods already defined and for creating and customize your own question type can just extend it and override what u want.

Current implementation.. Will probably change a little if I need to add more stuff

BaseQuestion

module.exports = class BaseQuestion {
    constructor({ type = 'pic-one', title = 'pick one', question = 'question text', correctAnswer = 'correct answer', answers = ['correct answer', 'wrong answer'] } = {}) {
        if (this.constructor == BaseQuestion) throw new Error("Abstract classes can't be instantiated.");

        this.type = type;
        this.title = title;

        this.question = question; //question text
        this.correctAnswer = correctAnswer; //correct answer
        this.answers = answers; //array of answer alternatives
    }

    isAnswerCorrect(answer) {
        return answer === this.correctAnswer;
    }
    calculateScore(answer, time) {
        if (this.isAnswerCorrect(answer)) return 100 + time * 10;
        else return 0;
    }
};
Enter fullscreen mode Exit fullscreen mode

I also made a new class by extending it and change the score system.

const BaseQuestion = require('./BaseQuestion');
module.exports = class PickOne extends BaseQuestion {
    constructor(...args) {
        super(...args);
    }
    calculateScore(answer, time) {
        if (this.isAnswerCorrect(answer)) return 100 + time * 100;
        else return 0;
    }
};
Enter fullscreen mode Exit fullscreen mode

And just to test things out I wanted to see if could easily implement a different question provider instead of just using hard coded questions. After a 2 second google i found open trivia database..

Threw together some code in the generateQuestions() function

const axios = require('axios');
const he = require('he');
const PickOne = require('../questions/PickOne');
const { shuffleArray } = require('./functions');

module.exports = async function generateQuestions(no) {
    try {
        const { data } = await axios.get(`https://opentdb.com/api.php?amount=${no}&type=multiple`);

        const selectedQuestions = [];

        data.results.forEach((element) => {
            const answers = shuffleArray(element.incorrect_answers.concat(element.correct_answer));
            selectedQuestions.push(new PickOne({ question: he.decode(element.question), answers: answers, correctAnswer: element.correct_answer, type: 'pick-one' }));
        });
        return selectedQuestions;
    } catch (error) {
        console.log(error);
        return [];
    }
};

Enter fullscreen mode Exit fullscreen mode

No error handling in that one, but who cares it was just a quick test..

n.. see.. we now have an actual trivia game going..
question

round_result

BTW, I did get the correct answer by just clicking mouse on random answer without reading the question cuz was bz doing screen shot before time ran out.. skill or luck?? ;)

Yes, still need to work on the CSS n junk, but yeah, later.. it is not important for now.. will keep implementing the core features.

Next up are:

  • Game browser, just a list of games that can join and the stats
  • Settings for creating game. Just frontend code, backend is already prepared
  • Display game results.
  • chat functionality, thinking maybe booth an in game chat and a global chat. Not hard to implement at least, probably like 2 lines of code or something on the backend ( one for global and one for game ;) )
  • loader component that can show on frontend if nee when stuff is bz.. (only really will be shown if have really slow connection later and the questions are like image based and need to be preloaded before round starts).

But yeah, if feel for it might just redo some of the current CSS.

💖 💪 🙅 🚩
zoppatorsk
Zoppatorsk

Posted on August 22, 2022

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related