This is a publish-subscribe API that uses a public socket server or PubNub to function. It is based on the previous projects Gametime.js and Gametime.js-2.0. This project relies only on pure JavaScript to work.
This API comes with a public socket server hosted by us. As an alternative, you can also use PubNub, but that is not completely free and is a bit slower. If the script fails to connect to our socket server, it will try to connect to PubNub instead (only if you provide your Publish/Subscribe keys). There is also an option to use PubNub completely instead of our server.
Gametime.js-X should be embedded in your web page in order to function properly.
<script src="https://cdn.jsdelivr.net/gh/Parking-Master/Gametime.js-X@latest/gametime.js"></script>
For the minified version:
<script src="https://cdn.jsdelivr.net/gh/Parking-Master/Gametime.js-X@latest/gametime.min.js"></script>Tip: always keep this library at the latest version for bug fixes and critical updates.
Setting up and using this API is simple and easy. Here, we'll show you how to connect to the Gametime.js-X socket server (or use PubNub instead), then we'll show you how to send a JavaScript function over the internet. We'll also show you additional methods like setting the max players on one channel, disconnecting player(s), and generating UUIDs for a user.
Channels (in the context of a socket server) are like chat rooms. Only people inside them will be able to send and recieve messages to and from other users connected to the channel. It is required to create a unique identifier to separate channels in a game or chat room.
In other words, a group of users connected to a certain channel will be able to interact with each other over the internet using Gametime.js-X.
To set the channel, use the set
method to specify a certain channel. Here is an example:
await gametime.set("channel", "example-channel123");
Specify the channel in the second field.
To use the API, you need to connect to a socket server first.
To use our public socket server, use the setCustomServer
method and specify our server's URL.
await gametime.setCustomServer("https://caribou-needed-implicitly.ngrok-free.app");
You can also specify mutliple servers in case any are down:
await gametime.setCustomServer(["https://caribou-needed-implicitly.ngrok-free.app", "https://new-suitably-gnu.ngrok-free.app"]);
To use PubNub instead, log in to your PubNub account first, and then go to your Dashboard and take note of your Publish/Subscribe keys. Then, specify them using the set
method below:
await gametime.set("key", "pub-c-xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx", "sub-c-xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx");
Note: Fill in the fields with your PubNub Publish/Subscribe keys.
Using either of these methods will most likely connect you to a server. If it doesn't, make sure your PubNub API plan is active, and that our public server is currently up. Our server may go down briefly from time to time, so if it's down for you, please wait for it to come back up.
Next, you will use an asynchronous function to wait until Gametime.js-X has successfully connected you to a channel. This step is critical, so if you don't do it, the API will not successfully connect you to the channel.
Here is an example of this, using the sustain
method:
await gametime.sustain();
Note: Make sure to separate this function from the channel/server setup, and the actual API usage.
Now that you've set up Gametime.js-X, you are ready to use it. First, you will define a function by default on the page, so every user on the page will have the functions to be run by other users (e.g. define a function that will show a message on the page when another user posts it). Then, you will run that using another function, and it will be run on the same page if other users are also connected to it.
on(eventName: String, callback: Function(arguments))
run(eventName: String, arguments: Array[])
on()
.Here is an example of defining a function:
gametime.on("postMessage", function(user, message) { if (user == gametime.player.position) return; // `message` is a custom argument that contains an example message posted by another user. document.querySelector(".exampleChatWrapper").textContent += message; });
Note: Functions run using Gametime.js-X will be run for every user in the channel. To specify every user except for the one who posted the message, we've included the line if (user == gametime.player.position) return;
in the example.
Now, this is how you can run that function:
gametime.run("postMessage", [gametime.player.position, "This is an example chat message!"]);
You can call the function whatever you want (in this example, “postMessage”), and you can specify as many arguments as you want in your function. This is a basic example showing how to define a chat room post-message function, and then run it when a user wants to send a message. Feel free to customize this however you'd like and create whatever you want with it.
on(eventName: String, callback: Function(arguments))
run(eventName: String, arguments: Array[])
on()
.sustain()
set(globalSetting: String("key" | "channel"), channel | publishKey: String, subscribeKey: String)
setCustomServer(socketServerURL: String)
uuidv4()
onconnect()
ondisconnect()
logger.info(message: any)
console.log
method with colored output and unicodes. This specific function is the info method.logger.error(message: any)
console.log
method with colored output and unicodes. This specific function is the error method.logger.warn(message: any)
console.log
method with colored output and unicodes. This specific function is the warn method.logger.success(message: any)
console.log
method with colored output and unicodes. This specific function is the success method.disconnect()
Note: These are all methods apart of the global gametime variable when the API is installed (e.g. gametime.on(), gametime.run(), etc.)
Example on sending arguments through a function:
gametime.on("myCustomFunction", function(arg1, arg2, arg3) { console.log(arg1, arg2, arg3); // Output: "foo bar baz" }); let arg1 = "foo"; let arg2 = "bar"; let arg3 = "baz"; gametime.run("myCustomFunction", [arg1, arg2, arg3]);
Example of setting the max amount of players/users:
// The default is 16 gametime.maxPlayers = 3;
Example of setting the socket server:
// Replace SERVER_URL with the URL to your socket server gametime.setCustomServer(SERVER_URL); // For example, this is the public socket server for Gametime.js-X gametime.setCustomServer("https://caribou-needed-implicitly.ngrok-free.app");
Example of setting multiple socket servers:
// If a specified socket server is not available, the API will use the next available one // If no servers are available, it will switch to PubNub instead gametime.setCustomServer([server1, server2, server3, server4]); // For example, these are two socket servers for Gametime.js-X gametime.setCustomServer(["https://caribou-needed-implicitly.ngrok-free.app", "https://new-suitably-gnu.ngrok-free.app"]);
Example chat room page:
<!DOCTYPE html> <html> <head> <title>Gametime.js-X chat room</title> <link rel="stylesheet" href="https://cdn.jsdelivr.net/gh/Parking-Master/Gametime.js-X@latest/example_chat.css"> <script src="https://cdn.jsdelivr.net/gh/Parking-Master/Gametime.js-X@latest/gametime.js"></script> </head> <body> <div id="loading">Loading chat...</div> <ul id="messages"></ul> <form id="form"> <input id="input" placeholder="Type your message here..."> <button class="send">Send</button> <button class="disconnect">Disconnect</button> </form> <script> (async () => { // We'll try to connect to a Gametime.js-X socket server, but will use PubNub instead if it is not available await gametime.setCustomServer("https://caribou-needed-implicitly.ngrok-free.app"); await gametime.set("channel", "my-chat-room1234"); await gametime.set("key", "pub-c-xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx", "sub-c-xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"); await gametime.sustain(); document.querySelector("#loading").remove(); gametime.on("postChatMessage", function(message) { let item = document.createElement("li"); item.textContent = message; messages.appendChild(item); window.scrollTo(0, document.body.scrollHeight); let chatHistory = localStorage["history"]; let noBug = chatHistory === "" ? "" : ","; localStorage.setItem("history", (chatHistory + noBug + encodeURIComponent(message)).split(",").toString()); }); let messages = document.querySelector("#messages"); let form = document.querySelector("#form"); let input = document.querySelector("#input"); if (!localStorage["history"]) { localStorage.setItem("history", ""); } else { for (var i = 0; i < localStorage["history"].split(",").length; i++) { var item = document.createElement("li"); item.textContent = decodeURIComponent(localStorage["history"].split(",")[i]); messages.appendChild(item); window.scrollTo(0, document.body.scrollHeight); } } form.onsubmit = function(event) { event.preventDefault(); if (input.value) { gametime.run("postChatMessage", [input.value]); input.value = ""; } }; document.querySelector(".disconnect").onclick = function(event) { event.preventDefault(); gametime.disconnect(); }; })(); </script> </body> </html>
Tip: Here is a live example of this page. Open the same page on multiple tabs, browsers, or devices, and try sending a message after the page is fully loaded.
For other open-source examples, see FPS-X which is an open source FPS game that you can build yourself with Gametime.js-X and pure JavaScript.
This project is licensed under the MIT license, and is free to use, remake, and distribute however you like.
Copyright © 2021-2024 Parking Master