<commit_before>var innerWidth = window.innerWidth;
var innerHeight = window.innerHeight;
var gameRatio = innerWidth/innerHeight;
var w = Math.floor(910*gameRatio);
var h = 910;
var game = new Phaser.Game(w, h, Phaser.AUTO, 'phaser-example', { preload: preload, create: create, update: update, render: render });

function preload() {
	game.scale.scaleMode = Phaser.ScaleManager.SHOW_ALL;
	game.load.tilemap('map', './map/test.json', null, Phaser.Tilemap.TILED_JSON);
	game.load.image('kenney', './img/kenney.png');
	//game.load.image('background', './img/background.png');
	game.load.spritesheet('dude', './img/pilot_animation.png', 100, 100);
	game.load.spritesheet('wave', './img/wave.png', 1232, 1000);
	game.load.image('menu', './img/buttons.png', 270, 180);

}

var player, background;
var facing = 'left';
var isTap = false;
var jumpTimer = 0;
var cursors;
var jumpButton;
var PI = 3.14;
var PI2 = 8*PI/18;
var PI3 = PI/3;
var PI4 = PI/4;
var oldSpeed = 0;

var onGround = false;

var map;
var layer, layer2;

var inTerrain=0;
var forceVector = 0;
var rotation = 0;

var startTime, jumpTime, score;
var scoreLabel;

var mainState = {preload: preload, create: create, update: update};
game.state.add('main', mainState);

function create() {
	//init
	inTerrain=0;
	forceVector = 0;
	rotation = 0;
	oldSpeed = 0;
	onGround = false;
	facing = 'left';
	isTap = false;
	jumpTimer = 0;
	startTime=0; jumpTime=0; score=0;

	/*
	background = game.add.sprite(0, 0, 'background');
	background.fixedToCamera = true;
	background.x = 0;
	background.y = 0;
	background.height = game.height;
	background.width = game.width;
	*/

	scoreLabel = game.add.text(100, 20, '0', {font: '24px Arial', fill: '#fff'});
	scoreLabel.fixedToCamera = true;

	/*
	 Code for the pause menu
	 */

	// Create a label to use as a button
	pause_label = game.add.text(w - 100, 20, 'Pause', {font: '24px Arial', fill: '#fff'});
	pause_label.inputEnabled = true;
	pause_label.fixedToCamera = true;
	pause_label.events.onInputUp.add(pause);

	// Add a input listener that can help us return from being paused
	game.input.onDown.add(unpause, self);
	game.input.keyboard.addKey(Phaser.Keyboard.ESC).onDown.add(escHandler, self);

	function escHandler() {
		if(game.paused) {
			destroyMenu();
		} else {
			pause();
		}
	}

	function pause(event) {
		// When the paus button is pressed, we pause the game
		game.paused = true;

		// Then add the menu
		menu = game.add.sprite(w / 2, h / 2, 'menu');
		menu.anchor.setTo(0.5, 0.5);

		// And a label to illustrate which menu item was chosen. (This is not necessary)
		choiseLabel = game.add.text(w / 2, h - 150, 'Click outside menu to continue', {font: '30px Arial', fill: '#fff'});
		choiseLabel.anchor.setTo(0.5, 0.5);
	}

	function destroyMenu() {
		// Remove the menu and the label
		menu.destroy();
		choiseLabel.destroy();

		// Unpause the game
		game.paused = false;
	}

	// unpause menu
	function unpause(event) {
		// Only act if paused
		if (game.paused) {
			// Calculate the corners of the menu
			var x1 = w / 2 - 270 / 2, x2 = w / 2 + 270 / 2,
					y1 = h / 2 - 180 / 2, y2 = h / 2 + 180 / 2;

			// Check if the click was inside the menu
			if (event.x > x1 && event.x < x2 && event.y > y1 && event.y < y2) {
				// The choicemap is an array that will help us see which item was clicked
				var choisemap = ['one', 'two', 'three', 'four', 'five', 'six'];

				// Get menu local coordinates for the click
				var x = event.x - x1,
						y = event.y - y1;

				// Calculate the choice
				var choise = Math.floor(x / 90) + 3 * Math.floor(y / 90);

				// Display the choice
				choiseLabel.text = 'You chose menu item: ' + choisemap[choise];
			}
			else {
				destroyMenu();
			}
		}
	};

	game.physics.startSystem(Phaser.Physics.P2JS);

	game.stage.backgroundColor = '#2d2d2d';

	wave = game.add.sprite(-1000, 600, 'wave');
	wave.animations.add('waving', [0, 1, 2, 3, 4], 10, true);
	game.physics.p2.enable(wave);
	wave.body.data.gravityScale = 0;
	wave.body.data.shapes[0].sensor = true;
	wave.animations.play('waving');

	map = game.add.tilemap('map');

	map.addTilesetImage('kenney');

	layer2 = map.createLayer('layer 2');
	layer = map.createLayer('layer 1');

	layer2.resizeWorld();
	layer.resizeWorld();

	var layerobjects_tiles = game.physics.p2.convertCollisionObjects(map,"objects1");

	game.physics.p2.restitution = 0.0;
	game.physics.p2.stiffness = 200;
	//game.physics.p2.relaxation = 0.1;
	game.physics.p2.gravity.y = 1400;
	game.physics.p2.applyGravity = true;
	//game.physics.p2.gravity.x = 200;

	game.physics.p2.world.defaultContactMaterial.friction = 0.01;
	game.physics.p2.world.setGlobalStiffness(1e5);

	player = game.add.sprite(150, 200, 'dude');
	player.animations.add('speedy', [8, 9, 10], 10, true);
	player.animations.add('turn', [0, 1, 2], 10, true);
	player.animations.add('right', [3, 4, 5, 6, 7], 10, true);

	game.physics.p2.enable(player);

	//var spriteMaterial = game.physics.p2.createMaterial('spriteMaterial', player.body);
	//var worldMaterial = game.physics.p2.createMaterial('worldMaterial');
	//var boxMaterial = game.physics.p2.createMaterial('worldMaterial');

	player.body.damping = 0.1;
	player.body.angularDamping = 0.5;
	player.body.collideWorldBounds = true;

	player.body.fixedRotation = false;
	//player.body.dynamic = true;
	//player.body.setMaterial(spriteMaterial);
	player.body.mass = 0.5;

	game.camera.follow(player);
	player.body.onBeginContact.add(blockHit, this);
	player.body.onEndContact.add(blockUnHit, this);

	//cursors = game.input.keyboard.createCursorKeys();
	//jumpButton = game.input.keyboard.addKey(Phaser.Keyboard.SPACEBAR);

	game.input.keyboard.addKey(Phaser.Keyboard.SPACEBAR).onDown.add(onTap, this);
	game.input.keyboard.addKey(Phaser.Keyboard.SPACEBAR).onUp.add(onUnTap, this);

	game.input.onDown.add(onTap, this);
	game.input.onUp.add(onUnTap, this);

	startTime = game.time.now;

}

function update() {

	if (Math.abs(player.body.velocity.x)>20){score += (game.time.now - startTime)/1000; scoreLabel.setText(Math.ceil(score));}
	startTime = game.time.now;
	wave.body.force.x=100;
	console.log(score);

	forceVector = player.body.velocity.y * player.body.velocity.x;
	rotation = player.body.rotation%PI;
	//console.log(player.body.angularForce);
	if (inTerrain){
		if (player.body.velocity.y<0.9 && player.body.velocity.y>-0.9){
			if (Math.abs(player.body.velocity.x)>10 && Math.abs(rotation)>PI4){
				//console.log("goal");
				player.body.rotation=0;
				player.body.angularForce=0;
			}
		}
		else if (forceVector > 0){
			if (rotation<-0.1 && oldSpeed*player.body.velocity.x>0){
				//console.log("goal2");
				player.body.rotation=0;
				player.body.angularForce=75;
			}
			else if (rotation>PI2){
				player.body.rotation=PI3;
			}
		}
		else if (forceVector < 0){
			if (rotation>0.1){
				//console.log("goal3", rotation);
				player.body.rotation=0;
				player.body.angularForce=-75;
			}
			else if (rotation<-PI2){
				player.body.rotation=-PI3;
			}
		}
	}
	else{
		if (rotation>PI4){player.body.rotation=PI4-0.05;}
		else if (rotation<-PI4){player.body.rotation=-PI4+0.05;}
	}
	oldSpeed = player.body.velocity.x;

	if (isTap){
		if (inTerrain){
			if (player.body.velocity.y>0){
				player.body.force.y += 500;
			}
			/*else if (player.body.velocity.y<-5){
				player.body.angularForce=-50;
			}*/
		}
		player.body.force.x = 750;
		if (facing != 'right' && inTerrain)
		{
			player.animations.play('right');
			facing = 'right';
		}
	}
	else
	{
		//player.body.velocity.x = 800;

		if (Math.abs(player.body.velocity.x)<25 && Math.abs(player.body.rotation)<0.2 && facing != 'idle')
		{
			player.animations.stop();

			//    player.frame = 5;
			facing = 'idle';
			player.animations.play('turn');
		}
		else if (Math.abs(player.body.velocity.x)> 25 && facing != 'speedy'){
			facing = 'speedy';
			player.animations.play('speedy');
		}

	}

}

function onTap(pointer, doubleTap) {
	isTap = true;
}
function onUnTap(pointer, doubleTap) {
	isTap = false;
	player.body.angularForce = 0;
}

function blockHit (body, bodyB, shapeA, shapeB, equation) {
	if (body)
	{
		if (body.sprite===null){
			onGround = true;
			inTerrain++;
			if (jumpTime!=0){
				score += (game.time.now - jumpTime)/50;
				jumpTime = 0;
				scoreLabel.setText(Math.ceil(score));
			}
		}
		else{
			if (body.sprite.key == 'wave'){
				//lose
				console.log('lose');
				game.state.start('main');
			}
		}
	}
	else
	{
		//win;
		console.log("win");
	}

}
function blockUnHit (body, bodyB, shapeA, shapeB, equation) {
	if (body)
	{
		if (body.sprite===null){
			onGround = false;
			inTerrain--;
			if (inTerrain<1){
				jumpTime = game.time.now;
				if (facing == 'right'){
					facing = 'speedy';
					player.animations.play('speedy');
				}
			}
		}
	}
	else
	{
		//console.log("wall");
	}

}

