# Set Up Core Loop & Gameplay

## Overview

Below, we walk your through the core elements of setting up your core loop and gameplay on MiniTon. Beginning with starting a match, reporting a score and eventually getting back to the MiniTon BOT. By the end of this article, you will have a complete core loop allowing you to fully test a standard MiniTon match.

## Launching Your Gameplay

When MiniTon launches, it will take control of the user experience. The player will start a match and MiniTon will notify the game. At this point, control is given back to your game to start the match gameplay. The examples below illustrate how to handle starting a match.

{% tabs %}
{% tab title="Unity/C#" %}
You should have previously implemented the `MiniTon Manager`. The `OnMatchWillBegin` extra logic function specified in the `MiniTonManager` can be used to:

1. Clear any previously stored match settings
2. Retrieve the Match object and utilize it to set gameplay parameters
3. Load your game scene, if you have specified a `Game Scene` in the `MiniTon Manager`.

{% code title="ExtraLogic.cs" %}

```csharp
// ...
    public void OnMatchWillBeginExtraLogic(Match matchInfo) {
        //Extra Logic Here
    }
// ...
```

{% endcode %}
{% endtab %}

{% tab title="JavaScript" %}
You should have previously implemented the MiniTon Manager. The `OnMatchWillBegin` extra logic function specified in the MiniTonManager can be used in JavaScript as follows:

{% code overflow="wrap" %}

```javascript
// Assuming you have an instance of MiniTonManager and a matchInfo object
// This function should be called when the match is about to begin
function onMatchWillBeginExtraLogic(matchInfo) {
    // Extra Logic Here
    // Clear any previously stored match settings
    // Retrieve the Match object and utilize it to set gameplay parameters
    // Load your game scene if you have specified a Game Scene in the MiniTon Manager
}

// Usage example
const MiniTonManager = new MiniTonManager(); // Replace with actual initialization code
const matchInfo = getMatchInfo(); // Replace with code to retrieve match info

onMatchWillBeginExtraLogic(matchInfo);
```

{% endcode %}

The `onMatchWillBeginExtraLogic` function should be called when the match is about to begin, and you can implement your extra logic inside it.
{% endtab %}
{% endtabs %}

## Completing Gameplay

### Submit Score

To ensure that both asynchronous and synchronous gameplay proceeds optimally, the score for the match should be submitted immediately using `SubmitScore` when the match ends, regardless of any remaining player input necessary to reach the match results screen. The score submission should be handled in the background without any explicit action by the player necessary to proceed.

The `SubmitScore` method is expecting three values - a score as well as Success and Failure Callbacks.

{% tabs %}
{% tab title="Unity/C#" %}
You should report the final score from a script that controls your game scene&#x20;

{% code title="logic.GameManager.cs" %}

```csharp
using MiniTon;
using UnityEngine;

public class GameManager : MonoBehaviour
{
    void SubmitScore() {
        MiniTonCrossPlatform.SubmitScore(GetScore(), Success, Failure);
    }

    void Success() {
        Debug.Log("Success");
        //Return to the MiniTon
    }

    void Failure(string reason) {
        Debug.LogWarning("Fail: " + reason);
        //Fallback score submission
    }
}
```

{% endcode %}
{% endtab %}

{% tab title="JavaScript" %}
To achieve optimal gameplay flow in JavaScript for both asynchronous and synchronous gameplay, you can submit the match score immediately using the `SubmitScore` method when the match ends, without requiring explicit player input to proceed. The `SubmitScore` method expects three values: the score, a success callback, and a failure callback.

You should report the final score from a script that controls your game scene logic.

{% code overflow="wrap" %}

```javascript
// Assuming you have a MiniTon object initialized
// This function should be called when the match ends
function submitScore() {
    const score = getScore(); // Replace with your score calculation logic

    MiniTon.SubmitScore(score, successCallback, failureCallback);
}

// Success callback function
function successCallback() {
    console.log("Success");
    // Return to the MiniTon or perform any other necessary actions
}

// Failure callback function
function failureCallback(reason) {
    console.warn("Fail: " + reason);
    // Implement a fallback score submission or handle the failure as needed
}

// Usage example
// Call submitScore() when your game match ends
submitScore();

```

{% endcode %}

In this JavaScript version, you should replace `getScore()` with your actual score calculation logic and ensure that you have a MiniTon object initialized. The `submitScore` function should be called when the match ends, and it will trigger the appropriate success or failure callbacks based on the result of the score submission.
{% endtab %}
{% endtabs %}

> #### Note on Progression
>
> After submitting a score, you have the opportunity to present the player with a granular score breakdown and an opportunity to allow the player to view their game progression. Setup for this is detailed further in the Progression Overview.

### Return To The MiniTon BOT

The `ReturnToMiniTon` method exits your gameplay scene and presents the MiniTon BOT. This must be called **after** the score has been successfully submitted with the `SubmitScore` method. After `SubmitScore` has been called, you can present users with high scores or progression systems to enhance the game experience before ultimately calling the `ReturnToMiniTon` method and loading the MiniTon BOT.&#x20;

In all cases, it will return true or false, depending on whether or not it is able to return the user to MiniTon. For the case of a match in progress, unless a score has been submitted, this method will return false and the user will not be returned to MiniTon. If a score has been submitted, it returns true and returns the user to MiniTon.

{% tabs %}
{% tab title="Unity/C#" %}
The ReturnToMiniTon method provides flexibility on how to hand the end of the match behavior.&#x20;

{% code title="GameManager.cs" %}

```csharp
using MiniTon;
using UnityEngine;

public class GameManager : MonoBehaviour
{
    void SubmitScore() {
        MiniTonCrossPlatform.SubmitScore(GetScore(), Success, Failure);
    }

    void Success() {
        Debug.Log("Success");
        MiniTonCrossPlatform.ReturnToMiniTon();
    }

    void Failure(string reason) {
        Debug.LogWarning("Fail: " + reason);
        //Fallback score submission
    }
}
```

{% endcode %}
{% endtab %}

{% tab title="JavaScript" %}
`ReturnToMiniTon` method is called to handle the end of the match, you can use the following code:

{% code overflow="wrap" %}

```javascript
// Assuming you have a MiniTon object initialized
// This function should be called when the match ends and you want to return to MiniTon
function returnToMiniTon() {
    MiniTon.ReturnToMiniTon();
}

// Success callback function
function successCallback() {
    console.log("Success");
    returnToMiniTon(); // Call the returnToMiniTon function when the match is successful
}

// Failure callback function
function failureCallback(reason) {
    console.warn("Fail: " + reason);
    // Implement a fallback score submission or handle the failure as needed
}

// Submit the score using MiniTon
function submitScore() {
    const score = getScore(); // Replace with your actual score calculation logic

    MiniTon.SubmitScore(score, successCallback, failureCallback);
}

// Usage example
// Call submitScore() when your game match ends
submitScore();

```

{% endcode %}

In this JavaScript version, you should replace `getScore()` with your actual score calculation logic, and ensure that you have a MiniTon object initialized.
{% endtab %}
{% endtabs %}

### Fallback Score Reporting

> #### Please Note:
>
> **ReportFinalScore** has been deprecated and replaced by the **DisplayTournamentResultsWithScore** method.

The primary method for reporting a score to MiniTon is through the methods defined above `SubmitScore` and `ReturnToMiniTon`. However, **DisplayTournamentResultsWithScore should always be implemented as a fallback in the event that the SubmitScore method fails.** This best practice ensures your user’s scores will never be lost. This method submits the player score, then immediately returns the user to the MiniTon.

Ensure that calling this method as fallback will prevent any pending/in-progress SubmitScore calls from triggering a new retry after the user returns to MiniTon. If you do not do this, the pending retry may execute in a new game and you could end up submitting a previous game’s score.

{% tabs %}
{% tab title="Unity/C#" %}
{% code title="GameManager.cs" %}

