[SOLVED] Give 1 point to each unique winner respectively in javascript

Issue

This Content is from Stack Overflow. Question asked by rich

First of all, I hope you can understand my English. I’m not really good at English. I’d like to ask for help on giving 1 point to every unique user(a user that joined, a live stream to be exact) for every correct answer.

The issue I have in the current coding is that instead of giving points to each user respectively, it counts all users as one. What I mean by that is, for example: When user A wins, he gets(displays) 1 point. When user B wins, he gets(displays) 2 points. The points keep adding for every other user.

I’d like it to be like this: When user A wins, he gets(displays) 1 point. When user B wins he also gets(displays) 1 point too. That means each user has their own winning record.

I hope you can understand what I’m trying to explain.
Please ask if you need further explanation on things you don’t understand.

I’d like to display the win count under/currently under the ‘function addPhoto’.
Following is the current code:

Thanks in advance!

// DATA
let connection = new TikTokIOConnection(undefined);
let gameWords = [];
let gamegameSelectedWord = null;
let gameTimer = null;
let gameStatus = false;
let wins = 0;

// Config
let confComment = false;
let confLike = false;
let confShare = false;
let confJoin = false;

// START
$(document).ready(() => {
    // Resize
    function resizeContainer() {
        let height = window.innerHeight;
        let width = Math.round((9 / 16) * height);
        $("#gameSize").html(width + 'x' + height);
        $(".container").outerWidth(width);
        $(".background").outerWidth(width);
        $(".printer").outerWidth(width);
        $(".animation").outerWidth(width);

        // Paper
        if (window.innerWidth >= 1366) {
            var paperHeight = $("#paperContainer").outerHeight() - 20;
        } else {
            var paperHeight = $("#paperContainer").outerHeight() + 7;
        }
        $("#paper").outerHeight(paperHeight);
    }
    resizeContainer();
    $(window).resize(function() {
        resizeContainer();
    });

    // Connect
    $("#targetConnect").click(function(e) {
        // Check
        if (gameStatus) {
            let targetLive = $("#targetUsername").val();
            connect(targetLive);
        } else {
            alert("Start game first!");
        }
        
    });

    // Test
    $("#btnPrepare").click(function(e) {
        // Check sound
        playSound(1);
        playSound(2);
        playSound(3);
        playSound(4);
        speakTTS(MSG_TEST);

        // Populate dummy
        for (let i = 0; i < 30; i++) {
            addContent("<div style='text-align:center;'>Welcome ๐Ÿฅณ๐Ÿฅณ๐Ÿฅณ</div>");
        }

        // Load game
        loadGame();

        // Setting
        loadSetting();

        // Set
        gameStatus = true;
    });

    // Save config
    $("#btnSave").click(function(e) {
        loadSetting();
    });
})

/*GAME PLAY
*/

function speakTTS(msg) {
    speak(msg, {
        amplitude: 100,
        pitch: 70,
        speed: 150,
        wordgap: 5
    });
}

/*function scramble( s ) {
 return s.replace(
  /b([a-z])([a-z]+)([a-z])b/gi,
  function( t, a, b, c ) {
   b = b.split( /B/ );
   for( var i = b.length, j, k; i; j = parseInt( Math.random() * i ),
    k = b[--i], b[i] = b[j], b[j] = k ) {}
   return a + b.join( '' ) + c;
  }
 );
}
document.forms.f.onsubmit = function() {
 this.elements.t.value = scramble( this.elements.t.value );
 return false;
};
document.forms.f.elements.t.value =
 scramble( gettext( document.getElementsByTagName( 'p' )[0] ) );
 */
function censor(word) {
    let censored = [];
    let length = word.length;
    let target = Math.ceil(length / 2);

    let range_start = 2;
    let range_end = target;

    for (let i = 0; i < length; i++) {
        let c = word.charAt(i);
        if (i >= range_start && i <= range_end) {
            if (c === " ") {
                censored.push("&nbsp;&nbsp;");
            } else {
                censored.push("*");
            }
        } else {
            censored.push(c);
        }
    }

    return censored.join("");
}

function copyArray(a) {
    let b = [];
    for (i = 0; i < a.length; i++) {
        b[i] = a[i];
    }
    return b;
}

function shuffle(a) {
    let j, x, i;
    for (i = a.length - 1; i > 0; i--) {
        j = Math.floor(Math.random() * (i + 1));
        x = a[i];
        a[i] = a[j];
        a[j] = x;
    }
    return copyArray(a);
}