function render() {

}<commit_msg>menu fixed to camera<commit_after>var innerWidth = window.innerWidth;
var innerHeight = window.innerHeight;
var gameRatio = innerWidth/innerHeight;
var w = Math.floor(910*gameRatio);
var h = 910;
var game = new Phaser.Game(w, h, Phaser.AUTO, 'phaser-example', { preload: preload, create: create, update: update, render: render });

function preload() {
	game.scale.scaleMode = Phaser.ScaleManager.SHOW_ALL;
	game.load.tilemap('map', './map/test.json', null, Phaser.Tilemap.TILED_JSON);
	game.load.image('kenney', './img/kenney.png');
	// game.load.image('background', './img/background.png');
	game.load.spritesheet('dude', './img/pilot_animation.png', 100, 100);
	game.load.spritesheet('wave', './img/wave.png', 1232, 1000);
	game.load.image('menu', './img/buttons.png', 270, 180);

}

var player, background;
var facing = 'left';
var isTap = false;
var jumpTimer = 0;
var cursors;
var jumpButton;
var PI = 3.14;
var PI2 = 8*PI/18;
var PI3 = PI/3;
var PI4 = PI/4;
var oldSpeed = 0;

var onGround = false;

var map;
var layer, layer2;

var inTerrain=0;
var forceVector = 0;
var rotation = 0;

var startTime, jumpTime, score;
var scoreLabel;

var mainState = {preload: preload, create: create, update: update};
game.state.add('main', mainState);

function create() {
	//init
	inTerrain=0;
	forceVector = 0;
	rotation = 0;
	oldSpeed = 0;
	onGround = false;
	facing = 'left';
	isTap = false;
	jumpTimer = 0;
	startTime=0; jumpTime=0; score=0;

	/*
	background = game.add.sprite(0, 0, 'background');
	background.fixedToCamera = true;
	background.x = 0;
	background.y = 0;
	background.height = game.height;
	background.width = game.width;
	*/

	scoreLabel = game.add.text(100, 20, '0', {font: '24px Arial', fill: '#fff'});
	scoreLabel.fixedToCamera = true;

	/*
	 Code for the pause menu
	 */

	// Create a label to use as a button
	pause_label = game.add.text(w - 100, 20, 'Pause', {font: '24px Arial', fill: '#fff'});
	pause_label.inputEnabled = true;
	pause_label.fixedToCamera = true;
	pause_label.events.onInputUp.add(pause);

	// Add a input listener that can help us return from being paused
	game.input.onDown.add(unpause, self);
	game.input.keyboard.addKey(Phaser.Keyboard.ESC).onDown.add(escHandler, self);

	function escHandler() {
		if(game.paused) {
			destroyMenu();
		} else {
			pause();
		}
	}

	function pause(event) {

		// When the paus button is pressed, we pause the game
		game.paused = true;

        // backgroundmenu = game.add.sprite(0, 0, 800, 600, 'backgroundmenu', 'backgroundmenu');
		// Then add the menu
        console.log(player.position.x);
        var centerXPos = (player.position.x > w / 2) ? player.position.x : w / 2;
		menu = game.add.sprite(centerXPos, h / 2, 'menu');
		menu.anchor.setTo(0.5, 0.5);

		// And a label to illustrate which menu item was chosen. (This is not necessary)
		choiseLabel = game.add.text(centerXPos, h - 150, 'Click outside menu to continue', {font: '30px Arial', fill: '#fff'});
		choiseLabel.anchor.setTo(0.5, 0.5);
	}

	function destroyMenu() {
		// Remove the menu and the label
		menu.destroy();
        // backgroundmenu.destroy();
		choiseLabel.destroy();

		// Unpause the game
		game.paused = false;
	}

	// unpause menu
	function unpause(event) {
		// Only act if paused
		if (game.paused) {
			// Calculate the corners of the menu
			var x1 = w / 2 - 270 / 2, x2 = w / 2 + 270 / 2,
					y1 = h / 2 - 180 / 2, y2 = h / 2 + 180 / 2;

			// Check if the click was inside the menu
			if (event.x > x1 && event.x < x2 && event.y > y1 && event.y < y2) {
				// The choicemap is an array that will help us see which item was clicked
				var choisemap = ['one', 'two', 'three', 'four', 'five', 'six'];

				// Get menu local coordinates for the click
				var x = event.x - x1,
						y = event.y - y1;

				// Calculate the choice
				var choise = Math.floor(x / 90) + 3 * Math.floor(y / 90);

				// Display the choice
				choiseLabel.text = 'You chose menu item: ' + choisemap[choise];
			}
			else {
				destroyMenu();
			}
		}
	};

	game.physics.startSystem(Phaser.Physics.P2JS);

	game.stage.backgroundColor = '#2d2d2d';

	wave = game.add.sprite(-1000, 600, 'wave');
	wave.animations.add('waving', [0, 1, 2, 3, 4], 10, true);
	game.physics.p2.enable(wave);
	wave.body.data.gravityScale = 0;
	wave.body.data.shapes[0].sensor = true;
	wave.animations.play('waving');

	map = game.add.tilemap('map');

	map.addTilesetImage('kenney');

	layer2 = map.createLayer('layer 2');
	layer = map.createLayer('layer 1');

	layer2.resizeWorld();
	layer.resizeWorld();

	var layerobjects_tiles = game.physics.p2.convertCollisionObjects(map,"objects1");

	game.physics.p2.restitution = 0.0;
	game.physics.p2.stiffness = 200;
	//game.physics.p2.relaxation = 0.1;
	game.physics.p2.gravity.y = 1400;
	game.physics.p2.applyGravity = true;
	//game.physics.p2.gravity.x = 200;

	game.physics.p2.world.defaultContactMaterial.friction = 0.01;
	game.physics.p2.world.setGlobalStiffness(1e5);

	player = game.add.sprite(150, 200, 'dude');
	player.animations.add('speedy', [8, 9, 10], 10, true);
	player.animations.add('turn', [0, 1, 2], 10, true);
	player.animations.add('right', [3, 4, 5, 6, 7], 10, true);

	game.physics.p2.enable(player);

	//var spriteMaterial = game.physics.p2.createMaterial('spriteMaterial', player.body);
	//var worldMaterial = game.physics.p2.createMaterial('worldMaterial');
	//var boxMaterial = game.physics.p2.createMaterial('worldMaterial');

	player.body.damping = 0.1;
	player.body.angularDamping = 0.5;
	player.body.collideWorldBounds = true;

	player.body.fixedRotation = false;
	//player.body.dynamic = true;
	//player.body.setMaterial(spriteMaterial);
	player.body.mass = 0.5;

	game.camera.follow(player);
	player.body.onBeginContact.add(blockHit, this);
	player.body.onEndContact.add(blockUnHit, this);

	//cursors = game.input.keyboard.createCursorKeys();
	//jumpButton = game.input.keyboard.addKey(Phaser.Keyboard.SPACEBAR);

	game.input.keyboard.addKey(Phaser.Keyboard.SPACEBAR).onDown.add(onTap, this);
	game.input.keyboard.addKey(Phaser.Keyboard.SPACEBAR).onUp.add(onUnTap, this);

	game.input.onDown.add(onTap, this);
	game.input.onUp.add(onUnTap, this);

	startTime = game.time.now;

}

function update() {

	if (Math.abs(player.body.velocity.x)>20){score += (game.time.now - startTime)/1000; scoreLabel.setText(Math.ceil(score));}
	startTime = game.time.now;
	wave.body.force.x=100;
	console.log(score);

	forceVector = player.body.velocity.y * player.body.velocity.x;
	rotation = player.body.rotation%PI;
	//console.log(player.body.angularForce);
	if (inTerrain){
		if (player.body.velocity.y<0.9 && player.body.velocity.y>-0.9){
			if (Math.abs(player.body.velocity.x)>10 && Math.abs(rotation)>PI4){
				//console.log("goal");
				player.body.rotation=0;
				player.body.angularForce=0;
			}
		}
		else if (forceVector > 0){
			if (rotation<-0.1 && oldSpeed*player.body.velocity.x>0){
				//console.log("goal2");
				player.body.rotation=0;
				player.body.angularForce=75;
			}
			else if (rotation>PI2){
				player.body.rotation=PI3;
			}
		}
		else if (forceVector < 0){
			if (rotation>0.1){
				//console.log("goal3", rotation);
				player.body.rotation=0;
				player.body.angularForce=-75;
			}
			else if (rotation<-PI2){
				player.body.rotation=-PI3;
			}
		}
	}
	else{
		if (rotation>PI4){player.body.rotation=PI4-0.05;}
		else if (rotation<-PI4){player.body.rotation=-PI4+0.05;}
	}
	oldSpeed = player.body.velocity.x;

	if (isTap){
		if (inTerrain){
			if (player.body.velocity.y>0){
				player.body.force.y += 500;
			}
			/*else if (player.body.velocity.y<-5){
				player.body.angularForce=-50;
			}*/
		}
		player.body.force.x = 750;
		if (facing != 'right' && inTerrain)
		{
			player.animations.play('right');
			facing = 'right';
		}
	}
	else
	{
		//player.body.velocity.x = 800;

		if (Math.abs(player.body.velocity.x)<25 && Math.abs(player.body.rotation)<0.2 && facing != 'idle')
		{
			player.animations.stop();

			//    player.frame = 5;
			facing = 'idle';
			player.animations.play('turn');
		}
		else if (Math.abs(player.body.velocity.x)> 25 && facing != 'speedy'){
			facing = 'speedy';
			player.animations.play('speedy');
		}

	}

}

function onTap(pointer, doubleTap) {
	isTap = true;
}
function onUnTap(pointer, doubleTap) {
	isTap = false;
	player.body.angularForce = 0;
}

