Hi everyone
I'm working on a game made with nodejs and mongoose.
This is a MMO game on an hexagonal map.
Each player owns one or more entities which can fight IA entities on the hexagonal map.
Each entity is an entry in my entity collection, whith fields like : life, maxLife, type, minAttack, maxAttack, defense, position ...
So for each fight, I will do that :
- find a target on the same hexa of my fighter
- then I will subtract its life by my fighter attack value
- then set the target flag death if its life is equal or below 0
- then update my entity parameters ( killcount, damagecount )
- then save the target.
So the code is more or less the following :
exports.fight = function( fighter, hexa, callback )
{
var conditions = fighter.type != 'ia' ?
{ 'position.x' : hexa.position.x, 'position.y' : hexa.position.y, '_id' : { $ne: fighter._id }, 'type' : 'ia', 'dead': false } :
{ 'position.x' : hexa.position.x, 'position.y' : hexa.position.y, '_id' : { $ne: fighter._id }, 'type' : { $ne: 'ia' }, 'dead' : false };
EntityModel.find( conditions ).limit( 1 ).exec( function( err, targets ) {
if ( targets.length == 0 )
{
callback( null, fighter);
return;
}
var target = targets[ 0 ];
var oldLife = target.life;
var attack = fighter.minAttack + Math.random() * ( fighter.maxAttack - fighter.minAttack ) - target.def;
attack = attack > 0 ? attack : 0;
target.life = oldLife - attack;
var damageCount = ( target.life > 0 ) ? attack : oldLife;
fighter.damageCount += damageCount;
if ( target.life <= 0 )
{
fighter.killCount ++;
target.remove( function( err ) {
fighter.save( function( err, fighter ) {
callback( null, fighter );
} );
} );
}
else
{
target.save( function( err, target ) {
fighter.save( function( err, fighter ) {
callback( null, fighter );
} );
} );
}
} );
}
My problem is the following :
if two fighters fight the same target at the same time, one of the fights may be skipped because the life value of the target may be read before the end of the first fight, and then the first fight will be skipped.
I've got the same problem if I want to regen an entity; if a fight is done while I'm doing a regen on an entity, the regen or the fight may not be well done.
Maybe an update instead of a save may solve this kind of issue, but sometimes, I'm not sure that i can do all these operations in just one update.
Si, if anyone has some information about solving these kinds of issue, i'm be glad to head about it.
Best regards
Cesar Langlois