skip to Main Content

I’m creating a game in Javascript which has a leaderboard.

I initially wanted to just have it so you can enter a player name then click play game.

The game has a countdown timer so I wanted to post the player score to the database in two scenarios:

  1. The timer reaches 0 and the game is over
  2. The player gets all the answers correct and completes the game

I would send an object like this:

{
 name: 'Fred Smith',
 score: 14
}

My question is this sensible without an actual account through register/login?

Because each time someone plays they will post a new score and name for e.g

  1. You set your player name to be Bob
  2. You play once, it inserts a new JS object to the DB
  3. You click play again and have another game, this will post a new JS object with the name Bob and a new score

I’m not too experienced with databases so was curious on if it would be able to manage the size, or if there is a better approach to this without implementing register/login.

Thanks

2

Answers


  1. You can implement an unique id for each distinct user and store it as a cookie. Then use that id to store in the database.

    Login or Signup to reply.
  2. To expand on @juliancq answer:

    1. a client app (browser) loads in the game.
    2. searches for the cookie.
    3. if none found, creates a new cookie with unique ID and stores it in the browser (possibly the name of the user too); if cookie exists – parse it to get UID or UID+name.
    4. user enters a name (if not parsed from cookie);
    5. plays the game until the end-condition.
    6. POST request sent to DB of choice.
    // js (commonJS)
    const { v1: uuidv1 } = require("uuid");
    const uid = 'uid='.concat(uuidv1());
    
    // the 'SameSite=' parameter could be omitted or set to 'Lax' in some cases
    // more info: https://developer.mozilla.org/en-US/docs/web/api/document/cookie
    
    const name = "name_from_form";
    
    document.cookie = `${uid}; SameSite=None; Secure`;
    document.cookie = `name=${name}; SameSite=None; Secure`;
    
    const uidCookieValue = document.cookie
      .split("; ")
      .find((row) => row.startsWith("uid="))
      ?.split("=")[1];
    const nameCookieValue = document.cookie
      .split(";")
      .find((row) => row.startsWith("name="))
      ?.split("=")[1];
    

    You can checkout the sandbox here: https://codesandbox.io/s/set-uuid-name-cookies-sw5gt3

    P.S. it’s a new account so i couldn’t comment 🙂

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search