function blockHit (body, bodyB, shapeA, shapeB, equation) {
	if (body)
	{
		if (body.sprite===null){
			onGround = true;
			inTerrain++;
			if (jumpTime!=0){
				score += (game.time.now - jumpTime)/50;
				jumpTime = 0;
				scoreLabel.setText(Math.ceil(score));
			}
		}
		else{
			if (body.sprite.key == 'wave'){
				//lose
				console.log('lose');
				game.state.start('main');
			}
		}
	}
	else
	{
		//win;
		console.log("win");
	}

}
function blockUnHit (body, bodyB, shapeA, shapeB, equation) {
	if (body)
	{
		if (body.sprite===null){
			onGround = false;
			inTerrain--;
			if (inTerrain<1){
				jumpTime = game.time.now;
				if (facing == 'right'){
					facing = 'speedy';
					player.animations.play('speedy');
				}
			}
		}
	}
	else
	{
		//console.log("wall");
	}

}

function render() {

}<|endoftext|>


<commit_before>var game = new Phaser.Game(800, 600, Phaser.CANVAS, '', {preload: preload, create: create, update: update});

var player;
var map;
var ladderMap;
var platforms;
var ladders;
var stoppers;
var npcs;

function preload() {
    // preload content
    game.load.image('tilesheet', 'assets/tileset.png');
    game.load.image('player', 'assets/player.png');
    game.load.spritesheet('NPC', 'assets/NPC.png', 10, 16);
    game.load.tilemap('map', 'assets/maps/level.json', null, Phaser.Tilemap.TILED_JSON);
}

function create() {
    // create entities
    game.stage.backgroundColor = '#47A3FF';
    game.physics.startSystem(Phaser.Physics.ARCADE);
    game.world.setBounds(0, 0, 1920, 1920);
    game.physics.arcade.gravity.y = 600;

    var text = game.add.text(32, 32, 'GREG IS HAPPY', {fontSize:'64px', fill: '#000'});
    text.anchor.set(0.5);
    text.x = game.width / 2;
    text.y = game.height / 4;

    map = game.add.tilemap('map');
    map.addTilesetImage('tileset', 'tilesheet');
    map.setCollisionBetween(1, 4);

    platforms = map.createLayer('Platforms');
    ladders = map.createLayer('Ladders');
    stoppers = map.createLayer('Stoppers');
    stoppers.visible = false;

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

    npcs = game.add.group();
    npcs.enableBody = true;
    var max = 5;
    var total = 0;
    var tiles = platforms.getTiles(0, 0, platforms.width, platforms.height);
    for (var i in tiles) {
        if (total >= max) {
            break;
        }

        if (i % 10 === 0) {
            total = 0;
        }

        var tile = tiles[i];
        if (tile.index == 3 && Math.random() > 0.9) {
            npc = new NPC(tile.worldX, 0);
            npc.y = tile.worldY - npc.height;
            npcs.add(npc);
            total += 1;
            if (total == 2) {
                break;
            }
         }
    }

    player = new Player();
    game.add.existing(player);
    game.camera.follow(player);
}

function update() {
    game.physics.arcade.collide(player, platforms);
    game.physics.arcade.collide(npcs, platforms);
    npcs.forEach(function(npc) {
        game.physics.arcade.overlap(npc, npcs, npcOverlap);
    });
}

function npcOverlap(npc1, npc2) {
    if (npc1.renderOrderID == npc2.renderOrderID) {
        return;
    }
    var rager;
    var victim;
    if (Math.random() <= 0.5) {
        rager = npc1;
        victim = npc2;
    } else {
        rager = npc2;
        victim = npc1;
    }
    // higher anger, higher chance of rage
    var chance = (rager.anger * 0.05) - 0.3;
    if (Math.random() >= chance) {
        rager.rageAt(victim);
    }
}

Player = function() {
    Phaser.Sprite.call(this, game, 0, 0, 'player');
    game.physics.arcade.enable(this);
};

Player.prototype = Object.create(Phaser.Sprite.prototype);
Player.prototype.constructor = Player;

Player.prototype.update = function() {
    this.body.velocity.x = 0;
    if (cursors.left.isDown) {
        this.body.velocity.x = -350;
    }else if (cursors.right.isDown) {
        this.body.velocity.x = 350;
    }

    if (cursors.up.isDown && this.body.onFloor()) {
        this.body.velocity.y = -300;
    }
};

NPC = function(x, y) {
    Phaser.Sprite.call(this, game, x, y, 'NPC');
    game.physics.arcade.enable(this);

    this.lastRaged = this.game.time.now - 100;
    this.anger = 0;

    this.body.velocity.x = 50;
    if (Math.random() > 0.5) {
        this.body.velocity.x *= -1;
    }
};

NPC.prototype = Object.create(Phaser.Sprite.prototype);
NPC.prototype.contstructor = NPC;

NPC.prototype.update = function() {
    // anger management
    if (this.anger < 9) {
        this.anger += game.time.physicsElapsed;
    }

    this.frame = Math.round(this.anger);
    if (Math.round(this.anger) > 9) {
        this.frame = 9;
    }

    // edge detection
    var tileX = stoppers.getTileX(this.x + this.body.width/2);
    var tileY = stoppers.getTileY(this.y + this.body.height/2);
    if (this.isEdge(stoppers.index, tileX, tileY)) {
        if (this.game.time.now - this.lastTime < 100) {
            return;
        }

        this.body.velocity.x *= -1;
        this.lastTime = this.game.time.now;
        /*
        if (this.animations.currentAnim.name == 'left') {
            this.animations.play('right');
            return;
        }

        this.animations.play('left');*/
    }
};

NPC.prototype.isEdge = function(index, x, y) {
    var leftTile = map.getTileLeft(index, x, y);
    var rightTile = map.getTileRight(index, x, y);

    if (!leftTile && rightTile) {
        return rightTile.index != -1;
    }

    if (!rightTile && leftTile) {
        return leftTile.index != -1;
    }

    return (leftTile.index != -1) || (rightTile.index != -1);
};

NPC.prototype.rageAt = function(otherNPC) {
    // TODO - implement different levels of rage
    if (this.game.time.now - this.lastRaged < 1000) {
        console.log("no rage");
        return;
    }

    otherNPC.anger *= 1.5;
    console.log("RAAAGE");
    this.lastRaged = otherNPC.lastRaged = this.game.time.now;
};

<commit_msg>js/game: rage counter in top corner<commit_after>var game = new Phaser.Game(800, 600, Phaser.CANVAS, '', {preload: preload, create: create, update: update});

var player;
var map;
var ladderMap;
var platforms;
var ladders;
var stoppers;
var npcs;
var rc;

function preload() {
    // preload content
    game.load.image('tilesheet', 'assets/tileset.png');
    game.load.image('player', 'assets/player.png');
    game.load.spritesheet('NPC', 'assets/NPC.png', 10, 16);
    game.load.tilemap('map', 'assets/maps/level.json', null, Phaser.Tilemap.TILED_JSON);
}

function create() {
    // create entities
    game.stage.backgroundColor = '#47A3FF';
    game.physics.startSystem(Phaser.Physics.ARCADE);
    game.world.setBounds(0, 0, 1920, 1920);
    game.physics.arcade.gravity.y = 600;

    var text = game.add.text(32, 32, 'GREG IS HAPPY', {fontSize:'64px', fill: '#000'});
    text.anchor.set(0.5);
    text.x = game.width / 2;
    text.y = game.height / 4;

    map = game.add.tilemap('map');
    map.addTilesetImage('tileset', 'tilesheet');
    map.setCollisionBetween(1, 4);

    platforms = map.createLayer('Platforms');
    ladders = map.createLayer('Ladders');
    stoppers = map.createLayer('Stoppers');
    stoppers.visible = false;

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

    npcs = game.add.group();
    npcs.enableBody = true;
    var max = 5;
    var total = 0;
    var tiles = platforms.getTiles(0, 0, platforms.width, platforms.height);
    for (var i in tiles) {
        if (total >= max) {
            break;
        }

        if (i % 10 === 0) {
            total = 0;
        }

        var tile = tiles[i];
        if (tile.index == 3 && Math.random() > 0.9) {
            npc = new NPC(tile.worldX, 0);
            npc.y = tile.worldY - npc.height;
            npcs.add(npc);
            total += 1;
            if (total == 2) {
                break;
            }
         }
    }

    player = new Player();
    game.add.existing(player);
    game.camera.follow(player);

    rc = new RageCounter();
    game.add.existing(rc);
}

function update() {
    game.physics.arcade.collide(player, platforms);
    game.physics.arcade.collide(npcs, platforms);

    var total = 0;
    npcs.forEach(function(npc) {
        total += npc.anger;
        game.physics.arcade.overlap(npc, npcs, npcOverlap);
    });

    rc.level = total;
}

function npcOverlap(npc1, npc2) {
    if (npc1.renderOrderID == npc2.renderOrderID) {
        return;
    }
    var rager;
    var victim;
    if (Math.random() <= 0.5) {
        rager = npc1;
        victim = npc2;
    } else {
        rager = npc2;
        victim = npc1;
    }
    // higher anger, higher chance of rage
    var chance = (rager.anger * 0.05) - 0.3;
    if (Math.random() >= chance) {
        rager.rageAt(victim);
    }
}

Player = function() {
    Phaser.Sprite.call(this, game, 0, 0, 'player');
    game.physics.arcade.enable(this);
};

Player.prototype = Object.create(Phaser.Sprite.prototype);
Player.prototype.constructor = Player;

Player.prototype.update = function() {
    this.body.velocity.x = 0;
    if (cursors.left.isDown) {
        this.body.velocity.x = -350;
    }else if (cursors.right.isDown) {
        this.body.velocity.x = 350;
    }

    if (cursors.up.isDown && this.body.onFloor()) {
        this.body.velocity.y = -300;
    }
};

NPC = function(x, y) {
    Phaser.Sprite.call(this, game, x, y, 'NPC');
    game.physics.arcade.enable(this);

    this.lastRaged = this.game.time.now - 100;
    this.anger = 0;

    this.body.velocity.x = 50;
    if (Math.random() > 0.5) {
        this.body.velocity.x *= -1;
    }
};

NPC.prototype = Object.create(Phaser.Sprite.prototype);
NPC.prototype.contstructor = NPC;

NPC.prototype.update = function() {
    // anger management
    if (this.anger < 9) {
        this.anger += game.time.physicsElapsed;
    }

    this.frame = Math.round(this.anger);
    if (Math.round(this.anger) > 9) {
        this.frame = 9;
    }

    // edge detection
    var tileX = stoppers.getTileX(this.x + this.body.width/2);
    var tileY = stoppers.getTileY(this.y + this.body.height/2);
    if (this.isEdge(stoppers.index, tileX, tileY)) {
        if (this.game.time.now - this.lastTime < 100) {
            return;
        }

        this.body.velocity.x *= -1;
        this.lastTime = this.game.time.now;
        /*
        if (this.animations.currentAnim.name == 'left') {
            this.animations.play('right');
            return;
        }

        this.animations.play('left');*/
    }
};

NPC.prototype.isEdge = function(index, x, y) {
    var leftTile = map.getTileLeft(index, x, y);
    var rightTile = map.getTileRight(index, x, y);

    if (!leftTile && rightTile) {
        return rightTile.index != -1;
    }

    if (!rightTile && leftTile) {
        return leftTile.index != -1;
    }

    return (leftTile.index != -1) || (rightTile.index != -1);
};

NPC.prototype.rageAt = function(otherNPC) {
    // TODO - implement different levels of rage
    if (this.game.time.now - this.lastRaged < 1000) {
        return;
    }

    otherNPC.anger *= 1.5;
    console.log("RAAAGE");
    this.lastRaged = otherNPC.lastRaged = this.game.time.now;
};

RageCounter = function() {
    Phaser.Text.call(this, game, 0, 0, "RAGE LEVEL: ", {});
    this.level = 0;
    this.fixedToCamera = true;
};

RageCounter.prototype = Object.create(Phaser.Text.prototype);
RageCounter.prototype.contstructor = RageCounter;

RageCounter.prototype.update = function() {
    this.text = "RAGE LEVEL: " + Math.round(this.level);
};

<|endoftext|>


<commit_before>Drac.Game = function(game) {
    score = 0;
    lives = 0;
};

/**
 * No preload function required here as that is handled in the Drac.Loader state.
 *
 * @type {Object}
 */
Drac.Game.prototype = {
    create: function() {
        this.createFloor();
    },
    update: function() {

    },
    touchDrac: function() {

    },
    hitDrac: function() {

    },
    quitGame: function(){
        this.state.start('Menu');
    },
    createFloor: function(){
        // Init vector shape
        this.ground = this.game.add.graphics(0, 0);
        this.ground.lineStyle(2, 0x663300, 1);
        this.ground.beginFill(0x331900, 1);

        // Draw shape
        this.ground.drawRect(-2, this.game.world.height-20, this.game.world.width+20, 20);
        this.ground.immovable = true;
    }
};<commit_msg>Loading stuff in game.js create function.<commit_after>Drac.Game = function(game) {
    score = 0;
    lives = 0;
};

/**
 * No preload function required here as that is handled in the Drac.Loader state.
 *
 * @type {Object}
 */
Drac.Game.prototype = {
    create: function() {
        this.game.physics.startSystem(Phaser.Physics.ARCADE);
        this.createFloor();
        this.player = this.game.add.sprite(32, this.game.world.height-160, 'you');
        this.game.physics.arcade.enable(this.player);

        this.player.animations.add('left', [117, 118, 119, 120, 121, 122, 123, 124, 125], 10, true);
        this.player.animations.add('right', [143, 144, 145, 146, 147, 148, 149, 150, 151], 10, true);

        this.cursors = this.game.input.keyboard.createCursorKeys();
    },
    update: function() {

    },
    touchDrac: function() {

    },
    hitDrac: function() {

    },
    quitGame: function(){
        this.state.start('Menu');
    },
    createFloor: function(){
        // Init vector shape
        this.ground = this.game.add.graphics(0, 0);
        this.ground.lineStyle(2, 0x663300, 1);
        this.ground.beginFill(0x331900, 1);

        // Draw shape
        this.ground.drawRect(-2, this.game.world.height-20, this.game.world.width+20, 20);
        this.ground.immovable = true;
    }
};<|endoftext|>


<commit_before>// loadFibers returns a FiberSource array of fibers contained in a JSON file.
function loadPhantom( path ) {
  var request = new XMLHttpRequest();
  request.overrideMimeType("text/plain");
  request.open("get", path, false);
  request.send(null);

  var phantom = new Phantom();
  var loadedfibers = JSON.parse(request.response).fiber_geometries;
  var loadedregions = JSON.parse(request.response).isotropic_regions;

  // Objects will be added in Phantom
  for (var property in loadedfibers) {
    if (loadedfibers.hasOwnProperty(property)) {
      var fiber = loadedfibers[property.toString()];
      // Control points need to be transleted to array-of-arrays form
      var newcp = [];
      for (var i = 0; i < fiber.control_points.length; i = i + 3) {
        newcp.push([fiber.control_points[i],
                    fiber.control_points[i+1],
                    fiber.control_points[i+2]]);
      }
      phantom.AddFiber(new FiberSource(newcp, fiber.tangents, fiber.radius));
    }
  }
  for (var property in loadedregions) {
    if (loadedregions.hasOwnProperty(property)) {
      var region = loadedregions[property.toString()];
      phantom.AddIsotropicRegion(new IsotropicRegionSource(region.center, region.radius));
    }
  }

  // log an error in case fibers or regions were not found.
  if (phantom.isotropicregions.source.length == 0) console.warn('Any region found in file '+path);
  if (phantom.fibers.source.length == 0) console.warn('Any fiber found in file '+path);
  return phantom;
}
<commit_msg>Move load.js to js/<commit_after>// loadFibers returns a FiberSource array of fibers contained in a JSON file.
function loadPhantom( path ) {
  var request = new XMLHttpRequest();
  request.overrideMimeType("text/plain");
  request.open("get", path, false);
  request.send(null);

  var phantom = new Phantom();
  var loadedfibers = JSON.parse(request.response).fiber_geometries;
  var loadedregions = JSON.parse(request.response).isotropic_regions;

  // Objects will be added in Phantom
  for (var property in loadedfibers) {
    if (loadedfibers.hasOwnProperty(property)) {
      var fiber = loadedfibers[property.toString()];
      // Control points need to be transleted to array-of-arrays form
      var newcp = [];
      for (var i = 0; i < fiber.controlPoints.length; i = i + 3) {
        newcp.push([fiber.controlPoints[i],
                    fiber.controlPoints[i+1],
                    fiber.controlPoints[i+2]]);
      }
      phantom.AddFiber(new FiberSource(newcp, fiber.tangents, fiber.radius));
    }
  }
  for (var property in loadedregions) {
    if (loadedregions.hasOwnProperty(property)) {
      var region = loadedregions[property.toString()];
      phantom.AddIsotropicRegion(new IsotropicRegionSource(region.center, region.radius));
    }
  }

  // log an error in case fibers or regions were not found.
  if (phantom.isotropicregions.source.length == 0) console.warn('Any region found in file '+path);
  if (phantom.fibers.source.length == 0) console.warn('Any fiber found in file '+path);
  return phantom;
}
<|endoftext|>


<commit_before>
/* Game namespace */
var game = {

    // an object where to store game information
    data : {
        // score
        score : 0
    },

    // Run on page load.
    "onload" : function () {
    // Initialize the video.
    if (!me.video.init(960, 640, {wrapper : "screen", scale : "auto"})) {
        alert("Your browser does not support HTML5 canvas.");
        return;
    }

    // add "#debug" to the URL to enable the debug Panel
    if (me.game.HASH.debug === true) {
        window.onReady(function () {
            me.plugin.register.defer(this, me.debug.Panel, "debug", me.input.KEY.V);
        });
    }

    // Initialize the audio.
    me.audio.init("mp3,ogg");

    // Set a callback to run when loading is complete.
    me.loader.onload = this.loaded.bind(this);

    // Load the resources.
    me.loader.preload(game.resources);

    // Initialize melonJS and display a loading screen.
    me.state.change(me.state.LOADING);
},

    // Run on game resources loaded.
    "loaded" : function () {
        me.state.set(me.state.MENU, new game.TitleScreen());
        me.state.set(me.state.PLAY, new game.PlayScreen());

        // add our player entity in the entity pool
        me.pool.register("mainPlayer", game.PlayerEntity);

        // Start the game.
        me.state.change(me.state.PLAY);
    }
};
<commit_msg>fixed indentation<commit_after>
/* Game namespace */
var game = {

    // an object where to store game information
    data : {
        // score
        score : 0
    },

    // Run on page load.
    "onload" : function () {
        // Initialize the video.
        if (!me.video.init(960, 640, {wrapper : "screen", scale : "auto"})) {
            alert("Your browser does not support HTML5 canvas.");
            return;
        }

        // add "#debug" to the URL to enable the debug Panel
        if (me.game.HASH.debug === true) {
            window.onReady(function () {
                me.plugin.register.defer(this, me.debug.Panel, "debug", me.input.KEY.V);
            });
        }

        // Initialize the audio.
        me.audio.init("mp3,ogg");

        // Set a callback to run when loading is complete.
        me.loader.onload = this.loaded.bind(this);

        // Load the resources.
        me.loader.preload(game.resources);

        // Initialize melonJS and display a loading screen.
        me.state.change(me.state.LOADING);
    },

    // Run on game resources loaded.
    "loaded" : function () {
        me.state.set(me.state.MENU, new game.TitleScreen());
        me.state.set(me.state.PLAY, new game.PlayScreen());

        // add our player entity in the entity pool
        me.pool.register("mainPlayer", game.PlayerEntity);

        // Start the game.
        me.state.change(me.state.PLAY);
    }
};
<|endoftext|>


