<commit_before>
// blockCoordinates = [4,0,4,1,5,0,5,1];
// singleCoordinates = [0,0];
// var canvas = document.getElementById("myCanvas");
// var ctx = canvas.getContext("2d");
// canvas.width = 300;
// canvas.height = 600;
// var handle = 0

// var piece = function(name) {

//   this.name = name

//   var renderLoop = function(name) {
//       this.name = name
//       for(i=1;i<name.length;i+=2){
//         name[i] += 1
//       };

//       if (name[1] < 19) {
//       canvas.width = canvas.width
//       drawPiece(name);

//       handle = window.requestAnimationFrame(renderLoop);
//       }
//           };renderLoop();

//     if (name === "single") {
//       renderLoop(singleCoordinates);
//     };
//     if (name === "block") {
//        drawPiece(blockCoordinates);
//     };
//   };

//   var drawPiece = function(coordinates){
//     for (i=0;i<coordinates.length;i+=2) {
//       x = coordinates[i];
//       y = coordinates[i + 1];
//       a = new square(x,y);
//       console.log(a);
//     }
//   }

//   var square = function(x, y) {
//     var unit = 30;
//     x = x*unit
//     y = y*unit
//     this.y = y
//     this.x = x
//     ctx.rect(x,y,30,30);
//     ctx.stroke();

//   };

//   var gravity = function() {

//   }

//   a = new piece("block")
//   a.coordinates;

//   var start = null;

Game = {
  FRAME_DELAY: 70,
  lastTick: 0,
  pieces: [],
  maxLine: 570,
};

Game.start = function(){
  Game.onAnimationFrame();
  board = new Game.Board
};

Game.onAnimationFrame = function(){
  var now = new Date().getTime();
  if ((now - this.lastTick) > this.FRAME_DELAY){
    this.tick();
  }
  requestAnimationFrame(this.onAnimationFrame);
}.bind(Game);

Game.tick = function(){
  this.lastTick = new Date().getTime();
  console.log('GAME TICK');
  this.pieces[this.pieces.length-1].drop();
  this.redraw();
}

// this.pieces.forEach(function(piece){
//     piece.drop(piece);
//   });

Game.redraw = function(){
  var canvas = document.getElementById("myCanvas");
  var ctx = canvas.getContext("2d");
  canvas.width = 300;
  canvas.height = 600;

  // WTF PANDA! (why????)
  // ctx.clearRect(0, 0,9999,9999);
  canvas.width = canvas.width

  this.pieces.forEach(function(piece){
    ctx.rect(piece.x,piece.y,30,30);
    ctx.stroke();
  });
  return this;
};

// for i in
Game.getMaxLine = function(){
  console.log(Game.pieces[Game.pieces.length - 1])
  console.log(Game.maxLine)
  for (i=0; i< Game.pieces.length; i++){
    if (Game.pieces[i].y === Game.maxLine) {
      Game.maxLine = (Game.pieces[i].y - 30);
    }
    else {
      console.log("fuck")
    }
    console.log(Game.maxLine)
  }
};

console.log(Game.maxLine);

