Advertisement

Should a clicker game use cookies or localStorage?

Started by November 28, 2021 04:19 AM
2 comments, last by 8Observer8 3 years ago

I'm developing a clicker game and wondering if I should use cookies or localStorage to save clicks?

None

If it's a typical clicker game that is served through a web page but played entirely locally, use local storage.

If it's a server-based online game, store the game state on the server, but use a cookie to store the player id.

In general, cookies are used for communicating with web servers. They should be small because each http request includes the full cookie. Local storage is for Javascript application to store state that doesn't go on the server, so it can much be bigger.

Advertisement

This example https://github.com/8Observer8/login-websocket-js is just for demonstration how to read information on server side. It uses WebSockets for communication. You can save records of your users to MySQL (MongoDB and so on) to show a record table. This simple example reads login/password from the users.json file.

users.json

[
    {
        "login": "Ivan",
        "password": "123abc"
    },
    {
        "login": "Peter",
        "password": "mypass"
    },
    {
        "login": "Artem",
        "password": "987654321"
    }
]

app.js

const express = require("express");
const http = require("http");
const ws = require("ws");
const path = require("path");
const fs = require("fs");

const app = express();
app.use(express.static(path.join(__dirname, "./public")));
app.get("/", (req, res) => { res.sendFile(path.join(__dirname, "index.html")) });

const httpServer = http.createServer(app);
const wss = new ws.Server({ server: httpServer });
wss.on("connection",
    (ws) =>
    {
        console.log("Client connected");

        let isLoggedin = false;

        const content = fs.readFileSync("users.json", "utf8");
        const users = JSON.parse(content);

        ws.onmessage =
            (event) =>
            {
                const msg = JSON.parse(event.data);

                if (msg.login)
                {
                    console.log(msg.login + ", " + msg.password);

                    if (!isLoggedin)
                    {
                        users.forEach(
                            user =>
                            {
                                if (user.login === msg.login && user.password === msg.password)
                                {
                                    isLoggedin = true;
                                    console.log("Ok")
                                    return;
                                }
                            });
                    }
                    console.log("isLoggedin: " + isLoggedin);
                    // Send an answer
                    ws.send(JSON.stringify({ isLoggedin: isLoggedin }));
                }
            }
    });

const port = process.env.PORT || 3000;
httpServer.listen(port, () => { console.log("Server started. Port: ", port); });

public/index.html

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <title>Login with WebSockets</title>
</head>

<body>
    Login: <input type="text" id="login" name="login" value="Peter"><br>
    Password: <input type="text" id="password" name="password" value="mypass"><br><br>
    <button id="login_password">Login</button>

    <script>
        const loginElement = document.getElementById("login");
        const passwordElement = document.getElementById("password");
        const loginButtonElement = document.getElementById("login_password");

        const ws = new WebSocket("ws://localhost:3000");
        ws.onopen =
            () =>
            {
                console.log("The client was connected to the server");

                loginButtonElement.onclick =
                    () =>
                    {
                        const login = loginElement.value;
                        const pass = passwordElement.value;

                        ws.send(JSON.stringify({ login: login, password: pass }));
                    };

                ws.onmessage =
                    (event) =>
                    {
                        console.log(event.data);
                    }
            };
    </script>
</body>

</html>

package.json

{
  "name": "login-websocket-js",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "dependencies": {
    "express": "^4.17.1",
    "ws": "^7.3.1"
  }
}

This topic is closed to new replies.

Advertisement