<commit_before>define(['app'], function() {

    return {

        app: null,
        ctx: null,
        ROW_COUNT: 7,
        MAX_ROW_COUNT: 7,
        COL_COUNT: 26,
        BRICKWIDTH: 0,
        BRICKHEIGHT: 18,
        PADDING: 2,
        bricks: [],
        drawIntervalId: null,
        addRowIntervalId: null,
        ballRadius: 9,
        rowColours: ["#f2665e", "#fcb040", "#6ac071", "#57cbf5"],
        paddleColour: "#656565",
        ballColour: "#f2665e",
        backColour: "#f4f0ed",
        paddleh: 13,
        paddlew: 110,
        paddlex: 0,
        PADDLE_POSITION_OFFSET: {
            x: 0,
            y: -30
        },
        paddlePosition: {
            x: 0,
            y: 0
        },
        ballPosition: {
            x: 25,
            y: 250,
        },
        ballSpeed: {
            x: 1.5,
            y: -4,
        },
        // Used to calculate where the ball is going/what it's hitting
        tempBallPosition: {
            x: 0,
            y: 0,
        },

        init: function(app) {
            this.app = app;
            this.app.init();
            this.ctx = this.app.ctx;
            this.BRICKWIDTH = (this.app.WIDTH / this.COL_COUNT) - this.PADDING;
            this.initPaddle();
            this.initBricks();
            this.startDrawInterval();
            this.startAddRowInterval();
            this.addListeners();
        },

        reset: function() {
            this.bricks = [];
            this.initBricks();
            this.startDrawInterval();
        },

        addListeners: function() {
            $(window).on('game.over', $.proxy(function() {
                clearInterval(this.drawIntervalId);
            }, this));

            $(window).on('game.reset', $.proxy(function() {
                this.reset();
            }, this));

            $(window).on('mouse.moved', $.proxy(function(e, x, y) {
                this.paddlex = Math.max(x - this.app.canvasMinX - (this.paddlew / 2), 0);
                this.paddlex = Math.min(this.app.WIDTH - this.paddlew, this.paddlex);
            }, this));
        },

        startDrawInterval: function() {
            this.drawIntervalId = setInterval($.proxy(function() {
                this.draw();
            }, this), 10);
        },

        draw: function() {
            this.ctx.fillStyle = this.backColour;
            this.clear();

            this.paddlePosition = {
                x: this.paddlex + this.PADDLE_POSITION_OFFSET.x,
                y: this.app.HEIGHT - this.paddleh + this.PADDLE_POSITION_OFFSET.y
            };

            this.tempBallPosition = {
                x: this.ballPosition.x + this.ballSpeed.x,
                y: this.ballPosition.y + this.ballSpeed.y
            };

            this.drawBall();
            this.drawPaddle();
            this.drawBricks();
            this.updateBricks();

            if (this.isBallOutOfBounds()) {
                $(window).trigger('player.died');
                return this.restart();
            }

            // If the ball has hit the wall
            if (this.hasBallHitWall()) {
                this.ballSpeed.x *= -1;
            }

            if (this.isBallNearPaddle()) {
                // Ball has hit paddle
                if (this.hasBallHitPaddle()) {
                    //move the ball differently based on where it hit the paddle
                    this.ballSpeed.x = 8 * ((this.ballPosition.x - (this.paddlex + this.paddlew / 2)) / this.paddlew);
                    this.ballSpeed.y *= -1;
                }
            } else if (this.hasBallHitTop()) {
                this.ballSpeed.y *= -1;
            }

            this.ballPosition = this.tempBallPosition;
        },

        restart: function() {
            this.ballPosition = {
                x: 25,
                y: 250,
            };
            this.ballSpeed = {
                x: 1.5,
                y: -4,
            };
        },

        initPaddle: function() {
            this.paddlex = (this.app.WIDTH - this.paddlew) / 2;
        },

        initBricks: function() {
            for(var i=0; i < this.ROW_COUNT; i++) {
                this.addRow();
            }
        },

        addRow: function() {
            // Prepend row
            this.bricks.unshift(this.createRow());
        },

        createRow: function() {
            var row = [];
            for(var i=0; i < this.COL_COUNT; i++) {
                row[i] = 1;
            }
            return row;
        },

        startAddRowInterval: function() {
            this.addRowIntervalId = setInterval($.proxy(function() {
                if (this.bricks.length < this.MAX_ROW_COUNT) {
                    this.addRow();
                }
            }, this), 5000);
        },

        drawBricks: function() {
            var rowCount = this.bricks.length;
            for(var i=0; i < rowCount; i++) {
                var row = this.bricks[i];

                this.ctx.fillStyle = (i < this.rowColours.length) ? this.rowColours[i] : this.rowColours[i % this.rowColours.length];

                var colCount = row.length;
                for(var j=0; j < colCount; j++) {
                    if (row[j] == 1) {
                        this.drawBrickForRowAndColumn(i, j);
                    }
                }
            }
        },

        drawBrickForRowAndColumn: function(row, column) {
            var x = (column * (this.BRICKWIDTH + this.PADDING)) + this.PADDING;
            var y = (row * (this.BRICKHEIGHT + this.PADDING)) + this.PADDING;
            this.rect(x, y, this.BRICKWIDTH, this.BRICKHEIGHT);
        },

        updateBricks: function() {
            //want to learn about real collision detection? go read
            // http://www.harveycartel.org/metanet/tutorials/tutorialA.html
            var rowheight = this.BRICKHEIGHT + this.PADDING;
            var colwidth = this.BRICKWIDTH + this.PADDING;
            var row = Math.floor(this.ballPosition.y / rowheight);
            var col = Math.floor(this.ballPosition.x / colwidth);
            var rowCount = this.bricks.length
            //reverse the ball and mark the brick as broken
            if (this.ballPosition.y < rowCount * rowheight && row >= 0 && col >= 0 && this.bricks[row][col] == 1) {
                this.ballSpeed.y *= -1;
                this.bricks[row][col] = 0;
                if (!this.isRowActive(this.bricks[row])) {
                    this.bricks.splice(row, 1);
                }
                $(window).trigger('brick.destroyed');
            }
        },

        isRowActive: function(row) {
            var isRowActive = false;
            var rowLength = row.length;
            for (var i=0; i < rowLength; i++) {
                var col = row[i];
                if (col == 1) {
                    isRowActive = true;
                    break;
                }
            };

            return isRowActive;
        },

        drawBall: function() {
            this.ctx.fillStyle = this.ballColour;
            this.circle(this.ballPosition.x, this.ballPosition.y, this.ballRadius);
        },

        drawPaddle: function() {

            // Move paddle
            if (this.app.rightDown && this.canPaddleMoveRight()) {
                this.paddlex += 5;
            } else if (this.app.leftDown && this.canPaddleMoveLeft()) {
                this.paddlex -= 5;
            }
            this.ctx.fillStyle = this.paddleColour;
            this.rect(this.paddlePosition.x, this.paddlePosition.y, this.paddlew, this.paddleh);
        },

        canPaddleMoveLeft: function() {
            return (this.paddlePosition.x > 0);
        },

        canPaddleMoveRight: function() {
            return (this.paddlePosition.x + this.paddlew < this.app.WIDTH);
        },

        hasBallHitWall: function() {
            return (this.tempBallPosition.x + this.ballRadius > this.app.WIDTH
                    || this.tempBallPosition.x - this.ballRadius < 0);
        },

        hasBallHitTop: function() {
            return (this.ballPosition.y + this.ballSpeed.y - this.ballRadius < 0);
        },

        /**
         * Is the ball about to hit the paddle. Check whether the ball is currently hittable
         * or whether it's too late/early
         */
        isBallNearPaddle: function() {
            return (this.tempBallPosition.y + this.ballRadius >= this.app.HEIGHT - this.paddleh + this.PADDLE_POSITION_OFFSET.y);
        },

        hasBallHitPaddle: function() {
            return (this.isBallMovingDown()
                    && this.ballPosition.x >= this.paddlePosition.x
                    && this.ballPosition.x <= this.paddlePosition.x + this.paddlew);
        },

        isBallMovingDown: function() {
            return (this.ballSpeed.y > 0);
        },

        isBallOutOfBounds: function() {
            return (this.tempBallPosition.y + this.ballRadius >= this.app.HEIGHT);
        },

        circle: function(x,y,r) {
            this.ctx.beginPath();
            this.ctx.arc(x, y, r, 0, Math.PI * 2, true);
            this.ctx.closePath();
            this.ctx.fill();
        },

        rect: function(x,y,w,h) {
            this.ctx.beginPath();
            this.ctx.rect(x, y, w, h);
            this.ctx.closePath();
            this.ctx.fill();
        },

        clear: function() {
            this.ctx.clearRect(0, 0, this.app.WIDTH, this.app.HEIGHT);
            this.rect(0, 0, this.app.WIDTH, this.app.HEIGHT);
        }
    }
});
<commit_msg>Now with inifite bricks<commit_after>define(['app'], function() {

    return {

        app: null,
        ctx: null,
        ROW_COUNT: 3,
        MAX_ROW_COUNT: 8,
        COL_COUNT: 25,
        BRICKWIDTH: 0,
        BRICKHEIGHT: 18,
        PADDING: 2,
        bricks: [],
        drawIntervalId: null,
        addRowIntervalId: null,
        ballRadius: 9,
        rowColours: ["#f2665e", "#fcb040", "#6ac071", "#57cbf5"],
        paddleColour: "#656565",
        ballColour: "#f2665e",
        backColour: "#f4f0ed",
        paddleh: 13,
        paddlew: 110,
        paddlex: 0,
        PADDLE_POSITION_OFFSET: {
            x: 0,
            y: -30
        },
        paddlePosition: {
            x: 0,
            y: 0
        },
        ballPosition: {
            x: 25,
            y: 250,
        },
        ballSpeed: {
            x: 1.5,
            y: -4,
        },
        // Used to calculate where the ball is going/what it's hitting
        tempBallPosition: {
            x: 0,
            y: 0,
        },

        init: function(app) {
            this.app = app;
            this.app.init();
            this.ctx = this.app.ctx;
            this.BRICKWIDTH = (this.app.WIDTH / this.COL_COUNT) - this.PADDING;
            this.initPaddle();
            this.initBricks();
            this.startDrawInterval();
            this.startAddRowInterval();
            this.addListeners();
        },

        reset: function() {
            this.bricks = [];
            this.initBricks();
            this.startDrawInterval();
        },

        addListeners: function() {
            $(window).on('game.over', $.proxy(function() {
                clearInterval(this.drawIntervalId);
            }, this));

            $(window).on('game.reset', $.proxy(function() {
                this.reset();
            }, this));

            $(window).on('mouse.moved', $.proxy(function(e, x, y) {
                this.paddlex = Math.max(x - this.app.canvasMinX - (this.paddlew / 2), 0);
                this.paddlex = Math.min(this.app.WIDTH - this.paddlew, this.paddlex);
            }, this));
        },

        startDrawInterval: function() {
            this.drawIntervalId = setInterval($.proxy(function() {
                this.draw();
            }, this), 10);
        },

        draw: function() {
            this.ctx.fillStyle = this.backColour;
            this.clear();

            this.paddlePosition = {
                x: this.paddlex + this.PADDLE_POSITION_OFFSET.x,
                y: this.app.HEIGHT - this.paddleh + this.PADDLE_POSITION_OFFSET.y
            };

            this.tempBallPosition = {
                x: this.ballPosition.x + this.ballSpeed.x,
                y: this.ballPosition.y + this.ballSpeed.y
            };

            this.drawBall();
            this.drawPaddle();
            this.drawBricks();
            this.updateBricks();

            if (this.isBallOutOfBounds()) {
                $(window).trigger('player.died');
                return this.restart();
            }

            // If the ball has hit the wall
            if (this.hasBallHitWall()) {
                this.ballSpeed.x *= -1;
            }

            if (this.isBallNearPaddle()) {
                // Ball has hit paddle
                if (this.hasBallHitPaddle()) {
                    //move the ball differently based on where it hit the paddle
                    this.ballSpeed.x = 8 * ((this.ballPosition.x - (this.paddlex + this.paddlew / 2)) / this.paddlew);
                    this.ballSpeed.y *= -1;
                }
            } else if (this.hasBallHitTop()) {
                this.ballSpeed.y *= -1;
            }

            this.ballPosition = this.tempBallPosition;
        },

        restart: function() {
            this.ballPosition = {
                x: 25,
                y: 250,
            };
            this.ballSpeed = {
                x: 1.5,
                y: -4,
            };
        },

        initPaddle: function() {
            this.paddlex = (this.app.WIDTH - this.paddlew) / 2;
        },

        initBricks: function() {
            for(var i=0; i < this.ROW_COUNT; i++) {
                this.addRow();
            }
        },

        addRow: function() {
            // Prepend row
            this.bricks.unshift(this.createRow());
        },

        createRow: function() {
            var row = [];
            for(var i=0; i < this.COL_COUNT; i++) {
                row[i] = 1;
            }
            return row;
        },

        startAddRowInterval: function() {
            this.addRowIntervalId = setInterval($.proxy(function() {
                if (this.bricks.length < this.MAX_ROW_COUNT) {
                    this.addRow();
                }
            }, this), 5000);
        },

        drawBricks: function() {
            var rowCount = this.bricks.length;
            for(var i=0; i < rowCount; i++) {
                var row = this.bricks[i];

                this.ctx.fillStyle = (i < this.rowColours.length) ? this.rowColours[i] : this.rowColours[i % this.rowColours.length];

                var colCount = row.length;
                for(var j=0; j < colCount; j++) {
                    if (row[j] == 1) {
                        this.drawBrickForRowAndColumn(i, j);
                    }
                }
            }
        },

        drawBrickForRowAndColumn: function(row, column) {
            var x = (column * (this.BRICKWIDTH + this.PADDING)) + this.PADDING;
            var y = (row * (this.BRICKHEIGHT + this.PADDING)) + this.PADDING;
            this.rect(x, y, this.BRICKWIDTH, this.BRICKHEIGHT);
        },

        updateBricks: function() {
            //want to learn about real collision detection? go read
            // http://www.harveycartel.org/metanet/tutorials/tutorialA.html
            var rowheight = this.BRICKHEIGHT + this.PADDING;
            var colwidth = this.BRICKWIDTH + this.PADDING;
            var row = Math.floor(this.ballPosition.y / rowheight);
            var col = Math.floor(this.ballPosition.x / colwidth);
            var rowCount = this.bricks.length
            //reverse the ball and mark the brick as broken
            if (this.ballPosition.y < rowCount * rowheight && row >= 0 && col >= 0 && this.bricks[row][col] == 1) {
                this.ballSpeed.y *= -1;
                this.bricks[row][col] = 0;
                if (!this.isLastRowActive()) {
                    // Remove row
                    this.bricks.splice(row, 1);
                }
                $(window).trigger('brick.destroyed');
            }
        },

        isLastRowActive: function() {
            var isRowActive = false;

            var lastRow = this.bricks[this.bricks.length - 1];
            for (var i=0; i < this.COL_COUNT; i++) {
                var col = lastRow[i];
                if (col == 1) {
                    isRowActive = true;
                    break;
                }
            };

            return isRowActive;
        },

        drawBall: function() {
            this.ctx.fillStyle = this.ballColour;
            this.circle(this.ballPosition.x, this.ballPosition.y, this.ballRadius);
        },

        drawPaddle: function() {

            // Move paddle
            if (this.app.rightDown && this.canPaddleMoveRight()) {
                this.paddlex += 5;
            } else if (this.app.leftDown && this.canPaddleMoveLeft()) {
                this.paddlex -= 5;
            }
            this.ctx.fillStyle = this.paddleColour;
            this.rect(this.paddlePosition.x, this.paddlePosition.y, this.paddlew, this.paddleh);
        },

        canPaddleMoveLeft: function() {
            return (this.paddlePosition.x > 0);
        },

        canPaddleMoveRight: function() {
            return (this.paddlePosition.x + this.paddlew < this.app.WIDTH);
        },

        hasBallHitWall: function() {
            return (this.tempBallPosition.x + this.ballRadius >= this.app.WIDTH
                    || this.tempBallPosition.x - this.ballRadius <= 0);
        },

        hasBallHitTop: function() {
            return (this.ballPosition.y + this.ballSpeed.y - this.ballRadius < 0);
        },

        /**
         * Is the ball about to hit the paddle. Check whether the ball is currently hittable
         * or whether it's too late/early
         */
        isBallNearPaddle: function() {
            return (this.tempBallPosition.y + this.ballRadius >= this.app.HEIGHT - this.paddleh + this.PADDLE_POSITION_OFFSET.y);
        },

        hasBallHitPaddle: function() {
            return (this.isBallMovingDown()
                    && this.ballPosition.x >= this.paddlePosition.x
                    && this.ballPosition.x <= this.paddlePosition.x + this.paddlew);
        },

        isBallMovingDown: function() {
            return (this.ballSpeed.y > 0);
        },

        isBallOutOfBounds: function() {
            return (this.tempBallPosition.y + this.ballRadius >= this.app.HEIGHT);
        },

        circle: function(x,y,r) {
            this.ctx.beginPath();
            this.ctx.arc(x, y, r, 0, Math.PI * 2, true);
            this.ctx.closePath();
            this.ctx.fill();
        },

        rect: function(x,y,w,h) {
            this.ctx.beginPath();
            this.ctx.rect(x, y, w, h);
            this.ctx.closePath();
            this.ctx.fill();
        },

        clear: function() {
            this.ctx.clearRect(0, 0, this.app.WIDTH, this.app.HEIGHT);
            this.rect(0, 0, this.app.WIDTH, this.app.HEIGHT);
        }
    }
});
<|endoftext|>


<commit_before>if (!String.prototype.trim) {
    String.prototype.trim = function () {
        return this.replace(/^\s+|\s+$/g, '');
    };
}
/******************************************************************************/
/********************************* Atto class *********************************/
/******************************************************************************/
var Atto = (function AttoClosure() {
    'use strict';
    var attoMap = {},
        emptyArray = [],
        slice = emptyArray.slice,
        atto,
        constants = {
            ATTO_SELECTOR_CLASS_PREFIX: 'js-atto-selector-'
        };

    function AttoException(message) {
        this.message = message;
        this.name = 'methodNotDefined';
        this.toString = function () {
            return this.message;
        };
    }

    /**************************************************************************/
    /***************************** private method *****************************/
    /**************************************************************************/
    function extend(obj1, obj2) {
        var returnObject = {};
        for (var prop in obj2) {
            if (obj2.hasOwnProperty(prop)) {
                returnObject[prop] = obj2[prop];
            }
        }
        for (var prop in obj1) {
            if (obj1.hasOwnProperty(prop)) {
                returnObject[prop] = obj1[prop];
            }
        }
        return returnObject;
    }
    function renderAttoElement(render, renderInSection) {
        if (renderInSection) {
            var section = document.createElement('section');
            if (typeof render === 'string') {
                section.innerHTML = render.trim();
            } else {
                section.appendChild(render);
            }
            return section;
        } else if (typeof render === 'string') {
            var div = document.createElement('div'),
                fragmet = document.createDocumentFragment();

            div.innerHTML = render.trim();
            while(div.firstChild) {
                fragmet.appendChild(div.firstChild);
            }

            // flag to know it is a fragment
            fragmet.isFragment = true;
            return fragmet;
        }
        return render;
    }
    function renderIntoElement(element) {
        var map = attoMap, elements,
            newElement = element.cloneNode(true),
            newElement1 = document.createDocumentFragment(),
            attributes = newElement.attributes,
            i, len;

        newElement.innerHTML = element.innerHTML;
        element.innerHTML = '';

        for (var name in map) {
            if (map.hasOwnProperty(name)) {
                elements = newElement.getElementsByTagName(map[name].name);
                while (0 < elements.length) {
                    new Atto({
                        target: elements[0],
                        name: name,
                        renderInSection: true
                    }).render(true);
                }
            }
        }

        element.parentNode.replaceChild(newElement, element);
    };

    /**************************************************************************/
    /****************************** constructor *******************************/
    /**************************************************************************/
    function Atto(option) {
        //target, name, configObject, thisObj, customAttributes, renderInSection
        var config,
            len, i,
            props = {}, attributes, target, customAttributes;

        config = option.config || attoMap[option.name] || {};
        target = option.target || [];
        customAttributes = option.ttributes || {};
        if (!config.isExtened && config.hasOwnProperty('extend')) {
            this.parent = attoMap[config.extend];
            this.config = extend(config, this.parent);
        } else {
            this.config = config;
        }
        if (target.hasOwnProperty('attributes')) {
            attributes = target.attributes;
            len = attributes.length;
            for (i = 0; i < len; i++) {
                props[attributes[i].name] = attributes[i].value;
            }
        }
        this.mergeWith(this.config);

        this.mergeWith.call(props, customAttributes);
        this.props = props;
        this.target = target
        this.class = config.class;
        this.id = config.id;
        this.renderInSection = option.renderInSection;
    };

    /**************************************************************************/
    /***************************** public method ******************************/
    /**************************************************************************/
    Atto.prototype = {
        AttoFromConfig: function Atto_renderFromConfig(config, thisObj) {
        },
        render: function Atto_render(inDom) {
            var renderer = this.config.render.apply(this, [this.config, this]),
                attributes = this.attributes,
                activeElement,
                element = renderAttoElement(renderer, this.renderInSection);
            if (typeof element === 'undefined') {
                throw new AttoException(
                    'Render method must be implemented and should return value.'
                );
            // render must be implement and return value
            } else if (element.isFragment) {
                activeElement = element.childNodes[0];
            } else {
                activeElement = element;
                for (var att in attributes) {
                    if (attributes.hasOwnProperty(att)) {
                        activeElement.setAttribute(att, attributes[att]);
                    }
                }
            }
            activeElement.settingAtto = this.config;
            activeElement.className += ' ' + (this.class || '') +
            (this.config.name ?
                 ' ' +
                 constants.ATTO_SELECTOR_CLASS_PREFIX + this.config.name
                 : '');
            if (this.id) {
                activeElement.id = this.id;
            }
            this.element = element;
            // put new element in dom
            if (inDom) {
                this.insert();
            }
            return activeElement;
        },

        insert: function Atto_insert() {
            this.target.parentNode.replaceChild(this.element, this.target);
        },
        setAttribute: function Atto_setattribute(name, value) {
            this.attributes[name] = value;
        },
        removeAttribute: function Atto_removeAttribute(name) {
            if (this.attributes.hasOwnProperty(name)) {
                delete this.attributes[name];
            }
        },
        get: function Atto_get(name) {
            if (attoMap.hasOwnProperty(name)) {
                return new Atto({
                    name: name
                });
            }
            return null;
        },
        observer: function Atto_event(name, callBack) {
            AttoNotification.observer(name, callBack, this);
        },
        post: function Atto_post(name, mixin) {
            AttoNotification.post(name, mixin);
        },
        rerender: function Atto_rerender() {
            this.target = this.element;
            this.render(true);
        },
        mergeWith: function Atto_mergeWith(object) {
            for (var prop in object) {
                if (object.hasOwnProperty(prop) && prop !== 'render') {
                    this[prop] = object[prop];
                }
            }
        }
    };

    /**************************************************************************/
    /***************************** static method ******************************/
    /**************************************************************************/
    Atto.define = function Atto_define(config) {
        if (config.hasOwnProperty('name')) {
           if (config.hasOwnProperty('extend')) {
               var ext = attoMap[config.extend];
               if (!ext) {
                   throw new AttoException(
                       'Cannot extend, unknown component "' + config.extend +
                       '".'
                   );
               }
               attoMap[config.name] = extend(config, ext);
               attoMap[config.name].isExtend = true;
           } else {
               attoMap[config.name] = config;
           }
        } else {
           throw new AttoException(
               'Name configuration property must be defined.'
           );
        }
    };
    Atto.run = function Atto_run(settings) {
        var elements, len, i;

        settings = settings || {};

        if (settings.hasOwnProperty('target') &&
            (elements = settings.target) &&
            typeof elements.length === 'number') {
            len = elements.length;
            for (i = 0; i < len; i++) {
                renderIntoElement(elements[i]);
            }
        } else {
            renderIntoElement(document.body);
        }
        this.settings = settings;
    };
    Atto.create = function Atto_create(config) {
        if (typeof config === 'object') {
            return new Atto({
                config: config,
                renderInSection: false
            });
        }
        // throw error
        return null;
    };

    Atto.find = function Atto_find(name, scope) {
        var elements,
            list = [],
            len, i, el;
        scope = scope || document;
        if (attoMap.hasOwnProperty(name)) {
            elements = scope.getElementsByClassName(
                constants.ATTO_SELECTOR_CLASS_PREFIX + name
            );
            len = elements.length;
            for (i = 0; i < len; i++) {
                el = elements[i];
                list.push(new Atto({target: el,
                    name: el.settingAtto.name,
                    config: el.settingAtto
                }));
            }

            return list;
        }

        return null;
    };

    Atto.get = function Atto_get(name, attributes) {
        if (attoMap.hasOwnProperty(name)) {
            return new Atto({
                name: name,
                config: attoMap[name],
                attributes: attributes,
                renderInSection: false
            });
        }
        // throw error
        return null;
    };

    return Atto;
}());

