How to make an Scores hanking of a javascript game

Asked

Viewed 55 times

-1

I have to generate a table with the first five colors stored in a json object. I believe I have many ways to do this, but what I have achieved so far is to filter the colors by level and by user:

let users = [{
                "id": 1,
                "username": "Gustavo",
                "pwd": "20",
                "scores": [{
                        "id": 2,
                        "score": 5,
                        "level": "hard"
                    },
                    {
                        "id": 3,
                        "score": 10,
                        "level": "easy"
                    },
                    {
                        "id": 4,
                        "score": 15,
                        "level": "easy"
                    }
                ]
            },
            {
                "id": 2,
                "username": "Elisa",
                "pwd": "10",
                "scores": [{
                    "id": 5,
                    "score": 150,
                    "level": "easy"
                }]
            },
            {
                "id": 3,
                "username": "Tati",
                "pwd": "2",
                "scores": [{
                        "id": 5,
                        "score": 20,
                        "level": "easy"
                    },
                    {
                        "id": 5,
                        "score": 2,
                        "level": "easy"
                    },
                    {
                        "id": 5,
                        "score": 10,
                        "level": "easy"
                    }
                ]
            }
        ]
`$ranking = users.map(users => ({ users: users.username, scores: users.scores.filter(scores => scores.level === "easy") }));`

não sei se esse resultado é necessário para listar, a parir daí, o username e o score, mas eu imaginei que eu teria que criar algo como $topFiveLevel[] = "cada posição recebe o username seguido do score", porém, não consigo fazer essa iteração... se alguém souber como, ou tiver uma solução mais adequada. Obrigado!

  • Sorry for the insensitivity, but exactly what’s the problem?

  • So, I don’t know how to present the result in the table (the dynamic table I can assemble), but I can’t put the name and the score, so I said in the question that you can have a more direct way of doing, without having to save the name and the score in an array to then sort, and then show it on the chart. Do this filter I got, I do not know if it is possible to see this in the image I put, only appear the names and the object "Scores" with only the values whose level is "easy", but how to list this is that I can not..

1 answer

1


The solution has become a bit extensive but I imagine you understand a lot of the problem.

/**
 * @typedef Score Pontuação de um usuário
 * @property {number} id ID da pontuação do usuário
 * @property {number} score Pontuação do usuário
 * @property {string} level Dificuldade
 */

/**
 * @typedef User
 * @property {number} id ID do usuário
 * @property {string} username Nome do usuário
 * @property {string} pwd ???
 * @property {Array<Score>} scores Lista de pontuações do usuário
 */

/** @type{Array<User>} */
const users = [
  {
id: 1,
username: "Gustavo",
pwd: "20",
scores: [
  {
    id: 2,
    score: 5,
    level: "hard",
  },
  {
    id: 3,
    score: 10,
    level: "easy",
  },
  {
    id: 4,
    score: 15,
    level: "easy",
  },
],
  },
  {
id: 2,
username: "Elisa",
pwd: "10",
scores: [
  {
    id: 5,
    score: 150,
    level: "easy",
  },
],
  },
  {
id: 3,
username: "Tati",
pwd: "2",
scores: [
  {
    id: 5,
    score: 20,
    level: "easy",
  },
  {
    id: 5,
    score: 2,
    level: "easy",
  },
  {
    id: 5,
    score: 10,
    level: "easy",
  },
],
  },
];

const highestToLowestSortingStrategy = (a, b) => b - a;
const lowestToHighestSortingStrategy = (a, b) => a - b;

/**
 * Filtra os dados de uma determinada lista de
 * usuários e ordena suas pontuações através
 * de uma dificuldade
 *
 * @param {Array<User>} users Lista de usuários
 * @param {string} difficulty Dificuldade utilizada para o filtro da pontuação
 * @param {(a: any, b: any) => number} sortingStrategy Estratégia de ordenamento de scores
 * @returns Retorna a lista filtrada de usuários
 */
const filterScoresByDifficulty = (
  users,
  difficulty,
  sortingStrategy = highestToLowestSortingStrategy
) =>
  users
.map(({ scores, ...user }) =>
  scores
    .filter((score) => score.level === difficulty)
    .map((score) => ({
      ...user,
      ...score,
    }))
)
.reduce((list, next) => [...list, ...next], [])
.sort((a, b) => sortingStrategy(a.score, b.score));

const filteredEasyScoresHighestToLowest = filterScoresByDifficulty(
  users,
  "easy"
);
const filteredHardScoresLowestToHighest = filterScoresByDifficulty(
  users,
  "hard",
  lowestToHighestSortingStrategy
);

console.log(filteredEasyScoresHighestToLowest);
console.log(filteredHardScoresLowestToHighest);

  • 1

    I appreciate your code, but this result I had already achieved, which is select by level, what I can’t do is list the name/score pair, because if it was a score for each user, a for in resolveria. the problem is that would have to associate the name to each score and in a for, for each position should record the name and value of a score and in a second record the same name and another score: type, [0]Gustavo 100pts, [1]Gustavo 200pts, [2]Elisa 500pts, Elisa 250pts..

  • No problems, code fixed now.

  • 1

    Eder, forgive me, reviewing your result I realized that it is different from what I had achieved. each position has the name, the level and the score. Now I can select by level and sort from the largest pro minor. Thank you!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.