content/hifi-content/wadewatts/scoreboard2.js
2022-02-14 02:04:11 +01:00

68 lines
2.1 KiB
JavaScript

(function() {
var messageChannel = 'MESSAGE_CHANNEL_GATE_GAME';
var entityID;
var scores;
function sendMessage(message) {
message.entityID = entityID;
Messages.sendMessage(
messageChannel,
JSON.stringify(message)
);
}
function onReceivedMessage(channel, message, senderID) {
try {
var data = JSON.parse(message);
} catch (e) {
print('Error parsing message: ' + message);
return;
}
print('data: ' + JSON.stringify(data));
switch (data.type) {
case 'PASS':
if (!scores[data.name]) {
scores[data.name] = {};
scores[data.name].name = data.name;
}
if (!scores[data.name].startTime) {
scores[data.name].startTime = Date.now();
scores[data.name].time = 'racing...';
} else {
scores[data.name].time = Math.floor((Date.now() - scores[data.name].startTime) / 1000) + ' sec';
scores[data.name].startTime = null;
}
renderScoreboard();
break;
}
}
function renderScoreboard() {
var text = '';
Object.keys(scores).forEach(function(score) {
text += score.name + ' ' + score.time + '\n';
});
Entities.editEntity(entityID, {
text: text
});
}
return {
preload: function(id) {
entityID = id;
scores = {};
Messages.subscribe(messageChannel);
Messages.messageReceived.connect(null, onReceivedMessage);
print('Hello Scoreboard');
Entities.editEntity(entityID, {
text: 'Hello Scoreboard'
});
},
unload: function(id) {
Messages.unsubscribe(messageChannel);
Messages.messageReceived.disconnect(null, onReceivedMessage);
},
};
})