var AttoNotification = (function AttoNotificationClosure() {
    'use strict';
    var notification = {};
    function AttoNotification(notificationName, callBack, id, context) {
        this.name = notificationName;
        this.callBack = callBack || function () {};
        this.id = id;
        this.target = context;
    }

    AttoNotification.prototype = {
        execute: function AttoNotification_execute(mixin) {
            this.callBack.apply(this.target, [mixin, this]);
        }
    };

    AttoNotification.observer = function AttoNotification_observer(name, callBack, context) {
        var notif, id;

        if (!notification.hasOwnProperty(name)) {
            notification[name] = [];
        }

        if (!context.hasOwnProperty('notifications')) {
            context.notifications = {};
        }

        notif = notification[name];
        id = notif.length;

        if (typeof context.notifications[name] === 'undefined') {
            notif.push(new AttoNotification(name, callBack, id, context));
            context.notifications[name] = id;
        }
    }
    AttoNotification.post = function AttoNotification_post(name, mixin) {
        var list, len, i = 0;
        if (notification.hasOwnProperty(name)) {
            list = notification[name];
        }
        len = list.length;
        var interval = setInterval(function () {
            if (i > len) {
                clearInterval(interval);
            }
            if (typeof list[i] !== 'undefined') {
                list[i].execute(mixin);
            } else {
                clearInterval(interval);
            }
            i++;
        }, 10);
    };

    return AttoNotification;
}());

