├── Procfile
├── .gitignore
├── .env-sample
├── public
├── explosion.js
├── invader.svg
├── winner.js
├── gameover.js
├── intro.js
├── style.css
├── script.js
└── space-invaders-hero.svg
├── package.json
├── views
├── gameover.html
├── winner.html
├── gameRoomFull.html
├── index.html
└── intro.html
├── README.md
├── server.js
├── CONTRIBUTING.md
├── server-worker.js
└── LICENSE
/Procfile:
--------------------------------------------------------------------------------
1 | web: node server.js
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | *node_modules
2 | .env
3 | .vscode
--------------------------------------------------------------------------------
/.env-sample:
--------------------------------------------------------------------------------
1 | ABLY_API_KEY={ABLY_API_KEY}
2 | PORT=8080
3 |
--------------------------------------------------------------------------------
/public/explosion.js:
--------------------------------------------------------------------------------
1 | class Explosion extends Phaser.GameObjects.Sprite {
2 | constructor(scene, x, y) {
3 | super(scene, x, y, "explosion");
4 | scene.add.existing(this);
5 | this.play("explode");
6 | }
7 | }
8 |
--------------------------------------------------------------------------------
/public/invader.svg:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
--------------------------------------------------------------------------------
/public/winner.js:
--------------------------------------------------------------------------------
1 | let winner = localStorage.getItem("winner");
2 | let firstRunnerUp = localStorage.getItem("firstRunnerUp");
3 | let secondRunnerUp = localStorage.getItem("secondRunnerUp");
4 | let totalPlayers = localStorage.getItem("totalPlayers");
5 |
6 | document.getElementById("winner-announcement").innerHTML =
7 | winner + " won the game!";
8 |
9 | if (firstRunnerUp) {
10 | document.getElementById("first-runnerup").innerHTML =
11 | firstRunnerUp + " is the first runner up";
12 | }
13 | if (secondRunnerUp) {
14 | document.getElementById("second-runnerup").innerHTML =
15 | secondRunnerUp + " is the second runner up";
16 | }
17 |
--------------------------------------------------------------------------------
/public/gameover.js:
--------------------------------------------------------------------------------
1 | let winner = localStorage.getItem("winner");
2 | let firstRunnerUp = localStorage.getItem("firstRunnerUp");
3 | let secondRunnerUp = localStorage.getItem("secondRunnerUp");
4 | let totalPlayers = localStorage.getItem("totalPlayers");
5 |
6 | document.getElementById("winner-announcement").innerHTML =
7 | winner + " won the game!";
8 |
9 | if (firstRunnerUp) {
10 | document.getElementById("first-runnerup").innerHTML =
11 | firstRunnerUp + " got the highest score";
12 | }
13 | if (secondRunnerUp) {
14 | document.getElementById("second-runnerup").innerHTML =
15 | secondRunnerUp + " got the next highest score";
16 | }
17 |
--------------------------------------------------------------------------------
/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "//1": "describes your app and its dependencies",
3 | "//2": "https://docs.npmjs.com/files/package.json",
4 | "//3": "updating this file will download and update your packages",
5 | "name": "hello-express",
6 | "version": "0.0.1",
7 | "description": "A simple Node app built on Express, instantly up and running.",
8 | "main": "server.js",
9 | "scripts": {
10 | "start": "node server.js"
11 | },
12 | "dependencies": {
13 | "ably": "^1.1.25",
14 | "dotenv": "^8.2.0",
15 | "express": "^4.17.1",
16 | "p2": "^0.7.1"
17 | },
18 | "engines": {
19 | "node": "12.x"
20 | },
21 | "repository": {
22 | "url": "https://glitch.com/edit/#!/hello-express"
23 | },
24 | "license": "MIT",
25 | "keywords": [
26 | "node",
27 | "glitch",
28 | "express"
29 | ]
30 | }
31 |
--------------------------------------------------------------------------------
/public/intro.js:
--------------------------------------------------------------------------------
1 | let nickname = "";
2 | let roomCode = "";
3 |
4 | function hostNewGame() {
5 | localStorage.clear();
6 | let nicknameInput = document.getElementById("create-nickname");
7 | nickname = nicknameInput.value;
8 | roomCode = getRandomRoomId();
9 | localStorage.setItem("isHost", true);
10 | localStorage.setItem("nickname", nickname);
11 | localStorage.setItem("roomCode", roomCode);
12 | window.location.replace("/gameplay?roomCode=" + roomCode + "&isHost=true");
13 | }
14 |
15 | function joinRoom() {
16 | localStorage.clear();
17 | let nicknameInput = document.getElementById("join-nickname");
18 | nickname = nicknameInput.value;
19 | roomCode = document.getElementById("join-room-code").value;
20 | localStorage.setItem("isHost", false);
21 | localStorage.setItem("nickname", nickname);
22 | localStorage.setItem("roomCode", roomCode);
23 | window.location.replace("/gameplay?roomCode=" + roomCode + "&isHost=false");
24 | }
25 |
26 | function getRandomRoomId() {
27 | return "room-" + Math.random().toString(36).substr(2, 8);
28 | }
29 |
--------------------------------------------------------------------------------
/views/gameover.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | Space Invaders
6 |
7 |
8 |
9 |
14 |
15 |
16 |
17 |
18 |
19 |
20 | Game over
21 |
24 |
28 |
29 |
30 |
31 |
--------------------------------------------------------------------------------
/views/winner.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | Space Invaders
6 |
7 |
8 |
9 |
14 |
15 |
16 |
17 |
18 |
19 |
20 | The game has ended
21 |
24 |
28 |
29 |
30 |
31 |
--------------------------------------------------------------------------------
/views/gameRoomFull.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | Space Invaders
6 |
7 |
8 |
9 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 | Sorry, the game room you are trying to join is either full or doesn't exist.
24 |
25 |
26 |
28 |
29 |
30 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | 
2 |
3 | # Realtime multiplayer game of Space Invaders
4 |
5 | This project runs a realtime multiplayer version of the classic retro game, Space Invaders.
6 |
7 | 
8 |
9 | ## Services/ libraries used in the game
10 |
11 | - [Phaser 3](https://phaser.io)
12 | - [p2 NPM library](https://www.npmjs.com/package/p2)
13 | - [Ably Realtime](https://www.ably.com)
14 |
15 | You will require an Ably API Key, to run this demo, [sign-up for FREE account](https://ably.com/sign-up)
16 |
17 | # How to run this game
18 |
19 | 1. Create a free account with [Ably Realtime](https://www.ably.com) and obtain an API Key
20 | 1. Clone this repo locally
21 | 1. Navigate to the project folder and run `npm install` to install the dependencies
22 | 1. Rename `.env-sample` to `.env`, then edit the file and add your Ably API key and prefered PORT (default 8080).
23 | 1. (Optional) You can update the `MIN_PLAYERS_TO_START_GAME` to enforce a minimum number of players. (see `server-worker.js`)
24 | 1. Run the server with `node server.js` and then open a brower to [localhost:8080](http://localhost:8080)
25 |
26 | Read the full blog post series on [dev.to](https://dev.to/ably/building-a-realtime-multiplayer-browser-game-in-less-than-a-day-part-1-4-14pm).
27 |
28 | Please [reach out to me on Twitter](https://www.twitter.com/Srushtika) for any questions,
29 | or follow us [@ablyrealtime](https://twitter.com/ablyrealtime)
30 |
--------------------------------------------------------------------------------
/views/index.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | Space Invaders
6 |
7 |
8 |
9 |
14 |
18 |
19 |
20 |
21 |
25 |
26 |
27 |
28 |
29 |
30 |
31 |
32 |
33 |
x
34 |
39 |
40 |
46 | Copy game link
47 |
48 |
49 |
50 |
51 |
52 |
Score: 0
53 |
Game room 0
54 |
55 |
56 |
57 | Audio
58 |
59 |
60 |
61 |
62 |
63 |
64 |
67 |
68 |
73 | Start game
74 |
75 |
76 |
77 |
78 |
79 |
--------------------------------------------------------------------------------
/server.js:
--------------------------------------------------------------------------------
1 | const {
2 | Worker,
3 | isMainThread,
4 | parentPort,
5 | workerData,
6 | threadId,
7 | MessageChannel,
8 | } = require("worker_threads");
9 |
10 | const envConfig = require("dotenv").config();
11 | const express = require("express");
12 | const Ably = require("ably");
13 | const p2 = require("p2");
14 | const app = express();
15 | const {ABLY_API_KEY, PORT} = process.env;
16 |
17 | console.log("Environment variables", envConfig)
18 |
19 | const globalGameName = "main-game-thread";
20 | const GAME_ROOM_CAPACITY = 6;
21 | let globalChannel;
22 | let activeGameRooms = {};
23 |
24 | // instantiate to Ably
25 | const realtime = new Ably.Realtime({
26 | key: ABLY_API_KEY,
27 | echoMessages: false,
28 | });
29 |
30 | // create a uniqueId to assign to clients on auth
31 | const uniqueId = function () {
32 | return "id-" + Math.random().toString(36).substr(2, 16);
33 | };
34 |
35 | app.use(express.static("public"));
36 |
37 | app.get("/auth", (request, response) => {
38 | const tokenParams = { clientId: uniqueId() };
39 | realtime.auth.createTokenRequest(tokenParams, function (err, tokenRequest) {
40 | if (err) {
41 | response
42 | .status(500)
43 | .send("Error requesting token: " + JSON.stringify(err));
44 | } else {
45 | response.setHeader("Content-Type", "application/json");
46 | response.send(JSON.stringify(tokenRequest));
47 | }
48 | });
49 | });
50 |
51 | app.get("/", (request, response) => {
52 | response.header("Access-Control-Allow-Origin", "*");
53 | response.header(
54 | "Access-Control-Allow-Headers",
55 | "Origin, X-Requested-With, Content-Type, Accept"
56 | );
57 | response.sendFile(__dirname + "/views/intro.html");
58 | });
59 |
60 | app.get("/gameplay", (request, response) => {
61 | let requestedRoom = request.query.roomCode;
62 | let isReqHost = request.query.isHost == "true";
63 | if (!isReqHost && activeGameRooms[requestedRoom]) {
64 | if (
65 | activeGameRooms[requestedRoom].totalPlayers + 1 <= GAME_ROOM_CAPACITY &&
66 | !activeGameRooms[requestedRoom].gameOn
67 | ) {
68 | response.sendFile(__dirname + "/views/index.html");
69 | } else {
70 | console.log("here");
71 | response.sendFile(__dirname + "/views/gameRoomFull.html");
72 | }
73 | } else if (isReqHost) {
74 | response.sendFile(__dirname + "/views/index.html");
75 | } else {
76 | response.sendFile(__dirname + "/views/gameRoomFull.html");
77 | }
78 | console.log(JSON.stringify(activeGameRooms));
79 | });
80 |
81 | app.get("/winner", (request, response) => {
82 | response.sendFile(__dirname + "/views/winner.html");
83 | });
84 |
85 | app.get("/gameover", (request, response) => {
86 | response.sendFile(__dirname + "/views/gameover.html");
87 | });
88 |
89 | const listener = app.listen(PORT, () => {
90 | console.log("Your app is listening on port " + listener.address().port);
91 | });
92 |
93 | // wait until connection with Ably is established
94 | realtime.connection.once("connected", () => {
95 | globalChannel = realtime.channels.get(globalGameName);
96 | // subscribe to new players entering the game
97 | globalChannel.presence.subscribe("enter", (player) => {
98 | generateNewGameThread(
99 | player.data.isHost,
100 | player.data.nickname,
101 | player.data.roomCode,
102 | player.clientId
103 | );
104 | });
105 | });
106 |
107 | function generateNewGameThread(
108 | isHost,
109 | hostNickname,
110 | hostRoomCode,
111 | hostClientId
112 | ) {
113 | if (isHost && isMainThread) {
114 | const worker = new Worker("./server-worker.js", {
115 | workerData: {
116 | hostNickname: hostNickname,
117 | hostRoomCode: hostRoomCode,
118 | hostClientId: hostClientId,
119 | },
120 | });
121 | console.log(`CREATING NEW THREAD WITH ID ${threadId}`);
122 | worker.on("error", (error) => {
123 | console.log(`WORKER EXITED DUE TO AN ERROR ${error}`);
124 | });
125 | worker.on("message", (msg) => {
126 | if (msg.roomName && !msg.resetEntry) {
127 | activeGameRooms[msg.roomName] = {
128 | roomName: msg.roomName,
129 | totalPlayers: msg.totalPlayers,
130 | gameOn: msg.gameOn,
131 | };
132 | } else if (msg.roomName && msg.resetEntry) {
133 | delete activeGameRooms[msg.roomName];
134 | }
135 | });
136 | worker.on("exit", (code) => {
137 | console.log(`WORKER EXITED WITH THREAD ID ${threadId}`);
138 | if (code !== 0) {
139 | console.log(`WORKER EXITED DUE TO AN ERROR WITH CODE ${code}`);
140 | }
141 | });
142 | }
143 | }
144 |
--------------------------------------------------------------------------------
/CONTRIBUTING.md:
--------------------------------------------------------------------------------
1 | Hi there, welcome to contributing guidelines for this project.
2 |
3 | ### What do I need to know to help?
4 |
5 | If you are interested in making a code contribution and would like to learn more about the technologies that this projects use, check out the list below.
6 |
7 | - [JavaScript](https://www.javascript.com/)
8 | - [NodeJS](https://nodejs.org/en/)
9 | - [Phaser3](https://phaser.io/)
10 | - [Ably Realtime](https://www.ably.io)
11 | - [p2 physics engine](https://www.npmjs.com/package/p2)
12 |
13 | A very detailed tutorial for this project is available on [Dev.to](https://dev.to/ablydev/building-a-realtime-multiplayer-browser-game-in-less-than-a-day-part-1-4-14pm)
14 |
15 | ### How do I make a contribution?
16 |
17 | 1. Find an issue tagged that you are interested in addressing or a feature that you would like to add.
18 |
19 | 2. Fork the repository associated with the issue to your local GitHub organization. This means that you will have a copy of the repository under your-GitHub-username/repository-name.
20 |
21 | 3. Clone the repository to your local machine using git clone https://github.com/github-username/repository-name.git.
22 | 4. Create a new branch for your fix using git checkout -b .
23 | 5. Make the appropriate changes for the issue you are trying to address or the feature that you want to add.
24 | 6. Use git add to add the file contents of the changed files to the "snapshot" git uses to manage the state of the project, also known as the index.
25 |
26 | 7. Use git commit -m "Insert a short message of the changes made here" to store the contents of the index with a descriptive message.
27 | 8. Push the changes to the remote repository using git push origin branch-name-here.
28 | 9. Submit a pull request to the upstream repository.
29 | 10. Title the pull request with a short description of the changes made and the issue or bug number associated with your change. For example, you can title an issue like so "Added volume control feature to address #4352".
30 | 11. In the description of the pull request, explain the changes that you made, any issues you think exist with the pull request you made, and any questions you have for the maintainer. It's OK if your pull request is not perfect (no pull request is), the reviewer will be able to help you fix any problems and improve it!
31 | 12. Wait for the pull request to be reviewed by a maintainer.
32 | 13. Make changes to the pull request if the reviewing maintainer recommends them.
33 | 14. Celebrate your success after your pull request is merged!
34 |
35 | ### Where can I go for help?
36 |
37 | If you need help, you can reach out to [Srushtika](https://twitter.com/Srushtika) on Twitter or open a support ticket at support@ably.com
38 |
39 | ## Any contributions you make will be under the MIT Software License
40 |
41 | In short, when you submit code changes, your submissions are understood to be under the same [MIT License](http://choosealicense.com/licenses/mit/) that covers the project. Feel free to contact the maintainers if that's a concern.
42 |
43 | ## Report bugs using Github's [issues](https://github.com/ably/depict-it/issues)
44 |
45 | We use GitHub issues to track public bugs. Report a bug by [opening a new issue](); it's that easy!
46 |
47 | ### Write bug reports with detail, background, and sample code
48 |
49 | **Great Bug Reports** tend to have:
50 |
51 | - A quick summary and/or background
52 | - Steps to reproduce
53 | - Be specific!
54 | - Give sample code if you can. [My stackoverflow question](http://stackoverflow.com/q/12488905/180626) includes sample code that _anyone_ with a base R setup can run to reproduce what I was seeing
55 | - What you expected would happen
56 | - What actually happens
57 | - Notes (possibly including why you think this might be happening, or stuff you tried that didn't work)
58 |
59 | We _love_ thorough bug reports! 💖
60 |
61 | ### License
62 |
63 | By contributing, you agree that your contributions will be licensed under its MIT License.
64 |
65 | ### Code of Conduct
66 |
67 | Our Code of Conduct means that you are responsible for treating everyone on the project with respect and courtesy regardless of their identity.
68 |
69 | If you are the victim of any inappropriate behavior or comments as described in our Code of Conduct, we are here for you and will do the best to ensure that the abuser is reprimanded appropriately. Please reach out to [Srushtika](https://twitter.com/Srushtika) in case of any concerns.
70 |
71 | ## References
72 |
73 | This document was adapted from the open-source contribution guidelines for [Facebook's Draft](https://github.com/facebook/draft-js/blob/a9316a723f9e918afde44dea68b5f9f39b7d9b00/CONTRIBUTING.md) and [Safia Abdalla's article](https://opensource.com/life/16/3/contributor-guidelines-template-and-tips) on OpenSource.com
74 |
--------------------------------------------------------------------------------
/views/intro.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | Space Invaders
6 |
7 |
8 |
9 |
14 |
20 |
24 |
25 |
26 |
27 |
28 |
29 |
30 |
31 | Use the arrow keys on your keyboard to move your avatar left or right to
32 | escape the bullets from the spaceship. Your goal is to make it to the
33 | other side, alive!
34 |
35 |
36 |
126 |
127 |
128 |
133 |
134 |
139 |
144 |
149 |
150 |
151 |
152 |
--------------------------------------------------------------------------------
/public/style.css:
--------------------------------------------------------------------------------
1 | body {
2 | margin: 0;
3 | padding: 10px;
4 | }
5 |
6 | * {
7 | box-sizing: border-box;
8 | }
9 |
10 | input {
11 | height: 40px;
12 | display: block;
13 | margin: 0;
14 | padding: 5px 10px;
15 | border: 0;
16 | border-right: 1px solid silver;
17 | border-radius: 0;
18 | font-size: 16px;
19 | }
20 |
21 | .intro-body {
22 | font-family: "VT323";
23 | font-size: 22px;
24 | text-align: center;
25 | color: #fff;
26 | background-color: black;
27 | background-image: url("https://cdn.glitch.com/f66772e3-bbf6-4f6d-b5d5-94559e3c1c6f%2FScreenshot%202020-05-19%20at%2013.36.26.png?v=1589892011044");
28 | }
29 |
30 | .intro-img {
31 | width: 80%;
32 | max-width: 800px;
33 | }
34 |
35 | .room-full-body {
36 | font-family: "VT323";
37 | font-size: 52px;
38 | text-align: center;
39 | color: #fff;
40 | background-color: black;
41 | background-image: url("https://cdn.glitch.com/f66772e3-bbf6-4f6d-b5d5-94559e3c1c6f%2FScreenshot%202020-05-19%20at%2013.36.26.png?v=1589892011044");
42 | }
43 |
44 | .index-body {
45 | font-family: "VT323";
46 | font-size: 22px;
47 | color: #fff;
48 | background-color: black;
49 | }
50 |
51 | .game-text {
52 | max-width: 700px;
53 | margin-left: auto;
54 | margin-right: auto;
55 | }
56 |
57 | .game-instructions {
58 | width: 80%;
59 | margin: 20px auto;
60 | padding-top: 20px;
61 | font-size: 30px;
62 | }
63 |
64 | .create-room {
65 | width: 60%;
66 | margin: 0 auto;
67 | padding: 10px 0;
68 | text-align: center;
69 | display: inline-block;
70 | }
71 |
72 | .button-center {
73 | display: inline-block;
74 | }
75 |
76 | .text-center {
77 | text-align: center;
78 | }
79 |
80 | .room-input {
81 | display: flex;
82 | justify-content: center;
83 | align-items: center;
84 | width: 70%;
85 | margin: 0 auto;
86 | padding: 10px 0;
87 | }
88 |
89 | .nickname {
90 | width: 30%;
91 | min-width: 300px;
92 | margin: 30px auto 10px;
93 | text-align: center;
94 | }
95 |
96 | #score {
97 | width: 100px;
98 | margin-right: 10px;
99 | }
100 |
101 | #room-code {
102 | width: 480px;
103 | }
104 |
105 | #deaths {
106 | margin-left: auto;
107 | text-align: right;
108 | }
109 |
110 | .game-area {
111 | display: flex;
112 | justify-content: space-between;
113 | }
114 |
115 | .game-div {
116 | margin: 20px;
117 | max-width: 1200px;
118 | text-align: center;
119 | }
120 |
121 | .game-div-container {
122 | text-align: center;
123 | display: block;
124 | }
125 |
126 | .game-headline-left {
127 | float: left;
128 | }
129 |
130 | .game-headline-right {
131 | float: right;
132 | }
133 |
134 | .winner-body {
135 | font-family: "VT323";
136 | font-size: 62px;
137 | text-align: center;
138 | color: #fff;
139 | background-color: black;
140 | background-image: url("https://cdn.glitch.com/f66772e3-bbf6-4f6d-b5d5-94559e3c1c6f%2FScreenshot%202020-05-19%20at%2013.36.26.png?v=1589892011044");
141 | }
142 |
143 | .winner-div {
144 | width: 80%;
145 | margin: 0 auto;
146 | padding-top: 20px;
147 | font-size: 82px;
148 | }
149 |
150 | .winner-text {
151 | text-transform: uppercase;
152 | }
153 |
154 | .runner-ups-div {
155 | width: 80%;
156 | margin: 0 auto;
157 | padding-top: 20px;
158 | font-size: 42px;
159 | }
160 |
161 | .bg-modal {
162 | display: none;
163 | position: absolute;
164 | top: 0;
165 | justify-content: center;
166 | align-items: center;
167 | width: 100%;
168 | height: 100%;
169 | color: #fff;
170 | background-color: rgba(0, 0, 0, 0.7);
171 | }
172 |
173 | .modal-content {
174 | position: relative;
175 | width: 500px;
176 | height: 300px;
177 | padding: 20px;
178 | border: 5px solid white;
179 | border-radius: 4px;
180 | text-align: center;
181 | }
182 |
183 | .button {
184 | display: inline-block;
185 | margin-top: 10px;
186 | padding: 10px 28px;
187 | border: 2px solid white;
188 | border-radius: 10px;
189 | text-decoration: none;
190 | font-size: 16px;
191 | font-family: "VT323";
192 | color: white;
193 | background-color: #000;
194 | }
195 |
196 | .button:hover {
197 | border: 2px solid black;
198 | color: #000;
199 | background-color: white;
200 | }
201 |
202 | .button:active {
203 | border: 2px solid black;
204 | color: #000;
205 | background-color: white;
206 | }
207 |
208 | label {
209 | display: block;
210 | margin: 15px auto;
211 | }
212 |
213 | .close {
214 | position: absolute;
215 | top: 0;
216 | right: 14px;
217 | font-size: 42px;
218 | cursor: pointer;
219 | }
220 |
221 | .text-group {
222 | border: none;
223 | color: white;
224 | background-color: black;
225 | }
226 |
227 | .input-button {
228 | flex-shrink: 0;
229 | width: max-content;
230 | height: 40px;
231 | padding: 0 20px;
232 | border: 0;
233 | color: var(--gray);
234 | font-weight: 400;
235 | font-size: 1rem;
236 | text-transform: uppercase;
237 | }
238 |
239 | .input-button:hover {
240 | color: white;
241 | background-color: var(--gray);
242 | }
243 |
244 | .room-input-text {
245 | margin: 0 10px;
246 | }
247 |
248 | .room-code {
249 | min-width: 300px;
250 | }
251 |
252 | .img-invaders {
253 | width: 60%;
254 | }
255 |
256 | .copy {
257 | width: 60px;
258 | height: 60px;
259 | }
260 |
261 | .audio-control {
262 | display: flex;
263 | width: 100px;
264 | margin-right: 10px;
265 | }
266 |
267 | .audio-label {
268 | margin: 0 15px;
269 | }
270 |
271 | .audio-chkbox {
272 | padding: 0;
273 | height: 25px;
274 | }
275 |
276 | /*======================*/
277 |
278 | .game-card {
279 | margin: 10px 50px;
280 | padding: 50px;
281 | background-image: url("https://user-images.githubusercontent.com/5900152/90127067-85382380-dd5c-11ea-87b1-4946c0df92d8.jpg");
282 | }
283 |
284 | .info-bar {
285 | display: flex;
286 | padding: 10px 50px;
287 | justify-content: space-evenly;
288 | }
289 |
290 | .start-btn-div {
291 | text-align: center;
292 | font-family: inherit;
293 | }
294 |
295 | .start-info-card {
296 | width: 50%;
297 | margin: 20px;
298 | }
299 |
300 | .nav-tabs {
301 | justify-content: center;
302 | }
303 |
304 | .input-box {
305 | text-align: center;
306 | }
307 |
308 | .create-wait-msg {
309 | display: none;
310 |
311 | }
--------------------------------------------------------------------------------
/server-worker.js:
--------------------------------------------------------------------------------
1 | const {
2 | Worker,
3 | isMainThread,
4 | parentPort,
5 | threadId,
6 | workerData,
7 | } = require("worker_threads");
8 | const envConfig = require("dotenv").config();
9 | const Ably = require("ably");
10 | const p2 = require("p2");
11 |
12 | const ABLY_API_KEY = process.env.ABLY_API_KEY;
13 |
14 | const CANVAS_HEIGHT = 700;
15 | const CANVAS_WIDTH = 1400;
16 | const SHIP_PLATFORM = CANVAS_HEIGHT - 12;
17 | const BULLET_PLATFORM = SHIP_PLATFORM - 32;
18 | const PLAYER_VERTICAL_INCREMENT = 20;
19 | const PLAYER_VERTICAL_MOVEMENT_UPDATE_INTERVAL = 1000;
20 | const PLAYER_SCORE_INCREMENT = 5;
21 | const P2_WORLD_TIME_STEP = 1 / 16;
22 | const MIN_PLAYERS_TO_START_GAME = 6;
23 | const GAME_TICKER_MS = 100;
24 |
25 | let players = {};
26 | let playerChannels = {};
27 | let shipX = between(20, CANVAS_WIDTH - 20);
28 | let shipY = SHIP_PLATFORM;
29 | let colorIndex = 0;
30 | let avatarTypes = ["A", "B", "C"];
31 | let gameOn = false;
32 | let alivePlayers = 0;
33 | let totalPlayers = 0;
34 | let gameRoomName = workerData.hostRoomCode + ":primary";
35 | let roomCode = workerData.hostRoomCode;
36 | let hostClientId = workerData.hostClientId;
37 | let hostNickname = workerData.hostNickname;
38 | let gameRoom;
39 | let gameTickerOn = false;
40 | let bulletTimer = 0;
41 | let shipBody;
42 | let world;
43 | let shipVelocityTimer = 0;
44 | let killerBulletId = "";
45 | let copyOfShipBody = {
46 | position: "",
47 | velocity: "",
48 | };
49 |
50 | // instantiate to Ably
51 | const realtime = new Ably.Realtime({
52 | key: ABLY_API_KEY,
53 | echoMessages: false,
54 | });
55 |
56 | // wait until connection with Ably is established
57 | realtime.connection.once("connected", () => {
58 | gameRoom = realtime.channels.get(gameRoomName);
59 |
60 | // subscribe to new players entering the game
61 | gameRoom.presence.subscribe("enter", (player) => {
62 | console.log("new player");
63 | let newPlayerId;
64 | alivePlayers++;
65 | totalPlayers++;
66 | parentPort.postMessage({
67 | roomName: roomCode,
68 | totalPlayers: totalPlayers,
69 | gameOn: gameOn,
70 | });
71 | newPlayerId = player.clientId;
72 | playerChannels[newPlayerId] = realtime.channels.get(
73 | workerData.hostRoomCode + ":clientChannel-" + player.clientId
74 | );
75 | if (++colorIndex == 6) {
76 | colorIndex = 0;
77 | }
78 | if (totalPlayers == 1) {
79 | gameTickerOn = true;
80 | startGameDataTicker();
81 | }
82 | newPlayerObject = {
83 | id: newPlayerId,
84 | invaderAvatarType: avatarTypes[between(0, 3)],
85 | invaderAvatarColor: randomColorGenerator(),
86 | x: playerXposition(colorIndex),
87 | y: 20,
88 | score: 0,
89 | nickname: player.data.nickname,
90 | isAlive: true,
91 | };
92 | players[newPlayerId] = newPlayerObject;
93 | subscribeToPlayerInput(playerChannels[newPlayerId], newPlayerId);
94 | });
95 |
96 | // subscribe to players leaving the game
97 | gameRoom.presence.subscribe("leave", (player) => {
98 | let leavingPlayer = player.clientId;
99 | alivePlayers--;
100 | totalPlayers--;
101 | parentPort.postMessage({
102 | roomName: roomCode,
103 | totalPlayers: totalPlayers,
104 | });
105 | delete players[leavingPlayer];
106 | if (totalPlayers <= 0) {
107 | killWorkerThread();
108 | }
109 | });
110 | gameRoom.publish("thread-ready", {
111 | start: true,
112 | });
113 | });
114 |
115 | // start the ship and bullets
116 | function startShipAndBullets() {
117 | gameOn = true;
118 |
119 | world = new p2.World({
120 | gravity: [0, -9.82],
121 | });
122 | shipBody = new p2.Body({
123 | position: [shipX, shipY],
124 | velocity: [calcRandomVelocity(), 0],
125 | });
126 | world.addBody(shipBody);
127 | startMovingPhysicsWorld();
128 |
129 | for (let playerId in players) {
130 | startDownwardMovement(playerId);
131 | }
132 | }
133 |
134 | // start the game tick
135 | function startGameDataTicker() {
136 | let tickInterval = setInterval(() => {
137 | if (!gameTickerOn) {
138 | clearInterval(tickInterval);
139 | } else {
140 | bulletOrBlank = "";
141 | bulletTimer += GAME_TICKER_MS;
142 | if (bulletTimer >= GAME_TICKER_MS * 5) {
143 | bulletTimer = 0;
144 | bulletOrBlank = {
145 | y: BULLET_PLATFORM,
146 | id: "bulletId-" + generateRandomId(),
147 | };
148 | }
149 | if (shipBody) {
150 | copyOfShipBody = shipBody;
151 | }
152 |
153 | // fan out the latest game state
154 | gameRoom.publish("game-state", {
155 | players: players,
156 | playerCount: totalPlayers,
157 | shipBody: copyOfShipBody.position,
158 | bulletOrBlank: bulletOrBlank,
159 | gameOn: gameOn,
160 | killerBullet: killerBulletId,
161 | });
162 | }
163 | }, GAME_TICKER_MS);
164 | }
165 |
166 | // subscribe to each player's input events
167 | function subscribeToPlayerInput(channelInstance, playerId) {
168 | channelInstance.subscribe("pos", (msg) => {
169 | if (msg.data.keyPressed == "left") {
170 | if (players[playerId].x - 20 < 20) {
171 | players[playerId].x = 25;
172 | } else {
173 | players[playerId].x -= 20;
174 | }
175 | } else if (msg.data.keyPressed == "right") {
176 | if (players[playerId].x + 20 > 1380) {
177 | players[playerId].x = 1375;
178 | } else {
179 | players[playerId].x += 20;
180 | }
181 | }
182 | });
183 | channelInstance.subscribe("start-game", (msg) => {
184 | startShipAndBullets();
185 | });
186 |
187 | // subscribe to players being shot
188 | channelInstance.subscribe("dead-notif", (msg) => {
189 | players[msg.data.deadPlayerId].isAlive = false;
190 | killerBulletId = msg.data.killerBulletId;
191 | alivePlayers--;
192 | if (alivePlayers == 0) {
193 | setTimeout(() => {
194 | finishGame("");
195 | }, 1000);
196 | }
197 | });
198 | }
199 |
200 | // update the y position of each player when the game starts
201 | function startDownwardMovement(playerId) {
202 | let interval = setInterval(() => {
203 | if (players[playerId] && players[playerId].isAlive) {
204 | players[playerId].y += PLAYER_VERTICAL_INCREMENT;
205 | players[playerId].score += PLAYER_SCORE_INCREMENT;
206 |
207 | if (players[playerId].y > SHIP_PLATFORM) {
208 | finishGame(playerId);
209 | clearInterval(interval);
210 | }
211 | } else {
212 | clearInterval(interval);
213 | }
214 | }, PLAYER_VERTICAL_MOVEMENT_UPDATE_INTERVAL);
215 | }
216 |
217 | // finish the game
218 | function finishGame(playerId) {
219 | console.log("finished");
220 | let firstRunnerUpName = "";
221 | let secondRunnerUpName = "";
222 | let winnerName = "Nobody";
223 | let leftoverPlayers = new Array();
224 | for (let item in players) {
225 | leftoverPlayers.push({
226 | nickname: players[item].nickname,
227 | score: players[item].score,
228 | });
229 | }
230 |
231 | leftoverPlayers.sort((a, b) => {
232 | return b.score - a.score;
233 | });
234 | if (playerId == "") {
235 | if (leftoverPlayers.length >= 3) {
236 | firstRunnerUpName = leftoverPlayers[0].nickname;
237 | secondRunnerUpName = leftoverPlayers[1].nickname;
238 | } else if (leftoverPlayers == 2) {
239 | firstRunnerUp = leftoverPlayers[0].nickname;
240 | }
241 | } else {
242 | winnerName = players[playerId].nickname;
243 | if (leftoverPlayers.length >= 3) {
244 | firstRunnerUpName = leftoverPlayers[1].nickname;
245 | secondRunnerUpName = leftoverPlayers[2].nickname;
246 | } else if (leftoverPlayers.length == 2) {
247 | firstRunnerUpName = leftoverPlayers[1].nickname;
248 | }
249 | }
250 |
251 | // fan out leaderboard info when the game has finished
252 | gameRoom.publish("game-over", {
253 | winner: winnerName,
254 | firstRunnerUp: firstRunnerUpName,
255 | secondRunnerUp: secondRunnerUpName,
256 | totalPlayers: totalPlayers,
257 | });
258 |
259 | killWorkerThread();
260 | }
261 |
262 | // reset all variables in the server
263 | function killWorkerThread() {
264 | parentPort.postMessage({
265 | resetEntry: true,
266 | roomName: roomCode,
267 | });
268 | for (let item in playerChannels) {
269 | playerChannels[item].detach();
270 | }
271 | process.exit(0);
272 | }
273 |
274 | // assign player position per color to form pride rainbow
275 | function playerXposition(index) {
276 | switch (index) {
277 | case 0:
278 | return between(22, 246);
279 | case 1:
280 | return between(247, 474);
281 | case 2:
282 | return between(475, 702);
283 | case 3:
284 | return between(703, 930);
285 | case 4:
286 | return between(931, 1158);
287 | case 5:
288 | return between(1159, 1378);
289 | default:
290 | return between(22, 246);
291 | }
292 | }
293 |
294 | function between(min, max) {
295 | return Math.floor(Math.random() * (max - min) + min);
296 | }
297 |
298 | function generateRandomId() {
299 | return Math.random().toString(36).substr(2, 8);
300 | }
301 |
302 | // start the server-side physics world
303 | function startMovingPhysicsWorld() {
304 | let p2WorldInterval = setInterval(function () {
305 | if (!gameOn) {
306 | clearInterval(p2WorldInterval);
307 | } else {
308 | // updates velocity every 5 seconds
309 | if (++shipVelocityTimer >= 80) {
310 | shipVelocityTimer = 0;
311 | shipBody.velocity[0] = calcRandomVelocity();
312 | }
313 | world.step(P2_WORLD_TIME_STEP);
314 | if (shipBody.position[0] > 1400 && shipBody.velocity[0] > 0) {
315 | shipBody.position[0] = 0;
316 | } else if (shipBody.position[0] < 0 && shipBody.velocity[0] < 0) {
317 | shipBody.position[0] = 1400;
318 | }
319 | }
320 | }, 1000 * P2_WORLD_TIME_STEP);
321 | }
322 |
323 | // calculate a random horizontal velocity for the ship
324 | function calcRandomVelocity() {
325 | let randomShipXVelocity = between(20, 200);
326 | randomShipXVelocity *= Math.floor(Math.random() * 2) == 1 ? 1 : -1;
327 | return randomShipXVelocity;
328 | }
329 |
330 | // method to randomly generate a color for the player
331 | function randomColorGenerator() {
332 | const randomColor = "000000".replace(/0/g, function () {
333 | return (~~(Math.random() * 16)).toString(16);
334 | });
335 | return "0x" + randomColor;
336 | }
337 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | Apache License
2 | Version 2.0, January 2004
3 | http://www.apache.org/licenses/
4 |
5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6 |
7 | 1. Definitions.
8 |
9 | "License" shall mean the terms and conditions for use, reproduction,
10 | and distribution as defined by Sections 1 through 9 of this document.
11 |
12 | "Licensor" shall mean the copyright owner or entity authorized by
13 | the copyright owner that is granting the License.
14 |
15 | "Legal Entity" shall mean the union of the acting entity and all
16 | other entities that control, are controlled by, or are under common
17 | control with that entity. For the purposes of this definition,
18 | "control" means (i) the power, direct or indirect, to cause the
19 | direction or management of such entity, whether by contract or
20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the
21 | outstanding shares, or (iii) beneficial ownership of such entity.
22 |
23 | "You" (or "Your") shall mean an individual or Legal Entity
24 | exercising permissions granted by this License.
25 |
26 | "Source" form shall mean the preferred form for making modifications,
27 | including but not limited to software source code, documentation
28 | source, and configuration files.
29 |
30 | "Object" form shall mean any form resulting from mechanical
31 | transformation or translation of a Source form, including but
32 | not limited to compiled object code, generated documentation,
33 | and conversions to other media types.
34 |
35 | "Work" shall mean the work of authorship, whether in Source or
36 | Object form, made available under the License, as indicated by a
37 | copyright notice that is included in or attached to the work
38 | (an example is provided in the Appendix below).
39 |
40 | "Derivative Works" shall mean any work, whether in Source or Object
41 | form, that is based on (or derived from) the Work and for which the
42 | editorial revisions, annotations, elaborations, or other modifications
43 | represent, as a whole, an original work of authorship. For the purposes
44 | of this License, Derivative Works shall not include works that remain
45 | separable from, or merely link (or bind by name) to the interfaces of,
46 | the Work and Derivative Works thereof.
47 |
48 | "Contribution" shall mean any work of authorship, including
49 | the original version of the Work and any modifications or additions
50 | to that Work or Derivative Works thereof, that is intentionally
51 | submitted to Licensor for inclusion in the Work by the copyright owner
52 | or by an individual or Legal Entity authorized to submit on behalf of
53 | the copyright owner. For the purposes of this definition, "submitted"
54 | means any form of electronic, verbal, or written communication sent
55 | to the Licensor or its representatives, including but not limited to
56 | communication on electronic mailing lists, source code control systems,
57 | and issue tracking systems that are managed by, or on behalf of, the
58 | Licensor for the purpose of discussing and improving the Work, but
59 | excluding communication that is conspicuously marked or otherwise
60 | designated in writing by the copyright owner as "Not a Contribution."
61 |
62 | "Contributor" shall mean Licensor and any individual or Legal Entity
63 | on behalf of whom a Contribution has been received by Licensor and
64 | subsequently incorporated within the Work.
65 |
66 | 2. Grant of Copyright License. Subject to the terms and conditions of
67 | this License, each Contributor hereby grants to You a perpetual,
68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69 | copyright license to reproduce, prepare Derivative Works of,
70 | publicly display, publicly perform, sublicense, and distribute the
71 | Work and such Derivative Works in Source or Object form.
72 |
73 | 3. Grant of Patent License. Subject to the terms and conditions of
74 | this License, each Contributor hereby grants to You a perpetual,
75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76 | (except as stated in this section) patent license to make, have made,
77 | use, offer to sell, sell, import, and otherwise transfer the Work,
78 | where such license applies only to those patent claims licensable
79 | by such Contributor that are necessarily infringed by their
80 | Contribution(s) alone or by combination of their Contribution(s)
81 | with the Work to which such Contribution(s) was submitted. If You
82 | institute patent litigation against any entity (including a
83 | cross-claim or counterclaim in a lawsuit) alleging that the Work
84 | or a Contribution incorporated within the Work constitutes direct
85 | or contributory patent infringement, then any patent licenses
86 | granted to You under this License for that Work shall terminate
87 | as of the date such litigation is filed.
88 |
89 | 4. Redistribution. You may reproduce and distribute copies of the
90 | Work or Derivative Works thereof in any medium, with or without
91 | modifications, and in Source or Object form, provided that You
92 | meet the following conditions:
93 |
94 | (a) You must give any other recipients of the Work or
95 | Derivative Works a copy of this License; and
96 |
97 | (b) You must cause any modified files to carry prominent notices
98 | stating that You changed the files; and
99 |
100 | (c) You must retain, in the Source form of any Derivative Works
101 | that You distribute, all copyright, patent, trademark, and
102 | attribution notices from the Source form of the Work,
103 | excluding those notices that do not pertain to any part of
104 | the Derivative Works; and
105 |
106 | (d) If the Work includes a "NOTICE" text file as part of its
107 | distribution, then any Derivative Works that You distribute must
108 | include a readable copy of the attribution notices contained
109 | within such NOTICE file, excluding those notices that do not
110 | pertain to any part of the Derivative Works, in at least one
111 | of the following places: within a NOTICE text file distributed
112 | as part of the Derivative Works; within the Source form or
113 | documentation, if provided along with the Derivative Works; or,
114 | within a display generated by the Derivative Works, if and
115 | wherever such third-party notices normally appear. The contents
116 | of the NOTICE file are for informational purposes only and
117 | do not modify the License. You may add Your own attribution
118 | notices within Derivative Works that You distribute, alongside
119 | or as an addendum to the NOTICE text from the Work, provided
120 | that such additional attribution notices cannot be construed
121 | as modifying the License.
122 |
123 | You may add Your own copyright statement to Your modifications and
124 | may provide additional or different license terms and conditions
125 | for use, reproduction, or distribution of Your modifications, or
126 | for any such Derivative Works as a whole, provided Your use,
127 | reproduction, and distribution of the Work otherwise complies with
128 | the conditions stated in this License.
129 |
130 | 5. Submission of Contributions. Unless You explicitly state otherwise,
131 | any Contribution intentionally submitted for inclusion in the Work
132 | by You to the Licensor shall be under the terms and conditions of
133 | this License, without any additional terms or conditions.
134 | Notwithstanding the above, nothing herein shall supersede or modify
135 | the terms of any separate license agreement you may have executed
136 | with Licensor regarding such Contributions.
137 |
138 | 6. Trademarks. This License does not grant permission to use the trade
139 | names, trademarks, service marks, or product names of the Licensor,
140 | except as required for reasonable and customary use in describing the
141 | origin of the Work and reproducing the content of the NOTICE file.
142 |
143 | 7. Disclaimer of Warranty. Unless required by applicable law or
144 | agreed to in writing, Licensor provides the Work (and each
145 | Contributor provides its Contributions) on an "AS IS" BASIS,
146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147 | implied, including, without limitation, any warranties or conditions
148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149 | PARTICULAR PURPOSE. You are solely responsible for determining the
150 | appropriateness of using or redistributing the Work and assume any
151 | risks associated with Your exercise of permissions under this License.
152 |
153 | 8. Limitation of Liability. In no event and under no legal theory,
154 | whether in tort (including negligence), contract, or otherwise,
155 | unless required by applicable law (such as deliberate and grossly
156 | negligent acts) or agreed to in writing, shall any Contributor be
157 | liable to You for damages, including any direct, indirect, special,
158 | incidental, or consequential damages of any character arising as a
159 | result of this License or out of the use or inability to use the
160 | Work (including but not limited to damages for loss of goodwill,
161 | work stoppage, computer failure or malfunction, or any and all
162 | other commercial damages or losses), even if such Contributor
163 | has been advised of the possibility of such damages.
164 |
165 | 9. Accepting Warranty or Additional Liability. While redistributing
166 | the Work or Derivative Works thereof, You may choose to offer,
167 | and charge a fee for, acceptance of support, warranty, indemnity,
168 | or other liability obligations and/or rights consistent with this
169 | License. However, in accepting such obligations, You may act only
170 | on Your own behalf and on Your sole responsibility, not on behalf
171 | of any other Contributor, and only if You agree to indemnify,
172 | defend, and hold each Contributor harmless for any liability
173 | incurred by, or claims asserted against, such Contributor by reason
174 | of your accepting any such warranty or additional liability.
175 |
176 | END OF TERMS AND CONDITIONS
177 |
178 | APPENDIX: How to apply the Apache License to your work.
179 |
180 | To apply the Apache License to your work, attach the following
181 | boilerplate notice, with the fields enclosed by brackets "[]"
182 | replaced with your own identifying information. (Don't include
183 | the brackets!) The text should be enclosed in the appropriate
184 | comment syntax for the file format. We also recommend that a
185 | file or class name and description of purpose be included on the
186 | same "printed page" as the copyright notice for easier
187 | identification within third-party archives.
188 |
189 | Copyright [yyyy] [name of copyright owner]
190 |
191 | Licensed under the Apache License, Version 2.0 (the "License");
192 | you may not use this file except in compliance with the License.
193 | You may obtain a copy of the License at
194 |
195 | http://www.apache.org/licenses/LICENSE-2.0
196 |
197 | Unless required by applicable law or agreed to in writing, software
198 | distributed under the License is distributed on an "AS IS" BASIS,
199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200 | See the License for the specific language governing permissions and
201 | limitations under the License.
202 |
--------------------------------------------------------------------------------
/public/script.js:
--------------------------------------------------------------------------------
1 | let globalChannel;
2 | let myClientId;
3 | let myChannel;
4 | let myChannelName;
5 | let gameOn = false;
6 | let players = {};
7 | let totalPlayers = 0;
8 | let latestShipPosition;
9 | let bulletThatShotMe;
10 | let bulletThatShotSomeone;
11 | let bulletOutOfBounds = "";
12 | let amIalive = false;
13 | let game;
14 | let myGameRoomName;
15 | let myGameRoomCh;
16 |
17 | const myNickname = localStorage.getItem("nickname");
18 | const myGameRoomCode = localStorage.getItem("roomCode");
19 | const amIHost = localStorage.getItem("isHost");
20 | const startGameBtn = document.getElementById("btn-startgame");
21 | const audioControlChkbox = document.getElementById("audio-chkbox");
22 |
23 | document.getElementById("room-code").innerHTML =
24 | "Other players can join using the code: " + myGameRoomCode;
25 |
26 | // connect to Ably
27 | const realtime = new Ably.Realtime({
28 | authUrl: "/auth",
29 | });
30 |
31 | //show modal
32 | if (amIHost == "true") {
33 | document.querySelector(".bg-modal").style.display = "flex";
34 | document.getElementById("game-link").innerHTML =
35 | "Invite your friends to join using the code: " + myGameRoomCode;
36 | document.querySelector(".close").addEventListener("click", () => {
37 | document.querySelector(".bg-modal").style.display = "none";
38 | });
39 | }
40 |
41 | function copyGameCode() {
42 | navigator.clipboard.writeText(myGameRoomCode);
43 | let copyButton = document.getElementById("copy-button");
44 | copyButton.style.backgroundColor = "white";
45 | copyButton.style.color = "black";
46 | copyButton.style.border = "2px solid black";
47 | copyButton.innerHTML = "Copied!";
48 | }
49 |
50 | // once connected to Ably, instantiate channels and launch the game
51 | realtime.connection.once("connected", () => {
52 | myClientId = realtime.auth.clientId;
53 | myGameRoomName = myGameRoomCode + ":primary";
54 | myChannelName = myGameRoomCode + ":clientChannel-" + myClientId;
55 | myGameRoomCh = realtime.channels.get(myGameRoomName);
56 | myChannel = realtime.channels.get(myChannelName);
57 |
58 | if (amIHost == "true") {
59 | const globalGameName = "main-game-thread";
60 | globalChannel = realtime.channels.get(globalGameName);
61 | myGameRoomCh.subscribe("thread-ready", (msg) => {
62 | myGameRoomCh.presence.enter({
63 | nickname: myNickname,
64 | isHost: amIHost,
65 | });
66 | });
67 | globalChannel.presence.enter({
68 | nickname: myNickname,
69 | roomCode: myGameRoomCode,
70 | isHost: amIHost,
71 | });
72 | startGameBtn.style.display = "inline-block";
73 | } else if (amIHost != "true") {
74 | myGameRoomCh.presence.enter({
75 | nickname: myNickname,
76 | isHost: amIHost,
77 | });
78 | startGameBtn.style.display = "none";
79 | }
80 | game = new Phaser.Game(config);
81 | });
82 |
83 | function startGame() {
84 | myChannel.publish("start-game", {
85 | start: true,
86 | });
87 | }
88 |
89 | // primary game scene
90 | class GameScene extends Phaser.Scene {
91 | constructor() {
92 | super("gameScene");
93 | }
94 |
95 | preload() {
96 | this.load.spritesheet(
97 | "avatarAanimated",
98 | "https://cdn.glitch.com/c0cf9403-8071-4ec0-afd7-8a5293120d79%2FavatarAanimated.png?v=1592436546438",
99 | {
100 | frameWidth: 48,
101 | frameHeight: 32,
102 | }
103 | );
104 | this.load.spritesheet(
105 | "avatarBanimated",
106 | "https://cdn.glitch.com/c0cf9403-8071-4ec0-afd7-8a5293120d79%2FavatarBanimated.png?v=1592436575703",
107 | {
108 | frameWidth: 48,
109 | frameHeight: 32,
110 | }
111 | );
112 | this.load.spritesheet(
113 | "avatarCanimated",
114 | "https://cdn.glitch.com/c0cf9403-8071-4ec0-afd7-8a5293120d79%2FavatarCanimated.png?v=1592436609339",
115 | {
116 | frameWidth: 48,
117 | frameHeight: 32,
118 | }
119 | );
120 | this.load.spritesheet(
121 | "ship",
122 | "https://cdn.glitch.com/f66772e3-bbf6-4f6d-b5d5-94559e3c1c6f%2FShip%402x.png?v=1589228730678",
123 | {
124 | frameWidth: 60,
125 | frameHeight: 32,
126 | }
127 | );
128 | this.load.spritesheet(
129 | "bullet",
130 | "https://cdn.glitch.com/f66772e3-bbf6-4f6d-b5d5-94559e3c1c6f%2Fbullet.png?v=1589229887570",
131 | {
132 | frameWidth: 48,
133 | frameHeight: 48,
134 | }
135 | );
136 | this.load.spritesheet(
137 | "explosion",
138 | "https://cdn.glitch.com/f66772e3-bbf6-4f6d-b5d5-94559e3c1c6f%2Fexplosion57%20(2).png?v=1589491279459",
139 | {
140 | frameWidth: 48,
141 | frameHeight: 48,
142 | }
143 | );
144 | this.load.audio(
145 | "move1",
146 | "https://cdn.glitch.com/f66772e3-bbf6-4f6d-b5d5-94559e3c1c6f%2Ffastinvader1.mp3?v=1589983955301"
147 | );
148 | this.load.audio(
149 | "move2",
150 | "https://cdn.glitch.com/f66772e3-bbf6-4f6d-b5d5-94559e3c1c6f%2Ffastinvader2.mp3?v=1589983959381"
151 | );
152 | this.load.audio(
153 | "move3",
154 | "https://cdn.glitch.com/f66772e3-bbf6-4f6d-b5d5-94559e3c1c6f%2Ffastinvader3.mp3?v=1589983969580"
155 | );
156 | this.load.audio(
157 | "move4",
158 | "https://cdn.glitch.com/f66772e3-bbf6-4f6d-b5d5-94559e3c1c6f%2Ffastinvader4.mp3?v=1589983973991"
159 | );
160 | this.load.audio(
161 | "myDeath",
162 | "https://cdn.glitch.com/f66772e3-bbf6-4f6d-b5d5-94559e3c1c6f%2Fexplosion.mp3?v=1589984025058"
163 | );
164 | this.load.audio(
165 | "opponentDeath",
166 | "https://cdn.glitch.com/f66772e3-bbf6-4f6d-b5d5-94559e3c1c6f%2Finvaderkilled.mp3?v=1589983981160"
167 | );
168 | this.load.audio(
169 | "shoot",
170 | "https://cdn.glitch.com/f66772e3-bbf6-4f6d-b5d5-94559e3c1c6f%2Fshoot.mp3?v=1589983990745"
171 | );
172 | }
173 | create() {
174 | this.avatars = {};
175 | this.visibleBullets = {};
176 | this.ship = {};
177 | this.cursorKeys = this.input.keyboard.createCursorKeys();
178 |
179 | // explode animation to play when a bullet hits an avatar
180 | this.anims.create({
181 | key: "explode",
182 | frames: this.anims.generateFrameNumbers("explosion"),
183 | frameRate: 20,
184 | repeat: 0,
185 | hideOnComplete: true,
186 | });
187 |
188 | this.anims.create({
189 | key: "animateA",
190 | frames: this.anims.generateFrameNumbers("avatarAanimated"),
191 | frameRate: 2,
192 | repeat: -1,
193 | });
194 |
195 | this.anims.create({
196 | key: "animateB",
197 | frames: this.anims.generateFrameNumbers("avatarBanimated"),
198 | frameRate: 2,
199 | repeat: -1,
200 | });
201 |
202 | this.anims.create({
203 | key: "animateC",
204 | frames: this.anims.generateFrameNumbers("avatarCanimated"),
205 | frameRate: 2,
206 | repeat: -1,
207 | });
208 |
209 | this.soundLoop = 0;
210 | this.shootSound = this.sound.add("shoot");
211 | this.move1 = this.sound.add("move1");
212 | this.move2 = this.sound.add("move2");
213 | this.move3 = this.sound.add("move3");
214 | this.move4 = this.sound.add("move4");
215 | this.myDeathSound = this.sound.add("myDeath");
216 | this.opponentDeathSound = this.sound.add("opponentDeath");
217 | this.movingSounds = [this.move1, this.move2, this.move3, this.move4];
218 |
219 | setInterval(() => {
220 | if (audioControlChkbox.checked === true) {
221 | this.movingSounds[this.soundLoop].play();
222 | this.soundLoop++;
223 | if (this.soundLoop == 4) {
224 | this.soundLoop = 0;
225 | }
226 | }
227 | }, 500);
228 |
229 | // subscribe to the game tick
230 | myGameRoomCh.subscribe("game-state", (msg) => {
231 | if (msg.data.gameOn) {
232 | gameOn = true;
233 | if (msg.data.shipBody["0"]) {
234 | latestShipPosition = msg.data.shipBody["0"];
235 | }
236 | if (msg.data.bulletOrBlank != "") {
237 | let bulletId = msg.data.bulletOrBlank.id;
238 | this.visibleBullets[bulletId] = {
239 | id: bulletId,
240 | y: msg.data.bulletOrBlank.y,
241 | toLaunch: true,
242 | bulletSprite: "",
243 | };
244 | }
245 | if (msg.data.killerBulletId) {
246 | bulletThatShotSomeone = msg.data.killerBulletId;
247 | }
248 | }
249 | players = msg.data.players;
250 | totalPlayers = msg.data.playerCount;
251 | });
252 |
253 | // subscribe to the game over event and switch to a new page
254 | myGameRoomCh.subscribe("game-over", (msg) => {
255 | gameOn = false;
256 | localStorage.setItem("totalPlayers", msg.data.totalPlayers);
257 | localStorage.setItem("winner", msg.data.winner);
258 | localStorage.setItem("firstRunnerUp", msg.data.firstRunnerUp);
259 | localStorage.setItem("secondRunnerUp", msg.data.secondRunnerUp);
260 | myGameRoomCh.detach();
261 | myChannel.detach();
262 | if (msg.data.winner == "Nobody") {
263 | window.location.replace("/gameover");
264 | } else {
265 | window.location.replace("/winner");
266 | }
267 | });
268 | }
269 |
270 | update() {
271 | if (gameOn) {
272 | // create and update the position of the ship
273 | if (this.ship.x) {
274 | this.ship.x = latestShipPosition;
275 | } else {
276 | this.ship = this.physics.add
277 | .sprite(latestShipPosition, config.scale.height - 32, "ship")
278 | .setOrigin(0.5, 0.5);
279 |
280 | this.ship.x = latestShipPosition;
281 | }
282 | // create and update the position of the bullets
283 | for (let item in this.visibleBullets) {
284 | if (this.visibleBullets[item].toLaunch) {
285 | this.visibleBullets[item].toLaunch = false;
286 | this.createBullet(this.visibleBullets[item]);
287 | } else {
288 | this.visibleBullets[item].bulletSprite.y -= 20;
289 | if (
290 | this.visibleBullets[item].bulletSprite.y < 0 ||
291 | this.visibleBullets[item].id == bulletThatShotSomeone
292 | ) {
293 | this.visibleBullets[item].bulletSprite.destroy();
294 | delete this.visibleBullets[item];
295 | }
296 | }
297 | }
298 | }
299 |
300 | // remove avatars of players that have left the game
301 | for (let item in this.avatars) {
302 | if (!players[item]) {
303 | this.avatars[item].destroy();
304 | delete this.avatars[item];
305 | }
306 | }
307 |
308 | // create and update avatars and scores of all the players
309 | for (let item in players) {
310 | let avatarId = players[item].id;
311 | if (this.avatars[avatarId] && players[item].isAlive) {
312 | this.avatars[avatarId].x = players[item].x;
313 | this.avatars[avatarId].y = players[item].y;
314 | if (avatarId == myClientId) {
315 | document.getElementById("score").innerHTML =
316 | "Score: " + players[item].score;
317 | }
318 | } else if (!this.avatars[avatarId] && players[item].isAlive) {
319 | if (players[item].id != myClientId) {
320 | let avatarName =
321 | "avatar" + players[item].invaderAvatarType + "animated";
322 | this.avatars[avatarId] = this.physics.add
323 | .sprite(players[item].x, players[item].y, avatarName)
324 | .setOrigin(0.5, 0.5)
325 | .setTintFill(players[item].invaderAvatarColor.toString());
326 | console.log(players[item].invaderAvatarColor);
327 | this.avatars[avatarId].play(
328 | "animate" + players[item].invaderAvatarType
329 | );
330 | this.avatars[avatarId].setCollideWorldBounds(true);
331 | document.getElementById("join-leave-updates").innerHTML =
332 | players[avatarId].nickname + " joined";
333 | setTimeout(() => {
334 | document.getElementById("join-leave-updates").innerHTML = "";
335 | }, 2000);
336 | } else if (players[item].id == myClientId) {
337 | let avatarName =
338 | "avatar" + players[item].invaderAvatarType + "animated";
339 | this.avatars[avatarId] = this.physics.add
340 | .sprite(players[item].x, players[item].y, avatarName)
341 | .setOrigin(0.5, 0.5);
342 | this.avatars[avatarId].play(
343 | "animate" + players[item].invaderAvatarType
344 | );
345 | this.avatars[avatarId].setCollideWorldBounds(true);
346 | amIalive = true;
347 | }
348 | } else if (this.avatars[avatarId] && !players[item].isAlive) {
349 | this.explodeAndKill(avatarId);
350 | }
351 | }
352 |
353 | // check for user input
354 | this.publishMyInput();
355 | }
356 |
357 | // play the explosion animation and destroy the avatar
358 | explodeAndKill(deadPlayerId) {
359 | this.avatars[deadPlayerId].disableBody(true, true);
360 | if (deadPlayerId == myClientId) {
361 | if (audioControlChkbox.checked === true) {
362 | this.myDeathSound.play();
363 | }
364 | } else {
365 | if (audioControlChkbox.checked === true) {
366 | this.opponentDeathSound.play();
367 | }
368 | }
369 | let explosion = new Explosion(
370 | this,
371 | this.avatars[deadPlayerId].x,
372 | this.avatars[deadPlayerId].y
373 | );
374 | delete this.avatars[deadPlayerId];
375 | document.getElementById("join-leave-updates").innerHTML =
376 | players[deadPlayerId].nickname + " died";
377 | setTimeout(() => {
378 | document.getElementById("join-leave-updates").innerHTML = "";
379 | }, 2000);
380 | }
381 |
382 | // publish user input to the game server
383 | publishMyInput() {
384 | if (Phaser.Input.Keyboard.JustDown(this.cursorKeys.left) && amIalive) {
385 | myChannel.publish("pos", {
386 | keyPressed: "left",
387 | });
388 | } else if (
389 | Phaser.Input.Keyboard.JustDown(this.cursorKeys.right) &&
390 | amIalive
391 | ) {
392 | myChannel.publish("pos", {
393 | keyPressed: "right",
394 | });
395 | }
396 | }
397 |
398 | // create a new bullet sprite
399 | createBullet(bulletObject) {
400 | let bulletId = bulletObject.id;
401 | this.visibleBullets[bulletId].bulletSprite = this.physics.add
402 | .sprite(this.ship.x + 23, bulletObject.y, "bullet")
403 | .setOrigin(0.5, 0.5);
404 | if (audioControlChkbox.checked === true) {
405 | this.shootSound.play();
406 | }
407 | // add an overlap callback if the current player is still alive
408 | if (amIalive) {
409 | if (
410 | this.physics.add.overlap(
411 | this.visibleBullets[bulletId].bulletSprite,
412 | this.avatars[myClientId],
413 | this.publishMyDeathNews,
414 | null,
415 | this
416 | )
417 | ) {
418 | bulletThatShotMe = bulletId;
419 | }
420 | }
421 | }
422 |
423 | // publish an eventto the server if the current player is hit
424 | publishMyDeathNews(bullet, avatar) {
425 | if (amIalive) {
426 | myChannel.publish("dead-notif", {
427 | killerBulletId: bulletThatShotMe,
428 | deadPlayerId: myClientId,
429 | });
430 | }
431 | amIalive = false;
432 | }
433 | }
434 |
435 | //game configuration
436 | const config = {
437 | type: Phaser.AUTO,
438 | backgroundColor: "#FFFFF",
439 | scale: {
440 | parent: "gameContainer",
441 | mode: Phaser.Scale.FIT,
442 | autoCenter: Phaser.Scale.CENTER_BOTH,
443 | width: 1400,
444 | height: 700,
445 | },
446 | //canvasStyle: "border:1px solid #ffffff;",
447 | scene: [GameScene],
448 | physics: {
449 | default: "arcade",
450 | arcade: {
451 | debug: false,
452 | },
453 | },
454 |
455 | };
456 |
--------------------------------------------------------------------------------
/public/space-invaders-hero.svg:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
24 |
25 |
26 |
27 |
28 |
29 |
30 |
31 |
32 |
33 |
34 |
35 |
36 |
37 |
38 |
39 |
40 |
41 |
42 |
43 |
44 |
45 |
46 |
47 |
48 |
49 |
50 |
51 |
52 |
53 |
54 |
55 |
56 |
57 |
58 |
59 |
60 |
61 |
62 |
63 |
64 |
65 |
66 |
67 |
68 |
69 |
70 |
71 |
72 |
73 |
74 |
75 |
76 |
77 |
78 |
79 |
80 |
81 |
82 |
83 |
84 |
85 |
86 |
87 |
88 |
89 |
90 |
91 |
92 |
93 |
94 |
95 |
96 |
97 |
98 |
99 |
100 |
101 |
102 |
103 |
104 |
105 |
106 |
107 |
108 |
109 |
110 |
111 |
112 |
113 |
114 |
115 |
116 |
117 |
118 |
119 |
120 |
121 |
122 |
123 |
124 |
125 |
126 |
127 |
128 |
129 |
130 |
131 |
132 |
133 |
134 |
135 |
136 |
137 |
138 |
139 |
140 |
141 |
142 |
143 |
144 |
145 |
146 |
147 |
148 |
149 |
150 |
151 |
152 |
153 |
154 |
155 |
156 |
157 |
158 |
159 |
160 |
161 |
162 |
163 |
164 |
165 |
166 |
167 |
168 |
169 |
170 |
171 |
172 |
173 |
174 |
175 |
176 |
177 |
178 |
179 |
180 |
181 |
182 |
183 |
184 |
185 |
186 |
187 |
188 |
189 |
190 |
191 |
192 |
193 |
194 |
195 |
196 |
197 |
198 |
199 |
200 |
201 |
202 |
203 |
204 |
205 |
206 |
207 |
208 |
209 |
210 |
211 |
212 |
213 |
214 |
215 |
216 |
217 |
218 |
219 |
220 |
221 |
222 |
223 |
224 |
225 |
226 |
227 |
228 |
229 |
230 |
231 |
232 |
233 |
234 |
235 |
236 |
237 |
238 |
239 |
240 |
241 |
242 |
243 |
244 |
245 |
246 |
247 |
248 |
249 |
250 |
251 |
252 |
253 |
254 |
255 |
256 |
257 |
258 |
259 |
260 |
261 |
262 |
263 |
264 |
265 |
266 |
267 |
268 |
269 |
270 |
271 |
272 |
273 |
274 |
275 |
276 |
277 |
278 |
279 |
280 |
281 |
282 |
283 |
284 |
285 |
286 |
287 |
288 |
289 |
290 |
291 |
292 |
293 |
294 |
295 |
296 |
297 |
298 |
299 |
300 |
301 |
302 |
303 |
304 |
305 |
306 |
307 |
308 |
309 |
310 |
311 |
312 |
313 |
314 |
315 |
316 |
317 |
318 |
319 |
320 |
321 |
322 |
323 |
324 |
325 |
326 |
327 |
328 |
329 |
330 |
331 |
332 |
333 |
334 |
335 |
336 |
337 |
338 |
339 |
340 |
341 |
342 |
343 |
344 |
345 |
346 |
347 |
348 |
349 |
350 |
351 |
352 |
353 |
354 |
355 |
356 |
357 |
358 |
359 |
360 |
361 |
362 |
363 |
364 |
365 |
366 |
367 |
368 |
369 |
370 |
371 |
372 |
373 |
374 |
375 |
376 |
377 |
378 |
379 |
380 |
381 |
382 |
383 |
384 |
385 |
386 |
387 |
388 |
389 |
390 |
391 |
392 |
393 |
394 |
395 |
396 |
397 |
398 |
399 |
400 |
401 |
402 |
403 |
404 |
405 |
406 |
407 |
408 |
409 |
410 |
411 |
412 |
413 |
414 |
415 |
416 |
417 |
418 |
419 |
420 |
421 |
422 |
423 |
424 |
425 |
426 |
427 |
428 |
429 |
430 |
431 |
432 |
433 |
434 |
435 |
436 |
437 |
438 |
439 |
440 |
441 |
442 |
443 |
444 |
445 |
446 |
447 |
448 |
449 |
450 |
451 |
452 |
453 |
454 |
455 |
456 |
457 |
458 |
459 |
460 |
461 |
462 |
463 |
464 |
465 |
466 |
467 |
468 |
469 |
470 |
471 |
472 |
473 |
474 |
475 |
476 |
477 |
478 |
479 |
480 |
481 |
482 |
483 |
484 |
485 |
486 |
487 |
488 |
489 |
490 |
--------------------------------------------------------------------------------