(function() { var messageChannel = 'MESSAGE_CHANNEL_GATE_GAME'; var entityID; var gates; var racers; 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 'INIT_GATE': gates.push(data.gateID); break; case 'REMOVE_GATE': var gateIndex = gates.indexOf(data.gateID); if (gateIndex > -1) { gates.splice(gateIndex, 1); } break; case 'REMOVE_RACER': if (racers[data.avatarSessionUUID]) { delete racers[data.avatarSessionUUID]; sendRenderMessage(); } break; case 'PASS_THROUGH_GATE': print('RACERS ' + JSON.stringify(racers)); print('GATES ' + gates.length + ' ' + JSON.stringify(gates)); var racer = racers[data.avatarSessionUUID]; if (!racer) { racers[data.avatarSessionUUID] = racer = { avatarDisplayName: data.avatarDisplayName || 'Anon', isRacing: false }; } if (!racer.isRacing && data.gateID === gates[0]) { racer.isRacing = true; racer.startTime = Date.now(); racer.gatesPassed = 1; racer.time = 'racing...'; } else if (racer.gatesPassed < gates.length && gates[racer.gatesPassed] === data.gateID) { racer.gatesPassed++; sendMessage({ type: 'CHECKPOINT', gateID: data.gateID }); } else if (racer.gatesPassed === gates.length && gates[0] === data.gateID) { // finish race by going into the starting ring again racer.isRacing = false; racer.time = ((Date.now() - racer.startTime) / 1000).toFixed(3) + ' sec'; if (!racer.bestTime || racer.time < racer.bestTime) { racer.bestTime = racer.time; } sendMessage({ type: 'CHECKPOINT', gateID: data.gateID }); } else { return; } sendRenderMessage(); break; } } function sendRenderMessage() { sendMessage({ type: 'RENDER', racers: racers }); } return { preload: function(id) { entityID = id; gates = []; racers = {}; Messages.subscribe(messageChannel); Messages.messageReceived.connect(null, onReceivedMessage); print('Hello Scoreboard'); }, unload: function(id) { Messages.unsubscribe(messageChannel); Messages.messageReceived.disconnect(null, onReceivedMessage); }, }; })