Last active
June 9, 2020 13:39
Code snippet 8 - For multiplayer space invaders article
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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