function countDown() {
    // Counter
    let timeleft = 60 * 4; // 4 Mins

    // Clear
    if (gameTimer != null) {
        clearInterval(gameTimer);
    }

    // Start
    gameTimer = setInterval(function() {
        // Reset
        if (timeleft <= 0){
            clearInterval(gameTimer);
            loadGame();
        }

        // Set
        $("#gameTimeout").html(timeleft.toLocaleString() + "s");
        timeleft -= 1;

    }, 1000);
}

function loadGame() {
    // Check
    if (gameWords.length < 1) {
        gameWords = shuffle(WORDS);
    }

    // Load
    gameSelectedWord = gameWords.pop();

    // Set remain words
    $("#gameWords").html(gameWords.length);

    // Check
    if (typeof gameSelectedWord === 'string') {
        // Normalize
        splittedWord = gameSelectedWord.split("|");
        gameSelectedWord = splittedWord[1];

        // Set
        $("#textGuess").html("<div style='font-size:70%;padding-bottom:5px;'>" + splittedWord[0] + "</div>" + censor(gameSelectedWord));
        //$("#textGuess").html("<div style='font-size:70%;padding-bottom:5px;'>" + splittedWord[0] + "</div>" + scramble(gameSelectedWord));

        // Timeout
        countDown()

    } else {
        loadGame();
    }
}

function checkWinner(data, msg) {
    // Check type
    if (typeof gameSelectedWord === 'string' && typeof msg === 'string') {
        // Check answer
        if (gameSelectedWord.trim().toLowerCase() == msg.trim().toLowerCase()) {
            // Print Photo
            addPhoto(data, "winner");

            // Sound
            playSound(4);

            // Play TTS
            let tssMsg = MSG_WINNER.replace("|username|", data.uniqueId);
            speakTTS(tssMsg);

            // Reload game
            loadGame();
        }
    }
}

function loadSetting() {
    // Load
    confComment = $("#confComment").prop('checked');
    confLike = $("#confLike").prop('checked');
    confShare = $("#confShare").prop('checked');
    confJoin = $("#confJoin").prop('checked');
}

/*LIVE TIKTOK
*/

function connect(targetLive) {
    if (targetLive !== '') {
        $('#stateText').text('Connecting...');
        $("#usernameTarget").html("@"+targetLive);
        connection.connect(targetLive, {
            enableExtendedGiftInfo: true
        }).then(state => {
            $('#stateText').text(`Connected ${state.roomId}`);
        }).catch(errorMessage => {
            $('#stateText').text(errorMessage);
        })
    } else {
        alert('Enter username first!');
    }
}

function sanitize(text) {
    return text.replace(/</g, '&lt;')
}

function isPendingStreak(data) {
    return data.giftType === 1 && !data.repeatEnd;
}

function playSound(mode) {
    document.getElementById("sfx"+mode).play();
}

function addContent(payload) {
    // Container
    let content = $('#paper');
    content.append("<div class='item'>" + payload + "</div>");

    // Scroll top bottom
    content.animate({ scrollTop: content.get(0).scrollHeight}, 333);
}

function addMessage(data, msg) {
    // DATA
    let userName = data.uniqueId;
    let message = sanitize(msg);

    // Check for voice
    let command = message.split(" ")[0];
    if (command == ":=say" || command == ":=cakap") {
        // TTS
        let cleanText = message.replace("=:say", "").replace("=:cakap", "");
        speakTTS(cleanText);

    } else {
        // Check setting
        if (confComment) {
            // Add
            addContent("<span style='font-weight: bold;'>" + userName + "</span>: " + message);

            // Sound
            playSound(1);
        }
        
    }
}
    
function addPhoto(data, mode) {
    // DATA
    let userName = data.uniqueId;
    let userAvatar = data.profilePictureUrl;
    let word = ['Nice going','Thatโ€™s better than ever','Thatโ€™s first class work','Iโ€™m impressed','Nothing can stop you now','Well done','Good job','You did it','Thatโ€™s the way','You rock','I knew you could do it','Keep up the good work','Thatโ€™s clever','Way to go','Outstanding','Tremendous','Fantastic','You are amazing','No one can beat you','You are the chosen one'];
    let words = word[Math.floor(Math.random()*word.length)];

    // Add
    if (mode == "winner")
        {
        wins++;
        addContent(
            `<div style="text-align:center;font-size: 1.25rem;">
                <div style='padding-bottom:.25rem;color:#1881FF;'>๐Ÿ‘๐Ÿป๐Ÿ‘๐Ÿป `+words+`</div>
                <div style='padding-bottom:.5rem;font-weight: bold;color:#20B601;'>`+userName+` โ—</div>
                <div>
                    <img src="`+userAvatar+`" style="width:135px;height:135px;border-radius: 15px;"/>
                    Wins: `+wins+`
                </div>
            </div>`
        );
    } else {
        addContent(
            `<div style="text-align:center;font-size: 1.25rem;">
                <div style='padding-bottom:.25rem;'>๐ŸŽ‰๐ŸŽ‰๐ŸŽ‰Thanks๐ŸŽ‰๐ŸŽ‰๐ŸŽ‰</div>
                <div style='padding-bottom:.5rem;font-weight: bold;color:#EA0C0C;'>`+userName+`</div>
                <div>
                    <img src="`+userAvatar+`" style="width:135px;height:135px;border-radius: 15px;"/>
                </div>
            </div>`
        );
    }

    // Sound
    playSound(3);
}

