aboutsummaryrefslogtreecommitdiff
path: root/server.js
diff options
context:
space:
mode:
Diffstat (limited to 'server.js')
-rwxr-xr-xserver.js53
1 files changed, 49 insertions, 4 deletions
diff --git a/server.js b/server.js
index 81df97c..47896e8 100755
--- a/server.js
+++ b/server.js
@@ -9,7 +9,7 @@ const app = express();
const server = http.Server(app);
const io = socketio(server);
-// gameid -> {pl: [socket], started: Bool}
+// gameid -> {pl: [socket]*{1,2}, started: Bool, nextServe: Int, score: [Int, Int]}
const games = new Map();
function genId() {
@@ -74,8 +74,9 @@ io.on("connection", (conn) => {
if (!gameobj || gameobj.pl.length != 2) return;
gameobj.pl[0].emit("status", "");
gameobj.pl[1].emit("status", "");
- gameobj.pl[0].emit("startBall");
- gameobj.pl[1].emit("start");
+ gameobj.pl[0].emit(gameobj.nextServe == 0 ? "startBall" : "start");
+ gameobj.pl[1].emit(gameobj.nextServe == 1 ? "startBall" : "start");
+ gameobj.nextServe = 1 - gameobj.nextServe;
}, 2000);
} else {
console.log(" full");
@@ -89,7 +90,7 @@ io.on("connection", (conn) => {
} else {
console.log(" new");
gameid = id;
- gameobj = {pl: [conn], started: false};
+ gameobj = {pl: [conn], started: false, nextServe: 0, score: [0, 0]};
games.set(gameid, gameobj);
conn.emit("status", "Waiting for other player...");
}
@@ -129,6 +130,50 @@ io.on("connection", (conn) => {
}
}
});
+
+ conn.on("ballvec", (x, y, vx, vy) => {
+ if (!gameobj) return;
+ for (const p of gameobj.pl) {
+ if (p != conn) {
+ p.emit("ballvec", x, y, vx, vy);
+ }
+ }
+ });
+
+ conn.on("ballout", () => {
+ if (!gameobj || gameobj.pl.length != 2) return;
+
+ gameobj.pl[0].emit("stop");
+ gameobj.pl[1].emit("stop");
+ gameobj.pl[0].emit("status", "Ball out!");
+ gameobj.pl[1].emit("status", "Ball out!");
+
+ for (let i = 0; i < gameobj.pl.length; i++) {
+ if (gameobj.pl[i] != conn) {
+ gameobj.score[i]++;
+ }
+ }
+
+ gameobj.pl[0].emit("score", gameobj.score);
+ gameobj.pl[1].emit("score", gameobj.score);
+
+ setTimeout(() => {
+ if (!gameobj || gameobj.pl.length != 2) return;
+ gameobj.pl[0].emit("status", "Get ready...");
+ gameobj.pl[1].emit("status", "Get ready...");
+ gameobj.pl[0].emit("serve", "left", 0.5, 0.5);
+ gameobj.pl[1].emit("serve", "right", 0.5, 0.5);
+
+ setTimeout(() => {
+ if (!gameobj || gameobj.pl.length != 2) return;
+ gameobj.pl[0].emit("status", "");
+ gameobj.pl[1].emit("status", "");
+ gameobj.pl[0].emit(gameobj.nextServe == 0 ? "startBall" : "start");
+ gameobj.pl[1].emit(gameobj.nextServe == 1 ? "startBall" : "start");
+ gameobj.nextServe = 1 - gameobj.nextServe;
+ }, 2000);
+ }, 2000);
+ });
});
server.listen(PORT, () => console.log("Listening on port " + PORT));