```csharp
using MiniTon;
using UnityEngine;

public class GameManager : MonoBehaviour
{
    void SubmitScore() {
        MiniTonCrossPlatform.SubmitScore(GetScore(), Success, Failure);
    }

    void Success() {
        Debug.Log("Success");
        MiniTonCrossPlatform.ReturnToMiniTon();
    }

    void Failure(string reason) {
        Debug.LogWarning("Fail: " + reason);
        MiniTonCrossPlatform.DisplayTournamentResultsWithScore(GetScore());
    }
}
```

{% endcode %}
{% endtab %}

{% tab title="JavaScript" %}
{% code overflow="wrap" %}

```javascript
// Assuming you have a MiniTon object initialized
// This function should be called when you want to submit the score
function submitScore() {
    const score = getScore(); // Replace with your actual score calculation logic

    MiniTon.SubmitScore(score, successCallback, failureCallback);
}

// Success callback function
function successCallback() {
    console.log("Success");
    returnToMiniTon(); // Call the returnToMiniTon function when the match is successful
}

// Failure callback function
function failureCallback(reason) {
    console.warn("Fail: " + reason);
    displayTournamentResultsWithScore(getScore()); // Call the displayTournamentResultsWithScore function on failure
}

// Function to return to MiniTon
function returnToMiniTon() {
    MiniTon.ReturnToMiniTon();
}

// Function to display tournament results with the score
function displayTournamentResultsWithScore(score) {
    MiniTon.DisplayTournamentResultsWithScore(score);
}

// Function to get the score (replace with your actual score calculation logic)
function getScore() {
    return 100; // Replace with the actual score value
}

// Usage example
// Call submitScore() when your game match ends
submitScore();
```

{% endcode %}
{% endtab %}
{% endtabs %}

### Incomplete Matches

There are a couple ways to end a match prematurely. First, you can allow the user to quit the game and submit their current score, which gives them an opportunity to win with the score they have. Second, you can abort them from a match, which will result in a loss.Depending on your specific gameplay, you will need to determine which method works best for you.

#### **Aborting**

Aborting a match is an alternative to reporting the final score. When a player aborts a match, they have forfeited it to the opponent.

{% tabs %}
{% tab title="Unity/C#" %}

```csharp
MiniTonCrossPlatform.AbortMatch();
```

{% endtab %}

{% tab title="JavaScript" %}

```javascript
// Assuming you have a MiniTonCrossPlatform object initialized
// This function should be called when you want to abort the match
function abortMatch() {
    MiniTonCrossPlatform.AbortMatch();
}

// Usage example
// Call abortMatch() when you want to abort the match
abortMatch();
```

{% endtab %}
{% endtabs %}

### Ending Replay

Many cash matches are recorded in order to allow players to view replays as well as allow MiniTon to monitor fair play. The SDK provides an option that will allow you to end the replay after successfully submitting scores before progressing. This prevents unnecessarily long replays when the players interact with other gameplay elements like Progression. If you choose not to manually end the replay, the replay will end when the game returns to the MiniTon.

You might want to consider supporting this feature in your game to allow users more control to conserve on resources i.e. battery, network etc.

> If you invoke this method before calling SubmitScore a value of `false` will be returned. It is always recommended, to submit the player score as soon as the match gameplay ends, if possible.

{% tabs %}
{% tab title="Unity/C#" %}

```csharp
bool success = MiniTonCrossPlatform.EndReplay();
```

{% endtab %}

{% tab title="JavaScript" %}
{% code overflow="wrap" %}

```javascript
// Assuming you have a MiniTonCrossPlatform object initialized
// This function should be called when you want to end the replay
function endReplay() {
    const success = MiniTonCrossPlatform.EndReplay();
    return success; // Return the success value if needed
}

// Usage example
// Call endReplay() when you want to end the replay
const replayEndedSuccessfully = endReplay();
```

{% endcode %}
{% endtab %}
{% endtabs %}


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://docs.miniton.games/developer-success/miniton-developer-documentation/set-up-core-loop-and-gameplay.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
