2

My intention:

Let's say you have two players, A and B, playing the same flash game embedded in their page but on two different computers.

If player A presses 'W' to jump or hits "PLAY" to jump, player B should see the same movement in their browser.

What I've already tried:

const game = document.getElementById('game');

var e = null;
game.addEventListener('keydown', (event) => {
    if (event.keyCode == 37) {
        console.log('Left was pressed');
    } else if (event.keyCode == 39) {
        console.log('Right was pressed');
    };
    e = event;
});

I've sent this event over to player B (using sockets)

e = // get it from player A
game.dispatchEvent(e)

This doesn't work. I believe that I need some sort of client side selenium thing so that I can simulate real keypresses onto html elements (in my case it's a flash game). However, I've failed to find one.

Is there a way to do what I want?

Lajos Arpad
  • 64,414
  • 37
  • 100
  • 175
Ravi Ghaghada
  • 21
  • 1
  • 2

1 Answers1

1

Basically you can create a new Event('keydown'), see this. On SO you can already see questions about programmatically induce a keyboard event, see this. However, you intend to export an event, send it and import it. You will need to implement an export, as far as I know and an import as well. But, if you manage to export the values you need correctly, then creating an event should not be very difficult.

However, I advise you to separate event handling from the functions which could be triggered by events. It is much wiser than your current approach to refactor your code, so functionalities can be executed without hack-creating an event and then you can just call your functionalities. You will need to communicate between Flash and Javascript for that purpose, see here and, you can also consider using WebSockets for better network protocol, to help in your gaming project.

Lajos Arpad
  • 64,414
  • 37
  • 100
  • 175
  • I read your comment and since then I've been down into a rabbithole with no end. Thanks for your input tho! – Ravi Ghaghada Mar 21 '20 at 18:56
  • @RaviGhaghada you need to persevere. If you do the refactoring and separate your events from the functions to be called inside the events, then you can just call those functions. Communication between Flash and Javascript is nontrivial, but luckily you are not the first programmer having to figure this out, so there is collective experience about this. – Lajos Arpad Mar 21 '20 at 19:21