Skip to content

Instantly share code, notes, and snippets.

@Srushtika
Last active June 9, 2020 13:39
Show Gist options
  • Save Srushtika/7f612c1c3c3d6749d80f854f6271a612 to your computer and use it in GitHub Desktop.
Save Srushtika/7f612c1c3c3d6749d80f854f6271a612 to your computer and use it in GitHub Desktop.
Code snippet 8 - For multiplayer space invaders article
const realtime = Ably.Realtime({
key: ABLY_API_KEY,
echoMessages: false,
});
//create a uniqueId to assign to clients on auth
const uniqueId = function () {
return "id-" + totalPlayers + Math.random().toString(36).substr(2, 16);
};
app.use(express.static("js"));
app.get("/auth", (request, response) => {
const tokenParams = { clientId: uniqueId() };
realtime.auth.createTokenRequest(tokenParams, function (err, tokenRequest) {
if (err) {
response
.status(500)
.send("Error requesting token: " + JSON.stringify(err));
} else {
response.setHeader("Content-Type", "application/json");
response.send(JSON.stringify(tokenRequest));
}
});
});
app.get("/", (request, response) => {
response.header("Access-Control-Allow-Origin", "*");
response.header(
"Access-Control-Allow-Headers",
"Origin, X-Requested-With, Content-Type, Accept"
);
if (++peopleAccessingTheWebsite > MIN_PLAYERS_TO_START_GAME) {
response.sendFile(__dirname + "/views/gameRoomFull.html");
} else {
response.sendFile(__dirname + "/views/intro.html");
}
});
app.get("/gameplay", (request, response) => {
response.sendFile(__dirname + "/views/index.html");
});
app.get("/winner", (request, response) => {
response.sendFile(__dirname + "/views/winner.html");
});
app.get("/gameover", (request, response) => {
response.sendFile(__dirname + "/views/gameover.html");
});
const listener = app.listen(process.env.PORT, () => {
console.log("Your app is listening on port " + listener.address().port);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment