<commit_before>/* global $, google */

$(function () {
    var MARKER_ICON = 'img/icon-pin-green.png';
    var LOCATION_ICON = 'img/icon-location.png';
    var API_URL = 'http://7cb0c2aa.ngrok.io'; //without final '/'

    var map;
    var geocoder;
    var markers;
    var _gmarkers;
    var areMarkersHidden = false;

    window._sendAllMarkersToBackend = function() {
        console.log('Sending ALL ' + allMarkers.length + ' places.');

        allMarkers.forEach(function(m){
            $.post(API_URL + '/local', m);
        })
    }

    function postPlace(place, callback) {
        console.log('Sending new place:');
        console.log(place);

        $.post(
            API_URL + '/local',
            place,
            function(data) {
                if (callback) {
                    console.log('Addition success');
                    callback();
                }
            }
        );
    }

    function getAllPlaces(successCB, failCB, alwaysCB) {
        console.log('Getting all places...');

        $.ajax({
            url: API_URL + '/local'
        }).done(function(data) {
            console.log(data);

            markers = data;

            if (successCB) {
                successCB();
            }
        })
        .fail(function() {
            if (failCB) {
                failCB();
            }
        })
        .always(function() {
            if (alwaysCB) {
                alwaysCB();
            }
        });
    }

    /**
     * The CenterControl adds a control to the map that recenters the map on Chicago.
     * This constructor takes the control DIV as an argument.
     * @constructor
     */
    function centerControl(controlDiv, map) {
        function _tryGeolocate() {
            if (navigator.geolocation) {
                navigator.geolocation.getCurrentPosition(function(position) {
                    var pos = {
                        lat: position.coords.latitude,
                        lng: position.coords.longitude
                    };

                    map.setCenter(pos);
                }, function() {
                    // handleLocationError(true, infoWindow, map.getCenter());
                });
            }
        }

        // Set CSS for the control border.
        var controlUI = document.createElement('div');
        controlUI.style.backgroundColor = '#fff';
        controlUI.style.border = '2px solid #fff';
        controlUI.style.borderRadius = '50%';
        // controlUI.style.boxShadow = '0 2px 6px rgba(0,0,0,.3)';
        controlUI.style.cursor = 'pointer';
        controlUI.style.margin = '0 20px 90px';
        controlUI.style.width = '38px';
        controlUI.style.height = '38px';
        controlUI.style.textAlign = 'center';
        controlUI.title = 'Clique para centralizar mapa';

        controlDiv.appendChild(controlUI);

        // Set CSS for the control interior.
        var controlText = document.createElement('div');
        controlText.style.color = '#30bb6a';
        controlText.style.fontSize = '20px';
        controlText.style.padding = '5px';
        controlText.innerHTML = '';
        controlUI.appendChild(controlText);

        // Setup the click event listeners: simply set the map to Chicago.
        controlUI.addEventListener('click', function() {
            _tryGeolocate();
        });

    }

    function addTestMarker() {
        // Add test marker
        var contentString = '
'+
        '
'+
        '
'+
        '
Uluru
'+
        '
'+
        '
Uluru, also referred to as Ayers Rock, is a large ' +
        'sandstone rock formation in the southern part of the '+
        'Northern Territory, central Australia. It lies 335 km (208 mi) '+
        'south west of the nearest large town, Alice Springs; 450 km '+
        '(280 mi) by road. Kata Tjuta and Uluru are the two major '+
        'features of the Uluru - Kata Tjuta National Park. Uluru is '+
        'sacred to the Pitjantjatjara and Yankunytjatjara, the '+
        'Aboriginal people of the area. It has many springs, waterholes, '+
        'rock caves and ancient paintings. Uluru is listed as a World '+
        'Heritage Site.
'+
        '
Attribution: Uluru, '+
        'https://en.wikipedia.org/w/index.php?title=Uluru '+
        '(last visited June 22, 2009).
'+
        '
'+
        '
';
        var infowindow = new google.maps.InfoWindow({
            content: contentString
        });
        var marker = new google.maps.Marker({
            position: {
                lat: -30.0458531,
                lng: -51.2295223
            },
            map: map,
            icon: MARKER_ICON,
            // title: 'Uluru (Ayers Rock)'
        });
        marker.addListener('click', function() {
            infowindow.open(map, marker);
        });
    }

    function updateMarkers() {
        _gmarkers = [];

        // Markers from Database
        if (markers && markers.length > 0) {
            // markers.forEach(function(m) {
            for(var i=0; i<markers.length; i++) {
                _gmarkers[i] = new google.maps.Marker({
                    position: {
                        lat: Number.parseFloat(markers[i].lng),
                        lng: Number.parseFloat(markers[i].lat)
                    },
                    map: map,
                    icon: MARKER_ICON,
                    // title: markers[i].text,
                });

                // var content = '
'+
                // '
' + markers[i].text + '
' +
                // '
structureType: ' + markers[i].structureType + '
' +
                // '
isPublic: ' + markers[i].isPublic + '
' +
                // '
';
                // var infowindow = new google.maps.InfoWindow({
                //     content: content
                // });

                (function (m) {
                    _gmarkers[i].addListener('click', function() {
                        // infowindow.open(map, _gmarkers[i]);
                        console.log(m.text);
                        console.log(m.structureType);
                        console.log(m.isPublic);
                    });
                }(markers[i]));
            }
            // });
        }
    }

    function searchLocation() {
        var address = $('#locationQueryInput').val();

        geocoder.geocode({'address': address}, function(results, status) {
            if (status === google.maps.GeocoderStatus.OK) {
                map.setCenter(results[0].geometry.location);

                // Set marker on located place
                // new google.maps.Marker({
                //     map: map,
                //     position: results[0].geometry.location
                // });
            } else {
                alert('Geocode was not successful for the following reason: ' + status);
            }
        });
    }

    // Sets the map on all markers in the array.
    function setMapOnAll(m) {
      for (var i = 0; i < _gmarkers.length; i++) {
        _gmarkers[i].setMap(m);
      }
    }

    // Removes the markers from the map, but keeps them in the array.
    function hideMarkers() {
        areMarkersHidden = true;
        setMapOnAll(null);
    }

    // Shows any markers currently in the array.
    function showMarkers() {
      areMarkersHidden = false;
      setMapOnAll(map);
    }

    // Deletes all markers in the array by removing references to them.
    function deleteMarkers() {
      clearMarkers();
      _gmarkers = [];
    }

    function toggleMarkers() {
        if (areMarkersHidden) {
            showMarkers();
        } else {
            hideMarkers();
        }
    }

    function addLocationModeToggle() {
        $('#addPlace').toggleClass('active')
        $('#newPlaceholder').toggle();
        toggleMarkers();
    }

    function addLocation() {
        console.log('add location');

        var mapCenter = map.getCenter();
        postPlace({
            lat: ''+mapCenter.lat(),
            lng: ''+mapCenter.lng(),
            isPublic: 'true',
            text: 'test'
        });

        updateMarkers();

        addLocationModeToggle();
    }

    var init = function () {
        map = new google.maps.Map(document.getElementById('map'), {
            center: {
                lat: -30.0458531,
                lng: -51.2295223},
            zoom: 16,
            disableDefaultUI: true,
            scaleControl: false,
        });

        geocoder = new google.maps.Geocoder();

        // Bike Layer
        var bikeLayer = new google.maps.BicyclingLayer();
        bikeLayer.setMap(map);

        // Geolocalization button
        if (navigator.geolocation) {
            var centerControlDiv = document.createElement('div');
            new centerControl(centerControlDiv, map);
            centerControlDiv.index = 1;
            map.controls[google.maps.ControlPosition.RIGHT_BOTTOM].push(centerControlDiv);
        }

        $('#locationQueryBtn').on('click', searchLocation);

        $('#addPlace').on('click', addLocationModeToggle);

        $('#newPlaceholder').on('click', addLocation);

        // addTestMarker();

        getAllPlaces(updateMarkers);
        // markers = allMarkers;
        // updateMarkers();

    };

    init();

    console.log('not good!');
});<commit_msg>random commit<commit_after>/* global $, google */

$(function () {
    var MARKER_ICON_GREEN = 'img/icon-pin-green.png';
    var MARKER_ICON_YELLOW = 'img/icon-pin-yellow-copy.png';
    var MARKER_ICON_RED = 'img/icon-yellow-copy-2.png';
    var LOCATION_ICON = 'img/icon-location.png';
    var API_URL = 'http://cdcf7843.ngrok.io'; //without final '/'

    var map;
    var geocoder;
    var markers;
    var _gmarkers;
    var areMarkersHidden = false;

    window._removeAll = function() {
        console.log('Removing all entries in 5 seconds...');

        setTimeout(function() {
            $.ajax({
                url: API_URL + '/local',
                type: 'DELETE'
            }).done(function(data) {
                console.log(data);
            });
        }, 5000)
    }

    window._sendAllMarkersToBackend = function() {
        console.log('Sending ALL ' + allMarkers.length + ' places.');

        allMarkers.forEach(function(m){
            $.post(API_URL + '/local', m);
        })
    }

    function postPlace(place, callback) {
        console.log('Sending new place:');
        console.log(place);

        $.post(
            API_URL + '/local',
            place,
            function(data) {
                if (callback) {
                    console.log('Addition success');
                    callback();
                }
            }
        );
    }

    function getAllPlaces(successCB, failCB, alwaysCB) {
        console.log('Getting all places...');

        $.ajax({
            url: API_URL + '/local'
        }).done(function(data) {
            console.log('Successfully retrieved ' + data.length + ' places!');

            markers = data;

            // mock some stuff
            markers.forEach(function(m) {
                m.average = Math.floor(Math.random() * 5) + 1
            })

            if (successCB) {
                successCB();
            }
        })
        .fail(function() {
            if (failCB) {
                failCB();
            }
        })
        .always(function() {
            if (alwaysCB) {
                alwaysCB();
            }
        });
    }

    function openDetails(i) {
        console.log(markers[i].text);
        console.log(markers[i].structureType);
        console.log(markers[i].isPublic);
    }

    /**
     * The CenterControl adds a control to the map that recenters the map on Chicago.
     * This constructor takes the control DIV as an argument.
     * @constructor
     */
    function centerControl(controlDiv, map) {
        function _tryGeolocate() {
            if (navigator.geolocation) {
                navigator.geolocation.getCurrentPosition(function(position) {
                    var pos = {
                        lat: position.coords.latitude,
                        lng: position.coords.longitude
                    };

                    map.setCenter(pos);
                }, function() {
                    // handleLocationError(true, infoWindow, map.getCenter());
                });
            }
        }

        // Set CSS for the control border.
        var controlUI = document.createElement('div');
        controlUI.style.backgroundColor = '#fff';
        controlUI.style.border = '2px solid #fff';
        controlUI.style.borderRadius = '50%';
        // controlUI.style.boxShadow = '0 2px 6px rgba(0,0,0,.3)';
        controlUI.style.cursor = 'pointer';
        controlUI.style.margin = '0 20px 90px';
        controlUI.style.width = '38px';
        controlUI.style.height = '38px';
        controlUI.style.textAlign = 'center';
        controlUI.title = 'Clique para centralizar mapa';

        controlDiv.appendChild(controlUI);

        // Set CSS for the control interior.
        var controlText = document.createElement('div');
        controlText.style.color = '#30bb6a';
        controlText.style.fontSize = '20px';
        controlText.style.padding = '5px';
        controlText.innerHTML = '';
        controlUI.appendChild(controlText);

        // Setup the click event listeners: simply set the map to Chicago.
        controlUI.addEventListener('click', function() {
            _tryGeolocate();
        });

    }

    function addTestMarker() {
        // Add test marker
        var contentString = '
'+
        '
'+
        '
'+
        '
Uluru
'+
        '
'+
        '
Uluru, also referred to as Ayers Rock, is a large ' +
        'sandstone rock formation in the southern part of the '+
        'Northern Territory, central Australia. It lies 335 km (208 mi) '+
        'south west of the nearest large town, Alice Springs; 450 km '+
        '(280 mi) by road. Kata Tjuta and Uluru are the two major '+
        'features of the Uluru - Kata Tjuta National Park. Uluru is '+
        'sacred to the Pitjantjatjara and Yankunytjatjara, the '+
        'Aboriginal people of the area. It has many springs, waterholes, '+
        'rock caves and ancient paintings. Uluru is listed as a World '+
        'Heritage Site.
'+
        '
Attribution: Uluru, '+
        'https://en.wikipedia.org/w/index.php?title=Uluru '+
        '(last visited June 22, 2009).
'+
        '
'+
        '
';
        var infowindow = new google.maps.InfoWindow({
            content: contentString
        });
        var marker = new google.maps.Marker({
            position: {
                lat: -30.0458531,
                lng: -51.2295223
            },
            map: map,
            icon: MARKER_ICON_GREEN,
            // title: 'Uluru (Ayers Rock)'
        });
        marker.addListener('click', function() {
            infowindow.open(map, marker);
        });
    }

    function updateMarkers() {
        _gmarkers = [];

        // Markers from Database
        if (markers && markers.length > 0) {
            // markers.forEach(function(m) {
            for(var i=0; i<markers.length; i++) {

                var whichIcon;
                if (markers[i].average > 0 && markers[i].average < 2) {
                    whichIcon = MARKER_ICON_RED;
                } else if (markers[i].average >= 2 && markers[i].average < 3.5) {
                    whichIcon = MARKER_ICON_YELLOW;
                } else {
                    whichIcon = MARKER_ICON_GREEN;
                }

                _gmarkers[i] = new google.maps.Marker({
                    position: {
                        lat: Number.parseFloat(markers[i].lng),
                        lng: Number.parseFloat(markers[i].lat)
                    },
                    map: map,
                    icon: whichIcon,
                });

                // var content = '
'+
                // '
' + markers[i].text + '
' +
                // '
structureType: ' + markers[i].structureType + '
' +
                // '
isPublic: ' + markers[i].isPublic + '
' +
                // '
';
                // var infowindow = new google.maps.InfoWindow({
                //     content: content
                // });

                (function (markerIndex) {
                    _gmarkers[markerIndex].addListener('click', function() {
                        openDetails(markerIndex);
                    });
                }(i));
            }
            // });
        }
    }

    function searchLocation() {
        var address = $('#locationQueryInput').val();

        geocoder.geocode({'address': address}, function(results, status) {
            if (status === google.maps.GeocoderStatus.OK) {
                map.setCenter(results[0].geometry.location);

                // Set marker on located place
                // new google.maps.Marker({
                //     map: map,
                //     position: results[0].geometry.location
                // });
            } else {
                alert('Geocode was not successful for the following reason: ' + status);
            }
        });
    }

    // Sets the map on all markers in the array.
    function setMapOnAll(m) {
      for (var i = 0; i < _gmarkers.length; i++) {
        _gmarkers[i].setMap(m);
      }
    }

    // Removes the markers from the map, but keeps them in the array.
    function hideMarkers() {
        areMarkersHidden = true;
        setMapOnAll(null);
    }

    // Shows any markers currently in the array.
    function showMarkers() {
      areMarkersHidden = false;
      setMapOnAll(map);
    }

    // Deletes all markers in the array by removing references to them.
    function deleteMarkers() {
      clearMarkers();
      _gmarkers = [];
    }

    function toggleMarkers() {
        if (areMarkersHidden) {
            showMarkers();
        } else {
            hideMarkers();
        }
    }

    function addLocationModeToggle() {
        $('#addPlace').toggleClass('active')
        $('#newPlaceholder').toggle();
        toggleMarkers();
    }

    function addLocation() {
        console.log('add location');

        var mapCenter = map.getCenter();
        postPlace({
            lat: ''+mapCenter.lat(),
            lng: ''+mapCenter.lng(),
            isPublic: 'true',
            text: 'test'
        });

        updateMarkers();

        addLocationModeToggle();
    }

    var init = function () {
        map = new google.maps.Map(document.getElementById('map'), {
            center: {
                lat: -30.0458531,
                lng: -51.2295223},
            zoom: 16,
            disableDefaultUI: true,
            scaleControl: false,
        });

        geocoder = new google.maps.Geocoder();

        // Bike Layer
        var bikeLayer = new google.maps.BicyclingLayer();
        bikeLayer.setMap(map);

        // Geolocalization button
        if (navigator.geolocation) {
            var centerControlDiv = document.createElement('div');
            new centerControl(centerControlDiv, map);
            centerControlDiv.index = 1;
            map.controls[google.maps.ControlPosition.RIGHT_BOTTOM].push(centerControlDiv);
        }

        $('#locationQueryBtn').on('click', searchLocation);

        $('#addPlace').on('click', addLocationModeToggle);

        $('#newPlaceholder').on('click', addLocation);

        // addTestMarker();

        getAllPlaces(updateMarkers);
        // markers = allMarkers;
        // updateMarkers();

    };

    init();
});<|endoftext|>


<commit_before>(Phaser => {
  const GAME_WIDTH = 460;
  const GAME_HEIGHT = 600;
  const GAME_CONTAINER_ID = 'game';
  const GFX = 'gfx';
  const INITIAL_MOVESPEED = 4;
  const PLAYER_BULLET_SPEED = 6;
  const ENEMY_SPAWN_FREQ = 100; // higher is less frequent
  const ENEMY_SPEED = 4.5;
  let cursors;
  let player;
  let playerBullets;
  let enemies;
  let enemyBullets;

  const preload = _ => {
    game.load.spritesheet(GFX, 'assets/shmup-spritesheet-140x56-28x28-tile.png', 28, 28);
  };

  const handlePlayerFire = _ => {
    playerBullets.add( game.add.sprite(player.x, player.y, GFX, 7) );
  };

  const create = _ => {
    game.physics.startSystem(Phaser.Physics.ARCADE);

    cursors = game.input.keyboard.createCursorKeys();
    cursors.fire = game.input.keyboard.addKey(Phaser.KeyCode.SPACEBAR);
    cursors.fire.onUp.add( handlePlayerFire );

    player = game.add.sprite(100, 100, GFX, 8);
    player.moveSpeed = INITIAL_MOVESPEED;
    playerBullets = game.add.group();
    enemies = game.add.group();
    enemyBullets = game.add.group();
    enemyBullets.enableBody = true;
  };

  const gameOver = _ => {
    game.state.destroy();
    game.add.text(90, 200, 'YOUR HEAD ASPLODE', { fill: '#FFFFFF' });
    let playAgain = game.add.text(120, 300, 'Play Again', { fill: '#FFFFFF' });
    playAgain.inputEnabled = true;
    playAgain.events.onInputUp.add(_ => {
      window.location.reload();
    });
  };

  const handlePlayerMovement = _ => {
    let movingH = Math.sqrt(2);
    let movingV = Math.sqrt(2);
    if( cursors.up.isDown || cursors.down.isDown){
      movingH = 1; // slow down diagonal movement
    }
    if( cursors.left.isDown || cursors.right.isDown){
      movingV = 1; // slow down diagonal movement
    }
    switch( true ){
      case cursors.left.isDown:
        player.x -= player.moveSpeed * movingH;
        break;
      case cursors.right.isDown:
        player.x += player.moveSpeed * movingH;
        break;
    }
    switch( true ){
      case cursors.down.isDown:
        player.y += player.moveSpeed * movingV;
        break;
      case cursors.up.isDown:
        player.y -= player.moveSpeed * movingV;
        break;
    }
  };

  const handlePlayerHit = _ => {
    gameOver();
  };

  const handleBulletAnimations = _ => {
    playerBullets.children.forEach( bullet => bullet.y -= PLAYER_BULLET_SPEED );
  };

  const handleEnemyActions = _ => {
    enemies.children.forEach( enemy => enemy.y += ENEMY_SPEED );
  };

  const randomlySpawnEnemy = _ => {
    if( Math.floor(Math.random()*ENEMY_SPAWN_FREQ) === 0 ){
      let randomX = Math.floor( Math.random()*GAME_WIDTH );
      enemies.add( game.add.sprite(randomX, -24, GFX, 0) );
    }
  };

  const removeBullet = bullet => bullet.destroy();

  const destroyEnemy = enemy => enemy.kill();

  const handleCollisions = _ => {
    // check if any bullets touch any enemies
    let enemiesHit = enemies.children
      .filter( enemy => enemy.alive )
      .filter( enemy => enemy.overlap(playerBullets) );

    if( enemiesHit.length > 0 ){
      // clean up bullets that land
      playerBullets.children
        .filter( bullet => bullet.overlap(enemies) )
        .forEach( removeBullet );

      enemiesHit.forEach( destroyEnemy );
    }

    // check if enemies hit the player
    enemiesHit = enemies.children
      .filter( enemy => enemy.overlap(player) );

    if( enemiesHit.length > 0 ){
      handlePlayerHit();

      enemiesHit.forEach( destroyEnemy );
    }
  };

  const cleanup = _ => {
    playerBullets.children
      .filter( bullet => bullet.y < 0 )
      .forEach( bullet => bullet.destroy() );
    enemies.children
      .filter( enemy => enemy.y > GAME_HEIGHT || !enemy.alive )
      .forEach( enemy => enemy.destroy() );
  };

  const update = _ => {
    handlePlayerMovement();
    handleBulletAnimations();
    handleEnemyActions();
    handleCollisions();
    randomlySpawnEnemy();

    cleanup();
  };

  const game = new Phaser.Game(GAME_WIDTH, GAME_HEIGHT, Phaser.AUTO, GAME_CONTAINER_ID, { preload, create, update });

})(window.Phaser);
<commit_msg>implement random enemy fire<commit_after>(Phaser => {
  const GAME_WIDTH = 460;
  const GAME_HEIGHT = 600;
  const GAME_CONTAINER_ID = 'game';
  const GFX = 'gfx';
  const INITIAL_MOVESPEED = 4;
  const PLAYER_BULLET_SPEED = 6;
  const ENEMY_SPAWN_FREQ = 100; // higher is less frequent
  const ENEMY_SPEED = 4.5;
  const ENEMY_FIRE_FREQ = 30; // higher is less frequent
  let cursors;
  let player;
  let playerBullets;
  let enemies;
  let enemyBullets;

  const preload = _ => {
    game.load.spritesheet(GFX, 'assets/shmup-spritesheet-140x56-28x28-tile.png', 28, 28);
  };

  const handlePlayerFire = _ => {
    playerBullets.add( game.add.sprite(player.x, player.y, GFX, 7) );
  };

  const create = _ => {
    game.physics.startSystem(Phaser.Physics.ARCADE);

    cursors = game.input.keyboard.createCursorKeys();
    cursors.fire = game.input.keyboard.addKey(Phaser.KeyCode.SPACEBAR);
    cursors.fire.onUp.add( handlePlayerFire );

    player = game.add.sprite(100, 100, GFX, 8);
    player.moveSpeed = INITIAL_MOVESPEED;
    playerBullets = game.add.group();
    enemies = game.add.group();
    enemyBullets = game.add.group();
    enemyBullets.enableBody = true;
  };

  const gameOver = _ => {
    game.state.destroy();
    game.add.text(90, 200, 'YOUR HEAD ASPLODE', { fill: '#FFFFFF' });
    let playAgain = game.add.text(120, 300, 'Play Again', { fill: '#FFFFFF' });
    playAgain.inputEnabled = true;
    playAgain.events.onInputUp.add(_ => {
      window.location.reload();
    });
  };

  const handlePlayerMovement = _ => {
    let movingH = Math.sqrt(2);
    let movingV = Math.sqrt(2);
    if( cursors.up.isDown || cursors.down.isDown){
      movingH = 1; // slow down diagonal movement
    }
    if( cursors.left.isDown || cursors.right.isDown){
      movingV = 1; // slow down diagonal movement
    }
    switch( true ){
      case cursors.left.isDown:
        player.x -= player.moveSpeed * movingH;
        break;
      case cursors.right.isDown:
        player.x += player.moveSpeed * movingH;
        break;
    }
    switch( true ){
      case cursors.down.isDown:
        player.y += player.moveSpeed * movingV;
        break;
      case cursors.up.isDown:
        player.y -= player.moveSpeed * movingV;
        break;
    }
  };

  const handlePlayerHit = _ => {
    gameOver();
  };

  const handleBulletAnimations = _ => {
    playerBullets.children.forEach( bullet => bullet.y -= PLAYER_BULLET_SPEED );
  };

  const randomEnemyFire = enemy => {
    if( Math.floor(Math.random()*ENEMY_FIRE_FREQ) === 0 ){
      let enemyBullet = game.add.sprite(enemy.x, enemy.y, GFX, 9);
      enemyBullet.checkWorldBounds = true;
      enemyBullet.outOfBoundsKill = true;
      enemyBullets.add( enemyBullet );
    }
  };

  const handleEnemyActions = _ => {
    enemies.children.forEach( enemy => enemy.y += ENEMY_SPEED );
    enemies.children.forEach( enemy => randomEnemyFire(enemy) );
  };

  const randomlySpawnEnemy = _ => {
    if( Math.floor(Math.random()*ENEMY_SPAWN_FREQ) === 0 ){
      let randomX = Math.floor( Math.random()*GAME_WIDTH );
      enemies.add( game.add.sprite(randomX, -24, GFX, 0) );
    }
  };

  const removeBullet = bullet => bullet.destroy();

  const destroyEnemy = enemy => enemy.kill();

  const handleCollisions = _ => {
    // check if any bullets touch any enemies
    let enemiesHit = enemies.children
      .filter( enemy => enemy.alive )
      .filter( enemy => enemy.overlap(playerBullets) );

    if( enemiesHit.length > 0 ){
      // clean up bullets that land
      playerBullets.children
        .filter( bullet => bullet.overlap(enemies) )
        .forEach( removeBullet );

      enemiesHit.forEach( destroyEnemy );
    }

    // check if enemies hit the player
    enemiesHit = enemies.children
      .filter( enemy => enemy.overlap(player) );

    if( enemiesHit.length > 0 ){
      handlePlayerHit();

      enemiesHit.forEach( destroyEnemy );
    }
  };

  const cleanup = _ => {
    playerBullets.children
      .filter( bullet => bullet.y < 0 )
      .forEach( bullet => bullet.destroy() );
    enemies.children
      .filter( enemy => enemy.y > GAME_HEIGHT || !enemy.alive )
      .forEach( enemy => enemy.destroy() );
  };

  const update = _ => {
    handlePlayerMovement();
    handleBulletAnimations();
    handleEnemyActions();
    handleCollisions();
    randomlySpawnEnemy();

    cleanup();
  };

  const game = new Phaser.Game(GAME_WIDTH, GAME_HEIGHT, Phaser.AUTO, GAME_CONTAINER_ID, { preload, create, update });

})(window.Phaser);
<|endoftext|>


