MediaWiki:TeamBingo.js: Difference between revisions

From Roat Pkz
Jump to navigation Jump to search
No edit summary
No edit summary
Tag: Reverted
Line 1: Line 1:
// --- Team Bingo Board with Captains and Live JSON ---
// --- Team Bingo Board with Captains and Manual Refresh ---
mw.hook('wikipage.content').add(function () {
mw.hook('wikipage.content').add(function () {


     const currentUser = mw.config.get('wgUserName'); // logged-in user
     const currentUser = mw.config.get('wgUserName'); // Logged-in user
     const containers = document.querySelectorAll(".teamBingoContainer");
     const containers = document.querySelectorAll(".teamBingoContainer");
     if (!containers.length) return;
     if (!containers.length) return;
Line 10: Line 10:


     // Set default bingo info immediately on page load
     // Set default bingo info immediately on page load
infoBox.innerHTML = `
    infoBox.innerHTML = `
<div style="text-align: center; font-weight: bold; font-size: 16px; margin-bottom: 8px;">
<div style="text-align: center; font-weight: bold; font-size: 16px; margin-bottom: 8px;">
   Team Bingo Challenge
   Team Bingo Challenge
Line 18: Line 18:
<strong>Rules:</strong><br>
<strong>Rules:</strong><br>
- Only <strong>team captains</strong> can mark tiles for their team.<br>
- Only <strong>team captains</strong> can mark tiles for their team.<br>
- Your board updates <strong>in real time every 30 seconds</strong> for all team members.<br>
- Your board updates <strong>in real time when a captain clicks "Refresh Board"</strong>.<br>
- Screenshots of drops/items are required for verification.<br>
- Screenshots of drops/items are required for verification.<br>
- Chests, crates, and boxes do <em>not</em> count.<br><br>
- Chests, crates, and boxes do <em>not</em> count.<br><br>
Line 31: Line 31:


     const boardState = {}; // central source of truth for all tiles
     const boardState = {}; // central source of truth for all tiles
     // Fetch JSON from Module page
     // Fetch JSON from Module page
     function fetchBoardData(callback) {
     function fetchBoardData(callback) {
Line 53: Line 54:
     }
     }


     // Render the board
     // Render a bingo board container
     function renderBoard(container, teamKey) {
     function renderBoard(container, teamKey) {
        container.innerHTML = "";


        container.innerHTML = "";
         const captainList = container.getAttribute("data-captain").split(",").map(u => u.trim());
         const captain = container.getAttribute("data-captain");
         const itemsAttr = container.getAttribute("data-items");
         const itemsAttr = container.getAttribute("data-items");
         if (!itemsAttr) return;
         if (!itemsAttr) return;
          
 
            // --- ADD TEAM NAME ---
         // --- TEAM NAME ---
    const teamNameDiv = document.createElement("div");
        const teamNameDiv = document.createElement("div");
    teamNameDiv.textContent = container.getAttribute("data-team") === "teamA" ? "Team A" : "Team B";
        teamNameDiv.textContent = teamKey === "teamA" ? "Team A" : "Team B";
    teamNameDiv.style.fontWeight = "bold";
        teamNameDiv.style.fontWeight = "bold";
    teamNameDiv.style.fontSize = "18px";
        teamNameDiv.style.fontSize = "18px";
    teamNameDiv.style.color = "#fff";
        teamNameDiv.style.color = "#fff";
    teamNameDiv.style.textAlign = "center";
        teamNameDiv.style.textAlign = "center";
    teamNameDiv.style.marginBottom = "10px";
        teamNameDiv.style.marginBottom = "10px";
    container.appendChild(teamNameDiv);
        container.appendChild(teamNameDiv);
    // --- END TEAM NAME ---
        // --- END TEAM NAME ---
 
        // --- REFRESH BUTTON (captains only) ---
        if (captainList.includes(currentUser)) {
            const updateBtn = document.createElement("button");
            updateBtn.textContent = "Refresh Board";
            updateBtn.style.margin = "10px auto";
            updateBtn.style.display = "block";
            updateBtn.style.padding = "6px 12px";
            updateBtn.style.fontWeight = "bold";
            updateBtn.style.cursor = "pointer";
            updateBtn.style.borderRadius = "4px";
            updateBtn.style.backgroundColor = "#4CAF50";
            updateBtn.style.color = "#fff";
            updateBtn.style.border = "none";
            updateBtn.style.transition = "0.2s";
            updateBtn.addEventListener("mouseenter", () => updateBtn.style.backgroundColor = "#45a049");
            updateBtn.addEventListener("mouseleave", () => updateBtn.style.backgroundColor = "#4CAF50");
            updateBtn.addEventListener("click", () => {
                fetchBoardData(() => renderBoard(container, teamKey));
            });
            container.appendChild(updateBtn);
        }
        // --- END REFRESH BUTTON ---


         const items = itemsAttr.split("|").filter(i => i.trim() !== "");
         const items = itemsAttr.split("|").filter(i => i.trim() !== "");
Line 91: Line 115:
         const cols = Math.ceil(parsedItems.length / rows);
         const cols = Math.ceil(parsedItems.length / rows);


        // Fetch images via parse API
         const allTemplates = parsedItems.map(item => `{{plinkp|${item.name}}}`).join("\n");
         const allTemplates = parsedItems.map(item => `{{plinkp|${item.name}}}`).join("\n");
         $.getJSON("/api.php", { action: "parse", text: allTemplates, format: "json" }).done(function(data) {
         $.getJSON("/api.php", { action: "parse", text: allTemplates, format: "json" }).done(function(data) {
Line 125: Line 150:
                     cellContainer.style.height = "100%";
                     cellContainer.style.height = "100%";


                    // Image
                     if (imgs[index]) {
                     if (imgs[index]) {
                         const img = document.createElement("img");
                         const img = document.createElement("img");
Line 137: Line 161:
                     }
                     }


                    // Name
                     const nameDiv = document.createElement("div");
                     const nameDiv = document.createElement("div");
                     nameDiv.textContent = item.name;
                     nameDiv.textContent = item.name;
Line 144: Line 167:
                     cellContainer.appendChild(nameDiv);
                     cellContainer.appendChild(nameDiv);


                    // Checkmark
                     const checkmark = document.createElement("div");
                     const checkmark = document.createElement("div");
                     checkmark.textContent = "✔";
                     checkmark.textContent = "✔";
Line 156: Line 178:
                     cellContainer.appendChild(checkmark);
                     cellContainer.appendChild(checkmark);


                     // Hover shows info but preserves green
                     // Hover shows info without overwriting green tiles
                     cell.addEventListener("mouseenter", function() {
                     cell.addEventListener("mouseenter", function() {
                         if (!boardState[teamKey][`tile_${index}`]) cell.style.background = "#3b4a6b";
                         if (!boardState[teamKey][`tile_${index}`]) cell.style.background = "#3b4a6b";
Line 194: Line 216:
<strong>Rules:</strong><br>
<strong>Rules:</strong><br>
- Only <strong>team captains</strong> can mark tiles for their team.<br>
- Only <strong>team captains</strong> can mark tiles for their team.<br>
- Your board updates <strong>in real time every 30 seconds</strong> for all team members.<br>
- Your board updates <strong>in real time when a captain clicks "Refresh Board"</strong>.<br>
- Screenshots of drops/items are required for verification.<br>
- Screenshots of drops/items are required for verification.<br>
- Chests, crates, and boxes do <em>not</em> count.<br><br>
- Chests, crates, and boxes do <em>not</em> count.<br><br>
Line 207: Line 229:
                     });
                     });


// Click to toggle (captain only)
                    // Click to toggle (captain only)
cell.addEventListener("click", function() {
                    cell.addEventListener("click", function() {
    // --- MULTIPLE CAPTAINS SUPPORT ---
                        if (!captainList.includes(currentUser)) return;
    const captainList = container.getAttribute("data-captain").split(",").map(u => u.trim());
                        const done = boardState[teamKey][`tile_${index}`];
    if (!captainList.includes(currentUser)) return; // Only allow if user is a captain
                        boardState[teamKey][`tile_${index}`] = !done;
    // --- END MULTIPLE CAPTAINS SUPPORT ---
                        checkmark.style.display = !done ? "block" : "none";
                        cell.style.background = !done ? "rgba(76,175,80,0.5)" : "#313e59";


    const done = boardState[teamKey][`tile_${index}`];
                        $.post(mw.util.wikiScript('api'), {
    boardState[teamKey][`tile_${index}`] = !done;
                            action: 'edit',
    checkmark.style.display = !done ? "block" : "none";
                            title: 'Module:TeamBingo/data.json',
    cell.style.background = !done ? "rgba(76,175,80,0.5)" : "#313e59";
                            token: mw.user.tokens.get('csrfToken'),
 
                            format: 'json',
    // Save to MediaWiki
                            text: JSON.stringify(boardState, null, 4)
    $.post(mw.util.wikiScript('api'), {
                        }).done(() => console.log("Board updated for everyone!"));
        action: 'edit',
                    });
        title: 'Module:TeamBingo/data.json',
        token: mw.user.tokens.get('csrfToken'),
        format: 'json',
        text: JSON.stringify(boardState, null, 4)
    }).done(() => console.log("Board updated for everyone!"));
});


                     cell.appendChild(cellContainer);
                     cell.appendChild(cellContainer);
Line 251: Line 268:


     // Initial render
     // Initial render
     fetchBoardData(function(boardData){
     fetchBoardData(() => {
         containers.forEach(container => {
         containers.forEach(container => {
             const teamKey = container.getAttribute("data-team");
             const teamKey = container.getAttribute("data-team");
Line 257: Line 274:
         });
         });
     });
     });
    // --- Live update every 5s ---
    setInterval(() => {
        fetchBoardData(function(boardData){
            containers.forEach(container => {
                const teamKey = container.getAttribute("data-team");
                const cells = container.querySelectorAll("td");
                cells.forEach((cell, index) => {
                    const checkmark = cell.querySelector(".bingoCheckmark");
                    const done = boardState[teamKey][`tile_${index}`];
                    if (checkmark) {
                        checkmark.style.display = done ? "block" : "none";
                        cell.style.background = done ? "rgba(76,175,80,0.5)" : "#313e59";
                    }
                });
            });
        });
    }, 30000);


});
});

Revision as of 16:58, 7 March 2026

// --- Team Bingo Board with Captains and Manual Refresh ---
mw.hook('wikipage.content').add(function () {

    const currentUser = mw.config.get('wgUserName'); // Logged-in user
    const containers = document.querySelectorAll(".teamBingoContainer");
    if (!containers.length) return;

    // Shared info box
    const infoBox = document.getElementById("teamBingoInfoBox");

    // Set default bingo info immediately on page load
    infoBox.innerHTML = `
<div style="text-align: center; font-weight: bold; font-size: 16px; margin-bottom: 8px;">
  Team Bingo Challenge
</div>
Welcome to the <strong>Roat Pkz Team Bingo #3</strong> event. Each team has its own bingo board — your goal is to collect the drops or items listed on your team’s board to score points. Each completed tile = 1 point.<br><br>

<strong>Rules:</strong><br>
- Only <strong>team captains</strong> can mark tiles for their team.<br>
- Your board updates <strong>in real time when a captain clicks "Refresh Board"</strong>.<br>
- Screenshots of drops/items are required for verification.<br>
- Chests, crates, and boxes do <em>not</em> count.<br><br>

<strong>Event ends:</strong> June 28th, 11:59 PM GMT<br><br>

<strong>Rewards:</strong><br>
- 500 CREDITS (25M+) — 1st place<br>
- 300 CREDITS (15M+) — 2nd place<br>
- 200 CREDITS (10M+) — 3rd place<br><br>
`;

    const boardState = {}; // central source of truth for all tiles

    // Fetch JSON from Module page
    function fetchBoardData(callback) {
        $.getJSON(mw.util.wikiScript('api'), {
            action: 'query',
            titles: 'Module:TeamBingo/data.json',
            prop: 'revisions',
            rvprop: 'content',
            format: 'json',
            formatversion: 2
        }).done(function(data){
            if (!data.query.pages[0].revisions) return;
            const content = data.query.pages[0].revisions[0].content;
            try {
                const json = JSON.parse(content);
                Object.assign(boardState, json); // update central state
                callback(boardState);
            } catch(e) {
                console.error("Failed to parse JSON from Module:TeamBingo/data.json", e);
            }
        });
    }

    // Render a bingo board container
    function renderBoard(container, teamKey) {
        container.innerHTML = "";

        const captainList = container.getAttribute("data-captain").split(",").map(u => u.trim());
        const itemsAttr = container.getAttribute("data-items");
        if (!itemsAttr) return;

        // --- TEAM NAME ---
        const teamNameDiv = document.createElement("div");
        teamNameDiv.textContent = teamKey === "teamA" ? "Team A" : "Team B";
        teamNameDiv.style.fontWeight = "bold";
        teamNameDiv.style.fontSize = "18px";
        teamNameDiv.style.color = "#fff";
        teamNameDiv.style.textAlign = "center";
        teamNameDiv.style.marginBottom = "10px";
        container.appendChild(teamNameDiv);
        // --- END TEAM NAME ---

        // --- REFRESH BUTTON (captains only) ---
        if (captainList.includes(currentUser)) {
            const updateBtn = document.createElement("button");
            updateBtn.textContent = "Refresh Board";
            updateBtn.style.margin = "10px auto";
            updateBtn.style.display = "block";
            updateBtn.style.padding = "6px 12px";
            updateBtn.style.fontWeight = "bold";
            updateBtn.style.cursor = "pointer";
            updateBtn.style.borderRadius = "4px";
            updateBtn.style.backgroundColor = "#4CAF50";
            updateBtn.style.color = "#fff";
            updateBtn.style.border = "none";
            updateBtn.style.transition = "0.2s";
            updateBtn.addEventListener("mouseenter", () => updateBtn.style.backgroundColor = "#45a049");
            updateBtn.addEventListener("mouseleave", () => updateBtn.style.backgroundColor = "#4CAF50");
            updateBtn.addEventListener("click", () => {
                fetchBoardData(() => renderBoard(container, teamKey));
            });
            container.appendChild(updateBtn);
        }
        // --- END REFRESH BUTTON ---

        const items = itemsAttr.split("|").filter(i => i.trim() !== "");
        if (!items.length) return;

        const parsedItems = items.map(entry => {
            const parts = entry.split("::");
            return { name: parts[0].trim(), tooltip: parts[1] ? parts[1].trim() : parts[0].trim() };
        });

        const table = document.createElement("table");
        table.style.tableLayout = "fixed";
        table.style.border = "2px solid #596e96";
        table.style.borderCollapse = "collapse";
        table.style.borderRadius = "8px";
        table.style.width = "100%";
        container.appendChild(table);

        const rows = Math.ceil(Math.sqrt(parsedItems.length));
        const cols = Math.ceil(parsedItems.length / rows);

        // Fetch images via parse API
        const allTemplates = parsedItems.map(item => `{{plinkp|${item.name}}}`).join("\n");
        $.getJSON("/api.php", { action: "parse", text: allTemplates, format: "json" }).done(function(data) {
            if (!data.parse || !data.parse.text) return;
            const tempDiv = document.createElement("div");
            tempDiv.innerHTML = data.parse.text["*"];
            const imgs = tempDiv.querySelectorAll("img");

            for (let r = 0; r < rows; r++) {
                const row = table.insertRow();
                for (let c = 0; c < cols; c++) {
                    const index = r * cols + c;
                    if (index >= parsedItems.length) break;

                    const item = parsedItems[index];
                    const cell = row.insertCell();
                    const id = `${container.id}_cell_${index}`;
                    cell.id = id;

                    cell.style.width = `${100 / cols}%`;
                    cell.style.padding = "10px";
                    cell.style.border = "1px solid #596e96";
                    cell.style.textAlign = "center";
                    cell.style.background = boardState[teamKey][`tile_${index}`] ? "rgba(76,175,80,0.5)" : "#313e59";
                    cell.style.color = "#fff";
                    cell.style.cursor = "pointer";
                    cell.style.transition = "all 0.2s ease";
                    cell.style.position = "relative";
                    cell.style.userSelect = "none";

                    const cellContainer = document.createElement("div");
                    cellContainer.style.position = "relative";
                    cellContainer.style.width = "100%";
                    cellContainer.style.height = "100%";

                    if (imgs[index]) {
                        const img = document.createElement("img");
                        img.src = imgs[index].src;
                        img.alt = item.name;
                        img.style.width = "40px";
                        img.style.height = "auto";
                        img.style.display = "block";
                        img.style.margin = "0 auto";
                        cellContainer.appendChild(img);
                    }

                    const nameDiv = document.createElement("div");
                    nameDiv.textContent = item.name;
                    nameDiv.style.marginTop = "5px";
                    nameDiv.style.pointerEvents = "none";
                    cellContainer.appendChild(nameDiv);

                    const checkmark = document.createElement("div");
                    checkmark.textContent = "✔";
                    checkmark.className = "bingoCheckmark";
                    checkmark.style.position = "absolute";
                    checkmark.style.top = "2px";
                    checkmark.style.right = "2px";
                    checkmark.style.fontSize = "20px";
                    checkmark.style.color = "#4CAF50";
                    checkmark.style.display = boardState[teamKey][`tile_${index}`] ? "block" : "none";
                    cellContainer.appendChild(checkmark);

                    // Hover shows info without overwriting green tiles
                    cell.addEventListener("mouseenter", function() {
                        if (!boardState[teamKey][`tile_${index}`]) cell.style.background = "#3b4a6b";

                        infoBox.innerHTML = "";
                        const header = document.createElement("div");
                        header.style.fontWeight = "bold";
                        header.style.marginBottom = "5px";
                        header.textContent = item.name;
                        infoBox.appendChild(header);

                        if (imgs[index]) {
                            const hoverImg = document.createElement("img");
                            hoverImg.src = imgs[index].src;
                            hoverImg.style.width = "40px";
                            hoverImg.style.height = "auto";
                            hoverImg.style.display = "block";
                            hoverImg.style.marginBottom = "5px";
                            infoBox.appendChild(hoverImg);
                        }

                        item.tooltip.split("%%").forEach(line => {
                            const div = document.createElement("div");
                            div.innerHTML = line.trim();
                            infoBox.appendChild(div);
                        });
                    });

                    cell.addEventListener("mouseleave", function() {
                        cell.style.background = boardState[teamKey][`tile_${index}`] ? "rgba(76,175,80,0.5)" : "#313e59";
                        infoBox.innerHTML = `
<div style="text-align: center; font-weight: bold; font-size: 16px; margin-bottom: 8px;">
  Team Bingo Challenge
</div>
Welcome to the <strong>Roat Pkz Team Bingo #3</strong> event. Each team has its own bingo board — your goal is to collect the drops or items listed on your team’s board to score points. Each completed tile = 1 point.<br><br>

<strong>Rules:</strong><br>
- Only <strong>team captains</strong> can mark tiles for their team.<br>
- Your board updates <strong>in real time when a captain clicks "Refresh Board"</strong>.<br>
- Screenshots of drops/items are required for verification.<br>
- Chests, crates, and boxes do <em>not</em> count.<br><br>

<strong>Event ends:</strong> June 28th, 11:59 PM GMT<br><br>

<strong>Rewards:</strong><br>
- 500 CREDITS (25M+) — 1st place<br>
- 300 CREDITS (15M+) — 2nd place<br>
- 200 CREDITS (10M+) — 3rd place<br><br>
`;
                    });

                    // Click to toggle (captain only)
                    cell.addEventListener("click", function() {
                        if (!captainList.includes(currentUser)) return;
                        const done = boardState[teamKey][`tile_${index}`];
                        boardState[teamKey][`tile_${index}`] = !done;
                        checkmark.style.display = !done ? "block" : "none";
                        cell.style.background = !done ? "rgba(76,175,80,0.5)" : "#313e59";

                        $.post(mw.util.wikiScript('api'), {
                            action: 'edit',
                            title: 'Module:TeamBingo/data.json',
                            token: mw.user.tokens.get('csrfToken'),
                            format: 'json',
                            text: JSON.stringify(boardState, null, 4)
                        }).done(() => console.log("Board updated for everyone!"));
                    });

                    cell.appendChild(cellContainer);
                }
            }

            // Progress
            const progressDiv = document.createElement("div");
            progressDiv.style.marginTop = "10px";
            progressDiv.style.color = "#fff";
            progressDiv.className = "bingoProgress";
            container.appendChild(progressDiv);

            function updateProgress() {
                let completed = 0;
                for (let i = 0; i < parsedItems.length; i++)
                    if (boardState[teamKey][`tile_${i}`]) completed++;
                progressDiv.textContent = `Completed ${completed} of ${parsedItems.length} items`;
            }
            updateProgress();
        });
    }

    // Initial render
    fetchBoardData(() => {
        containers.forEach(container => {
            const teamKey = container.getAttribute("data-team");
            renderBoard(container, teamKey);
        });
    });

});