Z
Z
zlodiak2020-04-17 00:26:45
JavaScript
zlodiak, 2020-04-17 00:26:45

How to get a set of points on the coordinate plane?

I set out to get rid of global variables and pass all the data necessary for the function to work through parameters. For the task of getting a set of points on the coordinate plane, I wrote the following code:

const walls$ = combineLatest(
  range(0, constants.wallsCnt),
  of(constants.canvasWidthPx),
  of(constants.canvasHeightPx),
  of(constants.wallSizePx),
)
.pipe(
  map(([range, canvasWidthPx, canvasHeightPx, wallSizePx]) => {
    return {
      x: Math.floor(Math.random() * Math.floor(canvasWidthPx - wallSizePx)),
      y: Math.floor(Math.random() * Math.floor(canvasHeightPx - wallSizePx)),
      strength: Math.floor(Math.random() * Math.floor(constants.wallStrengthMax)) + 1,
    }
  }),
  toArray(),
  tap(v => {
    console.log(v)
  }),
).subscribe()


The problem is that I get only one point in the output, although I should get 3. Because It is
constants.wallsCnt = 3

noteworthy that the problem is solved if we rewrite the code using global variables:
const walls$ = range(0, constants.wallsCnt)
.pipe(
  map(_ => {
    return {
      x: Math.floor(Math.random() * Math.floor(constants.canvasWidthPx - constants.wallSizePx)),
      y: Math.floor(Math.random() * Math.floor(constants.canvasHeightPx - constants.wallSizePx)),
      strength: Math.floor(Math.random() * Math.floor(constants.wallStrengthMax)) + 1,
    }
  }),
  toArray(),
)


But I need a record in the first version. Please help me fix the code.

Don't ask me why I need this. I'm writing a small 2D game, the full code is here if you're interested.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Anton Shvets, 2020-04-17
@zlodiak

However, you made me scratch my head with your question
. Of course, the way to calculate coordinates in this way is a complete perversion, however, this behavior of combineLatest puzzled me for a while :)
But everything turned out to be quite simple https://stackblitz.com/edit/tanks-field -without-gl...
Spot the difference.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question