I have a tic-tac-toe game that sends the moves to all connections and I also have a reset button that resets the game when it is over/won.
The moves work fine, they are seen. However, when the reset button is pressed, it is only seen by the connection that pressed the button, so the function is firing correctly but not emitting to all.
This is my server side code:
var express = require('express');
var app = express();
var http = require('http').Server(app);
var io = require('socket.io')(http);
app.use("/", express.static('public'));
io.on('connection', function(socket){
socket.on('move', function(move){
io.emit('move', move);
});
socket.on('reset', function(reset){
io.emit('reset', reset);
});
});
http.listen(3000, function(){
console.log('listening on *:3000');
});
This is section of my client side code that shows the moves and the button function.
function sendPickSquare(index) {
return function() {
if (gameover || buttons[index].innerHTML !== "")
return;
socket.emit('move', {
'index' : index,
'value' : selectTurn.value
});
};
}
socket.on('move', function(move) {
buttons[move.index].innerHTML = move.value;
if (move.value === 'X') {
selectTurn.value = 'O';
} else {
selectTurn.value = 'X';
}
checkWin();
});
function resetGame() {
for (var i = 0; i < buttons.length; i++) {
buttons[i].style.backgroundColor = '';
buttons[i].innerHTML = "";
}
gameover = false;
}
for (var i = 0; i < buttons.length; i++) {
buttons[i].onclick = sendPickSquare(i);
}
$("#replayButton").click(function(reset) {
socket.emit('reset', resetGame());
});
I am thinking that I might have to make a reference to the function that socket.io sees as an emit to all connections. Any assistance would be very appreciated.
Ok, I figured it out. Here is the answer for those who might run into the same problem. I didn't have to change anything on the server side. On the client side I changed the following:
$('#replayButton').click(function() {
socket.emit('reset', "");
});
socket.on('reset', function() {
resetGame();
});
Basically just needed to emit the button being clicked and then use socket.on to fire the function.