Z
Z
zlodiak2020-04-01 21:28:14
JavaScript
zlodiak, 2020-04-01 21:28:14

How to fill state?

I wrote a small game. In it, you can move the player's tank around the field using the cursor keys.

LIVE DEMO

The player's coordinates are stored in the state. Also in the state there is the walls key, which stores the array of wall coordinates. Separately, I generated this array in the walls$ thread, but I can't add it to state. Help me please.

In the program, the main actions take place here:

const game$ = combineLatest(keys$, walls$).pipe()

game$.subscribe((action) => {
  switch (action[0]) {
    case 'ArrowUp':
      if(state.y > 0) { state.y--; }
      break;
    case 'ArrowRight':
      if(state.x < gameWidth - 1) { state.x++; }
      break;
    case 'ArrowDown':
      if(state.y < gameHeight - 1) { state.y++; }
      break;
    case 'ArrowLeft':
      if(state.x > 0) { state.x--; }
      break;    
  }  
  renderGame(state);
  // console.log(state)
});


As you can see, I'm using combineLatest to combine the stream that tracks keystrokes and the stream of generated walls.

So, I'll repeat the problem again. I would like it to
// console.log(state)
output an array of generated walls. If it is, then I can draw it myself.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Demian Smith, 2020-04-02
@search

I didn’t quite understand the problem, but the walls are in the first element of the action array. If you want to pass them to the state, then this can be done something like this

game$.subscribe((action) => {
  switch (action[0]) {
    case 'ArrowUp':
      if(state.y > 0) { state.y--; }
      break;
    case 'ArrowRight':
      if(state.x < gameWidth - 1) { state.x++; }
      break;
    case 'ArrowDown':
      if(state.y < gameHeight - 1) { state.y++; }
      break;
    case 'ArrowLeft':
      if(state.x > 0) { state.x--; }
      break;    
  }
  
  state.walls = action[1];  
  renderGame(state);
  console.log(state)
});

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question