Skip to content

Instantly share code, notes, and snippets.

@kmoe
Created October 19, 2017 14:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kmoe/448ea75af49f8820c1ebea4f409495ec to your computer and use it in GitHub Desktop.
Save kmoe/448ea75af49f8820c1ebea4f409495ec to your computer and use it in GitHub Desktop.
var ws = require("nodejs-websocket")
let Game = function() {
this.gameProgress = 1;
this.playerConnections = [];
this.startGame = function() {
this.demandResponse();
};
this.addPlayer = function(connection) {
this.playerConnections.push(connection);
connection.send("WELCOME PLAYER");
if (this.playerConnections.length === 1) {
this.startGame();
}
};
this.demandResponse = function() {
let connection = this.playerConnections[this.gameProgress % this.playerConnections.length];
connection.send("YOUR NUMBER IS UP");
connection.send(this.gameProgress.toString());
};
this.expectedMessage = function() {
if (this.gameProgress % 35 === 0) {
return "barrels & casks";
}
if (this.gameProgress % 7 === 0) {
return "barrels";
}
if (this.gameProgress % 5 === 0) {
return "casks";
}
return this.gameProgress.toString();
}
this.progress = function () {
this.gameProgress += 1;
this.demandResponse();
}
this.nextPlayer = function() {
}
}
let game = new Game();
var server = ws.createServer(function (conn) {
console.log("New connection")
game.addPlayer(conn);
conn.on("text", function (str) {
str = str || "";
console.log("Received "+str)
conn.sendText(str.toUpperCase()+"!!!")
if (str === game.expectedMessage()) {
conn.sendText("You win this time");
} else {
conn.sendText("DRINK!");
}
game.progress();
})
conn.on("close", function (code, reason) {
console.log("Connection closed")
})
}).listen(8001)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment