Leaderboard

Any suggestions on how one might approach building a simple leaderboard when deploying to Netlify? I’m reading that I’ll have to set up an API endpoint or function app in Netlify then post the playerName/time to it, and then I’d pull down the top X players from there too. I have a simple timer app that starts when trigger is entered, stopped when player enters last checkpoint, the time is displayed in a text component. I believe I would just add this logic to my timer script.

I know there are plugins and quite a few different ways to approach this, but I’d like to hear other’s thoughts since I am working within certain constraints (Needle and Netlify specifically).

Original Post on Discord

by user 507643794963824650

Hello there – we have an experimental AI bot :robot: that might be able to help you with your question. Would you like to try this out?

How it works:
Reply to the messages of the bot that end with a thread_id to interact with it and ask follow-up questions. You can also mention the bot directly in this channel to get help.

Help requested: please wait a moment…

Here is what I found for you :brain: Discord

Hello 0nederful, building a leaderboard for your application hosted on Netlify can indeed involve setting up serverless functions that act as API endpoints. Here’s a high-level approach to implement this:

  1. Design API Endpoints: You would need at least two endpoints: one to submit scores (e.g., POST /submit-score) and another to retrieve the leaderboard (e.g., GET /leaderboard).

  2. Implement Netlify Functions: Write serverless Lambda functions in Netlify to handle the above API endpoints. Store the leaderboard data in a database or a simple data store that Netlify functions can access.

  3. Handle Score Submission: After the timer stops in your game, send a POST request from the client-side script (Needle Engine) to the /submit-score endpoint with the player name and time.

  4. Retrieve and Display Leaderboard: Use a GET request in your client-side to fetch the top scores from the /leaderboard endpoint and display them using a text component in Needle Engine.

  5. Secure Your API: Implement security measures like API keys or authentication to prevent abuse.

  6. CORS Configuration: Ensure that your Netlify functions support CORS since your client-side requests will be coming from a different origin.

Here’s an example of how you might update your Needle Engine timer script to integrate with the leaderboard API:

*thread_dYLyJ1PcwS07rqIDEwEBlLRX*

typescript
import { Behaviour, serializable, Text } from “@needle-tools/engine”;
import { HttpClient } from “@needle-tools/engine/networking/HttpClient”;

export class TimerScript extends Behaviour {
@serializable() private displayText: Text;

private startTime: number;
private endTime: number;

start() {
    this.startTime = performance.now();
}

stopTimer() {
    this.endTime = performance.now();
    const totalTime = this.endTime - this.startTime;
    this.displayText.text = `Time: ${totalTime.toFixed(2)}s`;
    this.submitScore("PlayerName", totalTime);
}

async submitScore(playerName: string, time: number) {
    try {
        const response = await HttpClient.post('/.netlify/functions/submit-score', {
            playerName,
            time
        });

        // Handle success or error response
        console.log(response);
    } catch (error) {
        console.error("Failed to submit score", error);
    }
}

// Other script methods...

}

*thread_dYLyJ1PcwS07rqIDEwEBlLRX*

Remember to handle success and error cases appropriately, updating your UI with the response from the server when necessary. Make sure to test your implementation thoroughly, especially the Netlify functions, to ensure they handle requests as expected.

1 messages left GPT 4
thread_dYLyJ1PcwS07rqIDEwEBlLRX

Is there an API endpoint somewhere in the package that’s already getting deployed with my project that I can modify instead of building one myself?

by user 507643794963824650

Can you walk me through these first 2 steps?

Design API Endpoints: You would need at least two endpoints: one to submit scores (e.g., POST /submit-score) and another to retrieve the leaderboard (e.g., GET /leaderboard).

Implement Netlify Functions: Write serverless Lambda functions in Netlify to handle the above API endpoints. Store the leaderboard data in a database or a simple data store that Netlify functions can access.

by user 507643794963824650

Here is what I found for you :brain: Discord

Certainly! Here’s a basic walkthrough of designing the API endpoints and implementing Netlify functions.

Design API Endpoints:

  1. Submit Scores Endpoint (POST /submit-score): This endpoint handles the submission of scores by the players. It should accept parameters such as the player’s name and their score.

  2. Retrieve Leaderboard Endpoint (GET /leaderboard): This endpoint retrieves the top scores from the leaderboard. It might not need any parameters, just a request to fetch the top scores.

Here’s an example of how you might design the Netlify functions:

Implement Netlify Functions:

For the purpose of this example, let’s assume you’re using JavaScript for your Netlify functions:

  1. Set Up Your Netlify Project:

    • Make sure you have the Netlify CLI installed.
    • Initialize a new Netlify project or navigate to your existing project using the CLI.
  2. Create the Functions Directory:

    • Within your project, create a directory to hold your serverless functions, e.g., netlify-functions.
  3. Write the Functions:

    • Inside the netlify-functions directory, create two JavaScript files, e.g., submit-score.js and leaderboard.js.
    • In submit-score.js, use JavaScript to handle the submission of scores. This would likely include receiving the player’s name and score and saving it to a data store.
    • In leaderboard.js, create the function that retrieves the leaderboard data. This would involve fetching the top scores from the data store.
  4. Store and Access Leaderboard Data:

    • For simplicity, you can store the leaderboard data in a JSON file or an object within your Netlify functions. For a more scalable solution, consider using a serverless database like FaunaDB or integrating with an external database.
  5. Deploy the Functions:
    thread_dYLyJ1PcwS07rqIDEwEBlLRX

  • Once you’ve written your functions, deploy the Netlify project. Netlify will recognize the netlify-funtions directory and deploy the functions alongside your client-side code.
  1. Testing Your Endpoints:
    • Once deployed, you can test your endpoints using tools like Postman or by making requests from the client-side of your game. This will ensure that the functions are handling requests and returning the expected data.

This is a high-level overview, and the actual implementation might involve more details depending on the data store you choose and any security/authentication measures you need to take. If you need more specific guidance on any of these steps, feel free to ask!

0 messages left GPT 3.5
thread_dYLyJ1PcwS07rqIDEwEBlLRX
Thanks for your feedback!

Or perhaps this is a better approach? Leaderboards

by user 507643794963824650

It seems Lootlocker, Unity’s UGS Leaderboard service, or Netlify Service for API are my 3 best options, suggestions welcome as I do more testing.

by user 507643794963824650

If you deploy to glitch you can modify the server right on the glich dev page for fast iteration, and add your APIs there.

Can you generate a typescript file that allows me to call an api endpoint, and displays the return data in the console?

by user 507643794963824650

Here is what I found for you :brain: Discord

Certainly, 0nederful. Here’s a step-by-step plan and the TypeScript code for calling an API endpoint and displaying the return data in the console:

  • Define an asynchronous function fetchData that makes a fetch call to the desired API endpoint.
  • Use the await keyword to wait for the response and to convert it to JSON format.
  • Log the JSON data to the console.
// Define the async function to fetch data from the API
async function fetchData(apiUrl: string): Promise<void> {
  try {
    // Make a GET request using the fetch API
    const response = await fetch(apiUrl);

    // If the response is not ok, throw an error
    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`);
    }

    // Parse the JSON response
    const data = await response.json();
    
    // Log the data to the console
    console.log(data);
  } catch (error) {
    // Log any errors that occur during the fetch
    console.error('Error fetching data: ', error);
  }
}

// Call the fetchData function with the API endpoint URL
fetchData('https://api.example.com/data');

Replace ‘https://api.example.com/data’ with the actual URL of the API endpoint you want to call. Make sure you handle any API keys or authentication details if required by the endpoint.

1 messages left GPT 4
thread_bIMIkH0DFOMfWAtIn7xgv9Lv

Thanks, I’m trying to make a simple API call from the game at this point, I have a backend setup. I believe I have to write it in TS but I can’t get this file to convert to C# with code similar to what the bot provided above.

Is something like this possible?

EDIT I’m also assuming by your post that you meant the API endpoint, if you meant the actual request, then I will definitely try that.

by user 507643794963824650

It would help to see what you tried so far (how does your code look like on the component and on the backend). The bots response is pretty ok

I have a backend API setup in Xano, if you hit this endpoint you’ll get a unique ID returned, this TS code works in https://www.typescriptlang.org/ and should work anywhere else. This is the request:

const postRequest = async () => {
const url = ‘https://x8ki-letl-twmt.n7.xano.io/api:gIB1bPgH/user’;
const options = {
method: ‘POST’,
headers: {
‘Content-Type’: ‘application/json’
},
body: JSON.stringify({})
};

try {
    const response = await fetch(url, options);
    if (!response.ok) {
        throw new Error(`HTTP error! status: ${response.status}`);
    }
    const data = await response.json();
    console.log('ID:', data.id); // Log the 'id' value from the response
} catch (error) {
    console.error('Error during API call:', error);
}

};

postRequest();

When I drop it in my /scripts folder, in Unity I’m getting “Compilation failed, see log for more info: D:/UnityProjects/LeaderBoardTest/Assets/…/Temp/component-compiler.log” - I didn’t see much useful in the log file, basically a lot of this:

 FirstStatement
 VariableDeclarationList
 VariableDeclaration
 Identifier
 ArrowFunction
 AsyncKeyword
 EqualsGreaterThanToken
 Block
 FirstStatement
 VariableDeclarationList
 VariableDeclaration
 Identifier

I have other known good TS scripts that convert over to C# no problem, but it doesn’t like this API call script. Do you have any other ways to do this?

by user 507643794963824650