Game.Board = function(){
  this.column = [[],[],[],[],[],[],[],[],[],[]];
  this.row = [[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[]];
};

Game.Piece = function(options){
  this.x = options.x;
  this.y = options.y;
};

Game.Piece.prototype.moveLeft = function(current_piece){
  this.x -= 30;
};

Game.Piece.prototype.moveRight = function(current_piece){
  this.x += 30;
};

Game.Piece.prototype.drop = function(current_piece){
  if (this.y < Game.maxLine) {
    this.y += 10;

  }
  else {
    Game.Board();
    board.column[this.x/30].push(this)
    console.log(board.column)
    Game.getMaxLine();
    Game.pieces.push(new Game.Piece({x:30,y:0,}))
  }

};

// if (!Game.Piece.drop();) {
  Game.pieces.push(new Game.Piece({x:30,y:0,}))
// }

// (Game.Board.maxLine) && (this.x !== Game.Board.maxLine.column)
//   var drawPiece = function(coordinates){
//     for (i=0;i<coordinates.length;i+=2) {
//       x = coordinates[i];
//       y = coordinates[i + 1];
//       a = new square(x,y);
//       console.log(a);
//     }
//   }

//   var square = function(x, y) {
//     var unit = 30;
//     x = x*unit
//     y = y*unit
//     this.y = y
//     this.x = x
//     ctx.rect(x,y,30,30);
//     ctx.stroke();

//   };

window.addEventListener('keydown', function(event) {
  switch(event.keyCode) {
    case 37:
    this.Game.pieces[this.Game.pieces.length-1].moveLeft();
  }
  switch(event.keyCode) {
    case 39:
    this.Game.pieces[this.Game.pieces.length-1].moveRight();
  }
});

Game.start()

<commit_msg>add a get maxColumn method unfinished<commit_after>
// blockCoordinates = [4,0,4,1,5,0,5,1];
// singleCoordinates = [0,0];
// var canvas = document.getElementById("myCanvas");
// var ctx = canvas.getContext("2d");
// canvas.width = 300;
// canvas.height = 600;
// var handle = 0

// var piece = function(name) {

//   this.name = name

//   var renderLoop = function(name) {
//       this.name = name
//       for(i=1;i<name.length;i+=2){
//         name[i] += 1
//       };

//       if (name[1] < 19) {
//       canvas.width = canvas.width
//       drawPiece(name);

//       handle = window.requestAnimationFrame(renderLoop);
//       }
//           };renderLoop();

//     if (name === "single") {
//       renderLoop(singleCoordinates);
//     };
//     if (name === "block") {
//        drawPiece(blockCoordinates);
//     };
//   };

//   var drawPiece = function(coordinates){
//     for (i=0;i<coordinates.length;i+=2) {
//       x = coordinates[i];
//       y = coordinates[i + 1];
//       a = new square(x,y);
//       console.log(a);
//     }
//   }

//   var square = function(x, y) {
//     var unit = 30;
//     x = x*unit
//     y = y*unit
//     this.y = y
//     this.x = x
//     ctx.rect(x,y,30,30);
//     ctx.stroke();

//   };

//   var gravity = function() {

//   }

//   a = new piece("block")
//   a.coordinates;

//   var start = null;

Game = {
  FRAME_DELAY: 70,
  lastTick: 0,
  pieces: [],
  maxLine: 570,
};

Game.start = function(){
  Game.onAnimationFrame();
  board = new Game.Board
};

Game.onAnimationFrame = function(){
  var now = new Date().getTime();
  if ((now - this.lastTick) > this.FRAME_DELAY){
    this.tick();
  }
  requestAnimationFrame(this.onAnimationFrame);
}.bind(Game);

Game.tick = function(){
  this.lastTick = new Date().getTime();
  console.log('GAME TICK');
  this.pieces[this.pieces.length-1].drop();
  this.redraw();
}

// this.pieces.forEach(function(piece){
//     piece.drop(piece);
//   });

Game.redraw = function(){
  var canvas = document.getElementById("myCanvas");
  var ctx = canvas.getContext("2d");
  canvas.width = 300;
  canvas.height = 600;

  // WTF PANDA! (why????)
  // ctx.clearRect(0, 0,9999,9999);
  canvas.width = canvas.width

  this.pieces.forEach(function(piece){
    ctx.rect(piece.x,piece.y,30,30);
    ctx.stroke();
  });
  return this;
};

// for i in
Game.getMaxLine = function(){
  console.log(Game.pieces[Game.pieces.length - 1])
  console.log(Game.maxLine)
  for (i=0; i< Game.pieces.length; i++){
    if (Game.pieces[i].y === Game.maxLine) {
      Game.maxLine = (Game.pieces[i].y - 30);
    }
    else {
      console.log("fuck")
    }
    console.log(Game.maxLine)
  }
};

console.log(Game.maxLine);

Game.Board = function(){
  this.column = [[],[],[],[],[],[],[],[],[],[]];
  this.row = [[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[]];
};

Game.Board.prototype.getMaxLineOfColumn = (function(columnz) {
  max = 570
  for (i=0;i<board.column[columnz].length; i++) {
    if (this.column[columnz][i].x > this.column[columnz][i+1].x) {
      max = this.column[columnz][i].x
      console.log(max)
    };
  };
})();

Game.Piece = function(options){
  this.x = options.x;
  this.y = options.y;
};

Game.Piece.prototype.moveLeft = function(current_piece){
  this.x -= 30;
};

Game.Piece.prototype.moveRight = function(current_piece){
  this.x += 30;
};

Game.Piece.prototype.drop = function(current_piece){
  column = this.x/30;
  if (this.y < Game.Board.getMaxLineOfColumn(this.x/30)) {
    this.y += 10;

  }
  else {
    board.column[this.x/30].push(this)
    console.log(board.column)
    Game.getMaxLine();
    Game.pieces.push(new Game.Piece({x:30,y:0,}))
  }

};

// if (!Game.Piece.drop();) {
  Game.pieces.push(new Game.Piece({x:30,y:0,}))
// }

// (Game.Board.maxLine) && (this.x !== Game.Board.maxLine.column)
//   var drawPiece = function(coordinates){
//     for (i=0;i<coordinates.length;i+=2) {
//       x = coordinates[i];
//       y = coordinates[i + 1];
//       a = new square(x,y);
//       console.log(a);
//     }
//   }

//   var square = function(x, y) {
//     var unit = 30;
//     x = x*unit
//     y = y*unit
//     this.y = y
//     this.x = x
//     ctx.rect(x,y,30,30);
//     ctx.stroke();

//   };

window.addEventListener('keydown', function(event) {
  switch(event.keyCode) {
    case 37:
    this.Game.pieces[this.Game.pieces.length-1].moveLeft();
  }
  switch(event.keyCode) {
    case 39:
    this.Game.pieces[this.Game.pieces.length-1].moveRight();
  }
});

Game.start()

<|endoftext|>


<commit_before>/*
 * Raphael SVG Import 0.0.1 - Extension to Raphael JS
 *
 * Copyright (c) 2009 Wout Fierens; Georgi Momchilov 2011
 * Licensed under the MIT (http://www.opensource.org/licenses/mit-license.php) license.
 */
Raphael.fn.importSVG = function (raw_svg) {
  try {
    if (raw_svg.blank()){
      throw "No data was provided.";
    }
    raw_svg = raw_svg.gsub(/\n|\r|\t/, '');
    if (!raw_svg.match(/<svg(.*?)>(.*)<\/svg>/i)){
      throw "The data you entered doesn't contain SVG.";
    }
    raw_svg.scan(/<(rect|polyline|circle|ellipse|path|polygon|image|text)(.*?)\/>/, (function(match) {
        var attr = { "stroke-width": 0, "fill":"#000" };
        var shape;
        if (match && match[2]) {
          var node = match[1],
              style;
          match[2].scan(/([a-z\-]+)="(.*?)"/, function(m) {
            switch(m[1]) {
              case "stroke-dasharray":
                attr[m[1]] = "- ";
              break;
              case "style":
                style = m[2];
              break;
              default:
                attr[m[1]] = m[2];
              break;
            }
          });
          if (style) {
            style.scan(/([a-z\-]+) ?: ?([^ ;]+)[ ;]?/, function(m) {
              attr[m[1]] = m[2];
            });
          }
        }
        switch(node) {
          case "rect":
            shape = this.rect();
          break;
          case "circle":
            shape = this.circle();
          break;
          case "ellipse":
            shape = this.ellipse();
          break;
          case "path":
            shape = this.path(attr["d"]);
          break;
          case "polygon":
            shape = this.polygon(attr["points"]);
          break;
          case "image":
            shape = this.image();
          break;
          //-F case "text":
          //-F   shape = this.text();
          //-F break;
        }
        shape.attr(attr);
    }).bind(this));
  } catch (error) {
    alert("The SVG data you entered was invalid! (" + error + ")");
  }
};

// extending raphael with a polygon function
Raphael.fn.polygon = function(point_string) {
  var poly_array = ["M"];
  $w(point_string).each(function(point, i) {
    point.split(",").each(function(c) {
      poly_array.push(parseFloat(c));
    });
    if (i == 0) poly_array.push("L");
  });
  poly_array.push("Z");
  return this.path(poly_array.compact());
};<commit_msg>georgious changes<commit_after>/*
 * Raphael SVG Import 0.0.2 - Extension to Raphael JS
 *
 * Copyright (c) 2011 Wout Fierens and Georgi Momchilov
 * Licensed under the MIT (http://www.opensource.org/licenses/mit-license.php) license.
 */
Raphael.fn.importSVG = function (rawSVG) {
  try {
    if (rawSVG.blank())
      throw 'No data was provided.';

    rawSVG = rawSVG.gsub(/\n|\r|\t/, '');

    if (!rawSVG.match(/<svg([^>]*)?>(.*)<\/svg>/i))
      throw "The data you entered doesn't contain SVG.";

    rawSVG.scan(/<(rect|polyline|circle|ellipse|path|polygon|image|text)(.*?)\/>/, (function(match) {
        var shape, attr = { 'stroke-width': 0, 'fill':'#000' };

        if (match && match[2]) {
          var style, node = match[1];

          match[2].scan(/([a-z\-]+)='(.*?)'/, function(m) {
            switch(m[1]) {
              case 'stroke-dasharray':
                attr[m[1]] = '- ';
              break;
              case 'style':
                style = m[2];
              break;
              default:
                attr[m[1]] = m[2];
              break;
            }
          });

          if (style)
            style.scan(/([a-z\-]+) ?: ?([^ ;]+)[ ;]?/, function(m) {
              attr[m[1]] = m[2];
            });
        }

        switch(node) {
          case 'rect':
            shape = this.rect();
          break;
          case 'circle':
            shape = this.circle();
          break;
          case 'ellipse':
            shape = this.ellipse();
          break;
          case 'path':
            shape = this.path(attr['d']);
          break;
          case 'polygon':
            shape = this.polygon(attr['points']);
          break;
          case 'image':
            shape = this.image();
          break;
          //-F case 'text':
          //-F   shape = this.text();
          //-F break;
        }
        shape.attr(attr);

    }).bind(this));
  } catch (error) {
    alert('The SVG data you entered was invalid! (' + error + ')');
  }
};

// extending raphael with a polygon function
Raphael.fn.polygon = function(point_string) {
  var polyArray = ['M'];
  $w(point_string).each(function(point, i) {
    point.split(',').each(function(c) {
      polyArray.push(parseFloat(c));
    });
    if (i == 0) polyArray.push('L');
  });

  polyArray.push('Z');

  return this.path(polyArray.compact());
};<|endoftext|>


<commit_before>(function () {
  'use strict';

  const PADDLE_HEIGHT = 100,
    PADDLE_WIDTH = 10,
    BALL_RADIUS = 10,
    WINNING_SCORE = 3;
  let canvas,
    canvasContext,
    ballX = 50,
    ballY = 50,
    ballSpeedX = 10,
    ballSpeedY = 4,
    paddle1Y = 250,
    paddle2Y = 250,
    player1Score = 0,
    player2Score = 0,
    showingWinScreen = false;

  window.addEventListener('load', function load(event) {
    canvas = document.getElementById('gameCanvas');
    canvasContext = canvas.getContext('2d');

    const framesPerSecond = 30;
    setInterval(function everyFrame() {
      update();
      render();
    }, 1000/framesPerSecond);

    canvas.addEventListener('mousemove', function move(event) {
      const mousePos = calculateMousePos(event);
      paddle1Y = mousePos.y - (PADDLE_HEIGHT / 2);
    });

    canvas.addEventListener('mousedown', handleMouseClick);
  });

  function handleMouseClick(event) {
    if (showingWinScreen) {
      player1Score = 0;
      player2Score = 0;
      showingWinScreen = false;
    }
  }

  function calculateMousePos(event) {
    const rect = canvas.getBoundingClientRect(),
      root = document.documentElement,
      mouseX = event.clientX - rect.left - root.scrollLeft,
      mouseY = event.clientY - rect.top - root.scrollTop;

    return {
      x: mouseX,
      y: mouseY
    };
  }

  function ballReset() {
    if (player1Score >= WINNING_SCORE || player2Score >= WINNING_SCORE) {
      showingWinScreen = !showingWinScreen;
    }

    ballX = canvas.width / 2;
    ballY = canvas.height / 2;
    ballSpeedX = -ballSpeedX;
  }

  function computerMovement() {
    const paddle2YCentre = paddle2Y + (PADDLE_HEIGHT / 2);
    if (paddle2YCentre < ballY - 35) paddle2Y += 6;
    else if (paddle2YCentre > ballY + 35) paddle2Y -= 6;
  }

  function update() {
    if (showingWinScreen) return;

    computerMovement();

    ballX += ballSpeedX;
    ballY += ballSpeedY;

    if (ballX < 0) {
      if (ballY > paddle1Y && ballY < paddle1Y + PADDLE_HEIGHT) {
        const deltaY = ballY - (paddle1Y + PADDLE_HEIGHT / 2);

        ballSpeedX = -ballSpeedX;
        ballSpeedY = deltaY * 0.35;
      }
      else {
        player2Score++;
        ballReset();
      }
    }
    if (ballX > canvas.width) {
      if (ballY > paddle2Y && ballY < paddle2Y + PADDLE_HEIGHT) {
        const deltaY = ballY - (paddle2Y + PADDLE_HEIGHT / 2);
        ballSpeedX = -ballSpeedX;
        ballSpeedY = deltaY * 0.35;
      }
      else {
        player1Score++;
        ballReset();
      }
    }
    if (ballY > canvas.height || ballY < 0) ballSpeedY = -ballSpeedY;
  }

  function drawNet() {
    for (let i = 0; i < canvas.height; i += 40) {
      colourRect(canvas.width / 2 - 1, i, 2, 20, 'white');
    }
  }

  function render() {
    colourRect(0, 0, canvas.width, canvas.height, 'black');

    if (showingWinScreen) {
      canvasContext.fillStyle = 'white';

      if (player1Score >= WINNING_SCORE) canvasContext.fillText('Left player won', 350, 200);
      else if (player2Score >= WINNING_SCORE) canvasContext.fillText('Right player won', 350, 200);

      canvasContext.fillText('Click to continue', 350, 500);

      return;
    }

    drawNet();
    colourRect(0, paddle1Y, PADDLE_WIDTH, PADDLE_HEIGHT, 'white');
    colourRect(canvas.width - PADDLE_WIDTH, paddle2Y, PADDLE_WIDTH, PADDLE_HEIGHT, 'white');
    colourCircle(ballX, ballY, BALL_RADIUS, 'white');
    canvasContext.fillText(player1Score, 100, 100);
    canvasContext.fillText(player2Score, canvas.width - 100, 100);
  }

  function colourRect(leftX, topY, width, height, colour) {
    canvasContext.fillStyle = colour;
    canvasContext.fillRect(leftX, topY, width, height);
  }

  function colourCircle(x, y, radius, colour) {
    canvasContext.fillStyle = colour;
    canvasContext.beginPath();
    canvasContext.arc(x, y, radius, 0, Math.PI * 2, true);
    canvasContext.fill();
  }
})()

<commit_msg>Remove old implementation<commit_after><|endoftext|>


<commit_before>var menu, front_layer, back_layer, emojiCursor, cameraSound;
var imagedata = JSON.parse(data);
var width = 400;
var height = 600;
var menuHeight = 75;
var game = new Phaser.Game(width, height, Phaser.AUTO, 'game', { preload: preload, create: create, update: update}, true, false);
var npc = {};
var initialScale = 0;
var initialX = 95;
var initialY = -400;
var hover = false;
var writing = false;
var fashionPhrases = ["Tres chic!", "So stylish", "<3 this look", "Cool outfit!", "Very hip"];

$("#toggle_blog").click(function() {
	$( "#blog, #game" ).toggle();
	$("#toggle_blog").text($("#blog").is(":visible") ? "Street" : "Blog");

});

function createRandomSprite(type){
	object = imagedata[type];
	var index = Math.floor((Math.random() * object.length));
	var frame1 = type + '/' + (index + 1) + '/' + object[index]["1"];
	var frame2 = type + '/' + (index + 1) + '/' + object[index]["2"];
	var sprite = back_layer.create(initialX, initialY, 'fashion', frame1);
	sprite.scale.setTo(initialScale, initialScale);
	sprite.animations.add('walk', [frame1, frame2], 2.5, true, false);
	sprite.animations.play('walk');
	sprite.name = type;
	return sprite;
}

function newNPC(){
	var npc = {};
	var spriteGroup = game.add.group();
	back_layer.add(spriteGroup);
	spriteGroup.add(createRandomSprite('body'));
	spriteGroup.add(createRandomSprite('hair'));

	var random = Math.floor((Math.random() * 2));
	if (random == 0){
		spriteGroup.add(createRandomSprite('jumpsuits'));
	}
	else {
		spriteGroup.add(createRandomSprite('pants'));
		spriteGroup.add(createRandomSprite('tops'));
	}

	spriteGroup.add(createRandomSprite('shoes'));
	spriteGroup.forEach(function(item) {
		item.inputEnabled = true;
		item.input.useHandCursor = true;
		item.events.onInputOver.add(function(){
			hover = true;
			emojiCursor.visible = true;
		}, this);
		item.events.onInputOut.add(function(){
			hover = false;
			emojiCursor.visible = false;
		}, this);
		item.events.onInputDown.add(clickOnStyle, this);
	}, this);

	npc.x = initialX;
	npc.y = initialY;
	npc.scale = initialScale;
	npc.sprites = spriteGroup;
	npc.blogged = false;
	return npc;
}

function clickOnStyle(){
	if (npc.blogged){
		return;
	}
	writing = true;
	cameraSound.play();
	text = new Phaser.BitmapText(game, 10, 50, "superscript", "I love your\noutfit!", 30);
	game.time.events.add(1000, text.destroy, text);
	front_layer.add(text);
	var bitmap = new Phaser.BitmapData(game, "bitmap", 78, 190);
	npc.sprites.forEach(function(item) {
		item.y = 0;
		item.x = 0;
		item.scale.setTo(1, 1);
		bitmap.draw(item);
		item.y = npc.y;
		item.x = npc.x;
		item.scale.setTo(npc.scale, npc.scale);
	}, this);
	var data = bitmap.baseTexture.source;
	var test = data.toDataURL("image/png");
	var index = Math.floor((Math.random() * fashionPhrases.length));
	$('body').append("

Write a blog post!
<form><textarea rows='5' class='emojis-wysiwyg'></textarea></form><button id='emojibutton'>Emoji</button><button id='post'>Post</button><button id='cancel'>Cancel</button>
");
	$('.emojis-wysiwyg').emojiarea({wysiwyg: true, button: '#emojibutton'});
	$('#post').click(function(){
		var entry = $('.emoji-wysiwyg-editor').html();
		$("#blog").append("

" + fashionPhrases[index] + "

Posted on "
			+ new Date($.now()) + "

" + entry + "

");
		$('#writepost').remove();
		npc.blogged = true;
		writing = false;
	});
	$('#cancel').click(function(){
		$('#writepost').remove();
		writing = false;
	});

}

function preload() {
	game.load.atlasJSONHash('fashion', 'images/fashion.png', 'images/fashion.json');
	game.load.bitmapFont('superscript', 'font/superscript.png', 'font/superscript.fnt');
	game.load.audio('camera', 'audio/166500__thompsonman__camera-shutter.wav');
	game.load.image('emojiCursor', 'emojiarea/packs/basic/images/camera.png')
}

function create() {
	back_layer = game.add.group();
	front_layer = game.add.group();
	cameraSound = game.add.audio('camera');
	emojiCursor = front_layer.create(0, 0, 'emojiCursor');
	emojiCursor.visible = false;
	emojiCursor.scale.setTo(0.5, 0.5);
	npc= newNPC();
}

function update() {
	if (!hover && !writing){
		npc.y += 1.5;
		npc.scale = (((npc.y)/height)*(1.5))+3;
		npc.sprites.forEach(function(item) {
			item.y = npc.y;
			item.scale.setTo(npc.scale, npc.scale);
		}, this);

		if (npc.y > height){
			npc = newNPC();
		}
	}
	else {
		emojiCursor.x = game.input.x;
		emojiCursor.y = game.input.y;
	}
}<commit_msg>Added on document ready<commit_after>$( document ).ready(function() {
	var menu, front_layer, back_layer, emojiCursor, cameraSound;
	var imagedata = JSON.parse(data);
	var width = 400;
	var height = 600;
	var menuHeight = 75;
	var game = new Phaser.Game(width, height, Phaser.AUTO, 'game', { preload: preload, create: create, update: update}, true, false);
	var npc = {};
	var initialScale = 0;
	var initialX = 95;
	var initialY = -400;
	var hover = false;
	var writing = false;
	var fashionPhrases = ["Tres chic!", "So stylish", "<3 this look", "Cool outfit!", "Very hip"];

	$("#toggle_blog").click(function() {
		$( "#blog, #game" ).toggle();
		$("#toggle_blog").text($("#blog").is(":visible") ? "Street" : "Blog");

	});

	function createRandomSprite(type){
		object = imagedata[type];
		var index = Math.floor((Math.random() * object.length));
		var frame1 = type + '/' + (index + 1) + '/' + object[index]["1"];
		var frame2 = type + '/' + (index + 1) + '/' + object[index]["2"];
		var sprite = back_layer.create(initialX, initialY, 'fashion', frame1);
		sprite.scale.setTo(initialScale, initialScale);
		sprite.animations.add('walk', [frame1, frame2], 2.5, true, false);
		sprite.animations.play('walk');
		sprite.name = type;
		return sprite;
	}

	function newNPC(){
		var npc = {};
		var spriteGroup = game.add.group();
		back_layer.add(spriteGroup);
		spriteGroup.add(createRandomSprite('body'));
		spriteGroup.add(createRandomSprite('hair'));

		var random = Math.floor((Math.random() * 2));
		if (random == 0){
			spriteGroup.add(createRandomSprite('jumpsuits'));
		}
		else {
			spriteGroup.add(createRandomSprite('pants'));
			spriteGroup.add(createRandomSprite('tops'));
		}

		spriteGroup.add(createRandomSprite('shoes'));
		spriteGroup.forEach(function(item) {
			item.inputEnabled = true;
			item.input.useHandCursor = true;
			item.events.onInputOver.add(function(){
				hover = true;
				emojiCursor.visible = true;
			}, this);
			item.events.onInputOut.add(function(){
				hover = false;
				emojiCursor.visible = false;
			}, this);
			item.events.onInputDown.add(clickOnStyle, this);
		}, this);

		npc.x = initialX;
		npc.y = initialY;
		npc.scale = initialScale;
		npc.sprites = spriteGroup;
		npc.blogged = false;
		return npc;
	}

	function clickOnStyle(){
		if (npc.blogged){
			return;
		}
		writing = true;
		cameraSound.play();
		text = new Phaser.BitmapText(game, 10, 50, "superscript", "I love your\noutfit!", 30);
		game.time.events.add(1000, text.destroy, text);
		front_layer.add(text);
		var bitmap = new Phaser.BitmapData(game, "bitmap", 78, 190);
		npc.sprites.forEach(function(item) {
			item.y = 0;
			item.x = 0;
			item.scale.setTo(1, 1);
			bitmap.draw(item);
			item.y = npc.y;
			item.x = npc.x;
			item.scale.setTo(npc.scale, npc.scale);
		}, this);
		var data = bitmap.baseTexture.source;
		var test = data.toDataURL("image/png");
		var index = Math.floor((Math.random() * fashionPhrases.length));
		$('body').append("

Write a blog post!
<form><textarea rows='5' class='emojis-wysiwyg'></textarea></form><button id='emojibutton'>Emoji</button><button id='post'>Post</button><button id='cancel'>Cancel</button>
");
		$('.emojis-wysiwyg').emojiarea({wysiwyg: true, button: '#emojibutton'});
		$('#post').click(function(){
			var entry = $('.emoji-wysiwyg-editor').html();
			$("#blog").append("

" + fashionPhrases[index] + "

Posted on "
				+ new Date($.now()) + "

" + entry + "

");
			$('#writepost').remove();
			npc.blogged = true;
			writing = false;
		});
		$('#cancel').click(function(){
			$('#writepost').remove();
			writing = false;
		});

	}

	function preload() {
		game.load.atlasJSONHash('fashion', 'images/fashion.png', 'images/fashion.json');
		game.load.bitmapFont('superscript', 'font/superscript.png', 'font/superscript.fnt');
		game.load.audio('camera', 'audio/166500__thompsonman__camera-shutter.wav');
		game.load.image('emojiCursor', 'emojiarea/packs/basic/images/camera.png')
	}

	function create() {
		back_layer = game.add.group();
		front_layer = game.add.group();
		cameraSound = game.add.audio('camera');
		emojiCursor = front_layer.create(0, 0, 'emojiCursor');
		emojiCursor.visible = false;
		emojiCursor.scale.setTo(0.5, 0.5);
		npc= newNPC();
	}

	function update() {
		if (!hover && !writing){
			npc.y += 1.5;
			npc.scale = (((npc.y)/height)*(1.5))+3;
			npc.sprites.forEach(function(item) {
				item.y = npc.y;
				item.scale.setTo(npc.scale, npc.scale);
			}, this);

			if (npc.y > height){
				npc = newNPC();
			}
		}
		else {
			emojiCursor.x = game.input.x;
			emojiCursor.y = game.input.y;
		}
	}
});<|endoftext|>


<commit_before>/*
┏-----------------------------------------------┓
|               Flappy Wumpus                   |
|             By A Generic Gamer                |
| Adapted from Goma Games Workshop: Flappy Flap |
|  By using this code you acknowledge and agree |
|      to the license in the master branch      |
┗-----------------------------------------------┛
*/

enchant(); // initialize
var game = new Core(1280, 720); // game stage
game.scale = 1;
game.fps = 60;
game.started = false;
game.distance = 0; // initial value, don't change

// settings
game.gravity = 0.5;
game.flap_strength = 9;
game.fly_speed = 3.5;
game.obstacle_frequency = 50;
game.keybind(32, 'jump');

var obstacles = new Group();

var scoreBoard = new Label();
scoreBoard.text = 0;
scoreBoard.color = '#fff';
scoreBoard.font = 'Open Sans';
scoreBoard.scaleX = 5;
scoreBoard.scaleY = 5;
scoreBoard.textAlign = 'center';
scoreBoard.x = game.width/2 - scoreBoard.width/2;
scoreBoard.y = 40;

// preload assets
game.preload('assets/background.png',
	'assets/blurple-vigenette.png',
	'assets/gameover.png',
	'assets/getready.png',
	'assets/ground.png',
	'assets/instructions.png',
	'assets/mallorySoftSoap.png',
	'assets/obstacle_top.png',
	'assets/obstacle_bottom.png',
	'assets/wumpusGolden.png',
	'assets/wumpusRainbow.png',
	'assets/wumpusTrump.png',
	'assets/wumpusVanilla.png',
	'sounds/FlappilyWumped.mp3',
	'sounds/flap.mp3');

// initialize game
game.onload = function(){

  // add the background
  game.bg = new Sprite(1280,720);
  game.bg.image = game.assets['assets/background.png'];

  // add game.bg to rootScene
	game.rootScene.addChild(game.bg);

  // add obstacles to rootScene
	game.rootScene.addChild(obstacles);

  // add scoreBoard to rootScene
	game.rootScene.addChild(scoreBoard);

  // add the start game screen
  game.getready = new Sprite(592,177);
  game.getready.image = game.assets['assets/getready.png'];
  game.getready.x = (game.width / 2) - (game.getready.width / 2);
  game.getready.y = (game.height / 2) - (game.getready.height / 2);

  // add game.getready to rootScene
	game.rootScene.addChild(game.getready);

  // add the floor
  game.ground = new Sprite(1280,86);
  game.ground.image = game.assets['assets/ground.png'];
  game.ground.x = 0;
  game.ground.y = game.height - 48;

  // add game.ground to rootScene
	game.rootScene.addChild(game.ground);

  // add the main character
  // Adds a 10% chance to get special characters :p
  var randomNumber = Math.random() * 100 + 1;
  if (randomNumber <= 10) {
    game.avatar = new Sprite(87,55);
    game.avatar.image = game.assets['assets/wumpusGolden.png'];
  } else if (randomNumber <= 20) {
    game.avatar = new Sprite(87,55);
    game.avatar.image = game.assets['assets/wumpusRainbow.png'];
  } else if (randomNumber <= 30) {
    game.avatar = new Sprite(87,55);
    game.avatar.image = game.assets['assets/wumpusTrump.png'];
  } else if (randomNumber <= 40) {
    game.avatar = new Sprite(87,85);
    game.avatar.image = game.assets['assets/mallorySoftSoap.png'];
  } else {
    game.avatar = new Sprite(87,55);
    game.avatar.image = game.assets['assets/wumpusVanilla.png'];
  }

  game.avatar.x = 100;
  game.avatar.y = 295;
  game.avatar.ySpeed = 0;

  // add game.avatar to rootScene
	game.rootScene.addChild(game.avatar);

  // add the instructions
  game.instructions = new Sprite(420,22);
  game.instructions.image = game.assets['assets/instructions.png'];
  game.instructions.x = (game.width/2) - (game.instructions.width/2);
  game.instructions.y = 460;

  // add game.instructions to rootScene
	game.rootScene.addChild(game.instructions);

  game.rootScene.addEventListener(enchant.Event.TOUCH_END, game_touched);
  game.rootScene.addEventListener(enchant.Event.UP_BUTTON_DOWN, game_touched);
} // end game.onload #initialize game

// listen for tap/click
function game_touched(){

  if(game.started){

    // flap
    game.avatar.ySpeed = -game.flap_strength;

  }else{

    // start game
    game.started = true;

	// remove getready and instructions
	game.rootScene.removeChild(game.getready);
	game.rootScene.removeChild(game.instructions);
  // 'flap' on click/up arrow which starts the game
  game.avatar.ySpeed = -game.flap_strength;

  }
}

// game loop
game.onenterframe = function(){
  if(game.started){
    game.avatar.ySpeed += game.gravity;
    game.avatar.y += game.avatar.ySpeed;

    // check if bird touches floor, or ceiling
    if(
       game.avatar.y+game.avatar.height > game.ground.y ||
       game.avatar.y < 0
    ){

      // end the game if avatar touches floor or ceiling
      gameover();

    }

    // move obstacles to the left
    obstacles.x -= game.fly_speed;

    // track flying progress
    game.distance += game.fly_speed;

    game.rootScene.addEventListener(enchant.Event.UP_BUTTON_DOWN,function(){
    	if(game.started){

            // flap
            game.avatar.ySpeed = -game.flap_strength;

       }else{

            // start game
            game.started = true;

	       // remove getready and instructions
	        game.rootScene.removeChild(game.getready);
	        game.rootScene.removeChild(game.instructions);

        }
  	});

    // check if we need to spawn obstacle
    if(game.distance % game.obstacle_frequency == 0){

      // spawn obstacle
      spawnObstacle();

      // clean up old obstacles
      for (var i = 0; i < obstacles.childNodes.length; i++) {
        if(obstacles.childNodes[i].x + obstacles.x + 100 < -85){
          obstacles.removeChild(obstacles.childNodes[i]);
        }
      }
    } // end if spawn obstacle

    // collision detection
    for (var i = 0; i < obstacles.childNodes.length; i++) {
      if(game.avatar.intersect(obstacles.childNodes[i])){

        // end the game if player hits obstacle
        gameover();

      }else if( // check for score
        !obstacles.childNodes[i].scored &&
        obstacles.childNodes[i].y < 0 &&
        obstacles.childNodes[i].x +
        obstacles.childNodes[i].width -
        game.distance < game.avatar.x
      ){
        obstacles.childNodes[i].scored = true;

        //increment score by 1
        scoreBoard.text++;
      }
    }

  }
} // end game.onenterframe #game loop

function spawnObstacle(){

  var pos = (Math.random()*400) + 240;
  var gap = 200;

  var top = new Sprite(85, 545);
  top.image = game.assets['assets/obstacle_top.png'];
  top.x = -obstacles.x + game.width;
  top.y = -550 + pos - gap;

  // add top obstacle to obstacles group
  obstacles.addChild(top);

  var bottom = new Sprite(85, 545);
  bottom.image = game.assets['assets/obstacle_bottom.png'];
  bottom.x = -obstacles.x + game.width;
  bottom.y = pos;

  // add bottom obstacle to obstacles group
  obstacles.addChild(bottom);

} // end spawnObstacle

function gameover(){
  // add the instructions
  game.gameover = new Sprite(602,163);
  game.gameover.image = game.assets['assets/gameover.png'];
  game.gameover.x = (game.width/2) - (game.gameover.width/2);
  game.gameover.y = 120;

  // show gameover graphic
  game.rootScene.addChild(game.gameover);

  game.rootScene.addEventListener(enchant.Event.TOUCH_END,function(){
    window.location.reload();
  });

  // stop the game loop
  game.onenterframe = null;

}

game.start();
<commit_msg>Magical.<commit_after>/*
┏-----------------------------------------------┓
|               Flappy Wumpus                   |
|             By A Generic Gamer                |
| Adapted from Goma Games Workshop: Flappy Flap |
|  By using this code you acknowledge and agree |
|      to the license in the master branch      |
┗-----------------------------------------------┛
*/

enchant(); // initialize
var game = new Core(1280, 720); // game stage
game.scale = 1;
game.fps = 60;
game.started = false;
game.distance = 0; // initial value, don't change

// settings
game.gravity = 0.5;
game.flap_strength = 9;
game.fly_speed = 3.5;
game.obstacle_frequency = 50;
game.keybind(32, 'jump');

var obstacles = new Group();

var scoreBoard = new Label();
scoreBoard.text = 0;
scoreBoard.color = '#fff';
scoreBoard.font = 'Open Sans';
scoreBoard.scaleX = 5;
scoreBoard.scaleY = 5;
scoreBoard.textAlign = 'center';
scoreBoard.x = game.width/2 - scoreBoard.width/2;
scoreBoard.y = 40;

// preload assets
game.preload('assets/halloween/background.png',
	'assets/blurple-vigenette.png',
	'assets/gameover.png',
	'assets/getready.png',
	'assets/ground.png',
	'assets/instructions.png',
	'assets/mallorySoftSoap.png',
	'assets/halloween/obstacle_top.png',
	'assets/halloween/obstacle_bottom.png',
	'assets/wumpusGolden.png',
	'assets/wumpusRainbow.png',
	'assets/wumpusTrump.png',
	'assets/wumpusVanilla.png',
	'sounds/FlappilyWumped.mp3',
	'sounds/flap.mp3');

// initialize game
game.onload = function(){

  // add the background
  game.bg = new Sprite(1280,720);
  game.bg.image = game.assets['assets/background.png'];

  // add game.bg to rootScene
	game.rootScene.addChild(game.bg);

  // add obstacles to rootScene
	game.rootScene.addChild(obstacles);

  // add scoreBoard to rootScene
	game.rootScene.addChild(scoreBoard);

  // add the start game screen
  game.getready = new Sprite(592,177);
  game.getready.image = game.assets['assets/getready.png'];
  game.getready.x = (game.width / 2) - (game.getready.width / 2);
  game.getready.y = (game.height / 2) - (game.getready.height / 2);

  // add game.getready to rootScene
	game.rootScene.addChild(game.getready);

  // add the floor
  game.ground = new Sprite(1280,86);
  game.ground.image = game.assets['assets/ground.png'];
  game.ground.x = 0;
  game.ground.y = game.height - 48;

  // add game.ground to rootScene
	game.rootScene.addChild(game.ground);

  // add the main character
  // Adds a 10% chance to get special characters :p
  var randomNumber = Math.random() * 100 + 1;
  if (randomNumber <= 10) {
    game.avatar = new Sprite(87,55);
    game.avatar.image = game.assets['assets/wumpusGolden.png'];
  } else if (randomNumber <= 20) {
    game.avatar = new Sprite(87,55);
    game.avatar.image = game.assets['assets/wumpusRainbow.png'];
  } else if (randomNumber <= 30) {
    game.avatar = new Sprite(87,55);
    game.avatar.image = game.assets['assets/wumpusTrump.png'];
  } else if (randomNumber <= 40) {
    game.avatar = new Sprite(87,85);
    game.avatar.image = game.assets['assets/mallorySoftSoap.png'];
  } else {
    game.avatar = new Sprite(87,55);
    game.avatar.image = game.assets['assets/wumpusVanilla.png'];
  }

  game.avatar.x = 100;
  game.avatar.y = 295;
  game.avatar.ySpeed = 0;

  // add game.avatar to rootScene
	game.rootScene.addChild(game.avatar);

  // add the instructions
  game.instructions = new Sprite(420,22);
  game.instructions.image = game.assets['assets/instructions.png'];
  game.instructions.x = (game.width/2) - (game.instructions.width/2);
  game.instructions.y = 460;

  // add game.instructions to rootScene
	game.rootScene.addChild(game.instructions);

  game.rootScene.addEventListener(enchant.Event.TOUCH_END, game_touched);
  game.rootScene.addEventListener(enchant.Event.UP_BUTTON_DOWN, game_touched);
} // end game.onload #initialize game

// listen for tap/click
function game_touched(){

  if(game.started){

    // flap
    game.avatar.ySpeed = -game.flap_strength;

  }else{

    // start game
    game.started = true;

	// remove getready and instructions
	game.rootScene.removeChild(game.getready);
	game.rootScene.removeChild(game.instructions);
  // 'flap' on click/up arrow which starts the game
  game.avatar.ySpeed = -game.flap_strength;

  }
}

// game loop
game.onenterframe = function(){
  if(game.started){
    game.avatar.ySpeed += game.gravity;
    game.avatar.y += game.avatar.ySpeed;

    // check if bird touches floor, or ceiling
    if(
       game.avatar.y+game.avatar.height > game.ground.y ||
       game.avatar.y < 0
    ){

      // end the game if avatar touches floor or ceiling
      gameover();

    }

    // move obstacles to the left
    obstacles.x -= game.fly_speed;

    // track flying progress
    game.distance += game.fly_speed;

    game.rootScene.addEventListener(enchant.Event.UP_BUTTON_DOWN,function(){
    	if(game.started){

            // flap
            game.avatar.ySpeed = -game.flap_strength;

       }else{

            // start game
            game.started = true;

	       // remove getready and instructions
	        game.rootScene.removeChild(game.getready);
	        game.rootScene.removeChild(game.instructions);

        }
  	});

    // check if we need to spawn obstacle
    if(game.distance % game.obstacle_frequency == 0){

      // spawn obstacle
      spawnObstacle();

      // clean up old obstacles
      for (var i = 0; i < obstacles.childNodes.length; i++) {
        if(obstacles.childNodes[i].x + obstacles.x + 100 < -85){
          obstacles.removeChild(obstacles.childNodes[i]);
        }
      }
    } // end if spawn obstacle

    // collision detection
    for (var i = 0; i < obstacles.childNodes.length; i++) {
      if(game.avatar.intersect(obstacles.childNodes[i])){

        // end the game if player hits obstacle
        gameover();

      }else if( // check for score
        !obstacles.childNodes[i].scored &&
        obstacles.childNodes[i].y < 0 &&
        obstacles.childNodes[i].x +
        obstacles.childNodes[i].width -
        game.distance < game.avatar.x
      ){
        obstacles.childNodes[i].scored = true;

        //increment score by 1
        scoreBoard.text++;
      }
    }

  }
} // end game.onenterframe #game loop

function spawnObstacle(){

  var pos = (Math.random()*400) + 240;
  var gap = 200;

  var top = new Sprite(85, 545);
  top.image = game.assets['assets/obstacle_top.png'];
  top.x = -obstacles.x + game.width;
  top.y = -550 + pos - gap;

  // add top obstacle to obstacles group
  obstacles.addChild(top);

  var bottom = new Sprite(85, 545);
  bottom.image = game.assets['assets/obstacle_bottom.png'];
  bottom.x = -obstacles.x + game.width;
  bottom.y = pos;

  // add bottom obstacle to obstacles group
  obstacles.addChild(bottom);

} // end spawnObstacle

function gameover(){
  // add the instructions
  game.gameover = new Sprite(602,163);
  game.gameover.image = game.assets['assets/gameover.png'];
  game.gameover.x = (game.width/2) - (game.gameover.width/2);
  game.gameover.y = 120;

  // show gameover graphic
  game.rootScene.addChild(game.gameover);

  game.rootScene.addEventListener(enchant.Event.TOUCH_END,function(){
    window.location.reload();
  });

  // stop the game loop
  game.onenterframe = null;

}

game.start();
<|endoftext|>


<commit_before>// Create the canvas
var canvas = document.createElement("canvas");
var ctx = canvas.getContext("2d");
canvas.width = 600;
canvas.height = 450;
document.body.appendChild(canvas);

// Background image
var bgReady = false;
var bgImage = new Image();
bgImage.onload = function () {
	bgReady = true;
};
bgImage.src = "images/background.png";

/////////////////////////////////////////////////////////////////////////
///////////////////////////Preloading Images/////////////////////////////
/////////////////////////////////////////////////////////////////////////
/*
var imageDict = {};

function loadImages() {
	var imageList = [
		"player1",
		"player2",
		"fireball",
		"shield"
	],
	i=0,L=imageList.length,image,doneLoading = false;
	for (i;i<L;i++) {
		image = imageList[i]
		imageDict[image] = new Image();
		imageDict[image].src = "images/"+image+".png";
		if (i===L-1) {imageDict[image].onload = function() {doneLoading = true;};}
	}
}

loadImages();
*/
/////////////////////////////////////////////////////////////////////////
/////////////////////////////Game Settings///////////////////////////////
/////////////////////////////////////////////////////////////////////////

var roundTime = 5000, //Time of each round in ms

	keybindings = { //Control bindings for players 1 and 2
	P1: {
		a: 87, //w
		b: 69, //e
		c: 65, //a
		d: 83, //s
		e: 68  //d
	},
	P2: {
		a: 79, //o
		b: 80, //p
		c: 76, //l
		d: 186,//;
		e: 222 //'
	}
};

/////////////////////////////////////////////////////////////////////////
/////////////////////////Constructor Functions///////////////////////////
/////////////////////////////////////////////////////////////////////////

function Actor(imagesrc,x,y) {
	this.image = new Image();
	this.image.src = "images/"+imagesrc+".png";
	//this.image = imageDict[imagesrc];
	this.x = x;
	this.y = y;
	this.draw = function() {ctx.drawImage(this.image,this.x,this.y)};
	this.isTouching = function(other) {
		var L1=this.x,
			R1=L1+this.image.width,
			U1=this.y,
			D1=U1+this.image.height,
			L2=other.x,
			R2=L2+other.image.width,
			U2=other.y,
			D2=U2+other.image.height;
		return (!(L1>R2 || L2>R1 || U1>D2 || U2>D1));
	};
	this.isOffscreen = function() {
		var L=this.x,R=L+this.image.width,U=this.y,D=U+this.image.height;
		return (L<0 || canvas.width<R || U<0 || canvas.height<D);
	};
	this.getTouching = function() {
		var combinedObjects = creatures + conjurations, L = combinedObjects.length, i=0, result=[];
		for (i;i<L;i++) {
			if (this.isTouching(combinedObjects[i])) {result.push(combinedObjects[i]);}
		}
		return result;
	};
	this.isCondemned = false;
}

function Creature(level,health,speed,controller,imagesrc,x,y) {
	Actor.call(this,imagesrc);
	this.level = level;
	this.health = health;
	this.speed = speed;
	this.controller = controller;
}

function Wizard(level,health,speed,imagesrc,x,y) {
	Creature.call(this,level,health,speed,this,imagesrc,x,y);
	this.words = new Words();
}

function Words() {
	this.history = [];
	this.getLast = function(n) {
		var history = this.history, L=history.length, returnList = [];
		if (n>history.length) {return undefined}
		for (n;n>0;n--) {returnList.push(history[L-n])}
		return returnList.join("");
	};
	this.findSpell = function() {
		var key,spell,spelling,matchList=[],result="";
		for (key in spellbook) {
			spell = spellbook[key];
			spelling = spell.spell;
			if (spelling === this.getLast(spelling.length)) {matchList.push(spell);}
		}
		var L=matchList.length,i=0;
		for (i;i<L;i++) {if (matchList[i]["spell"].length>result.length) {result=matchList[i];}}
		return result;
	};
	this.remember = function(c) {
		this.history.push(c);
		while (this.history.length > 20) {this.history.shift();}
	};
}

function Conjuration(caster,rate,duration,damage,imagesrc) { //Images should be from P1's perspective
	Actor.call(this,imagesrc,caster.x,caster.y);
	this.heading = (caster.controller===P1) ? 1 : -1;//heading;//-1 for left, 1 for right
	this.rate = rate;
	this.damage = damage;
	this.caster = caster;
	this.duration = duration;
	this.onUpkeep = function() {
		console.log(this.duration)
		this.duration -= 1;
		if (this.duration === 0) {
			this.isCondemned = true;
			if (this.onDestroy) {this.onDestroy();}
			return;}
		if (this.upkeep) {this.upkeep();}
	};

	//if (this.heading===-1) {ctx.scale(scaleH, scaleV)}
}

function Fireball(caster) {
	Conjuration.call(this,caster,256,1,5,"fireball");
	this.tag = "fireball"
}

function Shield(caster) {
	Conjuration.call(this,caster,0,1,0,"shield")
	this.tag = "shield"
	this.x -= 30;this.y -= 30;  //need to find a better solution than hardcoding. Problem is I can't refer to the width because the image is not loaded yet.
	caster.isShielded = true;
	this.onDestroy = function() {caster.isShielded = false};
}
/////////////////////////////////////////////////////////////////////////
/////////////////////////////////Spells//////////////////////////////////
/////////////////////////////////////////////////////////////////////////

var spellbook = {
	fireball: {
		spell:"a",//aabc; will use simple 1 character for testing
		onCast: function(caster) {
			var conj = new Fireball(caster);
			conjurations.push(conj);
		}
	},
	shield: {
		spell:"b",//aabc; will use simple 1 character for testing
		onCast: function(caster) {
			var conj = new Shield(caster);
			conjurations.push(conj);
		}
	}
}

/////////////////////////////////////////////////////////////////////////
//////////////////////////Variable Definitions///////////////////////////
/////////////////////////////////////////////////////////////////////////

var startX1 = canvas.width / 10,
	startX2 = canvas.width * 8 / 10,
	startY = canvas.height / 2,

	P1 = new Wizard(7,20,4,"player1",startX1,startY),
	P2 = new Wizard(7,20,4,"player2",startX2,startY),

	creatures = [P1,P2],
	conjurations = [],
	removeConjurations = [],
	removeCreatures = [],
	keysDown = {},
	orders = {P1:"",P2:""};

/////////////////////////////////////////////////////////////////////////
////////////////////////////Controls Handler/////////////////////////////
/////////////////////////////////////////////////////////////////////////

addEventListener("keydown", function (e) {
	keysDown[e.keyCode] = true;
}, false);

addEventListener("keyup", function (e) {
	delete keysDown[e.keyCode];
}, false);

/////////////////////////////////////////////////////////////////////////
/////////////////////////Game Update Functions///////////////////////////
/////////////////////////////////////////////////////////////////////////

// Update game objects
var update = function (modifier) {
	//console.log(keysDown);
	var P,key,controls;
	for (P in keybindings) {
		controls = keybindings[P]
		for (key in controls) {
			if (controls[key] in keysDown) {orders[P]=key}
		}
	}

	var i=0,L=conjurations.length,proj,removeIndices=[];
	for (i;i<L;i++) {
		proj = conjurations[i];
		var enemy = ((proj.caster===P1) ? P2 : P1);
		proj.x+=proj.rate*proj.heading*modifier;
		if (proj.isTouching(enemy)) {
			if (!enemy.isShielded) {enemy.health-=proj.damage}
			if (proj.onDestroy) {proj.onDestroy();}
			proj.isCondemned = true;
		}
		else if (proj.isOffscreen()) {proj.isCondemned=true;if (proj.onDestroy) {proj.onDestroy();}}
	}
	conjurations = conjurations.filter(function(x) {return (!x.isCondemned)})
};

// Reset the game
var reset = function() {
	P1.x = canvas.width / 10;
	P1.y = canvas.height / 2;

	// Throw the monster somewhere on the screen randomly
	P2.x = canvas.width * 8 / 10;
	P2.y = canvas.height / 2;
}

// Draw everything
var render = function () {
	//Draw background
	if (bgReady) {ctx.drawImage(bgImage, 0, 0);}
	//Draw creatures
	var i=0,L=creatures.length;
	for (i;i<L;i++) {creatures[i].draw();}
	//Draw conjurations
	L=conjurations.length;
	for (i=0;i<L;i++) {conjurations[i].draw();}

	// Score

	ctx.fillStyle = "rgb(250, 250, 250)";
	ctx.font = "24px Helvetica";
	ctx.fillStyle = "green";
	ctx.textBaseline = "top";

	ctx.textAlign = "left";
	ctx.fillText("Life: " + P1.health, 32, 400-32);
	ctx.textAlign = "right";
	ctx.fillText("Life: " + P2.health, 600-32, 400-32);

	// Time
	ctx.fillStyle = "rgb(250, 250, 250)";
	ctx.font = "24px Helvetica";
	ctx.textBaseline = "top";
	ctx.fillStyle = "black";
	ctx.textAlign = "center";
	var text = (parseInt((nextResolve-Date.now())/1000)+1).toString()
	ctx.fillText(text,300,200);
};

//Resolve player actions between rounds
var resolve = function() {
	var P1W = P1.words, P2W = P2.words;
	P1W.remember(orders.P1);
	P2W.remember(orders.P2);
	orders.P1 = "";
	orders.P2 = "";
	//Upkeep for existing spells
	var i=0, combined = creatures + conjurations, L = combined.length;
	conjurations.forEach(function(x,i,arr) {
		if (x.onUpkeep) {x.onUpkeep()}
	});
	for (i;i<L;i++) {
		console.log(combined[i].tag);
		if (combined[i].onUpkeep) {combined[i].onUpkeep();}
	}

	var P1S = P1W.findSpell(),P2S = P2W.findSpell();
	if (P1S) {P1S.onCast(P1)}
	if (P2S) {P2S.onCast(P2)}
	//console.log(P1.words.history);
	//console.log(P2.words.history);
}

// The main game loop
var main = function () {
	var now = Date.now();
	var delta = now - then;

	if (now>nextResolve) {
		resolve()
		nextResolve += roundTime;
	}

	update(delta / 1000);
	render();

	then = now;

	// Request to do this again ASAP
	requestAnimationFrame(main);
};

// Cross-browser support for requestAnimationFrame
var w = window;
requestAnimationFrame = w.requestAnimationFrame || w.webkitRequestAnimationFrame || w.msRequestAnimationFrame || w.mozRequestAnimationFrame;

// Let's play this game!
var nextResolve = Date.now() + roundTime;
var then = Date.now();
reset();
main();<commit_msg>Simplified code<commit_after>// Create the canvas
var canvas = document.createElement("canvas");
var ctx = canvas.getContext("2d");
canvas.width = 600;
canvas.height = 450;
document.body.appendChild(canvas);

// Background image
var bgReady = false;
var bgImage = new Image();
bgImage.onload = function () {
	bgReady = true;
};
bgImage.src = "images/background.png";

/////////////////////////////////////////////////////////////////////////
///////////////////////////Preloading Images/////////////////////////////
/////////////////////////////////////////////////////////////////////////
/*
var imageDict = {};

function loadImages() {
	var imageList = [
		"player1",
		"player2",
		"fireball",
		"shield"
	],
	i=0,L=imageList.length,image,doneLoading = false;
	for (i;i<L;i++) {
		image = imageList[i]
		imageDict[image] = new Image();
		imageDict[image].src = "images/"+image+".png";
		if (i===L-1) {imageDict[image].onload = function() {doneLoading = true;};}
	}
}

loadImages();
*/
/////////////////////////////////////////////////////////////////////////
/////////////////////////////Game Settings///////////////////////////////
/////////////////////////////////////////////////////////////////////////

var roundTime = 5000, //Time of each round in ms

	keybindings = { //Control bindings for players 1 and 2
		P1: {
			a: 87, //w
			b: 69, //e
			c: 65, //a
			d: 83, //s
			e: 68  //d
		},
		P2: {
			a: 79, //o
			b: 80, //p
			c: 76, //l
			d: 186,//;
			e: 222 //'
		}
	};

/////////////////////////////////////////////////////////////////////////
/////////////////////////Constructor Functions///////////////////////////
/////////////////////////////////////////////////////////////////////////

function Actor(imagesrc,x,y) {
	this.image = new Image();
	this.image.src = "images/"+imagesrc+".png";
	//this.image = imageDict[imagesrc];
	this.x = x;
	this.y = y;
	this.draw = function() {ctx.drawImage(this.image,this.x,this.y)};
	this.isTouching = function(other) {
		var L1=this.x,
			R1=L1+this.image.width,
			U1=this.y,
			D1=U1+this.image.height,
			L2=other.x,
			R2=L2+other.image.width,
			U2=other.y,
			D2=U2+other.image.height;
		return (!(L1>R2 || L2>R1 || U1>D2 || U2>D1));
	};
	this.isOffscreen = function() {
		var L=this.x,R=L+this.image.width,U=this.y,D=U+this.image.height;
		return (L<0 || canvas.width<R || U<0 || canvas.height<D);
	};
	this.getTouching = function() {
		var combinedObjects = creatures + conjurations;
		return combinedObjects.filter(function(o) {return (this.isTouching(o) && (o!==this))})
	};
	this.isCondemned = false;
}

function Creature(level,health,speed,controller,imagesrc,x,y) {
	Actor.call(this,imagesrc);
	this.level = level;
	this.health = health;
	this.speed = speed;
	this.controller = controller;
}

function Wizard(level,health,speed,imagesrc,x,y) {
	Creature.call(this,level,health,speed,this,imagesrc,x,y);
	this.words = new Words();
}

function Words() {
	this.history = [];
	this.getLast = function(n) {
		var history = this.history, L=history.length, returnList = [];
		if (n>history.length) {return undefined}
		for (n;n>0;n--) {returnList.push(history[L-n])}
		return returnList.join("");
	};
	this.findSpell = function() {
		var key,spell,spelling,matchList=[],result="";
		for (key in spellbook) {
			spell = spellbook[key];
			spelling = spell.spell;
			if (spelling === this.getLast(spelling.length)) {matchList.push(spell);}
		}
		return matchList.reduce(function(prev,curr) {return ((curr.spell.length > prev.spell.length) ? curr : prev)},spellbook["null"]);
		//for (i;i<L;i++) {if (matchList[i]["spell"].length>result.length) {result=matchList[i];}}
	};
	this.remember = function(c) {
		this.history.push(c);
		while (this.history.length > 20) {this.history.shift();}
	};
}

function Conjuration(caster,rate,duration,damage,imagesrc) { //Images should be from P1's perspective
	Actor.call(this,imagesrc,caster.x,caster.y);
	this.heading = (caster.controller===P1) ? 1 : -1;//heading;//-1 for left, 1 for right
	this.rate = rate;
	this.damage = damage;
	this.caster = caster;
	this.duration = duration;
	this.onUpkeep = function() {
		console.log(this.duration)
		this.duration -= 1;
		if (this.duration === 0) {
			this.isCondemned = true;
			if (this.onDestroy) {this.onDestroy();}
			return;}
		if (this.upkeep) {this.upkeep();}
	};

	//if (this.heading===-1) {ctx.scale(scaleH, scaleV)}
}

function Fireball(caster) {
	Conjuration.call(this,caster,256,1,5,"fireball");
	this.tag = "fireball"
}

function Shield(caster) {
	Conjuration.call(this,caster,0,1,0,"shield")
	this.tag = "shield"
	this.x -= 30;this.y -= 30;  //need to find a better solution than hardcoding. Problem is I can't refer to the width because the image is not loaded yet.
	caster.isShielded = true;
	this.onDestroy = function() {caster.isShielded = false};
}
/////////////////////////////////////////////////////////////////////////
/////////////////////////////////Spells//////////////////////////////////
/////////////////////////////////////////////////////////////////////////

var spellbook = {
	"null": {
		spell:"",
		onCast: function(caster) {}
	},
	fireball: {
		spell:"abc",//aabc; will use simple 1 character for testing
		onCast: function(caster) {
			var conj = new Fireball(caster);
			conjurations.push(conj);
		}
	},
	shield: {
		spell:"c",
		onCast: function(caster) {
			var conj = new Shield(caster);
			conjurations.push(conj);
		}
	}
}

/////////////////////////////////////////////////////////////////////////
//////////////////////////Variable Definitions///////////////////////////
/////////////////////////////////////////////////////////////////////////

var startX1 = canvas.width / 10,
	startX2 = canvas.width * 8 / 10,
	startY = canvas.height / 2,

	P1 = new Wizard(7,20,4,"player1",startX1,startY),
	P2 = new Wizard(7,20,4,"player2",startX2,startY),

	creatures = [P1,P2],
	conjurations = [],
	removeConjurations = [],
	removeCreatures = [],
	keysDown = {},
	orders = {P1:"",P2:""};

/////////////////////////////////////////////////////////////////////////
////////////////////////////Controls Handler/////////////////////////////
/////////////////////////////////////////////////////////////////////////

addEventListener("keydown", function (e) {
	keysDown[e.keyCode] = true;
}, false);

addEventListener("keyup", function (e) {
	delete keysDown[e.keyCode];
}, false);

/////////////////////////////////////////////////////////////////////////
/////////////////////////Game Update Functions///////////////////////////
/////////////////////////////////////////////////////////////////////////

// Update game objects
var update = function (modifier) {
	//console.log(keysDown);
	//Log key commands
	var P,key,controls;
	for (P in keybindings) {
		controls = keybindings[P]
		for (key in controls) {
			if (controls[key] in keysDown) {orders[P]=key}
		}
	}

	var enemy;
	conjurations.forEach(function(o,i) {
		enemy = ((o.caster===P1) ? P2 : P1);
		o.x += o.rate * o.heading * modifier;
		if (o.isTouching(enemy)) {
			if (!enemy.isShielded) {enemy.health -= o.damage}
			if (o.onDestroy) {o.onDestroy();}
			o.isCondemned = true;
		}
		else if (o.isOffscreen()) {o.isCondemned=true; if (o.onDestroy) {o.onDestroy();}}
	})

	conjurations = conjurations.filter(function(x) {return (!x.isCondemned)})
	creatures = creatures.filter(function(x) {return (!x.isCondemned)})
};

// Reset the game
var reset = function() {
	P1.x = canvas.width / 10;
	P1.y = canvas.height / 2;

	// Throw the monster somewhere on the screen randomly
	P2.x = canvas.width * 8 / 10;
	P2.y = canvas.height / 2;
}

// Draw everything
var render = function () {
	//Draw background
	if (bgReady) {ctx.drawImage(bgImage, 0, 0);}
	//Draw creatures
	var i=0,L=creatures.length;
	for (i;i<L;i++) {creatures[i].draw();}
	//Draw conjurations
	L=conjurations.length;
	for (i=0;i<L;i++) {conjurations[i].draw();}

	// Life
	ctx.fillStyle = "rgb(250, 250, 250)";
	ctx.font = "24px Helvetica";
	ctx.fillStyle = "green";
	ctx.textBaseline = "top";

	ctx.textAlign = "left";
	ctx.fillText("Life: " + P1.health, 32, 400-32);
	ctx.textAlign = "right";
	ctx.fillText("Life: " + P2.health, 600-32, 400-32);

	// Time
	ctx.fillStyle = "black";
	ctx.textAlign = "center";
	var text = (parseInt((nextResolve-Date.now())/1000)+1).toString();
	ctx.fillText(text,300,200);
};

//Resolve player actions between rounds
var resolve = function() {
	var P1W = P1.words, P2W = P2.words;
	P1W.remember(orders.P1);
	P2W.remember(orders.P2);
	orders.P1 = "";
	orders.P2 = "";

	//Upkeep for existing spells
	conjurations.forEach(function(x) {
		if (x.onUpkeep) {x.onUpkeep()}
	});

	var P1S = P1W.findSpell(),P2S = P2W.findSpell();
	if (P1S) {P1S.onCast(P1)}
	if (P2S) {P2S.onCast(P2)}
	console.log(P1.words.history);
	console.log(P2.words.history);
}

// The main game loop
var main = function () {
	var now = Date.now();
	var delta = now - then;

	if (now>nextResolve) {
		resolve()
		nextResolve += roundTime;
	}

	update(delta / 1000);
	render();

	then = now;

	// Request to do this again ASAP
	requestAnimationFrame(main);
};

// Cross-browser support for requestAnimationFrame
var w = window;
requestAnimationFrame = w.requestAnimationFrame || w.webkitRequestAnimationFrame || w.msRequestAnimationFrame || w.mozRequestAnimationFrame;

// Let's play this game!
var nextResolve = Date.now() + roundTime;
var then = Date.now();
reset();
main();<|endoftext|>


<commit_before>"use strict";

// regex matches if current player is 1 move away from winning & supplies winning move
var winningMovePatterns = [
                           [(/ OO....../),0],[(/O..O.. ../),6],[(/......OO /),8],
                           [(/.. ..O..O/),2],[(/ ..O..O../),0],[(/...... OO/),6],
                           [(/..O..O.. /),8],[(/OO ....../),2],[(/ ...O...O/),0],
                           [(/..O.O. ../),6],[(/O...O... /),8],[(/.. .O.O../),2],
                           [(/O O....../),1],[(/O.. ..O../),3],[(/......O O/),7],
                           [(/..O.. ..O/),5],[(/. ..O..O./),1],[(/... OO.../),3],
                           [(/.O..O.. ./),7],[(/...OO .../),5]
                          ];

// regex matches if opponent is 1 move away from winning & supplies blocking move
var blockingPatterns = [
                        [(/  X . X  /),1],[(/ XX....../),0],[(/X..X.. ../),6],
                        [(/......XX /),8],[(/.. ..X..X/),2],[(/ ..X..X../),0],
                        [(/...... XX/),6],[(/..X..X.. /),8],[(/XX ....../),2],
                        [(/.. .X...X/),2],[(/..X.X. ../),6],[(/X...X... /),8],
                        [(/.. .X.X../),2],[(/X X....../),1],[(/X.. ..X../),3],
                        [(/......X X/),7],[(/..X.. ..X/),5],[(/. ..X..X./),1],
                        [(/... XX.../),3],[(/.X..X.. ./),7],[(/...XX .../),5],
                        [(/ X X.. ../),0],[(/ ..X.. X /),6],[(/.. ..X X /),8],
                        [(/ X ..X.. /),2],[(/  XX.. ../),0],[(/X.. .. X /),6],
                        [(/.. .XX   /),8],[(/X  ..X.. /),2],[(/ X  ..X../),0],
                        [(/ ..X..  X/),6],[(/..X..  X /),8],[(/X  ..X.. /),2]
                       ];

// regex matches if a player has won & supplies the winning player
var hasWonPatterns = [
                      [(/OOO....../),'O'],[(/...OOO.../),'O'],[(/......OOO/),'O'],
                      [(/O..O..O../),'O'],[(/.O..O..O./),'O'],[(/..O..O..O/),'O'],
                      [(/O...O...O/),'O'],[(/..O.O.O../),'O'],[(/XXX....../),'X'],
                      [(/...XXX.../),'X'],[(/......XXX/),'X'],[(/X..X..X../),'X'],
                      [(/.X..X..X./),'X'],[(/..X..X..X/),'X'],[(/X...X...X/),'X'],
                      [(/..X.X.X../),'X']
                     ];

var board = [' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' '];
var player1 = 'X';
var player2 = 'O';
var currentTurn = player1;

// this searches winningMovePatterns then blockingPatterns and if there is no
// match run firstMove()
var findNextMove = function(){
  var nextPos = makeWinningMove(board);
  if(nextPos === -1){
    nextPos = makeBlockingMove(board);
    if(nextPos === -1){
      nextPos = firstMove();
    }
  }
  makeMove(nextPos,player2);
};

var makeMove = function(pos, player){
  if(player != currentTurn){return false;}
  if(+pos >= 0 && +pos <= 8 && !isNaN(+pos) && board[+pos] === ' '){
    board.splice(+pos, 1, player);
    currentTurn = (player === player1) ? player2 : player1;
    return true;
  }
  return false;
};

var board_display = function(){
  return ' '+board[0]+' |'+' '+board[1]+' |'+' '+board[2]+'\n===+===+===\n'+' '+
             board[3]+' |'+' '+board[4]+' |'+' '+board[5]+'\n===+===+===\n'+' '+
             board[6]+' |'+' '+board[7]+' |'+' '+board[8];
};

var logBoardToConsole = function(){
  console.log(board_display());
};

// return true if the board is filled
var isBoardFilled = function(){
  if(board.indexOf(' ') === -1){
    logBoardToConsole();
    console.log("Game over, it's a draw!");
    return true;
  }
  return false;
};

// if the board matches a pattern from hasWonPatterns, return the winner
var hasSomeoneWon = function(board){
  var board_string = board.join('');
  var theWinner = null;
  for(var i = 0;i < hasWonPatterns.length;i++){
    var array = board_string.match(hasWonPatterns[i][0]);
    if(array){
      theWinner = hasWonPatterns[i][1];
    }
  }
  if(theWinner){
    logBoardToConsole();
    console.log('Game over.', theWinner, 'is the winner!');
    return [true, theWinner];
  }
  return [false, null];
};

// return the next move by matching a pattern from winningMovePatterns and returning the number
// (the second value in the array)
var makeWinningMove = function(board){
  var board_string = board.join('');
  for(var i = 0;i < winningMovePatterns.length;i++){
    var array = board_string.match(winningMovePatterns[i][0]);
    if(array){ // this is only truthy when someone wins
      return winningMovePatterns[i][1];
    }
  }
  return -1;
};

// return the next move by matching a pattern from winningMovePatterns and returning the number
// (the second value in the array)
var makeBlockingMove = function(board){
  var board_string = board.join('');
  for(var i = 0;i < blockingPatterns.length;i++){
    var array = board_string.match(blockingPatterns[i][0]);
      if(array){return blockingPatterns[i][1];}
  }
  return -1;
};

// if the center of board is free, go there, if not go to position 0
var firstMove = function(){
  return board[4] === ' ' ? 4 : board.indexOf(' ');
};

var endGame = function(){
  process.exit();
};

var startGame = function(){
  logBoardToConsole();
  console.log("Enter [0-8]:");
  process.openStdin().on('data',function(res){
    if(makeMove(res, player1)){
      if(hasSomeoneWon(board)[0] || isBoardFilled()) {
        endGame();
      } else {
        findNextMove();
        if (hasSomeoneWon(board)[0] || isBoardFilled()) {
          endGame();
        } else {
          logBoardToConsole();
        }
      }
    }
  });
};

startGame();

// exports needed for tests
module.exports = {
  makeWinningMove : makeWinningMove,
  makeBlockingMove : makeBlockingMove,
  hasSomeoneWon : hasSomeoneWon
};
<commit_msg>Refactor startGame(). Related #10.<commit_after>"use strict";

// regex matches if current player is 1 move away from winning & supplies winning move
var winningMovePatterns = [
                           [(/ OO....../),0],[(/O..O.. ../),6],[(/......OO /),8],
                           [(/.. ..O..O/),2],[(/ ..O..O../),0],[(/...... OO/),6],
                           [(/..O..O.. /),8],[(/OO ....../),2],[(/ ...O...O/),0],
                           [(/..O.O. ../),6],[(/O...O... /),8],[(/.. .O.O../),2],
                           [(/O O....../),1],[(/O.. ..O../),3],[(/......O O/),7],
                           [(/..O.. ..O/),5],[(/. ..O..O./),1],[(/... OO.../),3],
                           [(/.O..O.. ./),7],[(/...OO .../),5]
                          ];

// regex matches if opponent is 1 move away from winning & supplies blocking move
var blockingPatterns = [
                        [(/  X . X  /),1],[(/ XX....../),0],[(/X..X.. ../),6],
                        [(/......XX /),8],[(/.. ..X..X/),2],[(/ ..X..X../),0],
                        [(/...... XX/),6],[(/..X..X.. /),8],[(/XX ....../),2],
                        [(/.. .X...X/),2],[(/..X.X. ../),6],[(/X...X... /),8],
                        [(/.. .X.X../),2],[(/X X....../),1],[(/X.. ..X../),3],
                        [(/......X X/),7],[(/..X.. ..X/),5],[(/. ..X..X./),1],
                        [(/... XX.../),3],[(/.X..X.. ./),7],[(/...XX .../),5],
                        [(/ X X.. ../),0],[(/ ..X.. X /),6],[(/.. ..X X /),8],
                        [(/ X ..X.. /),2],[(/  XX.. ../),0],[(/X.. .. X /),6],
                        [(/.. .XX   /),8],[(/X  ..X.. /),2],[(/ X  ..X../),0],
                        [(/ ..X..  X/),6],[(/..X..  X /),8],[(/X  ..X.. /),2]
                       ];

// regex matches if a player has won & supplies the winning player
var hasWonPatterns = [
                      [(/OOO....../),'O'],[(/...OOO.../),'O'],[(/......OOO/),'O'],
                      [(/O..O..O../),'O'],[(/.O..O..O./),'O'],[(/..O..O..O/),'O'],
                      [(/O...O...O/),'O'],[(/..O.O.O../),'O'],[(/XXX....../),'X'],
                      [(/...XXX.../),'X'],[(/......XXX/),'X'],[(/X..X..X../),'X'],
                      [(/.X..X..X./),'X'],[(/..X..X..X/),'X'],[(/X...X...X/),'X'],
                      [(/..X.X.X../),'X']
                     ];

var board = [' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' '];
var player1 = 'X';
var player2 = 'O';
var currentTurn = player1;

// this searches winningMovePatterns then blockingPatterns and if there is no
// match run firstMove()
var findNextMove = function(){
  var nextPos = makeWinningMove(board);
  if(nextPos === -1){
    nextPos = makeBlockingMove(board);
    if(nextPos === -1){
      nextPos = firstMove();
    }
  }
  makeMove(nextPos,player2);
};

var makeMove = function(pos, player){
  if(player != currentTurn){return false;}
  if(+pos >= 0 && +pos <= 8 && !isNaN(+pos) && board[+pos] === ' '){
    board.splice(+pos, 1, player);
    currentTurn = (player === player1) ? player2 : player1;
    return true;
  }
  return false;
};

var board_display = function(){
  return ' '+board[0]+' |'+' '+board[1]+' |'+' '+board[2]+'\n===+===+===\n'+' '+
             board[3]+' |'+' '+board[4]+' |'+' '+board[5]+'\n===+===+===\n'+' '+
             board[6]+' |'+' '+board[7]+' |'+' '+board[8];
};

var logBoardToConsole = function(){
  console.log(board_display());
};

// return true if the board is filled
var isBoardFilled = function(){
  if(board.indexOf(' ') === -1){
    logBoardToConsole();
    console.log("Game over, it's a draw!");
    return true;
  }
  return false;
};

// if the board matches a pattern from hasWonPatterns, return the winner
var hasSomeoneWon = function(board){
  var board_string = board.join('');
  var theWinner = null;
  for(var i = 0;i < hasWonPatterns.length;i++){
    var array = board_string.match(hasWonPatterns[i][0]);
    if(array){
      theWinner = hasWonPatterns[i][1];
    }
  }
  if(theWinner){
    logBoardToConsole();
    console.log('Game over.', theWinner, 'is the winner!');
    return [true, theWinner];
  }
  return [false, null];
};

// return the next move by matching a pattern from winningMovePatterns and returning the number
// (the second value in the array)
var makeWinningMove = function(board){
  var board_string = board.join('');
  for(var i = 0;i < winningMovePatterns.length;i++){
    var array = board_string.match(winningMovePatterns[i][0]);
    if(array){ // this is only truthy when someone wins
      return winningMovePatterns[i][1];
    }
  }
  return -1;
};

// return the next move by matching a pattern from winningMovePatterns and returning the number
// (the second value in the array)
var makeBlockingMove = function(board){
  var board_string = board.join('');
  for(var i = 0;i < blockingPatterns.length;i++){
    var array = board_string.match(blockingPatterns[i][0]);
      if(array){return blockingPatterns[i][1];}
  }
  return -1;
};

// if the center of board is free, go there, if not go to position 0
var firstMove = function(){
  return board[4] === ' ' ? 4 : board.indexOf(' ');
};

var endGame = function(){
  process.exit();
};

var startGame = function(){
  logBoardToConsole();
  console.log("Enter [0-8]:");
  process.openStdin().on('data',function(res){
    if(makeMove(res, player1)){
      if(hasSomeoneWon(board)[0] || isBoardFilled()) {
        endGame();
      }
      findNextMove();
      if(hasSomeoneWon(board)[0] || isBoardFilled()) {
        endGame();
      } else {
        logBoardToConsole();
      }
    }
  });
};

startGame();

// exports needed for tests
module.exports = {
  makeWinningMove : makeWinningMove,
  makeBlockingMove : makeBlockingMove,
  hasSomeoneWon : hasSomeoneWon
};
<|endoftext|>


<commit_before>"strict mode";
var raf = require("./raf");
var Canvas = require("./canvas");
var before = 0;

var game = {
        mouse: [],
        run: function() {
            var now = Date.now();
            var frameTime = now - before;
            if(game.state) {
                game.state.fire("update", now);
                game.state.fire("draw", { canvas: Canvas, now: now, frameTime: frameTime });
            }
            before = now;
            raf.call(window, game.run);
        },
        touches: {}
    },
    state = null;

Object.defineProperty(game, "state", {
    get: function() {
        return state;
    },
    set: function(newstate) {
        if(state) {
            state.fire("clear");
        }
        newstate.fire("init");
        state = newstate;
    }
});

window.addEventListener("keyup", function(e) {
    if(game.state) {
        game.state.fire("keyup", {
            code: e.keyCode,
            ctrl: e.ctrlKey,
            alt: e.altKey,
            shift: e.shiftKey
        });
    }
});
window.addEventListener("keydown", function(e) {
    if(game.state) {
        game.state.fire("keydown", {
            code: e.keyCode,
            ctrl: e.ctrlKey,
            alt: e.altKey,
            shift: e.shiftKey
        });
    }
});

window.addEventListener("mousemove", function(e) {
    if(game.state) {
        var x = e.clientX - Canvas.position.X;
        var y = e.clientY - Canvas.position.Y;
        game.state.fire("mousemove", {X: x, Y: y});
    }
});

Canvas.element.addEventListener("mousedown", function(e) {
    game.mouse[e.button] = Date.now();
    e.preventDefault();
    if(game.state) {
        var x = e.clientX - Canvas.position.X;
        var y = e.clientY - Canvas.position.Y;
        game.state.fire("mousedown", {X: x, Y: y, button: e.button});
    }
});

Canvas.element.addEventListener("mouseup", function(e) {
    var now = Date.now();
    var x, y;
    console.log(now - game.mouse[e.button]);
    if(now - game.mouse[e.button] < 150) {
        if(game.state) {
            x = e.clientX - Canvas.position.X;
            y = e.clientY - Canvas.position.Y;
            game.state.fire("click", {X: x, Y: y, button: e.button});
        }
    }
    game.mouse[e.button] = null;
    if(game.state) {
        x = e.clientX - Canvas.position.X;
        y = e.clientY - Canvas.position.Y;
        game.state.fire("mouseup", {X: x, Y: y, button: e.button});
    }
});

window.addEventListener("touchstart", function(e) {
    console.log("touchstart");
    if(game.state && game.state.mousedown) {
        var touches = e.changedTouches;
        if(touches.length > 0) {
            var x = (touches[0].pageX | 0);// - Canvas.position.X;
            var y = (touches[0].pageY | 0);// - Canvas.position.Y;
            game.state.fire("touchstart", touches);
            game.touches[touches[0].identifier] = Date.now();
        }
    }
});

window.addEventListener("touchmove", function(e) {
    console.log("touchmove");
    if(game.state && game.state.mousemove) {
        var touches = e.changedTouches;
        if(touches.length > 0) {
            var x = (touches[0].pageX | 0);// - Canvas.position.X;
            var y = (touches[0].pageY | 0);// - Canvas.position.Y;
            game.state.fire("touchmove", touches);
        }
    }
});

window.addEventListener("touchend", function(e) {
    console.log("touchend");
    var touches = e.changedTouches;
    var x, y;
    if(game.state && game.state.mouseup) {
        if(touches.length > 0) {
            x = (touches[0].pageX | 0);// - Canvas.position.X;
            y = (touches[0].pageY | 0);// - Canvas.position.Y;
            game.state.fire("touchend", touches);

        }
    }
});
module.exports = game;

<commit_msg>added delta time to update event as well<commit_after>"strict mode";
var raf = require("./raf");
var Canvas = require("./canvas");
var before = 0;

var game = {
        mouse: [],
        run: function() {
            var now = Date.now();
            var frameTime = now - before;
            if(game.state) {
                game.state.fire("update", { now:  now, frameTime: frameTime });
                game.state.fire("draw", { canvas: Canvas, now: now, frameTime: frameTime });
            }
            before = now;
            raf.call(window, game.run);
        },
        touches: {}
    },
    state = null;

Object.defineProperty(game, "state", {
    get: function() {
        return state;
    },
    set: function(newstate) {
        if(state) {
            state.fire("clear");
        }
        newstate.fire("init");
        state = newstate;
    }
});

window.addEventListener("keyup", function(e) {
    if(game.state) {
        game.state.fire("keyup", {
            code: e.keyCode,
            ctrl: e.ctrlKey,
            alt: e.altKey,
            shift: e.shiftKey
        });
    }
});
window.addEventListener("keydown", function(e) {
    if(game.state) {
        game.state.fire("keydown", {
            code: e.keyCode,
            ctrl: e.ctrlKey,
            alt: e.altKey,
            shift: e.shiftKey
        });
    }
});

window.addEventListener("mousemove", function(e) {
    if(game.state) {
        var x = e.clientX - Canvas.position.X;
        var y = e.clientY - Canvas.position.Y;
        game.state.fire("mousemove", {X: x, Y: y});
    }
});

Canvas.element.addEventListener("mousedown", function(e) {
    game.mouse[e.button] = Date.now();
    e.preventDefault();
    if(game.state) {
        var x = e.clientX - Canvas.position.X;
        var y = e.clientY - Canvas.position.Y;
        game.state.fire("mousedown", {X: x, Y: y, button: e.button});
    }
});

Canvas.element.addEventListener("mouseup", function(e) {
    var now = Date.now();
    var x, y;
    console.log(now - game.mouse[e.button]);
    if(now - game.mouse[e.button] < 150) {
        if(game.state) {
            x = e.clientX - Canvas.position.X;
            y = e.clientY - Canvas.position.Y;
            game.state.fire("click", {X: x, Y: y, button: e.button});
        }
    }
    game.mouse[e.button] = null;
    if(game.state) {
        x = e.clientX - Canvas.position.X;
        y = e.clientY - Canvas.position.Y;
        game.state.fire("mouseup", {X: x, Y: y, button: e.button});
    }
});

window.addEventListener("touchstart", function(e) {
    console.log("touchstart");
    if(game.state && game.state.mousedown) {
        var touches = e.changedTouches;
        if(touches.length > 0) {
            var x = (touches[0].pageX | 0);// - Canvas.position.X;
            var y = (touches[0].pageY | 0);// - Canvas.position.Y;
            game.state.fire("touchstart", touches);
            game.touches[touches[0].identifier] = Date.now();
        }
    }
});

window.addEventListener("touchmove", function(e) {
    console.log("touchmove");
    if(game.state && game.state.mousemove) {
        var touches = e.changedTouches;
        if(touches.length > 0) {
            var x = (touches[0].pageX | 0);// - Canvas.position.X;
            var y = (touches[0].pageY | 0);// - Canvas.position.Y;
            game.state.fire("touchmove", touches);
        }
    }
});

window.addEventListener("touchend", function(e) {
    console.log("touchend");
    var touches = e.changedTouches;
    var x, y;
    if(game.state && game.state.mouseup) {
        if(touches.length > 0) {
            x = (touches[0].pageX | 0);// - Canvas.position.X;
            y = (touches[0].pageY | 0);// - Canvas.position.Y;
            game.state.fire("touchend", touches);

        }
    }
});
module.exports = game;

<|endoftext|>