Rename shortbow files and cleanup several names

This commit is contained in:
Ryan Huffman 2017-02-02 09:31:31 -08:00
parent 84f82f1838
commit ecb8490978
9 changed files with 125 additions and 239 deletions

View file

@ -0,0 +1,4 @@
Shortbow
========
Shortbow is a wave-based archery game.

View file

@ -5,18 +5,20 @@
}; };
Enemy.prototype = { Enemy.prototype = {
preload: function(entityID) { preload: function(entityID) {
print("Loaded enemy entity");
this.entityID = entityID; this.entityID = entityID;
Script.addEventHandler(entityID, "collisionWithEntity", this.onCollide.bind(this));
// To avoid sending extraneous messages and checking entities that we've already
// seen, we keep track of which entities we've collided with previously.
this.entityIDsThatHaveCollidedWithMe = []; this.entityIDsThatHaveCollidedWithMe = [];
Script.addEventHandler(entityID, "collisionWithEntity", this.onCollide.bind(this));
var userData = Entities.getEntityProperties(this.entityID, 'userData').userData; var userData = Entities.getEntityProperties(this.entityID, 'userData').userData;
var data = utils.parseJSON(userData); var data = utils.parseJSON(userData);
if (data !== undefined && data.gameChannel !== undefined) { if (data !== undefined && data.gameChannel !== undefined) {
this.gameChannel = data.gameChannel; this.gameChannel = data.gameChannel;
} else { } else {
print("targetEntity.js | ERROR: userData does not contain a game channel and/or team number"); print("enemyEntity.js | ERROR: userData does not contain a game channel and/or team number");
} }
}, },
onCollide: function(entityA, entityB, collision) { onCollide: function(entityA, entityB, collision) {
@ -26,12 +28,8 @@
this.entityIDsThatHaveCollidedWithMe.push(entityB); this.entityIDsThatHaveCollidedWithMe.push(entityB);
var colliderName = Entities.getEntityProperties(entityB, 'name').name; var colliderName = Entities.getEntityProperties(entityB, 'name').name;
print("Hit: ", entityB);
// If the other entity's name includes 'projectile' and we haven't hit it before,
// continue on.
if (colliderName.indexOf("projectile") > -1) { if (colliderName.indexOf("projectile") > -1) {
print("Collided with: ", entityB);
Messages.sendMessage(this.gameChannel, JSON.stringify({ Messages.sendMessage(this.gameChannel, JSON.stringify({
type: "enemy-killed", type: "enemy-killed",
entityID: this.entityID, entityID: this.entityID,

View file

@ -1,4 +1,9 @@
SHORTBOW_ENTITIES = // This is a copy of the data in shortbow.json, which is an export of the shortbow
// scene.
//
// Because .json can't be Script.include'd directly, the contents are copied over
// to here and exposed as a global variable.
SHORTBOW_ENTITIES =
{ {
"Entities": [ "Entities": [
{ {

View file

@ -1,14 +1,5 @@
Script.include('utils.js'); Script.include('utils.js');
// Load the sounds that we will be using in the game so they are ready to be
// used when we need them.
var BEGIN_BUILDING_SOUND = SoundCache.getSound(Script.resolvePath("assets/sounds/gameOn.wav"));
var GAME_OVER_SOUND = SoundCache.getSound(Script.resolvePath("assets/sounds/gameOver.wav"));
var WAVE_COMPLETE_SOUND = SoundCache.getSound(Script.resolvePath("assets/sounds/waveComplete.wav"));
var EXPLOSION_SOUND = SoundCache.getSound(Script.resolvePath("assets/sounds/explosion.wav"));
var TARGET_HIT_SOUND = SoundCache.getSound(Script.resolvePath("assets/sounds/targetHit.wav"));
var ESCAPE_SOUND = SoundCache.getSound(Script.resolvePath("assets/sounds/escape.wav"));
// +--------+ +-----------+ +-----------------+ // +--------+ +-----------+ +-----------------+
// | | | |<-----+ | // | | | |<-----+ |
// | IDLE +----->| PLAYING | | BETWEEN_WAVES | // | IDLE +----->| PLAYING | | BETWEEN_WAVES |
@ -28,6 +19,15 @@ var GAME_STATES = {
GAME_OVER: 3, GAME_OVER: 3,
}; };
// Load the sounds that we will be using in the game so they are ready to be
// used when we need them.
var BEGIN_BUILDING_SOUND = SoundCache.getSound(Script.resolvePath("assets/sounds/gameOn.wav"));
var GAME_OVER_SOUND = SoundCache.getSound(Script.resolvePath("assets/sounds/gameOver.wav"));
var WAVE_COMPLETE_SOUND = SoundCache.getSound(Script.resolvePath("assets/sounds/waveComplete.wav"));
var EXPLOSION_SOUND = SoundCache.getSound(Script.resolvePath("assets/sounds/explosion.wav"));
var TARGET_HIT_SOUND = SoundCache.getSound(Script.resolvePath("assets/sounds/targetHit.wav"));
var ESCAPE_SOUND = SoundCache.getSound(Script.resolvePath("assets/sounds/escape.wav"));
// Encode a set of key-value pairs into a param string. Does NOT do any URL escaping. // Encode a set of key-value pairs into a param string. Does NOT do any URL escaping.
function encodeURLParams(params) { function encodeURLParams(params) {
var paramPairs = []; var paramPairs = [];
@ -56,9 +56,6 @@ function sendAndUpdateHighScore(highScoreChannel, entityID, score, wave, numPlay
var response = JSON.parse(req.responseText); var response = JSON.parse(req.responseText);
if (response.highScore !== undefined) { if (response.highScore !== undefined) {
Messages.sendMessage(highScoreChannel, response.highScore); Messages.sendMessage(highScoreChannel, response.highScore);
//Entities.editEntity(highScoreDisplayID, {
//text: response.highScore
//});
} }
} }
}; };
@ -67,24 +64,6 @@ function sendAndUpdateHighScore(highScoreChannel, entityID, score, wave, numPlay
req.send(); req.send();
} }
// The method of checking the local entity for the high score is currently disabled.
// As of 1/9/2017 we don't have support for getting nearby entity data in server entity scripts,
// so until then we have to rely on a remote source to store and retrieve that information.
function getHighScoreFromDisplay(entityID) {
var highScore = parseInt(Entities.getEntityProperties(entityID, 'text').text);
print("High score is: ", entityID, highScore);
if (highScore === NaN) {
return -1;
}
return highScore;
}
function setHighScoreOnDisplay(entityID, highScore) {
print("Setting high score to: ", entityID, highScore);
Entities.editEntity(entityID, {
text: highScore
});
}
var baseEnemyProperties = { var baseEnemyProperties = {
name: "WG.Enemy", name: "WG.Enemy",
damping: 0, damping: 0,
@ -124,7 +103,6 @@ var baseEnemyProperties = {
"y": -0.54996079206466675, "y": -0.54996079206466675,
"z": -0.54996079206466675 "z": -0.54996079206466675
}, },
//"restitution": 0.99000000953674316,
"rotation": { "rotation": {
"w": 0.52459806203842163, "w": 0.52459806203842163,
"x": 0.3808099627494812, "x": 0.3808099627494812,
@ -138,25 +116,19 @@ var baseEnemyProperties = {
y: 0, y: 0,
z: -3 z: -3
}, },
script: Script.resolvePath('enemyEntity.js'), script: Script.resolvePath('enemyClientEntity.js'),
serverScripts: Script.resolvePath('enemyServerEntity.js') serverScripts: Script.resolvePath('enemyServerEntity.js')
}; };
ShortbowGameManager = function(rootPosition, gatePosition, bowPositions, spawnPositions, rootEntityID, startButtonID, waveDisplayID, scoreDisplayID, livesDisplayID, highScoreDisplayID) { ShortbowGameManager = function(rootEntityID, bowPositions, spawnPositions) {
print("Starting game manager"); print("Starting game manager");
this.gameState = GAME_STATES.IDLE; this.gameState = GAME_STATES.IDLE;
this.bowPositions = bowPositions;
this.rootPosition = rootPosition;
this.spawnPositions = spawnPositions;
this.gatePosition = gatePosition;
this.rootEntityID = rootEntityID; this.rootEntityID = rootEntityID;
//this.startButtonID = startButtonID; this.bowPositions = bowPositions;
//this.waveDisplayID = waveDisplayID; this.rootPosition = null;
//this.scoreDisplayID = scoreDisplayID; this.spawnPositions = spawnPositions;
//this.livesDisplayID = livesDisplayID;
//this.highScoreDisplayID = highScoreDisplayID;
// Gameplay state // Gameplay state
this.waveNumber = 0; this.waveNumber = 0;
@ -164,41 +136,34 @@ ShortbowGameManager = function(rootPosition, gatePosition, bowPositions, spawnPo
this.score = 0; this.score = 0;
this.nextWaveTimer = null; this.nextWaveTimer = null;
this.spawnEnemyTimers = []; this.spawnEnemyTimers = [];
//this.enemyIDs = [];
this.remainingEnemies = []; this.remainingEnemies = [];
this.entityIDs = [];
this.bowIDs = []; this.bowIDs = [];
this.commChannelName = "shortbow-" + this.rootEntityID;
print("Listening on: ", this.commChannelName);
//this.scoreChannelName = "score-" + this.rootEntityID;
this.highscoreChannelName = "highscore-" + this.rootEntityID; this.highscoreChannelName = "highscore-" + this.rootEntityID;
//this.waveChannelName = "wave-" + this.rootEntityID;
//this.livesChannelName = "lives-" + this.rootEntityID;
this.startButtonChannelName = 'button-' + this.rootEntityID; this.startButtonChannelName = 'button-' + this.rootEntityID;
// Entity client and server scripts will send messages to this channel
this.commChannelName = "shortbow-" + this.rootEntityID;
Messages.subscribe(this.commChannelName); Messages.subscribe(this.commChannelName);
Messages.messageReceived.connect(this, this.onReceivedMessage); Messages.messageReceived.connect(this, this.onReceivedMessage);
print("Listening on: ", this.commChannelName);
this.reset(); this.reset();
sendAndUpdateHighScore(this.highscoreChannelName, this.rootEntityID, this.score, this.waveNumber, 1); sendAndUpdateHighScore(this.highscoreChannelName, this.rootEntityID, this.score, this.waveNumber, 1);
} }
ShortbowGameManager.prototype = { ShortbowGameManager.prototype = {
reset: function() { reset: function() {
//Entities.editEntity(this.startButtonID, {
//visible: true
//});
Messages.sendMessage(this.startButtonChannelName, 'show'); Messages.sendMessage(this.startButtonChannelName, 'show');
}, },
cleanup: function() { cleanup: function() {
Messages.unsubscribe(this.commChannelName); Messages.unsubscribe(this.commChannelName);
Messages.messageReceived.disconnect(this, this.onReceivedMessage); Messages.messageReceived.disconnect(this, this.onReceivedMessage);
for (var i = 0; i < this.entityIDs.length; i++) { if (this.checkEnemiesTimer) {
Entities.deleteEntity(this.entityIDs[i]); Script.clearInterval(this.checkEnemiesTimer);
this.checkEnemiesTimer = null;
} }
this.entityIDs = [];
for (var i = this.bowIDs.length - 1; i >= 0; i--) { for (var i = this.bowIDs.length - 1; i >= 0; i--) {
Entities.deleteEntity(this.bowIDs[i]); Entities.deleteEntity(this.bowIDs[i]);
} }
@ -207,57 +172,24 @@ ShortbowGameManager.prototype = {
Entities.deleteEntity(this.remainingEnemies[i].id); Entities.deleteEntity(this.remainingEnemies[i].id);
} }
this.remainingEnemies = []; this.remainingEnemies = [];
},
onReceivedMessage: function(channel, messageJSON, senderID) {
print("playWaveGame.js | Recieved: " + messageJSON + " from " + senderID, channel, this.commChannelName);
if (channel === this.commChannelName) { this.gameState = GAME_STATES.IDLE;
var message = utils.parseJSON(messageJSON);
if (message === undefined) {
print("playWaveGame.js | Received non-json message:", JSON.stringify(messageJSON));
return;
}
switch (message.type) {
case 'start-game':
this.startGame();
break;
case 'enemy-killed':
this.onEnemyKilled(message.entityID, message.position);
break;
case 'enemy-escaped':
this.onEnemyEscaped(message.entityID);
break;
case 'enemy-heartbeat':
for (var i = 0; i < this.remainingEnemies.length; i++) {
var enemy = this.remainingEnemies[i];
if (enemy.id == message.entityID) {
enemy.lastHeartbeat = Date.now();
enemy.lastKnownPosition = message.position;
break;
}
}
break;
default:
print("playWaveGame.js | Ignoring unknown message type: ", message.type);
break;
}
}
}, },
startGame: function() { startGame: function() {
if (this.gameState !== GAME_STATES.IDLE) { if (this.gameState !== GAME_STATES.IDLE) {
print("playWaveGameManager.js | Error, trying to start game when not in idle state"); print("shortbowGameManagerManager.js | Error, trying to start game when not in idle state");
return; return;
} }
print("Game started!!"); print("Game started!!");
//Entities.editEntity(this.startButtonID, { visible: false }); this.rootPosition = Entities.getEntityProperties(this.rootEntityID, 'position').position;
Messages.sendMessage(this.startButtonChannelName, 'hide');
Messages.sendMessage(this.startButtonChannelName, 'hide');
// Spawn bows // Spawn bows
for (var i = 0; i < this.bowPositions.length; ++i) { for (var i = 0; i < this.bowPositions.length; ++i) {
const bowPosition = this.bowPositions[i]; const bowPosition = Vec3.sum(this.rootPosition, this.bowPositions[i]);
Vec3.print("Creating bow: ", bowPosition); Vec3.print("Creating bow: ", bowPosition);
this.bowIDs.push(Entities.addEntity({ this.bowIDs.push(Entities.addEntity({
position: bowPosition, position: bowPosition,
@ -297,8 +229,7 @@ ShortbowGameManager.prototype = {
this.nextWaveTimer = Script.setTimeout(this.startNextWave.bind(this), 100); this.nextWaveTimer = Script.setTimeout(this.startNextWave.bind(this), 100);
this.spawnEnemyTimers = []; this.spawnEnemyTimers = [];
this.checkEnemyPositionsTimer = null; this.checkEnemiesTimer = null;
//this.enemyIDs = [];
this.remainingEnemies = []; this.remainingEnemies = [];
// SpawnQueue is a list of enemies left to spawn. Each entry looks like: // SpawnQueue is a list of enemies left to spawn. Each entry looks like:
@ -309,7 +240,7 @@ ShortbowGameManager.prototype = {
// to spawn the enemy. The list is sorted by spawnAt, ascending. // to spawn the enemy. The list is sorted by spawnAt, ascending.
this.spawnQueue = []; this.spawnQueue = [];
this.gameState = GAME_STATES.PLAYING; this.gameState = GAME_STATES.BETWEEN_WAVES;
Audio.playSound(BEGIN_BUILDING_SOUND, { Audio.playSound(BEGIN_BUILDING_SOUND, {
volume: 1.0, volume: 1.0,
@ -317,30 +248,25 @@ ShortbowGameManager.prototype = {
}); });
var self = this; var self = this;
//Script.setInterval(function() {
//print("Remaining enemies:");
//for (var i = 0; i < self.remainingEnemies.length; ++i) {
//print(" ", i, self.remainingEnemies[i].id);
//}
//}, 3000);
}, },
// Set the display text of one of the numbers on the scoreboard.
// Types: highscore, score, wave, lives
setDisplayText: function(type, value) { setDisplayText: function(type, value) {
var channel = type + '-' + this.rootEntityID; var channel = type + '-' + this.rootEntityID;
Messages.sendMessage(channel, value); Messages.sendMessage(channel, value);
}, },
startNextWave: function() { startNextWave: function() {
if (this.gameState !== GAME_STATES.BETWEEN_WAVES) {
return;
}
print("Starting next wave"); print("Starting next wave");
this.gameState = GAME_STATES.PLAYING; this.gameState = GAME_STATES.PLAYING;
this.waveNumber++; this.waveNumber++;
//this.enemyIDs = [];
this.remainingEnemies= []; this.remainingEnemies= [];
this.spawnQueue = []; this.spawnQueue = [];
this.spawnStartTime = Date.now(); this.spawnStartTime = Date.now();
//Entities.editEntity(this.waveDisplayID, {
//text: this.waveNumber
//});
this.setDisplayText('wave', this.waveNumber); this.setDisplayText('wave', this.waveNumber);
var numberOfEnemiesLeftToSpawn = this.waveNumber * 2; var numberOfEnemiesLeftToSpawn = this.waveNumber * 2;
@ -348,12 +274,12 @@ ShortbowGameManager.prototype = {
var currentDelay = 2000; var currentDelay = 2000;
print("Number of enemies:", numberOfEnemiesLeftToSpawn); print("Number of enemies:", numberOfEnemiesLeftToSpawn);
this.checkEnemyPositionsTimer = Script.setInterval(this.checkForEscapedEnemies.bind(this), 100); this.checkEnemiesTimer = Script.setInterval(this.checkEnemies.bind(this), 100);
for (var i = 0; i < numberOfEnemiesLeftToSpawn; ++i) { for (var i = 0; i < numberOfEnemiesLeftToSpawn; ++i) {
print("Adding enemy"); print("Adding enemy");
var idx = Math.floor(Math.random() * this.spawnPositions.length); var idx = Math.floor(Math.random() * this.spawnPositions.length);
this.spawnQueue.push({ spawnAt: currentDelay, position: this.spawnPositions[idx] }); this.spawnQueue.push({ spawnAt: currentDelay, position: Vec3.sum(this.rootPosition, this.spawnPositions[idx]) });
currentDelay += delayBetweenSpawns; currentDelay += delayBetweenSpawns;
} }
@ -365,12 +291,12 @@ ShortbowGameManager.prototype = {
return; return;
} }
if (this.spawnQueue.length <= 0 && this.remainingEnemies.length === 0) { if (this.spawnQueue.length === 0 && this.remainingEnemies.length === 0) {
this.gameState = GAME_STATES.BETWEEN_WAVES; this.gameState = GAME_STATES.BETWEEN_WAVES;
Script.setTimeout(this.startNextWave.bind(this), 5000); Script.setTimeout(this.startNextWave.bind(this), 5000);
Script.clearInterval(this.checkEnemyPositionsTimer); Script.clearInterval(this.checkEnemiesTimer);
this.checkEnemyPositionsTimer = null; this.checkEnemiesTimer = null;
// Play after 1.5s to let other sounds finish playing // Play after 1.5s to let other sounds finish playing
var self = this; var self = this;
@ -385,19 +311,19 @@ ShortbowGameManager.prototype = {
setLivesLeft: function(lives) { setLivesLeft: function(lives) {
lives = Math.max(0, lives); lives = Math.max(0, lives);
this.livesLeft = lives; this.livesLeft = lives;
//Entities.editEntity(this.livesDisplayID, {
//text: this.livesLeft
//});
this.setDisplayText('lives', this.livesLeft); this.setDisplayText('lives', this.livesLeft);
}, },
setScore: function(score) { setScore: function(score) {
this.score = score; this.score = score;
//Entities.editEntity(this.scoreDisplayID, {
//text: utils.formatNumberWithCommas(this.score)
//});
this.setDisplayText('score', this.score); this.setDisplayText('score', this.score);
}, },
checkSpawnQueue: function() { checkEnemies: function() {
if (this.gameState !== GAME_STATES.PLAYING) {
return;
}
// Check the spawn queueu to see if there are any enemies that need to
// be spawned
var waveElapsedTime = Date.now() - this.spawnStartTime; var waveElapsedTime = Date.now() - this.spawnStartTime;
while (this.spawnQueue.length > 0 && waveElapsedTime > this.spawnQueue[0].spawnAt) { while (this.spawnQueue.length > 0 && waveElapsedTime > this.spawnQueue[0].spawnAt) {
baseEnemyProperties.position = this.spawnQueue[0].position; baseEnemyProperties.position = this.spawnQueue[0].position;
@ -410,7 +336,6 @@ ShortbowGameManager.prototype = {
}); });
var entityID = Entities.addEntity(baseEnemyProperties); var entityID = Entities.addEntity(baseEnemyProperties);
//this.enemyIDs.push(entityID);
this.remainingEnemies.push({ this.remainingEnemies.push({
id: entityID, id: entityID,
lastKnownPosition: baseEnemyProperties.position, lastKnownPosition: baseEnemyProperties.position,
@ -424,14 +349,9 @@ ShortbowGameManager.prototype = {
}, 500 + Math.random() * 4000); }, 500 + Math.random() * 4000);
} }
//print("Spawn queue size: ", this.spawnQueue.length, "Elapsed time: ", waveElapsedTime, "Number of enemies:", this.enemyIDs.length);
},
checkForEscapedEnemies: function() {
// Move this somewhere else?
this.checkSpawnQueue();
//return;
// Check the list of remaining enemies to see if any are too far away
// or haven't been heard from in awhile - if so, delete them.
var enemiesEscaped = false; var enemiesEscaped = false;
for (var i = this.remainingEnemies.length - 1; i >= 0; --i) { for (var i = this.remainingEnemies.length - 1; i >= 0; --i) {
var enemy = this.remainingEnemies[i]; var enemy = this.remainingEnemies[i];
@ -440,7 +360,6 @@ ShortbowGameManager.prototype = {
if (timeSinceLastHeartbeat > 5000 || distance > 500) { if (timeSinceLastHeartbeat > 5000 || distance > 500) {
print("EXPIRING: ", enemy.id); print("EXPIRING: ", enemy.id);
Entities.deleteEntity(enemy.id); Entities.deleteEntity(enemy.id);
//this.enemyIDs.splice(i, 1);
this.remainingEnemies.splice(i, 1); this.remainingEnemies.splice(i, 1);
Audio.playSound(TARGET_HIT_SOUND, { Audio.playSound(TARGET_HIT_SOUND, {
volume: 1.0, volume: 1.0,
@ -449,31 +368,9 @@ ShortbowGameManager.prototype = {
this.setScore(this.score + 100); this.setScore(this.score + 100);
enemiesEscaped = true; enemiesEscaped = true;
} }
//var position = Entities.getEntityProperties(this.enemyIDs[i], 'position').position;
//if (position === undefined || Vec3.distance(position, this.rootPosition) > 100) {
// If the enemy can no longer be found, assume it was hit
//this.enemyIDs.splice(i, 1);
//Audio.playSound(TARGET_HIT_SOUND, {
//volume: 1.0,
//position: this.rootPosition,
//});
//this.setScore(this.score + 100);
//enemiesEscaped = true;
//} else if (position.z < this.gatePosition.z) {
//Entities.deleteEntity(this.enemyIDs[i]);
//this.enemyIDs.splice(i, 1);
//this.setLivesLeft(this.livesLeft - 1);
//Audio.playSound(ESCAPE_SOUND, {
//volume: 1.0,
//position: this.rootPosition
//});
//enemiesEscaped = true;
} }
//print("LIVES LEFT: ", this.livesLeft, this.numberOfEntitiesLeftForWave);
if (this.livesLeft <= 0) { if (enemiesEscaped) {
this.endGame();
} else if (enemiesEscaped) {
this.checkWaveComplete(); this.checkWaveComplete();
} }
}, },
@ -490,7 +387,6 @@ ShortbowGameManager.prototype = {
}); });
}, 1500); }, 1500);
//Entities.editEntity(this.livesDisplayID, { text: "GAME OVER" });
this.gameState = GAME_STATES.GAME_OVER; this.gameState = GAME_STATES.GAME_OVER;
print("GAME OVER"); print("GAME OVER");
@ -505,8 +401,8 @@ ShortbowGameManager.prototype = {
} }
this.spawnEnemyTimers = []; this.spawnEnemyTimers = [];
Script.clearInterval(this.checkEnemyPositionsTimer); Script.clearInterval(this.checkEnemiesTimer);
this.checkEnemyPositionsTimer = null; this.checkEnemiesTimer = null;
for (var i = this.bowIDs.length - 1; i >= 0; i--) { for (var i = this.bowIDs.length - 1; i >= 0; i--) {
@ -522,7 +418,6 @@ ShortbowGameManager.prototype = {
} }
Script.setTimeout(function() { Script.setTimeout(function() {
//Entities.editEntity(this.startButtonID, { visible: true });
Messages.sendMessage(this.startButtonChannelName, 'show'); Messages.sendMessage(this.startButtonChannelName, 'show');
this.gameState = GAME_STATES.IDLE; this.gameState = GAME_STATES.IDLE;
}.bind(this), 3000); }.bind(this), 3000);
@ -532,6 +427,34 @@ ShortbowGameManager.prototype = {
} }
this.remainingEnemies = []; this.remainingEnemies = [];
}, },
onReceivedMessage: function(channel, messageJSON, senderID) {
print("shortbowGameManager.js | Recieved: " + messageJSON + " from " + senderID, channel, this.commChannelName);
if (channel === this.commChannelName) {
var message = utils.parseJSON(messageJSON);
if (message === undefined) {
print("shortbowGameManager.js | Received non-json message:", JSON.stringify(messageJSON));
return;
}
switch (message.type) {
case 'start-game':
this.startGame();
break;
case 'enemy-killed':
this.onEnemyKilled(message.entityID, message.position);
break;
case 'enemy-escaped':
this.onEnemyEscaped(message.entityID);
break;
case 'enemy-heartbeat':
this.onEnemyHeartbeat(message.entityID, message.position);
break;
default:
print("shortbowGameManager.js | Ignoring unknown message type: ", message.type);
break;
}
}
},
onEnemyKilled: function(entityID, position) { onEnemyKilled: function(entityID, position) {
if (this.gameState !== GAME_STATES.PLAYING) { if (this.gameState !== GAME_STATES.PLAYING) {
return; return;
@ -543,7 +466,6 @@ ShortbowGameManager.prototype = {
this.remainingEnemies.splice(i, 1); this.remainingEnemies.splice(i, 1);
Audio.playSound(TARGET_HIT_SOUND, { Audio.playSound(TARGET_HIT_SOUND, {
volume: 1.0, volume: 1.0,
//position: position,
position: this.rootPosition, position: this.rootPosition,
}); });
@ -555,24 +477,12 @@ ShortbowGameManager.prototype = {
break; break;
} }
} }
//var idx = this.enemyIDs.indexOf(entityID);
//if (idx >= 0) {
// this.enemyIDs.splice(idx, 1);
// Audio.playSound(TARGET_HIT_SOUND, {
// volume: 1.0,
// //position: position,
// position: this.rootPosition,
// });
// // Update score
// this.setScore(this.score + 100);
// print("SCORE: ", this.score);
// this.checkWaveComplete();
//}
}, },
onEnemyEscaped: function(entityID, position) { onEnemyEscaped: function(entityID, position) {
if (this.gameState !== GAME_STATES.PLAYING) {
return;
}
var enemiesEscaped = false; var enemiesEscaped = false;
for (var i = this.remainingEnemies.length - 1; i >= 0; --i) { for (var i = this.remainingEnemies.length - 1; i >= 0; --i) {
var enemy = this.remainingEnemies[i]; var enemy = this.remainingEnemies[i];
@ -587,11 +497,20 @@ ShortbowGameManager.prototype = {
enemiesEscaped = true; enemiesEscaped = true;
} }
} }
//print("LIVES LEFT: ", this.livesLeft, this.numberOfEntitiesLeftForWave);
if (this.livesLeft <= 0) { if (this.livesLeft <= 0) {
this.endGame(); this.endGame();
} else if (enemiesEscaped) { } else if (enemiesEscaped) {
this.checkWaveComplete(); this.checkWaveComplete();
} }
}, },
onEnemyHeartbeat: function(entityID, position) {
for (var i = 0; i < this.remainingEnemies.length; i++) {
var enemy = this.remainingEnemies[i];
if (enemy.id == entityID) {
enemy.lastHeartbeat = Date.now();
enemy.lastKnownPosition = position;
break;
}
}
},
}; };

View file

@ -1,6 +1,6 @@
(function() { (function() {
Script.include('utils.js?' + Date.now()); Script.include('utils.js?' + Date.now());
Script.include('playWaveGame.js?' + Date.now()); Script.include('spawnShortbow.js?' + Date.now());
Script.include('shortbowGameManager.js?' + Date.now()); Script.include('shortbowGameManager.js?' + Date.now());
this.entityID = null; this.entityID = null;
@ -17,37 +17,22 @@
var rootPosition = props.position; var rootPosition = props.position;
// Generate goal that the enemies try to get to
goalPosition = Vec3.sum(rootPosition, { x: 0, y: -10, z: -20 });
const BASES_HEIGHT = 16;
const ROOF_HEIGHT = 0.2;
goalPosition.y += BASES_HEIGHT - ROOF_HEIGHT;
var platformID = data.platformID;
var buttonID = data.buttonID;
var waveDisplayID = data.waveDisplayID;
var livesDisplayID = data.livesDisplayID;
var scoreDisplayID = data.scoreDisplayID;
var highScoreDisplayID = data.highScoreDisplayID;
const BASES_SIZE = 15;
var goalPositionFront = Vec3.sum(goalPosition, { x: 0, y: 0, z: BASES_SIZE / 2 });
var bowPositions = []; var bowPositions = [];
var spawnPositions = []; var spawnPositions = [];
for (var i = 0; i < TEMPLATES.length; ++i) { for (var i = 0; i < TEMPLATES.length; ++i) {
var template = TEMPLATES[i]; var template = TEMPLATES[i];
if (template.name === "SB.BowSpawn") { if (template.name === "SB.BowSpawn") {
bowPositions.push(Vec3.sum(rootPosition, template.localPosition)); //bowPositions.push(Vec3.sum(rootPosition, template.localPosition));
Vec3.print("Pushing bow position", Vec3.sum(rootPosition, template.localPosition)); bowPositions.push(template.localPosition);
//Vec3.print("Pushing bow position", Vec3.sum(rootPosition, template.localPosition));
} else if (template.name === "SB.EnemySpawn") { } else if (template.name === "SB.EnemySpawn") {
spawnPositions.push(Vec3.sum(rootPosition, template.localPosition)); //spawnPositions.push(Vec3.sum(rootPosition, template.localPosition));
Vec3.print("Pushing spawnposition", Vec3.sum(rootPosition, template.localPosition)); spawnPositions.push(template.localPosition);
//Vec3.print("Pushing spawnposition", template.localPosition));
} }
} }
gameManager = new ShortbowGameManager(rootPosition, goalPositionFront, bowPositions, spawnPositions, this.entityID, buttonID, waveDisplayID, scoreDisplayID, livesDisplayID, highScoreDisplayID); gameManager = new ShortbowGameManager(this.entityID, bowPositions, spawnPositions);
}; };
this.unload = function() { this.unload = function() {
if (gameManager) { if (gameManager) {

View file

@ -101,13 +101,12 @@ function createLocalGame() {
// Create start button // Create start button
buttonID = spawnTemplate("SB.StartButton", { buttonID = spawnTemplate("SB.StartButton", {
parentID: scoreboardID, parentID: scoreboardID,
script: Script.resolvePath("startGameButton.js"), script: Script.resolvePath("startGameButtonClientEntity.js"),
serverScripts: Script.resolvePath("startGameButtonServerEntity.js"), serverScripts: Script.resolvePath("startGameButtonServerEntity.js"),
userData: JSON.stringify({ userData: JSON.stringify({
grabbableKey: { grabbableKey: {
wantsTrigger: true wantsTrigger: true
}, }
gameChannel: 'shortbow-' + scoreboardID
}), }),
}); });
entityIDs.push(buttonID); entityIDs.push(buttonID);
@ -125,7 +124,7 @@ function createLocalGame() {
userData: JSON.stringify({ userData: JSON.stringify({
displayType: "wave" displayType: "wave"
}), }),
serverScripts: Script.resolvePath("scoreboardEntity.js") serverScripts: Script.resolvePath("displayServerEntity.js")
}); });
entityIDs.push(waveDisplayID); entityIDs.push(waveDisplayID);
@ -134,7 +133,7 @@ function createLocalGame() {
userData: JSON.stringify({ userData: JSON.stringify({
displayType: "score" displayType: "score"
}), }),
serverScripts: Script.resolvePath("scoreboardEntity.js") serverScripts: Script.resolvePath("displayServerEntity.js")
}); });
entityIDs.push(scoreDisplayID); entityIDs.push(scoreDisplayID);
@ -143,7 +142,7 @@ function createLocalGame() {
userData: JSON.stringify({ userData: JSON.stringify({
displayType: "lives" displayType: "lives"
}), }),
serverScripts: Script.resolvePath("scoreboardEntity.js") serverScripts: Script.resolvePath("displayServerEntity.js")
}); });
entityIDs.push(livesDisplayID); entityIDs.push(livesDisplayID);
@ -152,7 +151,7 @@ function createLocalGame() {
userData: JSON.stringify({ userData: JSON.stringify({
displayType: "highscore" displayType: "highscore"
}), }),
serverScripts: Script.resolvePath("scoreboardEntity.js") serverScripts: Script.resolvePath("displayServerEntity.js")
}); });
entityIDs.push(highScoreDisplayID); entityIDs.push(highScoreDisplayID);
@ -191,9 +190,6 @@ function createLocalGame() {
Vec3.print("Pushing spawnposition", Vec3.sum(rootPosition, template.localPosition)); Vec3.print("Pushing spawnposition", Vec3.sum(rootPosition, template.localPosition));
} }
} }
const BASES_SIZE = 15;
goalPositionFront = Vec3.sum(goalPosition, { x: 0, y: 0, z: BASES_SIZE / 2 });
} }
if (Script.isClientScript()) { if (Script.isClientScript()) {

View file

@ -12,9 +12,8 @@
}, },
signalAC: function() { signalAC: function() {
print("Button pressed"); print("Button pressed");
var userData = Entities.getEntityProperties(this.entityID, ["userData"]).userData; print("Sending message to: ", this.commChannel);
print("Sending message to: ", JSON.parse(userData).gameChannel); Messages.sendMessage(this.commChannel, JSON.stringify({
Messages.sendMessage(JSON.parse(userData).gameChannel, JSON.stringify({
type: 'start-game' type: 'start-game'
})); }));
}, },

View file

@ -43,25 +43,5 @@ utils = {
return result.intersection; return result.intersection;
} }
return pos; return pos;
},
formatNumberWithCommas: function(number) {
return number + "";
if (number === 0) {
return "0";
}
var str = "";
while (number > 0) {
// Grab the digits in the
var belowThousand = number % 1000;
if (str !== "") {
str = "," + str;
}
str = belowThousand + str;
number = Math.floor(number / 1000);
}
return str;
} }
}; };