Rxjs-Javascript: How to catch the event of crossing the finish line by a running sprite

294 views
Skip to first unread message

A.B

unread,
Jul 3, 2020, 1:48:14 AM7/3/20
to RxJava

Hi guys,

below is the code of a game: a sprite moving along a straight line by pressing on the left and right keys of the keyboard from position (0,200) to (300,200) I need an observable that catches the event of crossing the finish line by the sprite in position x=300 and y = 200. Thank you so much.

This is my code:


<!DOCTYPE html>
<html>
 <head>
  <meta charset="utf-8"/>
  <title>TP RXJS</title>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/rxjs/6.5.5/rxjs.umd.js">
  </script>
  <style>
#screen{
  position: relative;
  border:1px solid black;
  width:300px;
  height:250px;
  }
  </style>
 </head>
 <body>
 <h1>Cours !  Cours ! Forest ...</h1>
<canvas id="screen" width="400" height="400"/>
  <script>
  var my_image = new Image();
  my_image.src = "http://jeanferdysusini.free.fr/images/png/runner.png";
let screen = document.getElementById('screen');
let ctx = screen.getContext('2d');
 const sprite_width=84
let  coureur = {
  x: 0
, y: 200
, pos:0
, mode:1
, img: new Image()
, draw: function(){

    ctx.clearRect(0, 0, 400, 400);
    switch(coureur.mode){
      case 1:{
        ctx.drawImage(coureur.img, coureur.pos, 0, sprite_width, 100, coureur.x, coureur.y, sprite_width, 100);
        coureur.pos += sprite_width;
        coureur.pos %= sprite_width*6;
    break;
        }
      case 2:{
        ctx.drawImage(this.img, this.pos, 160, sprite_width, 100, this.x, this.y, sprite_width, 100);
        this.pos += sprite_width;
        this.pos %= sprite_width*2;
    break;
        }
      }
    }
  };
coureur.img.src ="http://jeanferdysusini.free.fr/images/png/runner.png";
const code_touches = [
  "ArrowLeft"
, "ArrowRight"
  ];

let musique = new Audio('http://jeanferdysusini.free.fr/FF_vic.mp3');

// Zone à compléter : Javascript/RxJS ici
 

const { filter, first, map, mergeMap, take, tap, windowCount } = rxjs.operators;

// Initial page load event

let onload = rxjs.fromEvent(window, 'load').pipe(
  take(1),
  tap(_ => coureur.draw())
);

onload.subscribe();


// Key Down observable

let keyDown$ = rxjs.fromEvent(document, 'keydown');

// Filtres key down events by code_touches ( left arrow or right arrow )

let clavier = keyDown$.pipe(filter(event => code_touches.includes(event.code)));

let timer_jeu = rxjs.timer(0, 100).pipe(take(5));

let key$ = clavier.pipe(
  mergeMap(event =>
    timer_jeu.pipe(
      tap(_ => coureur.draw()),
      map(_ => event)
    )
  ),
  windowCount(5),
  mergeMap(events$ => events$.pipe(first()))
);

//key$.subscribe(console.log);




let compteur$  = key$.pipe(rxjs.operators.scan((acc, val) => acc+1, 0));

        
        
        
     compteur$.subscribe(y=> coureur.x = coureur.x + y);
     

    
    
   </script>
 </body>
</html>
Reply all
Reply to author
Forward
0 new messages