I am currently writing a small multiplayer game in nodejs.
When a player joins I want to load them onto the game world at their requested position. It is possible however that this position is occupied, if so I look around for the nearest available free space and load them at that location.
My way of doing this is as follows:
function playerJoin(){
let playerTank = new Tank();
this.findEmptyArea(playerTank, 100, 100).then((result) => {
if (!result.success) {
return;
}
addObjectToWorld(playerTank, result.x, result.y);
}
}
function findEmptyArea(object, x, y){
return new Promise((resolve, reject) => {
// Psuedo code: code iterates over game objects testing for
// collisions . if the requested position is free uses that else
// finds an empty nearby location and returns it
return resolve({success: true, x: freeX, y: freeY});
// fails to find empty location for object
return resolve({ success: false });
}
}
This is not the actual code but a stripped down version to make it clearer. My question is this:
When a user connects via the web socket, the function playerJoin runs. it then creates a new player tank , finds the free area and returns a promise, if it was successful the player tank is added to the world at the position.
Having looked closely at this I have wondered whether this code is flawed. Is it possible that addObjectToWorld is called on a location that is not actually free?
Such as the following:
- player1 connects playerJoin called for player1
- findEmptyArea called within playerJoin for player1
- player 2 connects playerJoin called for player2
- findEmptyArea called within playerJoin for player2
- findEmptyArea promise for player1 finds a free space at 10,10 and returns promise.
findEmptyArea promise for player2 finds a free space at 10,10 and returns promise.
The .then() Promise code block in playerJoin (after findEmptyArea) for player 1 runs, putting the player at 10,10 via addObjectToWorld
- The .then() Promise code block in playerJoin for player 2 runs, putting the player at 10,10 via addObjectToWorld.. and the game crashes
So I guess my question is, when a promise resolves, will the .then code block run immediately which runs addObjectToWorld runs straight away, or will other code potentially run first (such as another player also finding the area free)
Thank you for your help