<commit_before>var http = require('http'),
    https = require('https'),
    fs = require('fs'),
    path = require('path'),
    zlib = require('zlib'),
    tar = require('tar'),
    url = require('url'),
    prompt = require('prompt'),
    open = require('open'),
    bitballoon = require('./bitballoon'),
    auth = require('./auth'),
    api = require('./api');

var supportedTemplates = {
  angular: {
    url: 'https://codeload.github.com/firebase/angularFire-seed/' +
              'legacy.tar.gz/master',
    settings: {
      'public': 'app',
      'rules': 'config/security-rules.json',
    },
    config: 'app/js/config.js',
    configRegex: /https:\/\/INSTANCE\.firebaseio\.com/,
    completedMessage: 'BOOTSTRAPPING SUCCESSFUL'.green + ' - Instructions and' +
                        ' setup guide here: ' +
                        'https://github.com/firebase/angularFire-seed'.cyan
  }
};

var defaultSettings = {
  'public': '.'
}

module.exports = {
  init: function(argv) {
    auth.requireLogin(function(err) {
      if (err) {
        console.log('LOGIN ERROR'.red);
        process.exit(1);
      }
      auth.getFirebases(function(err, firebases) {
        if (err) {
          console.log('INITIALIZATION ERROR'.red);
          process.exit(1);
        }
        var settingsFile = path.resolve('./firebase.json');
        if (fs.existsSync(settingsFile)) {
          console.log('INITIALIZATION ERROR'.red + ' - Directory alread ' +
                        'initialized');
          process.exit(1);
        }
        if (firebases.length == 0) {
          console.log('NO FIREBASES'.red + ' - You need to create a Firebase ' +
                        'to initialize the app with at https://firebase.com');
          process.exit(1);
        }
        // Firebase names always a subset of ^[0-9a-z-]*$ so safe to regex
        var pattern = new RegExp('^(' + firebases.join('|') + ')$');
        if (!argv.firebase ||
            (typeof(argv.firebase) !== 'string') ||
            !argv.firebase.match(pattern)) {
          console.log('---------- YOUR FIREBASES ----------\n'.green +
                      firebases.join('\n') +
                      '\n------------------------------------'.green);
        }
        var schema = {
              properties: {
                firebase: {
                  required: true,
                  pattern: pattern,
                  description: 'Firebase:',
                  type: 'string'
                },
                'public': {
                  required: true,
                  description: 'Public Directory:',
                  default: defaultSettings['public'],
                  type: 'string'
                },
                rules: {
                  description: 'Security Rules File: (none)',
                  type: 'string'
                }
              }
            };
        prompt.get(schema, function(err, result) {
          if (err) {
            console.log('USER INPUT ERROR'.red);
            process.exit(1);
          }
          if (path.relative('.', result['public']).match(/^\./)) {
            console.log('PUBLIC DIRECTORY ERROR'.red + ' - Public directory ' +
                                  'must be within current working directory');
            process.exit(1);
          }
          if (!fs.existsSync(result['public'])) {
            console.log('PUBLIC DIRECTORY ERROR'.red + ' - Public directory ' +
                                  'does not exist');
            process.exit(1);
          }
          var settings = {
            firebase: result.firebase,
            'public': result['public']
          };
          if (result.rules) {
            if (fs.existsSync(result.rules) &&
                fs.statSync(result.rules).isFile()) {
              settings.rules = result.rules;
            } else {
              console.log('INITIALIZATION ERROR'.red + ' - rules file does ' +
                                    'not exist');
              process.exit(1);
            }
          }
          console.log('Initializing app into current directory');
          auth.checkCanAccess(result.firebase, function(err) {
            if (err) {
              console.log('PERMISSION ERROR'.red + ' - You do not have ' +
                                    'permission to use this Firebase');
              process.exit(1);
            }
            console.log('Writing firebase.json settings file');
            var settingsJSON = JSON.stringify(settings, null, 2) + "\n";
            try {
              fs.writeFileSync(settingsFile, settingsJSON);
              console.log('SUCCESSFULLY INITIALIZED APP'.green);
            } catch (err) {
              console.log('INITIALIZATION ERROR'.red);
              process.exit(1);
            }
          });
        });
      });
    });
  },
  bootstrap: function(argv) {
    auth.requireLogin(function(err) {
      if (err) {
        console.log('LOGIN ERROR'.red);
        process.exit(1);
      }
      auth.getFirebases(function(err, firebases) {
        if (err) {
          console.log('INITIALIZATION ERROR'.red);
          process.exit(1);
        }
        if (firebases.length == 0) {
          console.log('NO FIREBASES'.red + ' - You need to create a Firebase ' +
                        'to bootstrap the app with at https://firebase.com');
          process.exit(1);
        }
        // Firebase names always a subset of ^[0-9a-z-]*$ so safe to regex
        var firebasePattern = new RegExp('^(' + firebases.join('|') + ')$');
        var templatePattern = new RegExp('^(' +
                          Object.keys(supportedTemplates).join('|') + ')$');
        if (!argv.firebase ||
            (typeof(argv.firebase) !== 'string') ||
            !argv.firebase.match(firebasePattern)) {
          console.log('---------- YOUR FIREBASES ----------\n'.green +
                      firebases.join('\n') +
                      '\n------------------------------------'.green);
        }
        var schema = {
              properties: {
                firebase: {
                  required: true,
                  pattern: firebasePattern,
                  description: 'Firebase:',
                  type: 'string'
                }
              }
            };
        prompt.get(schema, function(err, result) {
          if (err) {
            console.log('USER INPUT ERROR'.red);
            process.exit(1);
          }
          var firebase = result.firebase;
          if (!argv.template ||
              (typeof(argv.template) !== 'string') ||
              !argv.template.match(templatePattern)) {
            console.log('------- AVAILABLE TEMPLATES --------\n'.green +
                        Object.keys(supportedTemplates).join('\n') +
                        '\n------------------------------------'.green);
          }
          auth.checkCanAccess(firebase, function(err) {
            if (err) {
              console.log('PERMISSION ERROR'.red + ' - You do not have ' +
                                    'permission to use this Firebase');
              process.exit(1);
            }
            var schema = {
                  properties: {
                    template: {
                      required: true,
                      pattern: templatePattern,
                      description: 'Template:',
                      type: 'string'
                    }
                  }
                };
            prompt.get(schema, function(err, result) {
              if (err) {
                console.log('USER INPUT ERROR'.red);
                process.exit(1);
              }
              var dir = firebase;
              var projectDir = path.resolve(dir);
              if (fs.existsSync(projectDir)) {
                var i = 1;
                do {
                  dir = firebase + '_' + i++;
                  projectDir = path.resolve(dir);
                } while (fs.existsSync(projectDir));
              }
              console.log('Bootstrapping into directory \'' + dir + '\'');
              try {
                fs.mkdirSync(projectDir, '0755');
              } catch (err) {
                console.log('FILESYSTEM ERROR'.red + ' - Could not create new' +
                              ' directory');
                process.exit(1);
              }

              console.log('Downloading and unpacking template');
              var gunzip = zlib.createGunzip();
              var untar = tar.Extract({
                path: projectDir,
                strip: 1
              });
              var urlParts = url.parse(supportedTemplates[result.template].url);
              var protocol, port;
              if (urlParts.protocol === 'https:') {
                protocol = https;
                port = 443;
              } else {
                protocol = http;
                port = 80;
              }
              if (urlParts.port) {
                port = urlParts.port;
              }
              var request = protocol.get({
                host: urlParts.hostname,
                path: urlParts.pathname,
                port: port
              });
              request.on('response', function(response) {
                try {
                  response.pipe(gunzip).pipe(untar);
                } catch (err) {
                  console.log('DOWNLOAD ERROR'.red + ' - Could not download ' +
                                'template');
                  process.exit(1);
                }
                response.on('end', function() {
                  var config = path.join(
                                 projectDir,
                                 supportedTemplates[result.template].config
                               );
                  try {
                    var data = fs.readFileSync(config, 'utf8'),
                        realtimeHost = api.realtime.protocol + '//' +
                                        firebase + '.' +
                                        api.realtime.host;
                    if (api.realtime.port) {
                      realtimeHost += ':' + api.realtime.port;
                    }
                    var replaced = data.replace(
                                     supportedTemplates[result.template].configRegex,
                                     realtimeHost
                                   );
                    fs.writeFileSync(config, replaced);
                  } catch (err) {
                    console.log('INITIALIZATION ERROR'.red + ' - Couldn\'t ' +
                                  'update template with project settings');
                    process.exit(1);
                  }

                  console.log('Writing firebase.json settings file');
                  var publicPath = supportedTemplates[result.template]
                                  .settings['public'].replace(/\//g, path.sep),
                      rulesPath = supportedTemplates[result.template]
                                  .settings['rules'].replace(/\//g, path.sep);
                  var settings = {
                    'firebase': firebase,
                    'public': publicPath,
                    'rules': rulesPath
                  };
                  var settingsJSON = JSON.stringify(settings, null, 2) + "\n";
                  var settingsFile = path.join(projectDir, 'firebase.json');
                  try {
                    fs.writeFileSync(settingsFile, settingsJSON);
                  } catch (err) {
                    console.log('FILESYSTEM ERROR'.red + ' - Could not save ' +
                      'settings file');
                    process.exit(1);
                  }
                  console.log(supportedTemplates[result.template].completedMessage);
                });
              });
            });
          });
        });
      });
    });
  },
  deploy: function() {
    auth.requireLogin(function(err) {
      if (err) {
        console.log('LOGIN ERROR'.red);
        process.exit(1);
      }
      var settingsFile = path.resolve('./firebase.json');
      if (!fs.existsSync(settingsFile)) {
        console.log('INITIALIZATION ERROR'.red + ' - Directory not ' +
                      'initialized');
        process.exit(1);
      }
      try {
        var settingsJSON = fs.readFileSync(settingsFile),
            settings = JSON.parse(settingsJSON);
      } catch (err) {
        console.log('INITIALIZATION ERROR'.red +' - Could not read ' +
                          'firebase.json settings file');
        process.exit(1);
      }
      if (typeof(settings.firebase) !== 'string') {
        console.log('INITIALIZATION ERROR'.red +' - Could not read ' +
                          'firebase.json settings file');
        process.exit(1);
      }
      auth.checkCanAccess(settings.firebase, function(err, bbToken, bbSite) {
        if (err) {
          console.log('PERMISSION ERROR'.red + ' - You do not have ' +
                                'permission to use this Firebase');
          process.exit(1);
        }
        if (bbToken) {
          settings.bbToken = bbToken;
        }
        if (bbSite) {
          settings.bbSite = bbSite;
        }
        for (var i in defaultSettings) {
          if (defaultSettings.hasOwnProperty(i) &&
                !settings.hasOwnProperty(i)) {
            settings[i] = defaultSettings[i];
          }
        }
        if (path.relative('.', settings['public']).match(/^\./)) {
          console.log('PUBLIC DIRECTORY ERROR'.red + ' - public directory' +
                            ' must be within current working directory');
          process.exit(1);
        }
        if (!fs.existsSync(settings['public'])) {
          console.log('PUBLIC DIRECTORY ERROR'.red + ' - Public directory ' +
                                'does not exist');
          process.exit(1);
        }
        if (fs.readdirSync(settings['public']).length == 0) {
          console.log('PUBLIC DIRECTORY ERROR'.red + ' - Public directory ' +
                                'must not be empty');
          process.exit(1);
        }
        auth.updateRules(settings.firebase,
                         settings.rules,
                         function(statusCode, response) {
          if (response.error) {
            console.log('SECURITY RULES ERROR'.red + ' - ' +
                                response.error.replace(/\n$/, ''));
            process.exit(1);
          }
          console.log('Deploying...');
          bitballoon.deploy(settings, function(err, url) {
            if (err) {
              console.log('DEPLOY ERROR'.red + ' - Couldn\'t deploy app');
              process.exit(1);
            }
            console.log('DEPLOYED SUCCESSFULLY'.green + ' - View your app' +
                              ' at: ' + url.cyan);
            setTimeout(open, 1000, url);
          });
        });
      });
    });
  }
};
<commit_msg>better messaging and error output<commit_after>var http = require('http'),
    https = require('https'),
    fs = require('fs'),
    path = require('path'),
    zlib = require('zlib'),
    tar = require('tar'),
    url = require('url'),
    prompt = require('prompt'),
    open = require('open'),
    bitballoon = require('./bitballoon'),
    auth = require('./auth'),
    api = require('./api');

var supportedTemplates = {
  angular: {
    url: 'https://codeload.github.com/firebase/angularFire-seed/' +
              'legacy.tar.gz/master',
    settings: {
      'public': 'app',
      'rules': 'config/security-rules.json',
    },
    config: 'app/js/config.js',
    configRegex: /https:\/\/INSTANCE\.firebaseio\.com/,
    completedMessage: 'BOOTSTRAPPING SUCCESSFUL'.green + ' - Instructions and' +
                        ' setup guide here: ' +
                        'https://github.com/firebase/angularFire-seed'.cyan
  }
};

var defaultSettings = {
  'public': '.'
}

module.exports = {
  init: function(argv) {
    auth.requireLogin(function(err) {
      if (err) {
        console.log('LOGIN ERROR'.red);
        process.exit(1);
      }
      auth.getFirebases(function(err, firebases) {
        if (err) {
          console.log('INITIALIZATION ERROR'.red);
          process.exit(1);
        }
        var settingsFile = path.resolve('./firebase.json');
        if (fs.existsSync(settingsFile)) {
          console.log('INITIALIZATION ERROR'.red + ' - Directory alread ' +
                        'initialized');
          process.exit(1);
        }
        if (firebases.length == 0) {
          console.log('NO FIREBASES'.red + ' - You need to create a Firebase ' +
                        'to initialize the app with at https://firebase.com');
          process.exit(1);
        }
        // Firebase names always a subset of ^[0-9a-z-]*$ so safe to regex
        var pattern = new RegExp('^(' + firebases.join('|') + ')$');
        if (!argv.firebase ||
            (typeof(argv.firebase) !== 'string') ||
            !argv.firebase.match(pattern)) {
          console.log('Choose A Firebase\n' +
                      '---------- YOUR FIREBASES ----------\n'.green +
                      firebases.join('\n') +
                      '\n------------------------------------'.green);
        }
        var schema = {
              properties: {
                firebase: {
                  required: true,
                  pattern: pattern,
                  description: 'Firebase:',
                  type: 'string'
                },
                'public': {
                  required: true,
                  description: 'Public Directory:',
                  default: defaultSettings['public'],
                  type: 'string'
                },
                rules: {
                  description: 'Security Rules File: (none)',
                  type: 'string'
                }
              }
            };
        prompt.get(schema, function(err, result) {
          if (err) {
            console.log('USER INPUT ERROR'.red);
            process.exit(1);
          }
          if (path.relative('.', result['public']).match(/^\./)) {
            console.log('PUBLIC DIRECTORY ERROR'.red + ' - Public directory ' +
                                  'must be within current working directory');
            process.exit(1);
          }
          if (!fs.existsSync(result['public'])) {
            console.log('PUBLIC DIRECTORY ERROR'.red + ' - Public directory ' +
                                  'does not exist');
            process.exit(1);
          }
          var settings = {
            firebase: result.firebase,
            'public': result['public']
          };
          if (result.rules) {
            if (fs.existsSync(result.rules) &&
                fs.statSync(result.rules).isFile()) {
              settings.rules = result.rules;
            } else {
              console.log('INITIALIZATION ERROR'.red + ' - rules file does ' +
                                    'not exist');
              process.exit(1);
            }
          }
          console.log('Initializing app into current directory');
          auth.checkCanAccess(result.firebase, function(err) {
            if (err) {
              console.log('PERMISSION ERROR'.red + ' - You do not have ' +
                                    'permission to use this Firebase');
              process.exit(1);
            }
            console.log('Writing firebase.json settings file');
            var settingsJSON = JSON.stringify(settings, null, 2) + "\n";
            try {
              fs.writeFileSync(settingsFile, settingsJSON);
              console.log('SUCCESSFULLY INITIALIZED APP'.green);
            } catch (err) {
              console.log('INITIALIZATION ERROR'.red);
              process.exit(1);
            }
          });
        });
      });
    });
  },
  bootstrap: function(argv) {
    auth.requireLogin(function(err) {
      if (err) {
        console.log('LOGIN ERROR'.red);
        process.exit(1);
      }
      auth.getFirebases(function(err, firebases) {
        if (err) {
          console.log('INITIALIZATION ERROR'.red);
          process.exit(1);
        }
        if (firebases.length == 0) {
          console.log('NO FIREBASES'.red + ' - You need to create a Firebase ' +
                        'to bootstrap the app with at https://firebase.com');
          process.exit(1);
        }
        // Firebase names always a subset of ^[0-9a-z-]*$ so safe to regex
        var firebasePattern = new RegExp('^(' + firebases.join('|') + ')$');
        var templatePattern = new RegExp('^(' +
                          Object.keys(supportedTemplates).join('|') + ')$');
        if (!argv.firebase ||
            (typeof(argv.firebase) !== 'string') ||
            !argv.firebase.match(firebasePattern)) {
          console.log('Choose A Firebase\n' +
                      '---------- YOUR FIREBASES ----------\n'.green +
                      firebases.join('\n') +
                      '\n------------------------------------'.green);
        }
        var schema = {
              properties: {
                firebase: {
                  required: true,
                  pattern: firebasePattern,
                  description: 'Firebase:',
                  type: 'string'
                }
              }
            };
        prompt.get(schema, function(err, result) {
          if (err) {
            console.log('USER INPUT ERROR'.red);
            process.exit(1);
          }
          var firebase = result.firebase;
          if (!argv.template ||
              (typeof(argv.template) !== 'string') ||
              !argv.template.match(templatePattern)) {
            console.log('Choose A Template\n' +
                        '------- AVAILABLE TEMPLATES --------\n'.green +
                        Object.keys(supportedTemplates).join('\n') +
                        '\n------------------------------------'.green);
          }
          auth.checkCanAccess(firebase, function(err) {
            if (err) {
              console.log('PERMISSION ERROR'.red + ' - You do not have ' +
                                    'permission to use this Firebase');
              process.exit(1);
            }
            var schema = {
                  properties: {
                    template: {
                      required: true,
                      pattern: templatePattern,
                      description: 'Template:',
                      type: 'string'
                    }
                  }
                };
            prompt.get(schema, function(err, result) {
              if (err) {
                console.log('USER INPUT ERROR'.red);
                process.exit(1);
              }
              var dir = firebase;
              var projectDir = path.resolve(dir);
              if (fs.existsSync(projectDir)) {
                var i = 1;
                do {
                  dir = firebase + '_' + i++;
                  projectDir = path.resolve(dir);
                } while (fs.existsSync(projectDir));
              }
              console.log('Bootstrapping into directory \'' + dir + '\'');
              try {
                fs.mkdirSync(projectDir, '0755');
              } catch (err) {
                console.log('FILESYSTEM ERROR'.red + ' - Could not create new' +
                              ' directory');
                process.exit(1);
              }

              console.log('Downloading and unpacking template');
              var gunzip = zlib.createGunzip();
              var untar = tar.Extract({
                path: projectDir,
                strip: 1
              });
              var urlParts = url.parse(supportedTemplates[result.template].url);
              var protocol, port;
              if (urlParts.protocol === 'https:') {
                protocol = https;
                port = 443;
              } else {
                protocol = http;
                port = 80;
              }
              if (urlParts.port) {
                port = urlParts.port;
              }
              var request = protocol.get({
                host: urlParts.hostname,
                path: urlParts.pathname,
                port: port
              });
              request.on('response', function(response) {
                try {
                  response.pipe(gunzip).pipe(untar);
                } catch (err) {
                  console.log('DOWNLOAD ERROR'.red + ' - Could not download ' +
                                'template');
                  process.exit(1);
                }
                response.on('end', function() {
                  var config = path.join(
                                 projectDir,
                                 supportedTemplates[result.template].config
                               );
                  try {
                    var data = fs.readFileSync(config, 'utf8'),
                        realtimeHost = api.realtime.protocol + '//' +
                                        firebase + '.' +
                                        api.realtime.host;
                    if (api.realtime.port) {
                      realtimeHost += ':' + api.realtime.port;
                    }
                    var replaced = data.replace(
                                     supportedTemplates[result.template].configRegex,
                                     realtimeHost
                                   );
                    fs.writeFileSync(config, replaced);
                  } catch (err) {
                    console.log('INITIALIZATION ERROR'.red + ' - Couldn\'t ' +
                                  'update template with project settings');
                    process.exit(1);
                  }

                  console.log('Writing firebase.json settings file');
                  var publicPath = supportedTemplates[result.template]
                                  .settings['public'].replace(/\//g, path.sep),
                      rulesPath = supportedTemplates[result.template]
                                  .settings['rules'].replace(/\//g, path.sep);
                  var settings = {
                    'firebase': firebase,
                    'public': publicPath,
                    'rules': rulesPath
                  };
                  var settingsJSON = JSON.stringify(settings, null, 2) + "\n";
                  var settingsFile = path.join(projectDir, 'firebase.json');
                  try {
                    fs.writeFileSync(settingsFile, settingsJSON);
                  } catch (err) {
                    console.log('FILESYSTEM ERROR'.red + ' - Could not save ' +
                      'settings file');
                    process.exit(1);
                  }
                  console.log(supportedTemplates[result.template].completedMessage);
                });
              });
            });
          });
        });
      });
    });
  },
  deploy: function() {
    auth.requireLogin(function(err) {
      if (err) {
        console.log('LOGIN ERROR'.red);
        process.exit(1);
      }
      var settingsFile = path.resolve('./firebase.json');
      if (!fs.existsSync(settingsFile)) {
        console.log('INITIALIZATION ERROR'.red + ' - Directory not ' +
                      'initialized');
        process.exit(1);
      }
      try {
        var settingsJSON = fs.readFileSync(settingsFile),
            settings = JSON.parse(settingsJSON);
      } catch (err) {
        console.log('INITIALIZATION ERROR'.red +' - Could not read ' +
                          'firebase.json settings file');
        process.exit(1);
      }
      if (typeof(settings.firebase) !== 'string') {
        console.log('INITIALIZATION ERROR'.red +' - Could not read ' +
                          'firebase.json settings file');
        process.exit(1);
      }
      auth.checkCanAccess(settings.firebase, function(err, bbToken, bbSite) {
        if (err) {
          console.log('PERMISSION ERROR'.red + ' - You do not have ' +
                                'permission to use this Firebase');
          process.exit(1);
        }
        if (bbToken) {
          settings.bbToken = bbToken;
        }
        if (bbSite) {
          settings.bbSite = bbSite;
        }
        for (var i in defaultSettings) {
          if (defaultSettings.hasOwnProperty(i) &&
                !settings.hasOwnProperty(i)) {
            settings[i] = defaultSettings[i];
          }
        }
        if (path.relative('.', settings['public']).match(/^\./)) {
          console.log('PUBLIC DIRECTORY ERROR'.red + ' - public directory' +
                            ' must be within current working directory');
          process.exit(1);
        }
        if (!fs.existsSync(settings['public'])) {
          console.log('PUBLIC DIRECTORY ERROR'.red + ' - Public directory ' +
                                'does not exist');
          process.exit(1);
        }
        if (fs.readdirSync(settings['public']).length == 0) {
          console.log('PUBLIC DIRECTORY ERROR'.red + ' - Public directory ' +
                                'must not be empty');
          process.exit(1);
        }
        auth.updateRules(settings.firebase,
                         settings.rules,
                         function(statusCode, response) {
          if (response.error) {
            console.log('SECURITY RULES ERROR'.red + ' - ' +
                                response.error.replace(/\n$/, ''));
            process.exit(1);
          }
          console.log('Deploying...');
          bitballoon.deploy(settings, function(err, url) {
            if (err) {
              console.log('DEPLOY ERROR'.red + ' - Couldn\'t deploy app');
              console.log(err);
              process.exit(1);
            }
            console.log('DEPLOYED SUCCESSFULLY'.green + ' - View your app' +
                              ' at: ' + url.cyan);
            setTimeout(open, 1000, url);
          });
        });
      });
    });
  }
};
<|endoftext|>


<commit_before>var EnemyTank = function (x, y, peerId, game, player, bullets) {
    this.game = game;
    this.health = 3;
    this.player = player;
    this.bullets = bullets;
    this.fireRate = 1000;
    this.nextFire = 0;
    this.alive = true;

    this.shadow = game.add.sprite(x, y, 'enemy', 'shadow');
    this.tank = game.add.sprite(x, y, 'enemy', 'tank1');
    this.turret = game.add.sprite(x, y, 'enemy', 'turret');

    this.shadow.anchor.set(0.5);
    this.tank.anchor.set(0.5);
    this.turret.anchor.set(0.3, 0.5);

    this.tank.name = index.toString();
    game.physics.enable(this.tank, Phaser.Physics.ARCADE);
    this.tank.body.immovable = false;
    this.tank.body.collideWorldBounds = true;
    this.tank.body.bounce.setTo(1, 1);
};

EnemyTank.prototype.damage = function() {
    this.health -= 1;

    if (this.health <= 0)
    {
        this.alive = false;

        this.shadow.kill();
        this.tank.kill();
        this.turret.kill();

        return true;
    }

    return false;
}

EnemyTank.prototype.update = function() {
    this.shadow.x = this.tank.x;
    this.shadow.y = this.tank.y;
    this.shadow.rotation = this.tank.rotation;

    this.turret.x = this.tank.x;
    this.turret.y = this.tank.y;
};

var game = new Phaser.Game(window.innerWidth, window.innerHeight, Phaser.AUTO, 'tanks', { preload: preload, create: create, update: update, render: render });

var host = 'localhost';
var port = 9000;
var peers = {};
var peer;
var myPeerId;

function preload () {

    peer = new Peer({host: host, port: 9000, path: '/tanks'});
    peer.on('open', function(id) {
      myPeerId = id;
    });
    connectToExistingPlayers();

    peer.on('connection', function(conn) {
        conn.on('data', function (data) {
            // use this to add enemies
            // enemies.push(new EnemyTank(x, y, peerId, game, tank, enemyBullets));
            var type = MESSAGE_TYPE[data.type];
            if (!type) {
                console.err('unrecognised message: ' + data);
                return;
            }
            handle(type, data);
        });
        conn.on('close', function () {
            console.log('connection closed');
        });
    });

    game.load.atlas('tank', 'assets/tanks.png', 'assets/tanks.json');
    game.load.atlas('enemy', 'assets/enemy-tanks.png', 'assets/tanks.json');
    game.load.image('logo', 'assets/logo.png');
    game.load.image('bullet', 'assets/bullet.png');
    game.load.image('earth', 'assets/scorched_earth.png');
    game.load.spritesheet('kaboom', 'assets/explosion.png', 64, 64, 23);

}

function connectToExistingPlayers () {
    $.getJSON(window.location.protocol + '//' + host + ':' + port + '/tanks/peerjs/peers', function (ps) {
        _.each(ps, function (p) {
            peers[p] = peer.connect(p);
            console.log('connecting to peer ' + p);
        });
        broadcastHello();
    });
}

var land;

var shadow;
var tank;
var turret;

var enemies = [];
var enemyBullets;
var enemiesTotal = 0;
var enemiesAlive = 0;
var explosions;

var logo;

var currentSpeed = 0;
var cursors;

var bullets;
var fireRate = 100;
var nextFire = 0;

function create () {

    //  Resize our game world to be a 2000 x 2000 square
    game.world.setBounds(-1000, -1000, 2000, 2000);

    //  Our tiled scrolling background
    land = game.add.tileSprite(0, 0, game.width, game.height, 'earth');
    land.fixedToCamera = true;

    //  The base of our tank
    tank = game.add.sprite(0, 0, 'tank', 'tank1');
    tank.anchor.setTo(0.5, 0.5);
    tank.animations.add('move', ['tank1', 'tank2', 'tank3', 'tank4', 'tank5', 'tank6'], 20, true);

    //  This will force it to decelerate and limit its speed
    game.physics.enable(tank, Phaser.Physics.ARCADE);
    tank.body.drag.set(0.2);
    tank.body.maxVelocity.setTo(400, 400);
    tank.body.collideWorldBounds = true;

    //  Finally the turret that we place on-top of the tank body
    turret = game.add.sprite(0, 0, 'tank', 'turret');
    turret.anchor.setTo(0.3, 0.5);

    //  The enemies bullet group
    enemyBullets = game.add.group();
    enemyBullets.enableBody = true;
    enemyBullets.physicsBodyType = Phaser.Physics.ARCADE;
    enemyBullets.createMultiple(100, 'bullet');

    enemyBullets.setAll('anchor.x', 0.5);
    enemyBullets.setAll('anchor.y', 0.5);
    enemyBullets.setAll('outOfBoundsKill', true);
    enemyBullets.setAll('checkWorldBounds', true);

    //  A shadow below our tank
    shadow = game.add.sprite(0, 0, 'tank', 'shadow');
    shadow.anchor.setTo(0.5, 0.5);

    //  Our bullet group
    bullets = game.add.group();
    bullets.enableBody = true;
    bullets.physicsBodyType = Phaser.Physics.ARCADE;
    bullets.createMultiple(30, 'bullet', 0, false);
    bullets.setAll('anchor.x', 0.5);
    bullets.setAll('anchor.y', 0.5);
    bullets.setAll('outOfBoundsKill', true);
    bullets.setAll('checkWorldBounds', true);

    //  Explosion pool
    explosions = game.add.group();

    for (var i = 0; i < 10; i++)
    {
        var explosionAnimation = explosions.create(0, 0, 'kaboom', [0], false);
        explosionAnimation.anchor.setTo(0.5, 0.5);
        explosionAnimation.animations.add('kaboom');
    }

    tank.bringToTop();
    turret.bringToTop();

    logo = game.add.sprite((game.width - 800) / 2, 200, 'logo');
    logo.fixedToCamera = true;

    game.input.onDown.add(removeLogo, this);

    game.camera.follow(tank);
    game.camera.deadzone = new Phaser.Rectangle(150, 150, 500, 300);
    game.camera.focusOnXY(0, 0);

    cursors = game.input.keyboard.createCursorKeys();

}

function removeLogo () {

    game.input.onDown.remove(removeLogo, this);
    logo.kill();

}

var MESSAGE_TYPE = {
    HELLO: 'h',
    POSITION: 'p'
};

function broadcast(messageType, data) {
    _.each(peers, function(peer) {
        peer.send(_.extend(data, {
            id: myPeerId,
            type: messageType
        }));
    });
}

function broadcastPosition () {
    broadcast(MESSAGE_TYPE.POSITION, { x: this.tank.x, y: this.tank.y });
}

function broadcastHello () {
    broadcast(MESSAGE_TYPE.HELLO);
}

// opposite of broadcast
function handle(messageType, data) {
    if (messageType === MESSAGE_TYPE.HELLO) {
        handleHello(data);
    }
    else if (messageType === MESSAGE_TYPE.POSITION) {
        handlePosition(data);
    }
}

function handleHello (data) {
    console.log('hello from: ' + data.id);
}

function handlePosition (data) {
    console.log('position from: ' + data.id);
}

function update () {

    game.physics.arcade.overlap(enemyBullets, tank, bulletHitPlayer, null, this);

    enemiesAlive = 0;

    for (var i = 0; i < enemies.length; i++)
    {
        if (enemies[i].alive)
        {
            enemiesAlive++;
            enemies[i].update();
        }
    }

    if (cursors.left.isDown)
    {
        tank.angle -= 4;
    }
    else if (cursors.right.isDown)
    {
        tank.angle += 4;
    }

    if (cursors.up.isDown)
    {
        //  The speed we'll travel at
        currentSpeed = 300;
    }
    else
    {
        if (currentSpeed > 0)
        {
            currentSpeed -= 4;
        }
    }

    if (currentSpeed > 0)
    {
        game.physics.arcade.velocityFromRotation(tank.rotation, currentSpeed, tank.body.velocity);
    }

    land.tilePosition.x = -game.camera.x;
    land.tilePosition.y = -game.camera.y;

    //  Position all the parts and align rotations
    shadow.x = tank.x;
    shadow.y = tank.y;
    shadow.rotation = tank.rotation;

    turret.x = tank.x;
    turret.y = tank.y;

    turret.rotation = game.physics.arcade.angleToPointer(turret);

    if (game.input.activePointer.isDown)
    {
        //  Boom!
        fire();
    }

    broadcastPosition ();

}

function bulletHitPlayer (tank, bullet) {

    bullet.kill();

}

// function bulletHitEnemy (tank, bullet) {

//     bullet.kill();

//     var destroyed = enemies[tank.name].damage();

//     if (destroyed)
//     {
//         var explosionAnimation = explosions.getFirstExists(false);
//         explosionAnimation.reset(tank.x, tank.y);
//         explosionAnimation.play('kaboom', 30, false, true);
//     }

// }

function fire () {

    if (game.time.now > nextFire && bullets.countDead() > 0)
    {
        nextFire = game.time.now + fireRate;

        var bullet = bullets.getFirstExists(false);

        bullet.reset(turret.x, turret.y);

        bullet.rotation = game.physics.arcade.moveToPointer(bullet, 1000, game.input.activePointer, 500);
    }

}

function render () {

    // game.debug.text('Active Bullets: ' + bullets.countLiving() + ' / ' + bullets.length, 32, 32);
    game.debug.text('Enemies: ' + enemiesAlive + ' / ' + enemiesTotal, 32, 32);

}
<commit_msg>updated to use azure<commit_after>var EnemyTank = function (x, y, peerId, game, player, bullets) {
    this.game = game;
    this.health = 3;
    this.player = player;
    this.bullets = bullets;
    this.fireRate = 1000;
    this.nextFire = 0;
    this.alive = true;

    this.shadow = game.add.sprite(x, y, 'enemy', 'shadow');
    this.tank = game.add.sprite(x, y, 'enemy', 'tank1');
    this.turret = game.add.sprite(x, y, 'enemy', 'turret');

    this.shadow.anchor.set(0.5);
    this.tank.anchor.set(0.5);
    this.turret.anchor.set(0.3, 0.5);

    this.tank.name = index.toString();
    game.physics.enable(this.tank, Phaser.Physics.ARCADE);
    this.tank.body.immovable = false;
    this.tank.body.collideWorldBounds = true;
    this.tank.body.bounce.setTo(1, 1);
};

EnemyTank.prototype.damage = function() {
    this.health -= 1;

    if (this.health <= 0)
    {
        this.alive = false;

        this.shadow.kill();
        this.tank.kill();
        this.turret.kill();

        return true;
    }

    return false;
}

EnemyTank.prototype.update = function() {
    this.shadow.x = this.tank.x;
    this.shadow.y = this.tank.y;
    this.shadow.rotation = this.tank.rotation;

    this.turret.x = this.tank.x;
    this.turret.y = this.tank.y;
};

var game = new Phaser.Game(window.innerWidth, window.innerHeight, Phaser.AUTO, 'tanks', { preload: preload, create: create, update: update, render: render });

var host = 'tanks.azurewebsites.net';
var port = 80;
var peers = {};
var peer;
var myPeerId;

function preload () {

    peer = new Peer({host: host, port: port, path: '/tanks'});
    peer.on('open', function(id) {
      myPeerId = id;
    });
    connectToExistingPlayers();

    peer.on('connection', function(conn) {
        conn.on('data', function (data) {
            // use this to add enemies
            // enemies.push(new EnemyTank(x, y, peerId, game, tank, enemyBullets));
            var type = MESSAGE_TYPE[data.type];
            if (!type) {
                console.err('unrecognised message: ' + data);
                return;
            }
            handle(type, data);
        });
        conn.on('close', function () {
            console.log('connection closed');
        });
    });

    game.load.atlas('tank', 'assets/tanks.png', 'assets/tanks.json');
    game.load.atlas('enemy', 'assets/enemy-tanks.png', 'assets/tanks.json');
    game.load.image('logo', 'assets/logo.png');
    game.load.image('bullet', 'assets/bullet.png');
    game.load.image('earth', 'assets/scorched_earth.png');
    game.load.spritesheet('kaboom', 'assets/explosion.png', 64, 64, 23);

}

function connectToExistingPlayers () {
    $.getJSON(window.location.protocol + '//' + host + ':' + port + '/tanks/peerjs/peers', function (ps) {
        _.each(ps, function (p) {
            peers[p] = peer.connect(p);
            console.log('connecting to peer ' + p);
        });
        broadcastHello();
    });
}

var land;

var shadow;
var tank;
var turret;

var enemies = [];
var enemyBullets;
var enemiesTotal = 0;
var enemiesAlive = 0;
var explosions;

var logo;

var currentSpeed = 0;
var cursors;

var bullets;
var fireRate = 100;
var nextFire = 0;

function create () {

    //  Resize our game world to be a 2000 x 2000 square
    game.world.setBounds(-1000, -1000, 2000, 2000);

    //  Our tiled scrolling background
    land = game.add.tileSprite(0, 0, game.width, game.height, 'earth');
    land.fixedToCamera = true;

    //  The base of our tank
    tank = game.add.sprite(0, 0, 'tank', 'tank1');
    tank.anchor.setTo(0.5, 0.5);
    tank.animations.add('move', ['tank1', 'tank2', 'tank3', 'tank4', 'tank5', 'tank6'], 20, true);

    //  This will force it to decelerate and limit its speed
    game.physics.enable(tank, Phaser.Physics.ARCADE);
    tank.body.drag.set(0.2);
    tank.body.maxVelocity.setTo(400, 400);
    tank.body.collideWorldBounds = true;

    //  Finally the turret that we place on-top of the tank body
    turret = game.add.sprite(0, 0, 'tank', 'turret');
    turret.anchor.setTo(0.3, 0.5);

    //  The enemies bullet group
    enemyBullets = game.add.group();
    enemyBullets.enableBody = true;
    enemyBullets.physicsBodyType = Phaser.Physics.ARCADE;
    enemyBullets.createMultiple(100, 'bullet');

    enemyBullets.setAll('anchor.x', 0.5);
    enemyBullets.setAll('anchor.y', 0.5);
    enemyBullets.setAll('outOfBoundsKill', true);
    enemyBullets.setAll('checkWorldBounds', true);

    //  A shadow below our tank
    shadow = game.add.sprite(0, 0, 'tank', 'shadow');
    shadow.anchor.setTo(0.5, 0.5);

    //  Our bullet group
    bullets = game.add.group();
    bullets.enableBody = true;
    bullets.physicsBodyType = Phaser.Physics.ARCADE;
    bullets.createMultiple(30, 'bullet', 0, false);
    bullets.setAll('anchor.x', 0.5);
    bullets.setAll('anchor.y', 0.5);
    bullets.setAll('outOfBoundsKill', true);
    bullets.setAll('checkWorldBounds', true);

    //  Explosion pool
    explosions = game.add.group();

    for (var i = 0; i < 10; i++)
    {
        var explosionAnimation = explosions.create(0, 0, 'kaboom', [0], false);
        explosionAnimation.anchor.setTo(0.5, 0.5);
        explosionAnimation.animations.add('kaboom');
    }

    tank.bringToTop();
    turret.bringToTop();

    logo = game.add.sprite((game.width - 800) / 2, 200, 'logo');
    logo.fixedToCamera = true;

    game.input.onDown.add(removeLogo, this);

    game.camera.follow(tank);
    game.camera.deadzone = new Phaser.Rectangle(150, 150, 500, 300);
    game.camera.focusOnXY(0, 0);

    cursors = game.input.keyboard.createCursorKeys();

}

function removeLogo () {

    game.input.onDown.remove(removeLogo, this);
    logo.kill();

}

var MESSAGE_TYPE = {
    HELLO: 'h',
    POSITION: 'p'
};

function broadcast(messageType, data) {
    _.each(peers, function(peer) {
        peer.send(_.extend(data, {
            id: myPeerId,
            type: messageType
        }));
    });
}

function broadcastPosition () {
    broadcast(MESSAGE_TYPE.POSITION, { x: this.tank.x, y: this.tank.y });
}

function broadcastHello () {
    broadcast(MESSAGE_TYPE.HELLO);
}

// opposite of broadcast
function handle(messageType, data) {
    if (messageType === MESSAGE_TYPE.HELLO) {
        handleHello(data);
    }
    else if (messageType === MESSAGE_TYPE.POSITION) {
        handlePosition(data);
    }
}

function handleHello (data) {
    console.log('hello from: ' + data.id);
}

function handlePosition (data) {
    console.log('position from: ' + data.id);
}

function update () {

    game.physics.arcade.overlap(enemyBullets, tank, bulletHitPlayer, null, this);

    enemiesAlive = 0;

    for (var i = 0; i < enemies.length; i++)
    {
        if (enemies[i].alive)
        {
            enemiesAlive++;
            enemies[i].update();
        }
    }

    if (cursors.left.isDown)
    {
        tank.angle -= 4;
    }
    else if (cursors.right.isDown)
    {
        tank.angle += 4;
    }

    if (cursors.up.isDown)
    {
        //  The speed we'll travel at
        currentSpeed = 300;
    }
    else
    {
        if (currentSpeed > 0)
        {
            currentSpeed -= 4;
        }
    }

    if (currentSpeed > 0)
    {
        game.physics.arcade.velocityFromRotation(tank.rotation, currentSpeed, tank.body.velocity);
    }

    land.tilePosition.x = -game.camera.x;
    land.tilePosition.y = -game.camera.y;

    //  Position all the parts and align rotations
    shadow.x = tank.x;
    shadow.y = tank.y;
    shadow.rotation = tank.rotation;

    turret.x = tank.x;
    turret.y = tank.y;

    turret.rotation = game.physics.arcade.angleToPointer(turret);

    if (game.input.activePointer.isDown)
    {
        //  Boom!
        fire();
    }

    broadcastPosition ();

}

function bulletHitPlayer (tank, bullet) {

    bullet.kill();

}

// function bulletHitEnemy (tank, bullet) {

//     bullet.kill();

//     var destroyed = enemies[tank.name].damage();

//     if (destroyed)
//     {
//         var explosionAnimation = explosions.getFirstExists(false);
//         explosionAnimation.reset(tank.x, tank.y);
//         explosionAnimation.play('kaboom', 30, false, true);
//     }

// }

function fire () {

    if (game.time.now > nextFire && bullets.countDead() > 0)
    {
        nextFire = game.time.now + fireRate;

        var bullet = bullets.getFirstExists(false);

        bullet.reset(turret.x, turret.y);

        bullet.rotation = game.physics.arcade.moveToPointer(bullet, 1000, game.input.activePointer, 500);
    }

}

function render () {

    // game.debug.text('Active Bullets: ' + bullets.countLiving() + ' / ' + bullets.length, 32, 32);
    game.debug.text('Enemies: ' + enemiesAlive + ' / ' + enemiesTotal, 32, 32);

}
<|endoftext|>


<commit_before>'use strict';
var app = function (options) {
  var express = require('express'),
      app = express(),
      logger = require('./logger')(options.silent),
      Controllers = require('./controllers'),
      controllers = new Controllers(options.directory, logger, options.indexDocument, options.errorDocument, options.fs),
      concat = require('concat-stream'),
      path = require('path'),
      https = require('https');

  /**
   * Log all requests
   */
  app.use(require('morgan')('tiny', {
    'stream': {
      write: function (message) {
        logger.info(message.slice(0, -1));
      }
    }
  }));

  app.use(function (req, res, next) {
    req.pipe(concat(function (data) {
      req.body = data;
      next();
    }));
  });

  app.use(function (req, res, next) {
    var host = req.headers.host.split(':')[0];

    if (options.indexDocument && host !== 'localhost' && host !== '127.0.0.1') {
      req.url = path.join('/', host, req.url);
    }

    if (options.cors) {
      if (req.method === 'OPTIONS') {
        if (req.headers['access-control-request-headers'])
          res.header('Access-Control-Allow-Headers', req.headers['access-control-request-headers']);
        if (req.headers['access-control-request-method'])
          res.header('Access-Control-Allow-Methods', req.headers['access-control-request-method']);
      }
      if (req.headers.origin)
        res.header('Access-Control-Allow-Origin', '*');
    }

    next();
  });

  app.disable('x-powered-by');

  /**
   * Routes for the application
   */
  app.get('/', controllers.getBuckets);
  app.get('/:bucket', controllers.bucketExists, controllers.getBucket);
  app.delete('/:bucket', controllers.bucketExists, controllers.deleteBucket);
  app.put('/:bucket', controllers.putBucket);
  app.put('/:bucket/:key(*)', controllers.bucketExists, controllers.putObject);
  app.get('/:bucket/:key(*)', controllers.bucketExists, controllers.getObject);
  app.head('/:bucket/:key(*)', controllers.getObject);
  app.delete('/:bucket/:key(*)', controllers.bucketExists, controllers.deleteObject);
  app.post('/:bucket', controllers.bucketExists, controllers.genericPost);

  return {
    serve: function (done) {
      var server = ((options.key && options.cert) || options.pfx) ? https.createServer(options, app) : app;
      return server.listen(options.port, options.hostname, function (err) {
        return done(err, options.hostname, options.port, options.directory);
      }).on('error', function (err) {
        return done(err);
      });
    }
  };
};

module.exports = app;
<commit_msg>Allow mounting of the server as an express app<commit_after>'use strict';

module.exports = function (options) {
  var express = require('express'),
      app = express(),
      logger = require('./logger')(options.silent),
      Controllers = require('./controllers'),
      controllers = new Controllers(options.directory, logger, options.indexDocument, options.errorDocument, options.fs),
      concat = require('concat-stream'),
      path = require('path'),
      https = require('https');

  /**
   * Log all requests
   */
  app.use(require('morgan')('tiny', {
    'stream': {
      write: function (message) {
        logger.info(message.slice(0, -1));
      }
    }
  }));

  app.use(function (req, res, next) {
    req.pipe(concat(function (data) {
      req.body = data;
      next();
    }));
  });

  app.use(function (req, res, next) {
    var host = req.headers.host.split(':')[0];

    if (options.indexDocument && host !== 'localhost' && host !== '127.0.0.1') {
      req.url = path.join('/', host, req.url);
    }

    if (options.cors) {
      if (req.method === 'OPTIONS') {
        if (req.headers['access-control-request-headers'])
          res.header('Access-Control-Allow-Headers', req.headers['access-control-request-headers']);
        if (req.headers['access-control-request-method'])
          res.header('Access-Control-Allow-Methods', req.headers['access-control-request-method']);
      }
      if (req.headers.origin)
        res.header('Access-Control-Allow-Origin', '*');
    }

    next();
  });

  app.disable('x-powered-by');

  /**
   * Routes for the application
   */
  app.get('/', controllers.getBuckets);
  app.get('/:bucket', controllers.bucketExists, controllers.getBucket);
  app.delete('/:bucket', controllers.bucketExists, controllers.deleteBucket);
  app.put('/:bucket', controllers.putBucket);
  app.put('/:bucket/:key(*)', controllers.bucketExists, controllers.putObject);
  app.get('/:bucket/:key(*)', controllers.bucketExists, controllers.getObject);
  app.head('/:bucket/:key(*)', controllers.getObject);
  app.delete('/:bucket/:key(*)', controllers.bucketExists, controllers.deleteObject);
  app.post('/:bucket', controllers.bucketExists, controllers.genericPost);

  app.serve = function (done) {
    var server = ((options.key && options.cert) || options.pfx) ? https.createServer(options, app) : app;
    return server.listen(options.port, options.hostname, function (err) {
      return done(err, options.hostname, options.port, options.directory);
    }).on('error', function (err) {
      return done(err);
    });
  };

  return app;
};
<|endoftext|>


<commit_before>var Game = function() {
  this.init();
}

Game.prototype = {
  init: function() {
    this.setBindings();
    window.addEventListener("keydown", this.uniKeyDown, false);
  },

  uniKeyDown: function(e) {
    switch (e.keyCode) {
      case 37:
        this.move('l');
        break;
      case 38:
        this.move('t');
        break;
      case 39:
        this.move('r');
        break;
      case 40:
        this.move('b');
        break;
    }
  },

  reqListener: function() {
    console.log(this.responseText);
  },

  move: function(dir) {
    var httpReq = new XMLHttpRequest();
    httpReq.onload = reqListener();
    httpReq.open('POST', 'craigdh.bld.corp.google.com:8080/move', false);
    httpReq.send(dir);
  },

  setBindings: function() {
    this.uniKeyDown = this.uniKeyDown.bind(this);
    this.move = this.move.bind(this);
  }
}
<commit_msg>May fix reqListener bug<commit_after>var Game = function() {
  this.init();
}

Game.prototype = {
  init: function() {
    this.setBindings();
    window.addEventListener("keydown", this.uniKeyDown, false);
  },

  uniKeyDown: function(e) {
    switch (e.keyCode) {
      case 37:
        this.move('l');
        break;
      case 38:
        this.move('t');
        break;
      case 39:
        this.move('r');
        break;
      case 40:
        this.move('b');
        break;
    }
  },

  reqListener: function() {
    console.log(this.responseText);
  },

  move: function(dir) {
    var httpReq = new XMLHttpRequest();
    httpReq.onload = this.reqListener();
    httpReq.open('POST', 'craigdh.bld.corp.google.com:8080/move', false);
    httpReq.send(dir);
  },

  setBindings: function() {
    this.uniKeyDown = this.uniKeyDown.bind(this);
    this.move = this.move.bind(this);
  }
}
<|endoftext|>


<commit_before>'use strict';

const escape = require('./html').escape;
const resolve = require('./resolve');

function stringify(value) {
	if (typeof value === 'number') return "" + value;
	if (!value) return "";
	return "" + value;
}

function LineStart(str) { this.str = str; }
LineStart.prototype.render = function* (context) {
	if (context.margin) yield context.margin;
}

function Literal(str) { this.str = str; }
Literal.prototype.render = function* (_context) { yield this.str; }

function Interpolation(path, verbatim) {
	this.path = path;
	this.verbatim = verbatim;
}

Interpolation.prototype.render = function* (context) {
	const maybeResolved = resolve(context, this.path);
	const resolved = stringify((maybeResolved instanceof Promise) ? (yield maybeResolved) : maybeResolved);

	if (this.verbatim) yield resolved;
	else yield* escape(resolved);
}

function Sequence(seq) { this.seq = seq; }

Sequence.prototype.render = function* (context) {
	for (var i = 0; i < this.seq.length; ++i) {
		yield* this.seq[i].render(context);
	}
};

function Section(path, nested) {
	this.path = path;
	this.nested = nested;
}
Section.prototype.render = function* (context) {
	const maybeResolved = resolve(context, this.path);
	const value = (maybeResolved instanceof Promise) ? (yield maybeResolved) : maybeResolved;

	if (!value) return;

	if (Array.isArray(value)) {
		for (let i = 0; i < value.length; ++i) {
			const maybeResolved = resolve(context.subcontext(value[i]), []);
			const element = (maybeResolved instanceof Promise) ? (yield maybeResolved) : maybeResolved;
			yield* this.nested.render(context.subcontext(element));
		}
	} else if (typeof value.next === 'function') {
		for (;;) {
			const it = value.next();
			if (it.done) break;
			const maybeResolved = resolve(context.subcontext(it.value), []);
			const element = (maybeResolved instanceof Promise) ? (yield maybeResolved) : maybeResolved;
			yield* this.nested.render(context.subcontext(element));
		}
	} else if (typeof value === 'object') {
		yield* this.nested.render(context.subcontext(value));
	} else {
		yield* this.nested.render(context.subcontext({ ".": value }));
	}
};

function NegativeSection(path, nested) {
	this.path = path;
	this.nested = nested;
}
NegativeSection.prototype.render = function* (context) {
	const maybeResolved = resolve(context, this.path);
	const value = (maybeResolved instanceof Promise) ? (yield maybeResolved) : maybeResolved;

	if (Array.isArray(value) && value.length) return;
	if (!Array.isArray(value) && value) return;

	yield* this.nested.render(context);
};

function Partial(partialName, margin) {
	this.partialName = partialName;
	this.margin = margin;
}
Partial.prototype.render = function* (context) {
	const unresolvedPartial = context.getPartial(this.partialName);
	if (!unresolvedPartial) return;
	const partial = (unresolvedPartial instanceof Promise) ? yield unresolvedPartial : unresolvedPartial;

	const subcontext = context.subcontext({});
	subcontext.margin = (context.margin || "") + (this.margin || "");

	// TODO: Something about paths for partials

	yield* partial.render(subcontext);
};

module.exports = {
	LineStart,
	Literal,
	Interpolation,
	Sequence,
	Section,
	NegativeSection,
	Partial
};
<commit_msg>Simplify iteration by using for..of<commit_after>'use strict';

const escape = require('./html').escape;
const resolve = require('./resolve');

function stringify(value) {
	if (typeof value === 'number') return "" + value;
	if (!value) return "";
	return "" + value;
}

function LineStart(str) { this.str = str; }
LineStart.prototype.render = function* (context) {
	if (context.margin) yield context.margin;
}

function Literal(str) { this.str = str; }
Literal.prototype.render = function* (_context) { yield this.str; }

function Interpolation(path, verbatim) {
	this.path = path;
	this.verbatim = verbatim;
}

Interpolation.prototype.render = function* (context) {
	const maybeResolved = resolve(context, this.path);
	const resolved = stringify((maybeResolved instanceof Promise) ? (yield maybeResolved) : maybeResolved);

	if (this.verbatim) yield resolved;
	else yield* escape(resolved);
}

function Sequence(seq) { this.seq = seq; }

Sequence.prototype.render = function* (context) {
	for (const item of this.seq) {
		yield* item.render(context);
	}
};

function Section(path, nested) {
	this.path = path;
	this.nested = nested;
}
Section.prototype.render = function* (context) {
	const maybeResolved = resolve(context, this.path);
	const value = (maybeResolved instanceof Promise) ? (yield maybeResolved) : maybeResolved;

	if (!value) return;

	if (value[Symbol.iterator]) {
		for (const item of value) {
			const maybeResolved = resolve(context.subcontext(item), []);
			const element = (maybeResolved instanceof Promise) ? (yield maybeResolved) : maybeResolved;
			yield* this.nested.render(context.subcontext(element));
		}
	} else if (typeof value === 'object') {
		yield* this.nested.render(context.subcontext(value));
	} else {
		yield* this.nested.render(context.subcontext({ ".": value }));
	}
};

function NegativeSection(path, nested) {
	this.path = path;
	this.nested = nested;
}
NegativeSection.prototype.render = function* (context) {
	const maybeResolved = resolve(context, this.path);
	const value = (maybeResolved instanceof Promise) ? (yield maybeResolved) : maybeResolved;

	if (Array.isArray(value) && value.length) return;
	if (!Array.isArray(value) && value) return;

	yield* this.nested.render(context);
};

function Partial(partialName, margin) {
	this.partialName = partialName;
	this.margin = margin;
}
Partial.prototype.render = function* (context) {
	const unresolvedPartial = context.getPartial(this.partialName);
	if (!unresolvedPartial) return;
	const partial = (unresolvedPartial instanceof Promise) ? yield unresolvedPartial : unresolvedPartial;

	const subcontext = context.subcontext({});
	subcontext.margin = (context.margin || "") + (this.margin || "");

	// TODO: Something about paths for partials

	yield* partial.render(subcontext);
};

module.exports = {
	LineStart,
	Literal,
	Interpolation,
	Sequence,
	Section,
	NegativeSection,
	Partial
};
<|endoftext|>


<commit_before>$(document).ready(function() {
  var canvas = $("#canvas")[0];
  var contex = canvas.getContext("2d");
  var width = $("#canvas").width();
  var height = $("#canvas").height();
  var cellWidth = 10;
  var defaultDirection;
  var food;
  var score;
  var snakeArray;
});<commit_msg>add init function<commit_after>$(document).ready(function() {
  var canvas = $("#canvas")[0];
  var contex = canvas.getContext("2d");
  var width = $("#canvas").width();
  var height = $("#canvas").height();
  var cellWidth = 10;
  var defaultDirection;
  var food;
  var score;
  var snakeArray;

  function init() {
    defaultDirection = "right";
    createSnake();
    createFood();
    score = 0;
    if(typeof gameLoop != "undefined") clearInterval(gameLoop);
    gameLoop = setInterval(paint, 60);
  }
  init();
});<|endoftext|>


<commit_before>'use strict';

// TODO: Clean up this mess and/or just create my own custom progress bar

var ProgressBar = require('progress');

var bar, counterMap, totalMap, active;

function init() {
	bar = new ProgressBar('[:bar] :percent :etas (:names)', { total: 0, incomplete: ' ' });
	counterMap = {};
	totalMap = {};
	active = false;
}

function isActive() {
	return active;
}

function render() {
	bar.render({ names: Object.keys(counterMap).join(', ') });
	active = true;
}

function clear() {
	if (active) {
		active = false;
		bar.stream.clearLine();
		bar.stream.cursorTo(0);
		bar.lastDraw = null;
	}
}

function reset() {
	clear();
	init();
}

function setTotal(total) {
	bar.total = total;
	// TODO: Cap bar width based on terminal width?
	bar.width = Math.min(bar.total, 20);
}

function add(name, nr) {
	nr = nr || 1;
	var counter = counterMap[name] || 0;
	counterMap[name] = counter + nr;
	var nameTotal = totalMap[name] || 0;
	totalMap[name] = nameTotal + nr;
	setTotal(bar.total + nr);
	if (!bar.start) {
		bar.start = new Date();
	}
	render();
}

function finish(name, nr) {
	nr = nr || 1;
	bar.curr += nr;
	var count = counterMap[name] - nr;
	if (count) {
		counterMap[name] = count;
	} else {
		var nameTotal = totalMap[name];
		bar.curr -= nameTotal;
		setTotal(bar.total - nameTotal);
		delete totalMap[name];
		delete counterMap[name];
	}
	if (bar.total) {
		render();
	} else {
		reset();
	}
}

init();

module.exports = {
	isActive: isActive,
	render: render,
	clear: clear,
	add: add,
	finish: finish,
	reset: reset
};
<commit_msg>Removed :names from template to prevent wrapping in narrow (width 80) consoles<commit_after>'use strict';

// TODO: Clean up this mess and/or just create my own custom progress bar

var ProgressBar = require('progress');

var bar, counterMap, totalMap, active;

function init() {
	// Removed :names from template to prevent wrapping in narrow (width 80) consoles
	bar = new ProgressBar('[:bar] :percent :etas', { total: 0, incomplete: ' ' });
	counterMap = {};
	totalMap = {};
	active = false;
}

function isActive() {
	return active;
}

function render() {
	bar.render({ names: Object.keys(counterMap).join(', ') });
	active = true;
}

function clear() {
	if (active) {
		active = false;
		bar.stream.clearLine();
		bar.stream.cursorTo(0);
		bar.lastDraw = null;
	}
}

function reset() {
	clear();
	init();
}

function setTotal(total) {
	bar.total = total;
	// TODO: Cap bar width based on terminal width?
	bar.width = Math.min(bar.total, 20);
}

function add(name, nr) {
	nr = nr || 1;
	var counter = counterMap[name] || 0;
	counterMap[name] = counter + nr;
	var nameTotal = totalMap[name] || 0;
	totalMap[name] = nameTotal + nr;
	setTotal(bar.total + nr);
	if (!bar.start) {
		bar.start = new Date();
	}
	render();
}

function finish(name, nr) {
	nr = nr || 1;
	bar.curr += nr;
	var count = counterMap[name] - nr;
	if (count) {
		counterMap[name] = count;
	} else {
		var nameTotal = totalMap[name];
		bar.curr -= nameTotal;
		setTotal(bar.total - nameTotal);
		delete totalMap[name];
		delete counterMap[name];
	}
	if (bar.total) {
		render();
	} else {
		reset();
	}
}

init();

module.exports = {
	isActive: isActive,
	render: render,
	clear: clear,
	add: add,
	finish: finish,
	reset: reset
};
<|endoftext|>