Skip to content

Instantly share code, notes, and snippets.

@jryio
Last active October 14, 2015 23:04
Show Gist options
  • Save jryio/23cb0ed16fd21fffb121 to your computer and use it in GitHub Desktop.
Save jryio/23cb0ed16fd21fffb121 to your computer and use it in GitHub Desktop.
var textBox = document.querySelector('.control input');
var ship = document.querySelector('.ship');
var button = document.querySelector('.control button');
var commandEntered = function(event) {
event.preventDefault();
var text = textBox.value;
textBox.value = '';
var words = text.split(' ');
var firstWord = words[0];
var secondWord = words[1];
if (firstWord === 'launch') {
launch();
}
else if (firstWord === 'go') {
go(secondWord);
}
else if (firstWord === 'rotate') {
rotate(secondWord);
}
else {
wrongCommand();
}
};
button.addEventListener('click', commandEntered);
var isLaunched = false;
var isDestroyed = false;
function launch() {
if (isDestroyed) {
return;
}
isLaunched = true;
ship.src = 'resources/spaceship.png';
};
var go = function(direction) {
if (!isLaunched) {
return wrongCommand();
}
var directions = {
left: [-80, 0],
right: [80, 0],
up: [0, 80],
down: [0, -80]
};
var displacement = directions[direction];
if (displacement === undefined) {
wrongCommand();
}
var shipLeftText = ship.style.left;
var shipBottomText = ship.style.bottom;
var shipLeftPosition = parseInt(shipLeftText);
var shipBottomPosition = parseInt(shipBottomText);
var properties = {
left: shipLeftPosition + displacement[0] + 'px',
bottom: shipBottomPosition + displacement[1] + 'px'
};
ship.style.left = shipLeftPosition + displacement[0] + 'px';
ship.style.bottom = shipBottomPosition + displacement[1] + 'px';
};
var rotate = function(amount) {
if (!isLaunched) {
return wrongCommand();
}
var degrees = parseInt(amount);
ship.style.transition = '1s ease-in';
ship.style.transform = 'rotate(' + degrees + 'deg)';
};
var wrongCommand = function() {
isLaunched = false;
isDestroyed = true;
ship.src = 'resources/explode.png';
// alert('Command not recognized');
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment