const crypto = require('crypto');

function hmacSHA256(key, message) {
    return crypto.createHmac('sha256', key).update(message).digest('hex');
}

function sha256(message) {
    return crypto.createHash('sha256').update(message).digest('hex');
}

function getSortedResult(serverSeed, clientSeed, nonce, numMines) {
    const allNums = Array.from({ length: 25 }, (_, i) => i);

    // Step 2: Combine client seed and nonce, and compute HMAC_SHA256
    const combined = `${clientSeed}:${nonce}`;
    const initialHash = hmacSHA256(serverSeed, combined);

    // Step 4: Seed manipulation through SHA256 hashing iterations
    let h = initialHash;
    for (let i = 0; i < 10; i++) {  // Adjust the number of iterations for higher accuracy
        h = sha256(h);
    }

    // Step 5: Pairing numbers with hash segments
    const pairs = allNums.map((num, index) => ({
        num,
        hash: parseInt(h.slice(index * 2, index * 2 + 2), 16)  // Extracting 2 characters per number and converting to an integer
    }));

    // Step 6: Sorting pairs based on hash values
    pairs.sort((a, b) => a.hash - b.hash);

    // Step 7: Extracting sorted numbers
    const resultList = pairs.map(pair => pair.num);

    // Randomly select mines from the sorted list
    const mines = [];
    for (let i = 0; i < numMines; i++) {
        mines.push(resultList[i]);  // Select the first numMines elements as mines
    }

    // Create a result object to differentiate between safe spots and mines
    const result = resultList.map(num => ({
        num,
        hasMine: mines.includes(num)
    }));

    return result;
}

function visualizeGrid(result) {
    const grid = Array(5).fill(null).map(() => Array(5).fill('S'));
    result.forEach(item => {
        const row = Math.floor(item.num / 5);
        const col = item.num % 5;
        grid[row][col] = item.hasMine ? 'M' : 'S';
    });

    return grid.map(row => row.join(' ')).join('\n');
}

// Example usage:
const serverSeed = '3687561c4add8f4b30e234db17a2af582caf3b2073e08ecf8364867fc09e5226';
const clientSeed = 'iQYXG4tC5jFDS655apEGa';
const nonce = 19;
const numMines = 24;  // Example number of mines

const result = getSortedResult(serverSeed, clientSeed, nonce, numMines);

// Display results
const sortedResult = result.map(item => item.num);
const minePositions = result.filter(item => item.hasMine).map(item => item.num);
const safePositions = result.filter(item => !item.hasMine).map(item => item.num);

console.log('Sorted Result List:', sortedResult);
console.log('Mine Positions:', minePositions);
console.log('Safe Positions:', safePositions);

// Visualize the 5x5 grid
console.log('5x5 Grid Visualization:');
console.log(visualizeGrid(result));

 

NodeJS Online Compiler

Write, Run & Share NodeJS code online using OneCompiler's NodeJS online compiler for free. It's one of the robust, feature-rich online compilers for NodeJS language,running on the latest LTS version NodeJS 16.14.2. Getting started with the OneCompiler's NodeJS editor is easy and fast. The editor shows sample boilerplate code when you choose language as NodeJS and start coding. You can provide the dependencies in package.json.

About NodeJS

Node.js is a free and open-source server environment. Node.js is very popular in recent times and a large number of companies like Microsoft, Paypal, Uber, Yahoo, General Electric and many others are using Node.js.

Key features

  • Built on Google chrome's javascript engine V8 and is pretty fast.
  • Node.js was developed by Ryan Dahl in 2009.
  • Server-side platform for building fast and scalable applications.
  • Node.js is Asynchronous, event-driven and works on single-thread model thus eliminating the dis-advantages of multi-thread model.
  • Supports various platforms like Windows, Linux, MacOS etc.
  • Provides rich library of java script modules which simplifies the development efforts.
  • Released under MIT license.

Express Framework

Express is one of the most popular web application framework in the NodeJS echosystem.

  • Pretty fast
  • Minimalist
  • Unopinionated
  • Very flexible

Syntax help

Examples

Using Moment

let moment = require('moment');

console.log(moment().format('MMMM Do YYYY, h:mm:ss a'));

Using Lodash

const _ = require("lodash");

let colors = ['blue', 'green', 'yellow', 'red'];

let firstElement = _.first(colors);
let lastElement = _.last(colors);

console.log(`First element: ${firstElement}`);
console.log(`Last element: ${lastElement}`);

Libraries supported

Following are the libraries supported by OneCompiler's NodeJS compiler.

  • lodash
  • moment
  • underscore
  • uuid
  • ejs
  • md5
  • url