<commit_msg>refactor renderAttoElement<commit_after>if (!String.prototype.trim) {
    String.prototype.trim = function () {
        return this.replace(/^\s+|\s+$/g, '');
    };
}
/******************************************************************************/
/********************************* Atto class *********************************/
/******************************************************************************/
var Atto = (function AttoClosure() {
    'use strict';
    var attoMap = {},
        emptyArray = [],
        slice = emptyArray.slice,
        atto,
        constants = {
            ATTO_SELECTOR_CLASS_PREFIX: 'js-atto-selector-'
        },
        AttoNotification;

    function AttoException(message) {
        this.message = message;
        this.name = 'methodNotDefined';
        this.toString = function () {
            return this.message;
        };
    }

    /**************************************************************************/
    /***************************** private method *****************************/
    /**************************************************************************/
    function extend(obj1, obj2) {
        var returnObject = {},
            prop;
        for (prop in obj2) {
            if (obj2.hasOwnProperty(prop)) {
                returnObject[prop] = obj2[prop];
            }
        }
        for (prop in obj1) {
            if (obj1.hasOwnProperty(prop)) {
                returnObject[prop] = obj1[prop];
            }
        }
        return returnObject;
    }
    function renderAttoElement(render, renderInSection) {
        var wrapper, len, i;
        if (renderInSection) {
            wrapper = document.createElement('section');
        } else {
            wrapper = document.createDocumentFragment();
            wrapper.isFragment = true;
        }
        if (toString.call(render) === '[object Array]') {
            len = render.length;
            for (i = 0; i < len; i++) {
                wrapper.appendChild(render[i]);
            }
        } else if (typeof render === 'string') {
            wrapper.innerHTML = render.trim();
        } else {
            wrapper.appendChild(render);
        }
        return wrapper;
    }
    function renderIntoElement(element) {
        var map = attoMap, elements,
            newElement = element.cloneNode(true),
            newElement1 = document.createDocumentFragment(),
            attributes = newElement.attributes,
            i, len, name;

        newElement.innerHTML = element.innerHTML;
        element.innerHTML = '';

        for (name in map) {
            if (map.hasOwnProperty(name)) {
                elements = newElement.getElementsByTagName(map[name].name);
                while (0 < elements.length) {
                    new Atto({
                        target: elements[0],
                        name: name,
                        renderInSection: true
                    }).render(true);
                }
            }
        }

        element.parentNode.replaceChild(newElement, element);
    }

    /**************************************************************************/
    /****************************** constructor *******************************/
    /**************************************************************************/
    function Atto(option) {
        //target, name, configObject, thisObj, customAttributes, renderInSection
        var config,
            len,
            i,
            props = {},
            attributes,
            target,
            customAttributes;

        config = option.config || attoMap[option.name] || {};
        target = option.target || [];
        customAttributes = option.ttributes || {};
        if (!config.isExtened && config.hasOwnProperty('extend')) {
            this.parent = attoMap[config.extend];
            this.config = extend(config, this.parent);
        } else {
            this.config = config;
        }
        if (target.hasOwnProperty('attributes')) {
            attributes = target.attributes;
            len = attributes.length;
            for (i = 0; i < len; i++) {
                props[attributes[i].name] = attributes[i].value;
            }
        }
        this.mergeWith(this.config);

        this.mergeWith.call(props, customAttributes);
        this.props = props;
        this.target = target;
        this.class = config.class;
        this.id = config.id;
        this.renderInSection = option.renderInSection;
    }

    /**************************************************************************/
    /***************************** public method ******************************/
    /**************************************************************************/
    Atto.prototype = {
        AttoFromConfig: function Atto_renderFromConfig(config, thisObj) {
        },
        render: function Atto_render(inDom) {
            var renderer = this.config.render.apply(this, [this.config, this]),
                attributes = this.attributes,
                activeElement,
                element = renderAttoElement(renderer, this.renderInSection),
                att;
            if (typeof element === 'undefined') {
                throw new AttoException(
                    'Render method must be implemented and should return value.'
                );
            // render must be implement and return value
            } else if (element.isFragment) {
                activeElement = element.childNodes[0];
            } else {
                activeElement = element;
                for (att in attributes) {
                    if (attributes.hasOwnProperty(att)) {
                        activeElement.setAttribute(att, attributes[att]);
                    }
                }
            }
            activeElement.settingAtto = this.config;
            activeElement.className += ' ' + (this.class || '') +
                (this.config.name ?
                        ' ' +
                        constants.ATTO_SELECTOR_CLASS_PREFIX + this.config.name
                        : '');
            if (this.id) {
                activeElement.id = this.id;
            }
            this.element = element;
            // put new element in dom
            if (inDom) {
                this.insert();
            }
            return activeElement;
        },

        insert: function Atto_insert() {
            this.target.parentNode.replaceChild(this.element, this.target);
        },
        setAttribute: function Atto_setattribute(name, value) {
            this.attributes[name] = value;
        },
        removeAttribute: function Atto_removeAttribute(name) {
            if (this.attributes.hasOwnProperty(name)) {
                delete this.attributes[name];
            }
        },
        get: function Atto_get(name) {
            if (attoMap.hasOwnProperty(name)) {
                return new Atto({
                    name: name
                });
            }
            return null;
        },
        observer: function Atto_event(name, callBack) {
            AttoNotification.observer(name, callBack, this);
        },
        post: function Atto_post(name, mixin) {
            AttoNotification.post(name, mixin);
        },
        rerender: function Atto_rerender() {
            this.target = this.element;
            this.render(true);
        },
        mergeWith: function Atto_mergeWith(object) {
            var prop;
            for (prop in object) {
                if (object.hasOwnProperty(prop) && prop !== 'render') {
                    this[prop] = object[prop];
                }
            }
        }
    };

    /**************************************************************************/
    /***************************** static method ******************************/
    /**************************************************************************/
    Atto.define = function Atto_define(config) {
        if (config.hasOwnProperty('name')) {
            if (config.hasOwnProperty('extend')) {
                var ext = attoMap[config.extend];
                if (!ext) {
                    throw new AttoException(
                        'Cannot extend, unknown component "' + config.extend +
                            '".'
                    );
                }
                attoMap[config.name] = extend(config, ext);
                attoMap[config.name].isExtend = true;
            } else {
                attoMap[config.name] = config;
            }
        } else {
            throw new AttoException(
                'Name configuration property must be defined.'
            );
        }
    };
    Atto.run = function Atto_run(settings) {
        var elements,
            len,
            i;

        settings = settings || {};

        if (settings.hasOwnProperty('target') &&
                (elements = settings.target) &&
                typeof elements.length === 'number') {
            len = elements.length;
            for (i = 0; i < len; i++) {
                renderIntoElement(elements[i]);
            }
        } else {
            renderIntoElement(document.body);
        }
        this.settings = settings;
    };
    Atto.create = function Atto_create(config) {
        if (typeof config === 'object') {
            return new Atto({
                config: config,
                renderInSection: false
            });
        }
        // throw error
        return null;
    };

    Atto.find = function Atto_find(name, scope) {
        var elements,
            list = [],
            len,
            i,
            el;
        scope = scope || document;
        if (attoMap.hasOwnProperty(name)) {
            elements = scope.getElementsByClassName(
                constants.ATTO_SELECTOR_CLASS_PREFIX + name
            );
            len = elements.length;
            for (i = 0; i < len; i++) {
                el = elements[i];
                list.push(new Atto({target: el,
                    name: el.settingAtto.name,
                    config: el.settingAtto
                    }));
            }

            return list;
        }

        return null;
    };

    Atto.get = function Atto_get(name, attributes) {
        if (attoMap.hasOwnProperty(name)) {
            return new Atto({
                name: name,
                config: attoMap[name],
                attributes: attributes,
                renderInSection: false
            });
        }
        // throw error
        return null;
    };

    AttoNotification = (function AttoNotificationClosure() {
        var notification = {};
        function AttoNotification(notificationName, callBack, id, context) {
            this.name = notificationName;
            this.callBack = callBack || function () {};
            this.id = id;
            this.target = context;
        }

        AttoNotification.prototype = {
            execute: function AttoNotification_execute(mixin) {
                this.callBack.apply(this.target, [mixin, this]);
            }
        };

        AttoNotification.observer = function AttoNotification_observer(name, callBack, context) {
            var notif, id;

            if (!notification.hasOwnProperty(name)) {
                notification[name] = [];
            }

            if (!context.hasOwnProperty('notifications')) {
                context.notifications = {};
            }

            notif = notification[name];
            id = notif.length;

            if (typeof context.notifications[name] === 'undefined') {
                notif.push(new AttoNotification(name, callBack, id, context));
                context.notifications[name] = id;
            }
        };
        AttoNotification.post = function AttoNotification_post(name, mixin) {
            var list,
                len,
                i = 0,
                interval;
            if (notification.hasOwnProperty(name)) {
                list = notification[name];
            }
            len = list.length;
            interval = setInterval(function () {
                if (i > len) {
                    clearInterval(interval);
                }
                if (typeof list[i] !== 'undefined') {
                    list[i].execute(mixin);
                } else {
                    clearInterval(interval);
                }
                i++;
            }, 10);
        };

        return AttoNotification;
    }());

    return Atto;
}());
<|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;

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

  function createSnake() {
    var length = 5;
    snakeArray = [];
    for (var i = length - 1; i >= 0; i--) {
      snakeArray.push({x:i, y:0});
    }
  }

  function createFood() {
    food = {
      x: Math.round(Math.random()*(width-cellWidth)/cellWidth),
      y: Math.round(Math.random()*(height-cellWidth)/cellWidth),
    };
  }

  function design() {
    contex.fillStyle = "white";
    contex.fillRect(0, 0, width, height);
    contex.strokeStyle = "black";
    contex.strokeRect(0, 0, width, height);
    var directionX = snakeArray[0].x;
    var directionY = snakeArray[0].y;
    if(defaultDirection == "right") directionX++;
    else if(defaultDirection == "left") directionX--;
    else if(defaultDirection == "up") directionY--;
    else if(defaultDirection == "down") directionY++;

    if(directionX == -1 || directionX == width/cellWidth || directionY == -1 || directionY == height/cellWidth || checkCollision(directionX, directionY, snakeArray)) {
      init();
      return;
    }

    if(directionX == food.x && directionY == food.y) {
      var tail = {x: directionX, y: directionY};
      score++;
      createFood();
    } else {
      var tail = snakeArray.pop();
      tail.x = directionX; tail.y = directionY;
    }
    snakeArray.unshift(tail);
    for(var i = 0; i < snakeArray.length; i++) {
      var cell = snakeArray[i];
      paint_cell(cell.x, cell.y);
    }

  }

});<commit_msg>add score variable to show score of game<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();

  function createSnake() {
    var length = 5;
    snakeArray = [];
    for (var i = length - 1; i >= 0; i--) {
      snakeArray.push({x:i, y:0});
    }
  }

  function createFood() {
    food = {
      x: Math.round(Math.random()*(width-cellWidth)/cellWidth),
      y: Math.round(Math.random()*(height-cellWidth)/cellWidth),
    };
  }

  function design() {
    contex.fillStyle = "white";
    contex.fillRect(0, 0, width, height);
    contex.strokeStyle = "black";
    contex.strokeRect(0, 0, width, height);
    var directionX = snakeArray[0].x;
    var directionY = snakeArray[0].y;
    if(defaultDirection == "right") directionX++;
    else if(defaultDirection == "left") directionX--;
    else if(defaultDirection == "up") directionY--;
    else if(defaultDirection == "down") directionY++;

    if(directionX == -1 || directionX == width/cellWidth || directionY == -1 || directionY == height/cellWidth || checkCollision(directionX, directionY, snakeArray)) {
      init();
      return;
    }

    if(directionX == food.x && directionY == food.y) {
      var tail = {x: directionX, y: directionY};
      score++;
      createFood();
    } else {
      var tail = snakeArray.pop();
      tail.x = directionX; tail.y = directionY;
    }

    snakeArray.unshift(tail);
    for(var i = 0; i < snakeArray.length; i++) {
      var cell = snakeArray[i];
      paint_cell(cell.x, cell.y);
    }

    paint_cell(food.x, food.y);
    var scoreText = "Score:" + score;
    contex.fillText(scoreText, 5, height - 5);
  }

});<|endoftext|>


<commit_before>export class TransmissionPower {

  constructor(dom) {
    this.dom = dom;
    this.dom.data('controller', this);
    this.sliderOptions = {
      tooltip: 'hide',
      ticks: [0,1,2,3,4,5,6,7]
    }
    this.setupView();
    this.slider = this.dom.data().slider;
    this.selected = $(this.slider.trackSelection);
    this.picker = $(this.slider.sliderElem);
    this.sliderChanged(this.dom.val());
  }

  setupView() {
    const changed = (obj) => {
      let sliderNewValue = obj.value.newValue
      this.sliderChanged(sliderNewValue);
    };

    this.dom.
      slider(this.sliderOptions).
      on('change', changed);
  }

  sliderChanged(sliderNewValue) {
    if (sliderNewValue == 0){
      this.slider.setValue(1, false, true);
      return false;
    }

    this.picker.attr('slider-select-value', sliderNewValue);
    this.dom.parents('.controls').find('.transmission-power-value span').text(sliderNewValue);
  }
}

$(function () {
  const el = $('#transmission_power');
  el.length && new TransmissionPower(el);
});<commit_msg>BOS-FF: Change property creator<commit_after>export class TransmissionPower {
  sliderOptions = {
    tooltip: 'hide',
    ticks: [0,1,2,3,4,5,6,7]
  };

  constructor(dom) {
    this.dom = dom;
    this.dom.data('controller', this);
    this.setupView();
    this.slider = this.dom.data().slider;
    this.selected = $(this.slider.trackSelection);
    this.picker = $(this.slider.sliderElem);
    this.sliderChanged(this.dom.val());
  }

  setupView() {
    const changed = (obj) => {
      let sliderNewValue = obj.value.newValue
      this.sliderChanged(sliderNewValue);
    };

    this.dom.
      slider(this.sliderOptions).
      on('change', changed);
  }

  sliderChanged(sliderNewValue) {
    if (sliderNewValue == 0){
      this.slider.setValue(1, false, true);
      return false;
    }

    this.picker.attr('slider-select-value', sliderNewValue);
    this.dom.parents('.controls').find('.transmission-power-value span').text(sliderNewValue);
  }
}

$(function () {
  const el = $('#transmission_power');
  el.length && new TransmissionPower(el);
});<|endoftext|>