function addGift(data) {
    // DATA
    let userName = data.uniqueId;
    let giftPictureUrl = data.giftPictureUrl;
    let giftName = data.giftName;
    let giftRepeat = data.repeatCount;
    let giftTotal = (data.diamondCount * data.repeatCount);
    let word = ['Appreciate it','Thanks','Thank you very much','It means a lot','Youโ€™re the best','Your gift helps me',];
    let words = word[Math.floor(Math.random()*word.length)];

    // Check
    if (giftTotal >= 10) {
        // Print Photo
        addPhoto(data);

    } else {
        // Add
        addContent(
            `<div style="text-align:center;font-size: 1.25rem;"><div style='padding-bottom:.5rem;'>`+words+` <span style='font-weight: bold;color:#EA0C0C;'>`+userName+`!</span></div>
            <div style='font-weight: bold;padding-bottom:.5rem;'><img src="`+giftPictureUrl+`" style="width:35px;height:35px;"/> Sent `+giftName+`</div>
            x`+giftRepeat.toLocaleString()+` worth `+giftTotal.toLocaleString()+` coins!</div>`
        );

        // Sound
        playSound(2);

        // Play TTS
        let tssMsg = MSG_GIFT.replace("|username|", userName);
        speakTTS(tssMsg);
    }
}

// New chat comment received
connection.on('chat', (data) => {
    addMessage(data, data.comment);
    checkWinner(data, data.comment);
})

// New gift received
connection.on('gift', (data) => {
    if (!isPendingStreak(data) && data.diamondCount > 0) {
        addGift(data);
    }
})

// Like
connection.on('like', (data) => {
    if (typeof data.totalLikeCount === 'number') {
        // Check setting
        if (confLike) {
            // Print like
            addMessage(data, data.label.replace('{0:user}', '').replace('likes', `${data.likeCount} likes`));
        }
    }
})

// Share, Follow
connection.on('social', (data) => {
    // Check setting
    if (confShare) {
        // Print share
        addMessage(data, data.label.replace('{0:user}', ''));
    }
})

// Member join
let joinMsgDelay = 0;
connection.on('member', (data) => {
    let addDelay = 250;
    if (joinMsgDelay > 500) addDelay = 100;
    if (joinMsgDelay > 1000) addDelay = 0;

    joinMsgDelay += addDelay;

    setTimeout(() => {
        joinMsgDelay -= addDelay;
        // Check setting
        if (confJoin) {
            // Print join
            addMessage(data, "has entered");
        }
    }, joinMsgDelay);
})

// End
connection.on('streamEnd', () => {
    $('#stateText').text('Stream ended.');
})



Solution

You should have an dictionary (object) of wins with keys the users, and values are the wins for each. Thus you save for each user its own wins.

So declare global:

let wins = {
    // name: wins, name2: wins2
}

Then whenever need to increase wins, do so for the wins[playerName] value.

if (mode == "winner") {
    wins[userName] = wins[userName] || 0
    wins[userName]++

    addContent(
        `<div style="text-align:center;font-size: 1.25rem;">
        <div style='padding-bottom:.25rem;color:#1881FF;'>๐Ÿ‘๐Ÿป๐Ÿ‘๐Ÿป `+ words + `</div>
        <div style='padding-bottom:.5rem;font-weight: bold;color:#20B601;'>`+ userName + ` โ—</div>
        <div>
            <img src="`+ userAvatar + `" style="width:135px;height:135px;border-radius: 15px;"/>
            Wins: `+ wins[userName] + `
        </div>
    </div>`
    );
}


This Question was asked in StackOverflow by rich and Answered by IT goldman It is licensed under the terms of CC BY-SA 2.5. - CC BY-SA 3.0. - CC BY-SA 4.0.

people found this article helpful. What about you?