I have an entry which looks like the below:
{
"__v": 10,
"_id": "50f8050ed714645500000002",
"sid": "DI7gZ0sprJ",
"lines": [
{
"text": "Well that's what some people say anyway",
"_id": "50f80526d714645500000003",
"user": "Player456"
},
{
"text": "They're people just like the rest of us",
"_id": "50f805925543712caf000005",
"user": "Player123"
},
],
"title": "Test",
"maxlines": 0
}
and have a socket.io script like below:
socket.on('sendchat', function (data) {
Story.findOne({ sid: socket.room }, function(err, story){
if (err) {
console.log(err);
}
else if(story == null) {
console.log(err);
}
else {
io.sockets.in(socket.room).emit('updatechat', socket.username, data);
story.maxlines = story.maxlines - 1;
if (story.maxlines == 0) {
// End Game Script - Redirect to view page
io.sockets.in(socket.room).emit('gameover', slugs(story.title), socket.room);
}
//Save Story to DB
story.lines.push({
user: socket.username,
text: data
});
story.save(function(err, story){
if (err) {
console.log(err);
}
else {
console.log("Story Updated");
}
});
};
});
});
Is there a way I can check to see if socket.username equals the user on the newest line that has been entered?
For example above Player123 is the last one to enter a line, so if Player123 tries again it just emits an error, but if Player456 enters a line, then Player123 is able to again
I'm trying to create a simple turn based game, which checks to make sure a person cannot enter a line when it's not their turn
You can directly check the last entry in the lines array in the story object. As in:
if (story.lines.length &&
story.lines[story.lines.length-1].user === socket.username) {
// error, same user is trying to enter another line
}