Adding the Score Metric
Now that we've set configured our score metric, it's time to add it to our application. Since we're using a custom
metric type, we'll need to add some code to js/app.js
to record Toggle's distance.
Our game already sends a message named gameEnded
. We'll listen for the gameEnded
message using a JavaScript eventListener, which will execute our code each time the message is emitted. When our listener gets triggered, we'll grab the value of distanceMeter.digits
from our runner
object, convert it to an integer, and pass it to our custom Score
event. Here's the code we'll use:
// Listen for game over and trigger custom event
document.addEventListener("gameEnded", function(){
var score = parseInt(runner.distanceMeter.digits.join(""));
ldclient.track("Score", null, score);
});
Let's add the code directly below the setSpeed
function we added earlier in js/app.js
. Our new code should look like this:
function setSpeed() {
// Update Toggle's speed and console log the value
config.SPEED = ldclient.variation('runner-speed', 6);
console.log('User key: \x1b[31m%s\x1b[0m, Speed: \x1b[31m%s\x1b[0m', lduser.key, config.SPEED);
}
// Listen for game over and trigger custom event
document.addEventListener("gameEnded", function(){
var score = parseInt(runner.distanceMeter.digits.join(""));
ldclient.track("Score", null, score);
});
// Call the updateUser() functon when the user clicks on the header
document.getElementById("heading").addEventListener("click", updateUser);
Once you've added your code, make sure to click the Run button at the top of your Replit:
We're in the home stretch now! Now that we've got our metric configured and our code implemented, all we need to do is convert our runner-speed
flag into an experiment. Those steps are detailed in the next section.